Merge main into feat/stylus-wheel

This commit is contained in:
dotCooCoo
2026-11-13 16:54:59 -08:00
473 changed files with 36485 additions and 3159 deletions
+11 -3
View File
@@ -418,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
// Save as Template writes every artboard, with the .ai options.
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
} else {
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
// PSD).
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale, ppi);
// An option the format doesn't read comes back in the warnings, so each goes out only
// when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
// formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
// written hidden.
if outline_text {
params["outlineText"] = json!(true);
}
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
params["hiddenLayers"] = json!(true);
}
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
+21
View File
@@ -177,6 +177,27 @@ fn convert_reports_import_warnings() {
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
}
/// A conversion sends each format only the options it reads, so its warnings name an unused
/// option only when the command line gave one: `--outline-text` for a format without it.
#[test]
fn convert_warns_about_an_unused_option_only_when_one_was_given() {
let svg = tmp("unused-option.svg");
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="20" height="10"/></svg>"#).unwrap();
let unused = |out: &Value| -> Vec<String> {
let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}"));
w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
};
for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] {
let path = tmp(&format!("unused-option.{ext}"));
let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{ext}: {out}");
}
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{out}");
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap();
assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}");
}
#[test]
fn convert_writes_legacy_ai_with_its_options() {
// Two artboards, a shown rectangle and a hidden one.
+14 -10
View File
@@ -58,7 +58,10 @@ pollster = "1"
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
# display's color profile for the canvas.
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# The renderer's worker count follows those cores (src/windows_cores.rs).
vectorcraft-render = { workspace = true }
@@ -93,29 +96,30 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a
# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
# RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs).
x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
# so Automatic draws on that one. Both are already in the build through winit.
# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's
# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither
# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build
# through winit.
wayland-client = "0.31"
# Copy and Paste of text through the compositor's core data-device protocol on the window's
# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak
# on a Wayland session). MIT, already in the build through egui-winit.
smithay-clipboard = "0.7"
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
# Waits for the screen color sampler's portal answer and for the portal leaving the bus at the same
# time (src/linux_screen_color/request.rs). Apache-2.0 OR MIT, already in the build through zbus.
futures-lite = "2"
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
# exactly: review the diff before bumping.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
zbus = "=5.19.0"
# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
# through zbus.
futures-lite = "2"
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
# arboard.
+3
View File
@@ -219,6 +219,9 @@ impl App {
self.app.services.dock_monitors = window::dock_monitors(w, zoom);
self.monitors_listed = Some((now, zoom));
}
if let Some(w) = &self.winit_window {
self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
}
self.app.tick(ctx);
if self.pending_maximize {
if let Some(w) = &self.winit_window {
File diff suppressed because it is too large Load Diff
+629
View File
@@ -0,0 +1,629 @@
//! Reads the ICC profile of the display that shows most of the main window, for Preferences ›
//! Performance › Use Monitor Profile for Canvas, and hands it to [`DisplayProfile::report`].
//!
//! - Windows: the display's default profile for its standard color mode. A display with Advanced
//! Color on (HDR or Automatic Color Management) is converted by Windows, and nothing is read.
//! - X11: colord's profile for the RandR output, then the output's `_ICC_PROFILE` property, then
//! the screen's `_ICC_PROFILE` when only one output is active.
//! - Wayland, XWayland included: the compositor gives applications no display profile, and the
//! canvas stays sRGB.
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
//!
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
//! and at once when the window moves to another display.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use vectorcraft_ui_egui::display_profile::{DisplayProfile, Found, Reading};
/// Seconds between two readings of the same display.
const EVERY: f64 = 10.0;
/// Seconds between two checks of which display shows the window.
const LOOK_EVERY: f64 = 1.0;
/// Starts the readings from the main window's frames.
#[derive(Default)]
pub(crate) struct Reader {
/// When the last reading started, and the display it was for.
last: Option<(f64, Option<String>)>,
/// When the window's display was last looked up.
looked: Option<f64>,
/// A reading is running.
busy: Arc<AtomicBool>,
}
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
struct Done(Arc<AtomicBool>);
impl Drop for Done {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
impl Reader {
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return;
}
self.looked = Some(now);
let display = window.current_monitor().and_then(|m| m.name());
if !due(self.last.as_ref(), now, display.as_deref()) {
return;
}
self.last = Some((now, display.clone()));
profile.pending();
self.busy.store(true, Ordering::Release);
let done = Done(self.busy.clone());
let (profile, ctx) = (profile.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
let _done = done;
if profile.report(read(display)) {
ctx.request_repaint();
}
});
if let Err(e) = spawned {
log::warn!("couldn't start reading the display profile: {e}");
}
}
}
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
/// display, [`EVERY`] seconds later, or a clock that went back.
fn due(last: Option<&(f64, Option<String>)>, now: f64, display: Option<&str>) -> bool {
last.is_none_or(|(at, shown)| shown.as_deref() != display || !(*at..at + EVERY).contains(&now))
}
#[cfg(windows)]
fn read(display: Option<String>) -> Reading {
let found = win::read(display.as_deref());
Reading { display, found }
}
#[cfg(target_os = "linux")]
fn read(display: Option<String>) -> Reading {
let found = if wayland_session(|k| std::env::var_os(k)) {
Found::NoProfile("a Wayland session doesn't give applications the display's profile".into())
} else {
x11::read(display.as_deref())
};
Reading { display, found }
}
#[cfg(all(target_os = "macos", feature = "wgpu"))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::System("macOS converts the window to the display's profile".into()) }
}
#[cfg(not(any(windows, target_os = "linux", all(target_os = "macos", feature = "wgpu"))))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::NoProfile("this build doesn't read display profiles on this system".into()) }
}
/// Whether the app runs in a Wayland session, read from the environment `var` gives. XWayland
/// windows count: the variables stay set for them.
#[cfg(any(target_os = "linux", test))]
fn wayland_session(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
["WAYLAND_DISPLAY", "WAYLAND_SOCKET"].iter().any(|k| var(k).is_some_and(|v| !v.is_empty()))
}
/// The X11 reading from colord's answer `colord` (the profile file it names, read) and the X11
/// properties `properties`: colord's profile when its file can be read, otherwise the
/// properties' profile. When neither has one, the reason colord gave is kept.
#[cfg(any(target_os = "linux", test))]
fn x11_choice(colord: Option<Result<Option<Found>, String>>, properties: impl FnOnce() -> Result<Option<Found>, String>) -> Found {
let colord_reason = match colord {
Some(Ok(Some(found @ Found::Profile { .. }))) => return found,
Some(Ok(Some(Found::NoProfile(e) | Found::System(e)))) | Some(Err(e)) => Some(e),
Some(Ok(None)) | None => None,
};
match properties() {
Ok(Some(found)) => found,
Ok(None) => Found::NoProfile(match colord_reason {
Some(e) => format!("no profile is set for this display ({e})"),
None => "no profile is set for this display".into(),
}),
Err(e) => Found::NoProfile(e),
}
}
/// `found` when it is not a profile or the profile can be used, otherwise why it can't, so the
/// next source is tried.
#[cfg(any(target_os = "linux", test))]
fn usable(found: Found) -> Found {
match found {
Found::Profile { icc, from } => match vectorcraft_ui_egui::display_profile::check_profile(&icc) {
Ok(()) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(format!("{from}: {e}")),
},
other => other,
}
}
/// The ICC file at `path`, refused before it is read when it is larger than [`MAX_PROFILE_BYTES`].
///
/// [`MAX_PROFILE_BYTES`]: vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES
#[cfg(any(windows, target_os = "linux", test))]
fn read_icc(path: &std::path::Path) -> Result<Vec<u8>, String> {
use std::io::Read as _;
let max = vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES;
let too_large = || format!("{} is larger than {} MiB", path.display(), max >> 20);
let file = std::fs::File::open(path).map_err(|e| format!("couldn't open {}: {e}", path.display()))?;
let len = file.metadata().map_err(|e| format!("couldn't read {}: {e}", path.display()))?.len();
if len > max as u64 {
return Err(too_large());
}
let mut bytes = Vec::with_capacity(len as usize);
file.take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("couldn't read {}: {e}", path.display()))?;
if bytes.len() > max { Err(too_large()) } else { Ok(bytes) }
}
/// The file a profile `name` stands for: `name` itself when it is a path, otherwise the file of
/// that name in the system's color folder `dir`.
#[cfg(any(windows, test))]
fn profile_path(dir: Option<&std::path::Path>, name: &str) -> std::path::PathBuf {
match dir {
Some(dir) if !name.contains(['\\', '/']) => dir.join(name),
_ => std::path::PathBuf::from(name),
}
}
/// `path`'s profile, or why there is none.
#[cfg(any(windows, target_os = "linux"))]
fn profile_file(path: &std::path::Path) -> Found {
let from = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
match read_icc(path) {
Ok(icc) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(e),
}
}
#[cfg(windows)]
#[allow(unsafe_code)]
mod win {
use std::path::PathBuf;
use std::sync::OnceLock;
use vectorcraft_ui_egui::display_profile::Found;
use windows::Win32::Devices::Display::{
DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig,
};
use windows::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS, HLOCAL, LUID, LocalFree};
use windows::Win32::Graphics::Gdi::{CreateDCW, DeleteDC};
use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
use windows::Win32::UI::ColorSystem::{
CPST_STANDARD_DISPLAY_COLOR_MODE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER,
};
use windows::core::{HRESULT, PCWSTR, PWSTR, s, w};
/// `ColorProfileGetDisplayDefault` and `ColorProfileGetDisplayUserScope` (mscms.dll), which
/// older Windows versions don't have.
type GetDefault = unsafe extern "system" fn(i32, LUID, u32, i32, i32, *mut PWSTR) -> HRESULT;
type GetScope = unsafe extern "system" fn(LUID, u32, *mut i32) -> HRESULT;
/// The display path that shows a GDI device.
struct Path {
source: u32,
target_adapter: LUID,
target: u32,
}
pub(super) fn read(display: Option<&str>) -> Found {
let Some(device) = display else { return Found::NoProfile("Windows didn't name the window's display".into()) };
let path = match find_path(device) {
Ok(path) => path,
Err(e) => return Found::NoProfile(e),
};
if path.as_ref().is_some_and(advanced_color) {
return Found::System("Windows manages this display's colors (Advanced Color)".into());
}
let name = match path.as_ref().and_then(default_profile) {
Some(Ok(name)) => name,
Some(Err(e)) => return Found::NoProfile(e),
// Older Windows, or a display without an active path: GDI's profile for the device.
None => match icm_profile(device) {
Ok(name) => name,
Err(e) => return Found::NoProfile(e),
},
};
match name {
Some(name) => super::profile_file(&super::profile_path(color_directory().as_deref(), &name)),
None => Found::NoProfile("no color profile is set for this display".into()),
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
fn until_nul(w: &[u16]) -> String {
String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())])
}
/// The active display paths.
fn paths() -> Result<Vec<DISPLAYCONFIG_PATH_INFO>, String> {
for _ in 0..4 {
let (mut paths_len, mut modes_len) = (0u32, 0u32);
// SAFETY: both pointers are to live `u32`s.
let e = unsafe { GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, &mut modes_len) };
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); paths_len as usize];
let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); modes_len as usize];
// SAFETY: the arrays hold as many elements as the lengths passed with them.
let e =
unsafe { QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, paths.as_mut_ptr(), &mut modes_len, modes.as_mut_ptr(), None) };
if e == ERROR_INSUFFICIENT_BUFFER {
// The displays changed between the two calls.
continue;
}
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
paths.truncate(paths_len as usize);
return Ok(paths);
}
Err("the displays kept changing while Windows listed them".into())
}
/// The path whose source is the GDI device `device` (`\\.\DISPLAY1`), if one is active.
fn find_path(device: &str) -> Result<Option<Path>, String> {
for p in paths()? {
let mut name = DISPLAYCONFIG_SOURCE_DEVICE_NAME {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
adapterId: p.sourceInfo.adapterId,
id: p.sourceInfo.id,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_SOURCE_DEVICE_NAME` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut name.header) } == 0 && until_nul(&name.viewGdiDeviceName).eq_ignore_ascii_case(device) {
return Ok(Some(Path { source: p.sourceInfo.id, target_adapter: p.targetInfo.adapterId, target: p.targetInfo.id }));
}
}
Ok(None)
}
/// Whether Windows color-manages the path's display itself: Advanced Color is on (HDR), or
/// wide color is enforced (Automatic Color Management on an SDR display).
fn advanced_color(path: &Path) -> bool {
let mut info = DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO,
size: size_of::<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>() as u32,
adapterId: path.target_adapter,
id: path.target,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut info.header) } != 0 {
return false;
}
// SAFETY: every bit pattern is a valid `u32`.
let bits = unsafe { info.Anonymous.value };
// advancedColorEnabled is bit 1 and wideColorEnforced bit 2.
bits & 0b110 != 0
}
fn api() -> Option<(GetDefault, GetScope)> {
static API: OnceLock<Option<(GetDefault, GetScope)>> = OnceLock::new();
*API.get_or_init(|| {
// SAFETY: mscms.dll is loaded from System32 only, and stays loaded for the process.
let module = unsafe { LoadLibraryExW(w!("mscms.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?;
// SAFETY: the names are NUL-terminated, and the module is loaded.
let (default, scope) = unsafe {
(GetProcAddress(module, s!("ColorProfileGetDisplayDefault"))?, GetProcAddress(module, s!("ColorProfileGetDisplayUserScope"))?)
};
// SAFETY: both exports have these signatures (icm.h).
unsafe {
Some((
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetDefault>(default),
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetScope>(scope),
))
}
})
}
/// The display's default profile name for its standard color mode, `None` without the API.
fn default_profile(path: &Path) -> Option<Result<Option<String>, String>> {
let (get_default, get_scope) = api()?;
let mut scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
// SAFETY: `scope` is a live `i32`.
if unsafe { get_scope(path.target_adapter, path.source, &mut scope) }.is_err() {
scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
}
let mut name = PWSTR::null();
// SAFETY: `name` is a live pointer the function fills with a string it allocates.
let hr = unsafe { get_default(scope, path.target_adapter, path.source, CPT_ICC.0, CPST_STANDARD_DISPLAY_COLOR_MODE.0, &mut name) };
if hr.is_err() {
return Some(Err(format!("Windows couldn't give the display's profile (error {:#010x})", hr.0)));
}
if name.is_null() {
return Some(Ok(None));
}
// SAFETY: `name` is a NUL-terminated string from the call above, freed once with LocalFree.
let text = unsafe { name.to_string() };
// SAFETY: as above.
let _ = unsafe { LocalFree(Some(HLOCAL(name.0.cast()))) };
Some(text.map(|t| Some(t).filter(|t| !t.is_empty())).map_err(|e| format!("the display's profile name isn't readable: {e}")))
}
/// GDI's profile file for the display device `device`.
fn icm_profile(device: &str) -> Result<Option<String>, String> {
let device = wide(device);
// SAFETY: both strings are NUL-terminated and outlive the call.
let dc = unsafe { CreateDCW(w!("DISPLAY"), PCWSTR(device.as_ptr()), PCWSTR::null(), None) };
if dc.is_invalid() {
return Err("Windows couldn't open the display".into());
}
let mut len = 0u32;
// SAFETY: a null buffer asks for the length only.
let _ = unsafe { GetICMProfileW(dc, &mut len, None) };
let mut buf = vec![0u16; len.clamp(1, 32 * 1024) as usize];
len = buf.len() as u32;
// SAFETY: `buf` holds `len` characters.
let ok = unsafe { GetICMProfileW(dc, &mut len, Some(PWSTR(buf.as_mut_ptr()))) }.as_bool();
// SAFETY: `dc` came from CreateDCW above.
let _ = unsafe { DeleteDC(dc) };
Ok(ok.then(|| until_nul(&buf)).filter(|n| !n.is_empty()))
}
/// The system's color folder (`…\spool\drivers\color`).
fn color_directory() -> Option<PathBuf> {
let mut bytes = 0u32;
// SAFETY: a null buffer asks for the size only, in bytes.
let _ = unsafe { GetColorDirectoryW(PCWSTR::null(), None, &mut bytes) };
let mut buf = vec![0u16; (bytes as usize / 2).clamp(1, 32 * 1024)];
bytes = (buf.len() * 2) as u32;
// SAFETY: `buf` holds `bytes` bytes.
unsafe { GetColorDirectoryW(PCWSTR::null(), Some(PWSTR(buf.as_mut_ptr())), &mut bytes) }.as_bool().then(|| PathBuf::from(until_nul(&buf)))
}
#[cfg(test)]
mod tests {
use windows::Win32::Graphics::Gdi::{DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DISPLAY_DEVICEW, EnumDisplayDevicesW};
use super::*;
/// The GDI names (`\\.\DISPLAY1`) of the displays attached to the desktop.
fn attached_displays() -> Vec<String> {
let mut names = Vec::new();
for i in 0.. {
let mut device = DISPLAY_DEVICEW { cb: size_of::<DISPLAY_DEVICEW>() as u32, ..Default::default() };
// SAFETY: `device` is a live `DISPLAY_DEVICEW` with `cb` set to its size.
if !unsafe { EnumDisplayDevicesW(PCWSTR::null(), i, &mut device, 0) }.as_bool() {
break;
}
if device.StateFlags.contains(DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) {
names.push(until_nul(&device.DeviceName));
}
}
names
}
#[test]
fn windows_reads_each_attached_display_and_refuses_an_unknown_one() {
assert_eq!(read(None), Found::NoProfile("Windows didn't name the window's display".into()));
assert!(color_directory().is_none_or(|dir| dir.is_absolute()));
match find_path(r"\\.\DISPLAY999") {
Ok(path) => {
assert!(path.is_none());
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile("Windows couldn't open the display".into()));
}
// A session without displays (a service): the reading gives Windows' error.
Err(e) => {
eprintln!("the displays couldn't be listed: {e}");
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile(e));
return;
}
}
for name in attached_displays() {
// A display without an active path is read through GDI (`icm_profile`).
let path = find_path(&name).unwrap();
// winit names the display in GDI's spelling; the match ignores letter case.
let lower = find_path(&name.to_lowercase()).unwrap();
assert_eq!(lower.map(|p| (p.source, p.target)), path.as_ref().map(|p| (p.source, p.target)), "{name} in lowercase");
match read(Some(&name)) {
Found::Profile { icc, from } => {
eprintln!("{name}: profile {from}, {} bytes", icc.len());
assert!(!icc.is_empty() && !from.is_empty());
assert!(!path.as_ref().is_some_and(advanced_color));
}
Found::System(e) => {
eprintln!("{name}: system, {e}");
assert!(path.as_ref().is_some_and(advanced_color));
}
Found::NoProfile(e) => {
eprintln!("{name}: no profile, {e}");
assert!(!e.is_empty());
}
}
}
}
}
}
#[cfg(target_os = "linux")]
mod x11 {
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use vectorcraft_ui_egui::display_profile::{Found, MAX_PROFILE_BYTES};
use x11rb::connection::Connection as _;
use x11rb::protocol::randr;
use x11rb::protocol::xproto::{self, AtomEnum};
use zbus::blocking::{connection::Builder, proxy::Proxy};
use zbus::zvariant::OwnedObjectPath;
const COLORD: &str = "org.freedesktop.ColorManager";
const COLORD_ROOT: &str = "/org/freedesktop/ColorManager";
const COLORD_MANAGER: &str = "org.freedesktop.ColorManager";
const COLORD_DEVICE: &str = "org.freedesktop.ColorManager.Device";
const COLORD_PROFILE: &str = "org.freedesktop.ColorManager.Profile";
pub(super) fn read(output: Option<&str>) -> Found {
let colord = output.map(|o| colord_profile(o).map(|path| path.map(|path| super::usable(super::profile_file(Path::new(&path))))));
super::x11_choice(colord, || properties(output))
}
/// The file colord assigns the RandR output `output`.
fn colord_profile(output: &str) -> Result<Option<String>, String> {
let connection = Builder::system()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?
.method_timeout(Duration::from_secs(2))
.build()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?;
let manager = Proxy::new(&connection, COLORD, COLORD_ROOT, COLORD_MANAGER).map_err(|e| format!("couldn't reach colord: {e}"))?;
let devices: Vec<OwnedObjectPath> =
manager.call("GetDevicesByKind", &("display",)).map_err(|e| format!("colord couldn't list the displays: {e}"))?;
for path in devices {
let Ok(device) = Proxy::new(&connection, COLORD, &path, COLORD_DEVICE) else { continue };
let Ok(metadata) = device.get_property::<HashMap<String, String>>("Metadata") else { continue };
if metadata.get("XRANDR_name").map(String::as_str) != Some(output) {
continue;
}
// `*` asks for the device's default profile.
let Ok(profile_path) = device.call::<_, _, OwnedObjectPath>("GetProfileForQualifiers", &(vec!["*"],)) else { return Ok(None) };
let profile =
Proxy::new(&connection, COLORD, &profile_path, COLORD_PROFILE).map_err(|e| format!("couldn't reach colord's profile: {e}"))?;
return Ok(profile.get_property::<String>("Filename").ok().filter(|f| !f.is_empty()));
}
Ok(None)
}
/// The `_ICC_PROFILE` property of the RandR output `output`, or of the screen when only one
/// output is active.
fn properties(output: Option<&str>) -> Result<Option<Found>, String> {
let (conn, screen) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
let root = conn.setup().roots.get(screen).ok_or_else(|| "the X11 display has no screen".to_string())?.root;
let atom = xproto::intern_atom(&conn, true, b"_ICC_PROFILE")
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.reply()
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.atom;
if atom == 0 {
return Ok(None);
}
let resources = randr::get_screen_resources_current(&conn, root)
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?
.reply()
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?;
let (mut active, mut shown) = (0usize, None);
for o in resources.outputs {
let Ok(Ok(info)) = randr::get_output_info(&conn, o, resources.config_timestamp).map(|c| c.reply()) else { continue };
if info.connection != randr::Connection::CONNECTED || info.crtc == 0 {
continue;
}
active += 1;
if output.is_some_and(|name| info.name == name.as_bytes()) {
shown = Some(o);
}
}
let longs = (MAX_PROFILE_BYTES / 4) as u32;
let too_large = || Found::NoProfile(format!("the display's profile is larger than {} MiB", MAX_PROFILE_BYTES >> 20));
if let Some(o) = shown
&& let Ok(Ok(p)) = randr::get_output_property(&conn, o, atom, AtomEnum::ANY, 0, longs, false, false).map(|c| c.reply())
&& !p.data.is_empty()
{
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
return Ok(Some(Found::Profile { icc: p.data, from: "the X11 output's _ICC_PROFILE".into() }));
}
if active != 1 {
return Ok(None);
}
let Ok(Ok(p)) = xproto::get_property(&conn, false, root, atom, AtomEnum::ANY, 0, longs).map(|c| c.reply()) else { return Ok(None) };
if p.value.is_empty() {
return Ok(None);
}
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
Ok(Some(Found::Profile { icc: p.value, from: "the X11 screen's _ICC_PROFILE".into() }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_is_due_first_after_ten_seconds_and_when_the_window_changes_display() {
assert!(due(None, 0.0, None));
let last = (100.0, Some("DP-1".to_string()));
assert!(!due(Some(&last), 100.0, Some("DP-1")));
assert!(!due(Some(&last), 109.9, Some("DP-1")));
assert!(due(Some(&last), 110.0, Some("DP-1")));
assert!(due(Some(&last), 101.0, Some("HDMI-1")));
assert!(due(Some(&last), 101.0, None));
// A clock that went back.
assert!(due(Some(&last), 50.0, Some("DP-1")));
}
#[test]
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| std::ffi::OsString::from(v))
};
assert!(wayland_session(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")])));
assert!(wayland_session(env(&[("WAYLAND_SOCKET", "5")])));
assert!(!wayland_session(env(&[("DISPLAY", ":0")])));
assert!(!wayland_session(env(&[("WAYLAND_DISPLAY", ""), ("DISPLAY", ":0")])));
}
#[test]
fn profile_files_larger_than_the_limit_are_refused_before_they_are_read() {
let dir = tempfile::tempdir().unwrap();
let small = dir.path().join("small.icc");
std::fs::write(&small, [1u8, 2, 3]).unwrap();
assert_eq!(read_icc(&small).unwrap(), [1, 2, 3]);
let big = dir.path().join("big.icc");
let f = std::fs::File::create(&big).unwrap();
f.set_len(vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES as u64 + 1).unwrap();
assert!(read_icc(&big).unwrap_err().contains("larger than 1 MiB"));
assert!(read_icc(&dir.path().join("missing.icc")).unwrap_err().starts_with("couldn't open"));
}
#[test]
fn x11_takes_the_output_property_when_colord_s_file_cannot_be_read() {
let icc = |b: u8| Found::Profile { icc: vec![b], from: "test".into() };
let property = || Ok(Some(icc(2)));
// colord's profile, read: the property is not asked for.
assert_eq!(x11_choice(Some(Ok(Some(icc(1)))), || panic!("not asked")), icc(1));
// colord names a file that can't be read, or has no profile, or isn't running.
assert_eq!(x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), property), icc(2));
assert_eq!(x11_choice(Some(Ok(None)), property), icc(2));
assert_eq!(x11_choice(Some(Err("no colord".into())), property), icc(2));
assert_eq!(x11_choice(None, property), icc(2));
// Neither has a profile: colord's reason is kept.
assert_eq!(
x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), || Ok(None)),
Found::NoProfile("no profile is set for this display (couldn't open a.icc)".into())
);
assert_eq!(x11_choice(None, || Ok(None)), Found::NoProfile("no profile is set for this display".into()));
assert_eq!(x11_choice(None, || Err("no X11".into())), Found::NoProfile("no X11".into()));
// colord's file holds no usable profile: the property is used.
let broken = usable(Found::Profile { icc: vec![1, 2, 3], from: "a.icc".into() });
assert_eq!(broken, Found::NoProfile("a.icc: the file is not an ICC profile".into()));
assert_eq!(x11_choice(Some(Ok(Some(broken))), property), icc(2));
assert_eq!(usable(Found::NoProfile("none".into())), Found::NoProfile("none".into()));
}
#[test]
fn a_profile_name_is_found_in_the_color_folder_and_a_path_is_kept() {
let dir = std::path::Path::new("C:/Windows/System32/spool/drivers/color");
assert_eq!(profile_path(Some(dir), "Display.icm"), dir.join("Display.icm"));
assert_eq!(profile_path(Some(dir), "D:\\profiles\\Display.icm"), std::path::PathBuf::from("D:\\profiles\\Display.icm"));
assert_eq!(profile_path(None, "Display.icm"), std::path::PathBuf::from("Display.icm"));
}
}
@@ -4,7 +4,6 @@
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
mod portal;
mod request;
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
@@ -61,9 +61,9 @@ pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<
/// after it has no bound, and ends when the portal answers or leaves the bus.
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
let token = super::request::token("vectorcraft_color").map_err(Failure::Failed)?;
let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?;
// Made before the call: a portal can send its answer before the call returns.
let replies = super::request::Responses::new(conn).map_err(Failure::Failed)?;
let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?;
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
.map_err(|e| Failure::Failed(e.to_string()))?;
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
@@ -106,6 +106,7 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f3
#[cfg(test)]
mod tests {
use super::*;
use crate::portal_request::test_bus::private_bus;
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
@@ -186,35 +187,6 @@ mod tests {
}
}
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
fn client(address: &str) -> Connection {
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
@@ -1,127 +0,0 @@
//! The answer to the color sampler's XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>).
//! The wait ends with the request's `Response`, or with an error when the portal leaves the bus
//! first.
use std::io::Read as _;
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
pub(super) fn token(prefix: &str) -> Result<String, String> {
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(super) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(super) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes.
pub(super) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Reply(replies.next().await) }, async { Event::Owner(owners.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
let header = reply.header();
if header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
{
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
}
+9 -2
View File
@@ -28,6 +28,7 @@ mod clipboard;
mod compositor_gpu;
mod control_server;
mod cursor_theme;
mod display_profile;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
@@ -53,6 +54,8 @@ mod mac_tablet;
mod mac_window;
#[cfg(target_os = "macos")]
mod open_documents;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
mod portal_request;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
mod portal_save;
mod prefs_dir;
@@ -104,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
#[cfg(windows)]
use titlebar::set_taskbar_icon;
#[cfg(all(test, feature = "wgpu"))]
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
@@ -129,6 +132,8 @@ struct App {
held_files: Vec<String>,
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
monitors_listed: Option<(f64, f32)>,
/// Reads the profile of the display that shows the main window, for the canvas.
display_profile: display_profile::Reader,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
}
@@ -362,7 +367,7 @@ fn main() -> std::process::ExitCode {
};
#[cfg(feature = "wgpu")]
let crash = left_out.crash.clone();
let custom_titlebar = custom_titlebar(saved.as_ref());
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
@@ -588,6 +593,7 @@ fn main() -> std::process::ExitCode {
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.caption_layout = caption_layout;
app.desktop_frame = !custom_titlebar;
if let Some(port) = control_port {
let rx = control_server::start(port, cc.egui_ctx.clone());
@@ -632,6 +638,7 @@ fn main() -> std::process::ExitCode {
maximize_tries: 8,
held_files,
monitors_listed: None,
display_profile: Default::default(),
frame_start: None,
}))
}),
+231
View File
@@ -0,0 +1,231 @@
//! Linux and the BSDs: the answer to an XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>),
//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler
//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the
//! portal leaves the bus first.
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
#[cfg(target_os = "linux")]
pub(crate) fn token(prefix: &str) -> Result<String, String> {
use std::io::Read as _;
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(crate) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(crate) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes. A
/// `Response` the portal sent before it left is still the answer.
pub(crate) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let answers = |reply: &zbus::Message| {
let header = reply.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
};
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
if answers(&reply) {
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
// zbus puts each message in every matching stream before it reads the
// next one, so a `Response` that came before the bus's report is
// already queued: it is still the answer.
while let Some(Some(reply)) = future::poll_once(replies.next()).await {
if let Ok(reply) = reply
&& answers(&reply)
{
return Ok(reply);
}
}
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
/// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent
/// before it left is still the answer; without one the wait ends with an error.
#[test]
fn a_queued_answer_wins_over_the_portal_leaving() {
use std::collections::HashMap;
use zbus::blocking::connection::Builder;
use zbus::zvariant::OwnedValue;
for answered in [true, false] {
let Some((_daemon, address)) = test_bus::private_bus() else { return };
let address = address.as_str();
let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap();
let unique = portal.unique_name().unwrap().to_string();
let client = Builder::address(address).unwrap().build().unwrap();
let responses = Responses::new(&client).unwrap();
// zbus puts each message in every matching stream before it reads the next one
// (`src/connection/socket_reader.rs`), so once this stream has the bus's report,
// `responses` holds the `Response` sent before it.
let gone_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.unwrap()
.member("NameOwnerChanged")
.unwrap()
.arg(0, DESKTOP)
.unwrap()
.build();
let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap();
let path = "/org/freedesktop/portal/desktop/request/test/t1";
if answered {
let results = HashMap::<String, OwnedValue>::new();
portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap();
}
portal.close().unwrap();
// On a thread of its own, so a report that never comes fails the test instead of
// hanging it.
let (seen, report) = std::sync::mpsc::channel();
let left = unique.clone();
std::thread::spawn(move || {
let mut gone = gone;
let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false))));
});
assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone");
// The call's reply as `wait` reads it: the request path, from the portal's connection.
let call = zbus::Message::signal("/", "org.example.Test", "Reply")
.unwrap()
.sender(unique.as_str())
.unwrap()
.build(&OwnedObjectPath::try_from(path).unwrap())
.unwrap();
let waited = responses.wait(&call);
assert_eq!(waited.is_ok(), answered, "{waited:?}");
}
}
}
/// The private session bus that the D-Bus tests of the portal requests run on.
#[cfg(test)]
pub(crate) mod test_bus {
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
pub(crate) fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
pub(crate) struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
}
+56 -45
View File
@@ -8,6 +8,7 @@
//! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension.
//! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its
//! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call.
//! rfd also shows the dialog when the portal leaves the bus before it answers.
//!
//! The dialog's parent is the window: `x11:<window id>` on X11, and on Wayland (Linux) a handle
//! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`).
@@ -183,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option<V
fn save_file(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result<Option<Saved>, String> {
use std::sync::atomic::{AtomicU32, Ordering};
use zbus::blocking::{MessageIterator, Proxy};
use zbus::zvariant::OwnedObjectPath;
use zbus::blocking::Proxy;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
const REQUEST: &str = "org.freedesktop.portal.Request";
static NEXT: AtomicU32 = AtomicU32::new(0);
let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
// Listen before asking, on every request path: a portal older than version 0.9 ignores
// `handle_token` and answers on the request path it returns, and its answer can come before
// the call's reply. The stream keeps every `Response` from the time it is made.
let rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface(REQUEST))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?;
// Made before the call: a portal can send its answer before the call returns, and a portal
// that leaves the bus while its dialog is open ends the wait.
let responses = crate::portal_request::Responses::new(conn)?;
let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?;
// The title is empty, as rfd sends it for a save.
let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?;
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
// The answer is the `Response` on the path returned, from the connection that returned it.
let portal = call.header().sender().map(|s| s.as_str().to_string());
let reply = responses
.filter_map(Result::ok)
.find(|m| {
let header = m.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref()
})
.ok_or("the save dialog closed without an answer")?;
let reply = responses.wait(&call)?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
answer(code, &results)
}
@@ -495,26 +477,22 @@ mod tests {
Old,
/// As `Old`, with the `Response` sent before the reply that names its path.
OldEarly,
/// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a
/// portal that exits while its dialog is open.
Exits,
/// Leaves the bus right after its reply, without a `Response`.
ExitsAtOnce,
/// Sends its `Response` right after its reply, then leaves the bus.
AnswersAndExits,
}
/// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser`
/// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it.
/// `None` when there is no `dbus-daemon` to run.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
use std::io::BufRead as _;
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> {
use zbus::zvariant::OwnedObjectPath;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let mut daemon = daemon.ok()?;
let mut address = String::new();
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
let address = address.trim().to_string();
let (daemon, address) = crate::portal_request::test_bus::private_bus()?;
let server =
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
let seen = Seen::default();
@@ -539,8 +517,8 @@ mod tests {
});
let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break };
let token = match portal {
Portal::Current => text("handle_token").unwrap_or_default(),
Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()),
Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(),
};
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break };
@@ -558,14 +536,22 @@ mod tests {
if server.reply(&header, &handle).is_err() {
break;
}
if portal == Portal::Old {
if matches!(portal, Portal::Old | Portal::Exits) {
// As a person answers the dialog: after the caller has the path returned.
std::thread::sleep(std::time::Duration::from_millis(300));
}
if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) {
break;
}
if portal != Portal::OldEarly && respond().is_err() {
break;
}
if portal == Portal::AnswersAndExits {
break;
}
}
// The portal leaves the bus: the bus sends `NameOwnerChanged` for its name.
let _ = server.close();
});
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
Some((client, seen, daemon))
@@ -589,7 +575,7 @@ mod tests {
#[test]
fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() {
let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)];
let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else {
let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else {
eprintln!("no dbus-daemon: skipped");
return;
};
@@ -599,7 +585,6 @@ mod tests {
assert_eq!(save_within(&conn, &request), Ok(None));
let seen = seen.lock().map(|s| s.clone()).unwrap_or_default();
assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone()))));
let _ = daemon.kill();
}
/// A portal older than 0.9 answers on the request path it returns, and the answer is awaited
@@ -607,13 +592,12 @@ mod tests {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn the_answer_is_awaited_on_the_path_the_portal_returns() {
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
let _ = daemon.kill();
}
/// A portal older than 0.9 can answer before its reply names the request path: the answer is
@@ -622,14 +606,41 @@ mod tests {
#[test]
fn an_answer_that_comes_before_the_path_is_kept() {
let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)];
let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else {
let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
assert_eq!(save_within(&conn, &request), Ok(None));
let _ = daemon.kill();
}
/// A portal that leaves the bus after its reply without answering, while its dialog is open or
/// at once, ends the wait with an error, and rfd shows the dialog.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_portal_that_exits_during_the_dialog_ends_the_wait() {
for portal in [Portal::Exits, Portal::ExitsAtOnce] {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string()));
}
}
/// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer
/// or the bus's report comes first depends on timing here; `portal_request`'s
/// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn an_answer_sent_just_before_the_portal_exits_is_kept() {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
}
/// The labels go to the dialog in the interface's language, which is how the answer is matched.
+33 -6
View File
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
}
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default buttons, and the desktop frame stays
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
#[test]
fn the_start_frame_applies_the_app_title_bar_preference() {
use craft_window::{Button, Frame, Layout};
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
}
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let custom = super::custom_titlebar(saved);
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
@@ -312,7 +339,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None),
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
+36 -8
View File
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
}
/// The frame this start uses, before the System Title Bar preference is applied
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
/// layout, since `custom_titlebar_from` reads only which frame it is.
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
let probed_app = matches!(probed, craft_window::Frame::App(_));
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
(true, frame @ craft_window::Frame::App(_)) => frame,
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
(true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame,
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let caption = |b: &craft_window::Button| match b {
craft_window::Button::Minimize => Caption::Minimize,
craft_window::Button::Maximize => Caption::Maximize,
craft_window::Button::Close => Caption::Close,
};
match frame.layout() {
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
None => CaptionLayout::default(),
}
}
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
/// [`custom_titlebar_from`]).
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
}
/// The `craft-window` probe's answer for this process (its override variable is
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
fn probed_choice() -> &'static craft_window::Choice {
@@ -131,7 +158,8 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
CUSTOM_TITLEBAR && !opted_into_system
}
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// Whether this start draws its own title bar, and where its caption buttons go
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) {
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
@@ -160,7 +188,7 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
custom_titlebar_from(&frame, opted_into_system)
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {