mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 00:59:29 +01:00
Merge pull request #836 from vangel76/feat/wayland-tablet-816
Linux: open the window through Xwayland when a pen is attached on Wayland, so the pen works
This commit is contained in:
10 files changed
+358
-29
No files matched your search
@@ -28,6 +28,7 @@ licensed and keep their license file next to them.
|
||||
| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) |
|
||||
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
|
||||
| `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) |
|
||||
| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 |
|
||||
|
||||
## Third-party assets compiled into the binary
|
||||
|
||||
@@ -52,6 +53,8 @@ time (nothing is bundled); see [docs/localization-parity.md](docs/localization-p
|
||||
| `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 |
|
||||
| `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 |
|
||||
| `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
|
||||
| `x11rb-protocol` | X11 setup and Xauthority for the Linux pen startup probe | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
|
||||
| `rustix` | Linux socket and hostname APIs for the X11 setup probe | https://github.com/bytecodealliance/rustix | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT |
|
||||
| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT |
|
||||
|
||||
## Procedural content (no asset files)
|
||||
|
||||
Generated
+3
@@ -5819,6 +5819,7 @@ dependencies = [
|
||||
name = "texturecraft"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-image-codecs",
|
||||
"craft-menu",
|
||||
"craft-update",
|
||||
@@ -5829,6 +5830,7 @@ dependencies = [
|
||||
"log",
|
||||
"rfd",
|
||||
"ron",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"texturecraft-automation",
|
||||
"texturecraft-engine",
|
||||
@@ -5836,6 +5838,7 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"x11rb-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors
|
||||
Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors (adapted Linux pen and display probing code)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -12,6 +12,16 @@ Third-party material
|
||||
This product bundles third-party material under its own licenses, listed below. The per-file
|
||||
list (author, source, license) is in ATTRIBUTION.md.
|
||||
|
||||
PhotoCraft Linux pen and display probing code, adapted in apps/texturecraft/src/xwayland_pen.rs
|
||||
from storytold/photocraft at 830316b775f1f6734498ac6e39fd1298955ff93f.
|
||||
Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors.
|
||||
Licensed under the MIT License or the Apache License, Version 2.0, at your option
|
||||
(LICENSE-MIT, LICENSE-APACHE).
|
||||
|
||||
Linux X11 setup probe components:
|
||||
- rustix — Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT.
|
||||
- x11rb-protocol — MIT OR Apache-2.0. Copyright 2019 x11rb contributors.
|
||||
|
||||
Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr),
|
||||
by Sergej Majboroda (Poly Haven) — CC0-1.0.
|
||||
Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256).
|
||||
|
||||
@@ -23,6 +23,8 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The message box for errors that end the app (a Windows release build has no console).
|
||||
rfd = { workspace = true }
|
||||
# Pass the selected window backend to the title bar and UI runtime
|
||||
craft-host = { workspace = true }
|
||||
# Reads the saved System title bar setting before the window opens (eframe's settings format).
|
||||
ron = "0.12"
|
||||
|
||||
@@ -35,6 +37,12 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s
|
||||
# The update helper is a copy of this program (`main`).
|
||||
craft-update = { workspace = true }
|
||||
|
||||
# X11 setup probing and event loop selection for Wayland pen support
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { workspace = true, features = ["net", "system"] }
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
x11rb-protocol = "0.13"
|
||||
|
||||
# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
craft-menu = { workspace = true }
|
||||
|
||||
@@ -15,6 +15,8 @@ mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod window_frame;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod xwayland_pen;
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
@@ -334,8 +336,7 @@ fn launch_arguments(arguments: Vec<OsString>) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`. A
|
||||
// Nightly install is updated by ArtCraft Launcher, so it never installs an update itself.
|
||||
// Stable handles --finish-update on Windows while the launcher updates Nightly
|
||||
#[cfg(windows)]
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable
|
||||
&& let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
@@ -343,15 +344,16 @@ fn main() {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
|
||||
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with
|
||||
// its own argument. It reads no user state and is started without the profile tokens, so it
|
||||
// runs before the launch protocol would refuse it.
|
||||
// Dispatch the Windows pointer keeper before launch validation because it has no profile tokens
|
||||
#[cfg(windows)]
|
||||
if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) {
|
||||
std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer());
|
||||
}
|
||||
|
||||
let Some(arguments) = prepare_launch() else { return };
|
||||
let Some(arguments) = prepare_launch() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
let args = match launch_arguments(arguments).and_then(parse_args_from) {
|
||||
Ok(Some(a)) => a,
|
||||
@@ -361,8 +363,8 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// The control server is a stable-install service: a Nightly window is driven by the Launcher,
|
||||
// and its token file would sit in the shared temp folder rather than its private profile.
|
||||
|
||||
// Keep the control token out of the shared temp folder for a private Nightly profile
|
||||
if nightly && args.control.is_some() {
|
||||
eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli");
|
||||
std::process::exit(2);
|
||||
@@ -377,9 +379,8 @@ fn main() {
|
||||
previous_hook(info);
|
||||
}));
|
||||
|
||||
// Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe
|
||||
// is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the
|
||||
// folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`).
|
||||
// Scripted runs use temporary files to protect saved settings
|
||||
// An explicit eframe path keeps app.ron with ui.json and errors.log despite the app ID
|
||||
let no_prefs_path =
|
||||
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
|
||||
let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron")));
|
||||
@@ -393,8 +394,16 @@ fn main() {
|
||||
prefs.apply_work_threads();
|
||||
prefs.apply_resource_limits();
|
||||
let session = initial_session(&args);
|
||||
let frame_decision = TitleBar::decide(prefs.system_title_bar);
|
||||
|
||||
// Xwayland can forward pen input as pointer events on Wayland desktops
|
||||
#[cfg(target_os = "linux")]
|
||||
let use_xwayland_for_pen = xwayland_pen::opens_through_xwayland();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let use_xwayland_for_pen = false;
|
||||
let backend = if use_xwayland_for_pen { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() };
|
||||
let frame_decision = TitleBar::decide(prefs.system_title_bar, backend);
|
||||
let title_bar = TitleBar::of(&frame_decision.frame);
|
||||
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_app_id(os_window::app_id())
|
||||
.with_title(os_window::name())
|
||||
@@ -403,15 +412,32 @@ fn main() {
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
|
||||
let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport);
|
||||
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
|
||||
#[cfg(target_os = "linux")]
|
||||
if use_xwayland_for_pen {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11 as _;
|
||||
|
||||
options.event_loop_builder = Some(Box::new(|builder| {
|
||||
builder.with_x11();
|
||||
}));
|
||||
let notice = texturecraft_ui_egui::i18n::trf(
|
||||
"Opening the window through Xwayland for pen input. Set {variable}=1 to keep Wayland.",
|
||||
&[("variable", &xwayland_pen::NATIVE_WAYLAND_VARIABLE)],
|
||||
);
|
||||
eprintln!("texturecraft: {notice}");
|
||||
}
|
||||
|
||||
if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) {
|
||||
fatal(&e.to_string(), true);
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
let control = args.control;
|
||||
// The Nightly session record: one owner per profile, an unclean exit reported by the next
|
||||
// start, and no document name, path or diagnostic payload collected.
|
||||
|
||||
// Nightly records one owner per profile so the next launch can report an unclean exit
|
||||
// The record carries no document name, path or diagnostics
|
||||
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
build_flavor::BUILT_VERSION,
|
||||
@@ -424,12 +450,13 @@ fn main() {
|
||||
}
|
||||
};
|
||||
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
// Set once a window has posted the interruption notice; until then the record must survive.
|
||||
|
||||
// Keep the record until a window has posted the interruption notice
|
||||
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let notice_shown_in_window = unclean_notice_shown.clone();
|
||||
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
|
||||
// The exit hook is the controlled return on macOS, where every quit ends the process inside
|
||||
// AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes.
|
||||
|
||||
// AppKit terminates the process without returning from run_native, so macOS needs the exit hook
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
@@ -450,7 +477,8 @@ fn main() {
|
||||
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) {
|
||||
log::warn!("the app menu could not be installed: {e}");
|
||||
}
|
||||
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?;
|
||||
|
||||
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision, backend)?;
|
||||
let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.title_bar = title_bar;
|
||||
@@ -470,8 +498,8 @@ fn main() {
|
||||
Ok(Box::new(Shell { app, window_frame: frame_guard, exit_hook: Some(Box::new(finish_at_exit)) }))
|
||||
}),
|
||||
);
|
||||
// A controlled return, including a handled startup error. On macOS a window already finished in
|
||||
// its exit hook, so this is then a no-op.
|
||||
|
||||
// Close the session record on controlled return, including handled startup errors
|
||||
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
if let Err(e) = result {
|
||||
fatal(&e.to_string(), true);
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! A pen on a Wayland desktop opens the window through Xwayland (#816).
|
||||
//!
|
||||
//! Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors for the adapted code.
|
||||
//! Licensed under the MIT License or the Apache License, Version 2.0, at your option.
|
||||
//!
|
||||
//! Wayland compositors give a pen only to clients that bind the tablet protocol (`zwp_tablet_v2`),
|
||||
//! which winit 0.30 doesn't (and binding it on winit's connection needs `unsafe`, which this app
|
||||
//! forbids). Some compositors (KWin) then send the window nothing from the pen: no cursor, no
|
||||
//! painting. Xwayland binds the protocol and serves the pen as an X11 pointer, so with a pen
|
||||
//! attached the window opens there. `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland.
|
||||
//!
|
||||
//! Adapted from PhotoCraft (storytold/photocraft `830316b7`, MIT OR Apache-2.0):
|
||||
//! `apps/photocraft/src/tablet.rs` (`display_session`, `pen_needs_xwayland`, `has_pen`, `bit_set`)
|
||||
//! and `apps/photocraft/src/linux_libs.rs` (`session_from_env`, `ldconfig_has`, the library
|
||||
//! search), reduced to the pen decision. See the repository's NOTICE for the port.
|
||||
|
||||
use std::io::{Read as _, Write as _};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb_protocol::connect::Connect;
|
||||
use x11rb_protocol::xauth::{Family, get_auth};
|
||||
|
||||
/// Set (and not `0`) to keep native Wayland with a pen attached
|
||||
pub(super) const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND";
|
||||
|
||||
/// `BTN_TOOL_PEN` (linux/input-event-codes.h): the key a tablet's stylus, a pen display's or a
|
||||
/// pen-enabled touchscreen's pen reports
|
||||
const BTN_TOOL_PEN: u32 = 0x140;
|
||||
|
||||
/// `ABS_X` and `ABS_Y` (linux/input-event-codes.h): the absolute axes every pen reports
|
||||
const ABS_X: u32 = 0x00;
|
||||
const ABS_Y: u32 = 0x01;
|
||||
|
||||
/// What winit 0.30 loads at run time for an X11 window: Xlib, Xlib-xcb, xcb, Xcursor, XInput2 and
|
||||
/// xkbcommon with its X11 part
|
||||
const X11_LIBRARIES: &[&str] =
|
||||
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
|
||||
|
||||
// Give local Xwayland time to answer while bounding the wait before falling back to Wayland
|
||||
const X11_SETUP_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland
|
||||
/// has the required libraries and accepts an X11 client setup.
|
||||
pub fn opens_through_xwayland() -> bool {
|
||||
let var = |name: &str| std::env::var(name).ok();
|
||||
let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices));
|
||||
pen_needs_xwayland(var, pen, |display| x11_libraries_available() && x_server_accepts_setup(display))
|
||||
}
|
||||
|
||||
/// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or
|
||||
/// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland.
|
||||
fn pen_needs_xwayland(var: impl Fn(&str) -> Option<String>, pen: impl FnOnce() -> bool, xwayland_ready: impl FnOnce(&str) -> bool) -> bool {
|
||||
let set = |name: &str| var(name).is_some_and(|value| !value.is_empty());
|
||||
let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET");
|
||||
let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0");
|
||||
wayland && !keeps_wayland && var("DISPLAY").filter(|display| !display.is_empty()).is_some_and(|display| pen() && xwayland_ready(&display))
|
||||
}
|
||||
|
||||
/// winit commits to its forced backend, so require an accepted X11 setup before forcing X11.
|
||||
fn x_server_accepts_setup(display: &str) -> bool {
|
||||
let Some((display_number, screen)) = local_display(display) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let Some(socket) = connect_local_x_server(display_number) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let hostname = rustix::system::uname();
|
||||
let auth_hostname = std::env::var_os("XAUTHLOCALHOSTNAME");
|
||||
let auth_address = auth_hostname.as_ref().map_or(hostname.nodename().to_bytes(), |name| name.as_encoded_bytes());
|
||||
let (auth_name, auth_data) = get_auth(Family::LOCAL, auth_address, display_number).ok().flatten().unwrap_or_default();
|
||||
let (setup, request) = Connect::with_authorization(auth_name, auth_data);
|
||||
exchange_x11_setup(socket, setup, &request, screen)
|
||||
}
|
||||
|
||||
/// Parse the display and screen of a local X server such as `:0`, `:0.0` or `unix:0`.
|
||||
fn local_display(display: &str) -> Option<(u16, usize)> {
|
||||
let local = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?;
|
||||
let (display_number, screen) = local.split_once('.').unwrap_or((local, "0"));
|
||||
Some((display_number.parse().ok()?, screen.parse().ok()?))
|
||||
}
|
||||
|
||||
fn connect_local_x_server(display_number: u16) -> Option<UnixStream> {
|
||||
use rustix::net::{AddressFamily, SocketAddrUnix, SocketFlags, SocketType, connect, socket_with};
|
||||
|
||||
let path = format!("/tmp/.X11-unix/X{display_number}");
|
||||
|
||||
// Try the abstract socket first, as Xlib does on Linux
|
||||
[SocketAddrUnix::new_abstract_name(path.as_bytes()), SocketAddrUnix::new(&path)].into_iter().find_map(|address| {
|
||||
let address = address.ok()?;
|
||||
|
||||
// A full Unix socket backlog must not block app startup
|
||||
let socket = UnixStream::from(socket_with(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::NONBLOCK | SocketFlags::CLOEXEC, None).ok()?);
|
||||
connect(&socket, &address).ok()?;
|
||||
socket.set_nonblocking(false).ok()?;
|
||||
Some(socket)
|
||||
})
|
||||
}
|
||||
|
||||
fn exchange_x11_setup(mut socket: UnixStream, mut setup: Connect, request: &[u8], screen: usize) -> bool {
|
||||
let start = Instant::now();
|
||||
if socket.set_write_timeout(Some(X11_SETUP_TIMEOUT)).is_err() || socket.write_all(request).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
while !setup.buffer().is_empty() {
|
||||
let remaining = X11_SETUP_TIMEOUT.saturating_sub(start.elapsed());
|
||||
if remaining.is_zero() || socket.set_read_timeout(Some(remaining)).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Ok(received) = socket.read(setup.buffer()) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if received == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
if setup.advance(received) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
setup.into_setup().is_ok_and(|reply| screen < reply.roots.len())
|
||||
}
|
||||
|
||||
/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has
|
||||
/// `BTN_TOOL_PEN` and its `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as libinput asks of a tablet
|
||||
/// tool. The key alone isn't enough: a virtual keyboard made with uinput claims every key code.
|
||||
fn has_pen(devices: &str) -> bool {
|
||||
devices.split("\n\n").any(|device| {
|
||||
let bitmap = |name: &str| device.lines().find_map(|line| line.strip_prefix(name));
|
||||
bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y))
|
||||
})
|
||||
}
|
||||
|
||||
/// Bit `bit` of a `/proc/bus/input/devices` bitmap: hex words of the kernel's `long`, most
|
||||
/// significant first. Short or malformed bitmaps have no bits set.
|
||||
fn bit_set(bitmap: &str, bit: u32) -> bool {
|
||||
let word_bits = usize::BITS;
|
||||
let word = usize::try_from(bit / word_bits).unwrap_or(usize::MAX);
|
||||
bitmap.split_whitespace().rev().nth(word).and_then(|hex| u64::from_str_radix(hex, 16).ok()).is_some_and(|value| (value >> (bit % word_bits)) & 1 == 1)
|
||||
}
|
||||
|
||||
/// Are the libraries an X11 window needs installed? The linker cache (`ldconfig -p`) or the usual
|
||||
/// library directories must list each; one that can't be found counts as missing.
|
||||
fn x11_libraries_available() -> bool {
|
||||
let cache = linker_cache();
|
||||
let dirs = library_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref());
|
||||
X11_LIBRARIES.iter().all(|soname| cache.as_deref().is_some_and(|cache| ldconfig_has(cache, soname)) || dirs.iter().any(|dir| dir.join(soname).exists()))
|
||||
}
|
||||
|
||||
/// `ldconfig -p` in English (it is parsed), from where distributions put it
|
||||
fn linker_cache() -> Option<String> {
|
||||
["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"].into_iter().find_map(|command| {
|
||||
let output = std::process::Command::new(command).arg("-p").env("LC_ALL", "C").output().ok()?;
|
||||
output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Does an `ldconfig -p` listing have `soname` for this build's architecture? Lines look like
|
||||
/// `\tlibXi.so.6 (libc6,x86-64) => /lib/x86_64-linux-gnu/libXi.so.6`.
|
||||
fn ldconfig_has(cache: &str, soname: &str) -> bool {
|
||||
let architecture = if cfg!(target_arch = "x86_64") {
|
||||
Some("x86-64")
|
||||
} else if cfg!(target_arch = "aarch64") {
|
||||
Some("AArch64")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
cache.lines().any(|line| {
|
||||
let Some((name, rest)) = line.trim_start().split_once(' ') else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let flags = rest.split_once('(').and_then(|(_, after)| after.split_once(')')).map_or("", |(flags, _)| flags);
|
||||
name == soname && architecture.is_none_or(|tag| flags.split(',').any(|flag| flag.trim() == tag))
|
||||
})
|
||||
}
|
||||
|
||||
/// `LD_LIBRARY_PATH`, then the usual system and Flatpak library directories
|
||||
fn library_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
|
||||
let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" };
|
||||
let mut dirs: Vec<PathBuf> = ld_library_path.into_iter().flat_map(|value| value.split(':')).filter(|dir| !dir.is_empty()).map(PathBuf::from).collect();
|
||||
dirs.extend(["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"].map(PathBuf::from));
|
||||
dirs.extend([Path::new("/usr/lib").join(triplet), Path::new("/lib").join(triplet)]);
|
||||
dirs
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Capabilities from /proc/bus/input/devices for a touchpad and a Wacom pen
|
||||
const TOUCHPAD: &str = "N: Name=\"SYNA2B33:00 06CB:CE26 Touchpad\"\nB: KEY=e520 10000 0 0 0 0\nB: ABS=2e0800000000003\n";
|
||||
const PEN: &str = "N: Name=\"Wacom Intuos Pro M Pen\"\nB: KEY=1c03 0 0 0 0 0\nB: ABS=1000f000003\n";
|
||||
|
||||
// The uinput keyboard claims the pen key but reports no axes
|
||||
const VIRTUAL_KEYBOARD: &str = "N: Name=\"RustDesk UInput Keyboard\"\nB: EV=20013\nB: KEY=ffffffffff 0 7ffffff000301ff 1000f7fffffff 7fe001fffff000f 7ffffffffffffff ffffffff0003fdff 7fff8fff00ff03ff 1ffffffffffff07 ffffffffffffffff ffffffffffefffff fffffffffffffffe\n";
|
||||
|
||||
#[test]
|
||||
fn a_pen_is_a_device_with_the_pen_key_and_absolute_axes() {
|
||||
assert!(has_pen(&format!("{TOUCHPAD}\n{PEN}")));
|
||||
assert!(!has_pen(TOUCHPAD), "a touchpad is no pen");
|
||||
assert!(!has_pen(&format!("{VIRTUAL_KEYBOARD}\n{TOUCHPAD}")), "a keyboard claiming the pen key has no pen axes");
|
||||
assert!(!has_pen("B: KEY=zz 0 0 0 0 0\nB: ABS=3\n"), "a malformed bitmap is no pen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_on_wayland_opens_the_window_through_xwayland() {
|
||||
fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
|
||||
move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string())
|
||||
}
|
||||
const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
|
||||
|
||||
assert!(pen_needs_xwayland(env(WAYLAND), || true, |display| display == ":0"));
|
||||
assert!(!pen_needs_xwayland(env(WAYLAND), || false, |_| true), "no pen");
|
||||
assert!(!pen_needs_xwayland(env(WAYLAND), || true, |_| false), "Xwayland can't run the window");
|
||||
assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, |_| true), "no Xwayland");
|
||||
assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, |_| true), "kept");
|
||||
assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, |_| true));
|
||||
assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), |_| panic!("probed off Wayland")), "X11 already has the pen");
|
||||
assert_eq!([":1.2", "unix:0", "remote:0", ":0.bad"].map(local_display), [Some((1, 2)), Some((0, 0)), None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_keeps_wayland_when_the_x_server_rejects_setup() -> std::io::Result<()> {
|
||||
use x11rb_protocol::protocol::xproto::{Screen, Setup, SetupFailed};
|
||||
use x11rb_protocol::x11_utils::Serialize as _;
|
||||
|
||||
const REPLY_HEADER_BYTES: usize = 8;
|
||||
const BYTES_PER_X11_WORD: usize = 4;
|
||||
let reason = b"Setup denied".to_vec();
|
||||
let rejected = SetupFailed { protocol_major_version: 11, length: (reason.len() / BYTES_PER_X11_WORD) as u16, reason, ..Default::default() };
|
||||
let mut accepted = Setup { status: 1, protocol_major_version: 11, roots: vec![Screen::default()], ..Default::default() };
|
||||
accepted.length = ((accepted.serialize().len() - REPLY_HEADER_BYTES) / BYTES_PER_X11_WORD) as u16;
|
||||
|
||||
for (reply, screen, selects_xwayland) in [(rejected.serialize(), 0, false), (accepted.serialize(), 1, false), (accepted.serialize(), 0, true)] {
|
||||
let (client, mut server) = UnixStream::pair()?;
|
||||
server.write_all(&reply)?;
|
||||
let (setup, request) = Connect::with_authorization(Vec::new(), Vec::new());
|
||||
let var = |name: &str| match name {
|
||||
"WAYLAND_DISPLAY" => Some("wayland-0".into()),
|
||||
"DISPLAY" => Some(format!(":0.{screen}")),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let xwayland = pen_needs_xwayland(
|
||||
var,
|
||||
|| true,
|
||||
|display| local_display(display).is_some_and(|(_, screen)| exchange_x11_setup(client, setup, &request, screen)),
|
||||
);
|
||||
|
||||
assert_eq!(xwayland, selects_xwayland);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -48,14 +48,15 @@ fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSy
|
||||
if let Some(frame) = frame {
|
||||
spec = spec.frame(frame);
|
||||
}
|
||||
|
||||
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
|
||||
}
|
||||
|
||||
/// Installs the runtime on the desktop window's context, once, before the first pass, with the window's `frame`
|
||||
/// ([`crate::titlebar::TitleBar::decide`]).
|
||||
/// ([`crate::titlebar::TitleBar::decide`]) and the `backend` the window opened on.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn install(ctx: &egui::Context, frame: Decision) -> Result<(), String> {
|
||||
let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env());
|
||||
pub fn install(ctx: &egui::Context, frame: Decision, backend: craft_host::target::Backend) -> Result<(), String> {
|
||||
let shell = ShellInfo::default().backend(backend);
|
||||
install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows), Some(frame))
|
||||
}
|
||||
|
||||
|
||||
@@ -68,12 +68,12 @@ const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [
|
||||
impl TitleBar {
|
||||
/// Decide who draws the title bar; call once at startup, before the window is created, and
|
||||
/// hand the decision to the window ([`viewport`]) and the runtime (`framework::install`).
|
||||
/// `system` is Settings › Interface › System title bar.
|
||||
pub fn decide(system: bool) -> Decision {
|
||||
/// `system` is Settings › Interface › System title bar; `backend` is the one the window opens on.
|
||||
pub fn decide(system: bool, backend: craft_host::target::Backend) -> Decision {
|
||||
let choice = craft_window::Choice::probe(PREFIX);
|
||||
let wanted = Self::from_choice(choice.frame(), choice.overridden(), system);
|
||||
let pref = if wanted == TitleBar::System { TitleBarPref::System } else { TitleBarPref::Integrated };
|
||||
craft_window::policy::decide_for(PREFIX, craft_host::target::Backend::from_env(), pref)
|
||||
craft_window::policy::decide_for(PREFIX, backend, pref)
|
||||
}
|
||||
|
||||
/// The bar a decided `frame` gives.
|
||||
@@ -93,6 +93,7 @@ impl TitleBar {
|
||||
if overridden.is_none() && system {
|
||||
return TitleBar::System;
|
||||
}
|
||||
|
||||
match frame {
|
||||
Frame::App(layout) => TitleBar::App(layout.clone()),
|
||||
Frame::Desktop if overridden.is_some() => TitleBar::System,
|
||||
@@ -238,15 +239,18 @@ mod tests {
|
||||
#[test]
|
||||
fn the_override_wins_then_the_setting_then_the_platform() {
|
||||
let gnome = Frame::App(Layout::parse("appmenu:close"));
|
||||
// TEXTURECRAFT_TITLEBAR=app / =system, whatever the setting.
|
||||
|
||||
// The environment override wins regardless of the saved setting
|
||||
for system in [false, true] {
|
||||
assert_eq!(TitleBar::from_choice(&gnome, Some(true), system), TitleBar::App(Layout::parse("appmenu:close")));
|
||||
assert_eq!(TitleBar::from_choice(&Frame::Desktop, Some(false), system), TitleBar::System);
|
||||
}
|
||||
// The setting brings the system's frame back.
|
||||
|
||||
// The saved setting selects the system frame without an override
|
||||
assert_eq!(TitleBar::from_choice(&gnome, None, true), TitleBar::System);
|
||||
assert_eq!(TitleBar::from_choice(&Frame::Desktop, None, true), TitleBar::System);
|
||||
// The platform: a compositor that leaves the frame to the app gets the app's.
|
||||
|
||||
// Otherwise the desktop determines who draws the frame
|
||||
assert_eq!(TitleBar::from_choice(&gnome, None, false), TitleBar::App(Layout::parse("appmenu:close")));
|
||||
let desktop = TitleBar::from_choice(&Frame::Desktop, None, false);
|
||||
let expected = if cfg!(windows) {
|
||||
|
||||
@@ -267,6 +267,13 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
- **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux
|
||||
desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same
|
||||
strip, and the system's frame instead with `prefs.system_title_bar` through `ui.set` (for now).
|
||||
- **A pen on a Linux Wayland desktop** can move the cursor and paint as a pointer through Xwayland.
|
||||
At launch, TextureCraft uses Xwayland when it detects a pen, finds the X11 libraries and the
|
||||
local X server accepts setup. Otherwise it uses native Wayland. Set
|
||||
`TEXTURECRAFT_NATIVE_WAYLAND=1` to keep native Wayland. The Flatpak grants X11 access only as a
|
||||
fallback when Wayland is unavailable. Linux pen pressure is tracked separately in
|
||||
[#818](https://github.com/storytold/texturecraft/pull/818) and
|
||||
[#816](https://github.com/storytold/texturecraft/issues/816).
|
||||
- **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed
|
||||
them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out
|
||||
beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar.
|
||||
|
||||
Reference in new issue
Block a user