repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/src/lib.rs
druid-derive/src/lib.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! derive macros for Druid. #![deny(clippy::trivially_copy_pass_by_ref)] #![doc( html_logo_url = "https://raw.githubusercontent.com/linebender/druid/screenshots/images/doc_logo.png" )] extern crate proc_macro; mod attr; mod data; mod lens; use proc_macro::TokenStream; use syn::parse_macro_input; /// Generates implementations of the `Data` trait. /// /// This macro supports a `data` field attribute with the following arguments: /// /// - `#[data(ignore)]` makes the generated `Data::same` function skip comparing this field. /// - `#[data(same_fn="foo")]` uses the function `foo` for comparing this field. `foo` should /// be the name of a function with signature `fn(&T, &T) -> bool`, where `T` is the type of /// the field. /// - `#[data(eq)]` is shorthand for `#[data(same_fn = "PartialEq::eq")]` /// /// # Example /// /// ```rust /// use druid_derive::Data; /// /// #[derive(Clone, Data)] /// struct State { /// number: f64, /// // `Vec` doesn't implement `Data`, so we need to either ignore it or supply a `same_fn`. /// #[data(eq)] /// // same as #[data(same_fn="PartialEq::eq")] /// indices: Vec<usize>, /// // This is just some sort of cache; it isn't important for sameness comparison. /// #[data(ignore)] /// cached_indices: Vec<usize>, /// } /// ``` #[proc_macro_derive(Data, attributes(data))] pub fn derive_data(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); data::derive_data_impl(input) .unwrap_or_else(|err| err.to_compile_error()) .into() } /// Generates lenses to access the fields of a struct. /// /// An associated constant is defined on the struct for each field, /// having the same name as the field. /// /// This macro supports a `lens` field attribute with the following arguments: /// /// - `#[lens(ignore)]` skips creating a lens for one field. /// - `#[lens(name="foo")]` gives the lens the specified name (instead of the default, which is to /// create a lens with the same name as the field). /// /// # Example /// /// ```rust /// use druid_derive::Lens; /// /// #[derive(Lens)] /// struct State { /// // The Lens derive will create a `State::text` constant implementing /// // `druid::Lens<State, String>` /// text: String, /// // The Lens derive will create a `State::lens_number` constant implementing /// // `druid::Lens<State, f64>` /// #[lens(name = "lens_number")] /// number: f64, /// // The Lens derive won't create anything for this field. /// #[lens(ignore)] /// blah: f64, /// } /// ``` #[proc_macro_derive(Lens, attributes(lens))] pub fn derive_lens(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); lens::derive_lens_impl(input) .unwrap_or_else(|err| err.to_compile_error()) .into() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/src/data.rs
druid-derive/src/data.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The implementation for #[derive(Data)] use crate::attr::{DataAttr, Field, FieldKind, Fields}; use quote::{quote, quote_spanned}; use syn::{spanned::Spanned, Data, DataEnum, DataStruct}; pub(crate) fn derive_data_impl( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { match &input.data { Data::Struct(s) => derive_struct(&input, s), Data::Enum(e) => derive_enum(&input, e), Data::Union(u) => Err(syn::Error::new( u.union_token.span(), "Data implementations cannot be derived from unions", )), } } fn derive_struct( input: &syn::DeriveInput, s: &DataStruct, ) -> Result<proc_macro2::TokenStream, syn::Error> { let ident = &input.ident; let impl_generics = generics_bounds(&input.generics); let (_, ty_generics, where_clause) = &input.generics.split_for_impl(); let fields = Fields::<DataAttr>::parse_ast(&s.fields)?; let diff = if fields.len() > 0 { let same_fns = fields .iter() .filter(|f| f.attrs != DataAttr::Ignore) .map(Field::same_fn_path_tokens); let fields = fields .iter() .filter(|f| f.attrs != DataAttr::Ignore) .map(Field::ident_tokens); quote!( #( #same_fns(&self.#fields, &other.#fields) )&&* ) } else { quote!(true) }; let res = quote! { impl<#impl_generics> ::druid::Data for #ident #ty_generics #where_clause { fn same(&self, other: &Self) -> bool { #diff } } }; Ok(res) } fn ident_from_str(s: &str) -> proc_macro2::Ident { proc_macro2::Ident::new(s, proc_macro2::Span::call_site()) } fn is_c_style_enum(s: &DataEnum) -> bool { s.variants.iter().all(|variant| match &variant.fields { syn::Fields::Named(fs) => fs.named.is_empty(), syn::Fields::Unnamed(fs) => fs.unnamed.is_empty(), syn::Fields::Unit => true, }) } fn derive_enum( input: &syn::DeriveInput, s: &DataEnum, ) -> Result<proc_macro2::TokenStream, syn::Error> { let ident = &input.ident; let impl_generics = generics_bounds(&input.generics); let (_, ty_generics, where_clause) = &input.generics.split_for_impl(); if is_c_style_enum(s) { let res = quote! { impl<#impl_generics> ::druid::Data for #ident #ty_generics #where_clause { fn same(&self, other: &Self) -> bool { self == other } } }; return Ok(res); } let cases: Vec<proc_macro2::TokenStream> = s .variants .iter() .map(|variant| { let fields = Fields::<DataAttr>::parse_ast(&variant.fields)?; let variant = &variant.ident; // the various inner `same()` calls, to the right of the match arm. let tests: Vec<_> = fields .iter() .filter(|f| f.attrs != DataAttr::Ignore) .map(|field| { let same_fn = field.same_fn_path_tokens(); let var_left = ident_from_str(&format!("__self_{}", field.ident_string())); let var_right = ident_from_str(&format!("__other_{}", field.ident_string())); quote!( #same_fn(#var_left, #var_right) ) }) .collect(); if let FieldKind::Named = fields.kind { let lefts: Vec<_> = fields .iter() .map(|field| { let ident = field.ident_tokens(); let var = ident_from_str(&format!("__self_{}", field.ident_string())); quote!( #ident: #var ) }) .collect(); let rights: Vec<_> = fields .iter() .map(|field| { let ident = field.ident_tokens(); let var = ident_from_str(&format!("__other_{}", field.ident_string())); quote!( #ident: #var ) }) .collect(); Ok(quote! { (#ident :: #variant { #( #lefts ),* }, #ident :: #variant { #( #rights ),* }) => { #( #tests )&&* } }) } else { let vars_left: Vec<_> = fields .iter() .map(|field| ident_from_str(&format!("__self_{}", field.ident_string()))) .collect(); let vars_right: Vec<_> = fields .iter() .map(|field| ident_from_str(&format!("__other_{}", field.ident_string()))) .collect(); if fields.iter().count() > 0 { Ok(quote! { ( #ident :: #variant( #(#vars_left),* ), #ident :: #variant( #(#vars_right),* )) => { #( #tests )&&* } }) } else { Ok(quote! { ( #ident :: #variant , #ident :: #variant ) => { true } }) } } }) .collect::<Result<Vec<proc_macro2::TokenStream>, syn::Error>>()?; let res = quote! { impl<#impl_generics> ::druid::Data for #ident #ty_generics #where_clause { fn same(&self, other: &Self) -> bool { match (self, other) { #( #cases ),* _ => false, } } } }; Ok(res) } fn generics_bounds(generics: &syn::Generics) -> proc_macro2::TokenStream { let res = generics.params.iter().map(|gp| { use syn::GenericParam::*; match gp { Type(ty) => { let ident = &ty.ident; let bounds = &ty.bounds; if bounds.is_empty() { quote_spanned!(ty.span()=> #ident : ::druid::Data) } else { quote_spanned!(ty.span()=> #ident : #bounds + ::druid::Data) } } Lifetime(lf) => quote!(#lf), Const(cst) => quote!(#cst), } }); quote!( #( #res, )* ) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/src/lens.rs
druid-derive/src/lens.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use super::attr::{FieldKind, Fields, LensAttrs}; use proc_macro2::{Ident, Span}; use quote::quote; use std::collections::HashSet; use syn::{spanned::Spanned, Data, GenericParam, TypeParam}; pub(crate) fn derive_lens_impl( input: syn::DeriveInput, ) -> Result<proc_macro2::TokenStream, syn::Error> { match &input.data { Data::Struct(_) => derive_struct(&input), Data::Enum(e) => Err(syn::Error::new( e.enum_token.span(), "Lens implementations cannot be derived from enums", )), Data::Union(u) => Err(syn::Error::new( u.union_token.span(), "Lens implementations cannot be derived from unions", )), } } fn derive_struct(input: &syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> { let ty = &input.ident; let fields = if let syn::Data::Struct(syn::DataStruct { fields, .. }) = &input.data { Fields::<LensAttrs>::parse_ast(fields)? } else { return Err(syn::Error::new( input.span(), "Lens implementations can only be derived from structs with named fields", )); }; if fields.kind != FieldKind::Named { return Err(syn::Error::new( input.span(), "Lens implementations can only be derived from structs with named fields", )); } let twizzled_name = if is_camel_case(&ty.to_string()) { let temp_name = format!("{}_derived_lenses", to_snake_case(&ty.to_string())); proc_macro2::Ident::new(&temp_name, proc_macro2::Span::call_site()) } else { return Err(syn::Error::new( ty.span(), "Lens implementations can only be derived from CamelCase types", )); }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let mut lens_ty_idents = Vec::new(); let mut phantom_decls = Vec::new(); let mut phantom_inits = Vec::new(); for gp in input.generics.params.iter() { if let GenericParam::Type(TypeParam { ident, .. }) = gp { lens_ty_idents.push(quote! {#ident}); phantom_decls.push(quote! {std::marker::PhantomData<*const #ident>}); phantom_inits.push(quote! {std::marker::PhantomData}); } } let lens_ty_generics = quote! { <#(#lens_ty_idents),*> }; // Define lens types for each field let defs = fields.iter().filter(|f| !f.attrs.ignore).map(|f| { let field_name = &f.ident.unwrap_named(); let struct_docs = format!("Lens for the field `{field_name}` on [`{ty}`](super::{ty})."); let fn_docs = format!( "Creates a new lens for the field `{field_name}` on [`{ty}`](super::{ty}). \ Use [`{ty}::{field_name}`](super::{ty}::{field_name}) instead." ); quote! { #[doc = #struct_docs] #[allow(non_camel_case_types)] #[derive(Debug, Copy, Clone)] pub struct #field_name#lens_ty_generics(#(#phantom_decls),*); impl #lens_ty_generics #field_name#lens_ty_generics{ #[doc = #fn_docs] pub const fn new()->Self{ Self(#(#phantom_inits),*) } } } }); let used_params: HashSet<String> = input .generics .params .iter() .flat_map(|gp: &GenericParam| match gp { GenericParam::Type(TypeParam { ident, .. }) => Some(ident.to_string()), _ => None, }) .collect(); let gen_new_param = |name: &str| { let mut candidate: String = name.into(); let mut count = 1usize; while used_params.contains(&candidate) { candidate = format!("{name}_{count}"); count += 1; } Ident::new(&candidate, Span::call_site()) }; let func_ty_par = gen_new_param("F"); let val_ty_par = gen_new_param("V"); let impls = fields.iter().filter(|f| !f.attrs.ignore).map(|f| { let field_name = &f.ident.unwrap_named(); let field_ty = &f.ty; quote! { impl #impl_generics druid::Lens<#ty#ty_generics, #field_ty> for #twizzled_name::#field_name#lens_ty_generics #where_clause { fn with<#val_ty_par, #func_ty_par: FnOnce(&#field_ty) -> #val_ty_par>(&self, data: &#ty#ty_generics, f: #func_ty_par) -> #val_ty_par { f(&data.#field_name) } fn with_mut<#val_ty_par, #func_ty_par: FnOnce(&mut #field_ty) -> #val_ty_par>(&self, data: &mut #ty#ty_generics, f: #func_ty_par) -> #val_ty_par { f(&mut data.#field_name) } } } }); let associated_items = fields.iter().filter(|f| !f.attrs.ignore).map(|f| { let field_name = &f.ident.unwrap_named(); let lens_field_name = f.attrs.lens_name_override.as_ref().unwrap_or(field_name); quote! { /// Lens for the corresponding field. pub const #lens_field_name: #twizzled_name::#field_name#lens_ty_generics = #twizzled_name::#field_name::new(); } }); let mod_docs = format!("Derived lenses for [`{ty}`]."); let expanded = quote! { #[doc = #mod_docs] pub mod #twizzled_name { #(#defs)* } #(#impls)* #[allow(non_upper_case_globals)] impl #impl_generics #ty #ty_generics #where_clause { #(#associated_items)* } }; Ok(expanded) } //I stole these from rustc! fn char_has_case(c: char) -> bool { c.is_lowercase() || c.is_uppercase() } fn is_camel_case(name: &str) -> bool { let name = name.trim_matches('_'); if name.is_empty() { return true; } // start with a non-lowercase letter rather than non-uppercase // ones (some scripts don't have a concept of upper/lowercase) !name.chars().next().unwrap().is_lowercase() && !name.contains("__") && !name.chars().collect::<Vec<_>>().windows(2).any(|pair| { // contains a capitalisable character followed by, or preceded by, an underscore char_has_case(pair[0]) && pair[1] == '_' || char_has_case(pair[1]) && pair[0] == '_' }) } fn to_snake_case(mut str: &str) -> String { let mut words = vec![]; // Preserve leading underscores str = str.trim_start_matches(|c: char| { if c == '_' { words.push(String::new()); true } else { false } }); for s in str.split('_') { let mut last_upper = false; let mut buf = String::new(); if s.is_empty() { continue; } for ch in s.chars() { if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper { words.push(buf); buf = String::new(); } last_upper = ch.is_uppercase(); buf.extend(ch.to_lowercase()); } words.push(buf); } words.join("_") }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ignore.rs
druid-derive/tests/ignore.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! testing the ignore attribute use druid::Data; #[test] fn simple_ignore() { #[derive(Clone, Data)] struct Point { x: f64, #[data(ignore)] #[allow(dead_code)] y: f64, } let p1 = Point { x: 0.0, y: 1.0 }; let p2 = Point { x: 0.0, y: 9.0 }; assert!(p1.same(&p2)); } #[test] fn ignore_item_without_data_impl() { use std::path::PathBuf; #[derive(Clone, Data)] #[allow(dead_code)] struct CoolStruct { len: usize, #[data(ignore)] #[allow(dead_code)] path: PathBuf, } } #[test] fn tuple_struct() { #[derive(Clone, Data)] struct Tup( usize, #[data(ignore)] #[allow(dead_code)] usize, ); let one = Tup(1, 1); let two = Tup(1, 5); assert!(one.same(&two)); } #[test] fn enums() { #[derive(Clone, Data)] enum Hmm { Named { one: usize, #[data(ignore)] two: usize, }, Tuple(#[data(ignore)] usize, usize), } let name_one = Hmm::Named { one: 5, two: 4 }; let name_two = Hmm::Named { one: 5, two: 42 }; let tuple_one = Hmm::Tuple(2, 4); let tuple_two = Hmm::Tuple(9, 4); assert!(!name_one.same(&tuple_one)); assert!(name_one.same(&name_two)); assert!(tuple_one.same(&tuple_two)); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/with_lens.rs
druid-derive/tests/with_lens.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use float_cmp::assert_approx_eq; use druid::Data; use druid::Lens; #[test] fn derive_lens() { #[derive(Lens)] struct State { text: String, #[lens(name = "lens_number")] number: f64, #[lens(ignore)] ignored: f64, } let mut state = State { text: "1.0".into(), number: 1.0, ignored: 2.0, }; let text_lens = State::text; let number_lens = State::lens_number; //named lens for number text_lens.with(&state, |data| assert_eq!(data, "1.0")); number_lens.with(&state, |data| assert_approx_eq!(f64, *data, 1.0)); text_lens.with_mut(&mut state, |data| *data = "2.0".into()); number_lens.with_mut(&mut state, |data| *data = 2.0); assert_eq!(state.text, "2.0"); assert_approx_eq!(f64, state.number, 2.0); assert_approx_eq!(f64, state.ignored, 2.0); } #[test] fn mix_with_data_lens() { #[derive(Clone, Lens, Data)] struct State { #[data(ignore)] text: String, #[data(same_fn = "same_sign")] #[lens(name = "lens_number")] number: f64, } //test lens let mut state = State { text: "1.0".into(), number: 1.0, }; let text_lens = State::text; let number_lens = State::lens_number; //named lens for number text_lens.with(&state, |data| assert_eq!(data, "1.0")); number_lens.with(&state, |data| assert_approx_eq!(f64, *data, 1.0)); text_lens.with_mut(&mut state, |data| *data = "2.0".into()); number_lens.with_mut(&mut state, |data| *data = 2.0); assert_eq!(state.text, "2.0"); assert_approx_eq!(f64, state.number, 2.0); //test data let two = State { text: "666".into(), number: 200.0, }; assert!(state.same(&two)) } #[allow(clippy::trivially_copy_pass_by_ref)] fn same_sign(one: &f64, two: &f64) -> bool { one.signum() == two.signum() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/with_same.rs
druid-derive/tests/with_same.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use druid::Data; #[test] fn same_fn() { #[derive(Clone, Data)] struct Nanana { bits: f64, #[data(eq)] peq: f64, } let one = Nanana { bits: 1.0, peq: f64::NAN, }; let two = Nanana { bits: 1.0, peq: f64::NAN, }; //according to partialeq, two NaNs are never equal assert!(!one.same(&two)); let one = Nanana { bits: f64::NAN, peq: 1.0, }; let two = Nanana { bits: f64::NAN, peq: 1.0, }; // the default 'same' impl uses bitwise equality, so two bitwise-equal NaNs are equal assert!(one.same(&two)); } #[test] fn enums() { #[derive(Debug, Clone, Data)] enum Hi { One { bits: f64, }, Two { #[data(same_fn = "same_sign")] bits: f64, }, Tri(#[data(same_fn = "same_sign")] f64), } let oneone = Hi::One { bits: f64::NAN }; let onetwo = Hi::One { bits: f64::NAN }; assert!(oneone.same(&onetwo)); let twoone = Hi::Two { bits: -1.1 }; let twotwo = Hi::Two { bits: f64::NEG_INFINITY, }; assert!(twoone.same(&twotwo)); let trione = Hi::Tri(1001.); let tritwo = Hi::Tri(-1.); assert!(!trione.same(&tritwo)); } #[allow(clippy::trivially_copy_pass_by_ref)] fn same_sign(one: &f64, two: &f64) -> bool { one.signum() == two.signum() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/lens_generic.rs
druid-derive/tests/lens_generic.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use druid::{Lens, LensExt}; use std::fmt::Debug; use std::marker::PhantomData; #[derive(Lens)] struct Wrapper<T> { x: T, } #[test] fn one_plain_param() { let wrap = Wrapper::<u64> { x: 45 }; let val = Wrapper::<u64>::x.with(&wrap, |val| *val); assert_eq!(wrap.x, val); let wrap = Wrapper::<String> { x: "pop".into() }; let val = Wrapper::<String>::x.with(&wrap, |val| val.clone()); assert_eq!(wrap.x, val) } #[derive(Lens)] struct DebugWrapper<T: Debug> { x: T, } #[test] fn one_trait_param() { let wrap = DebugWrapper::<u64> { x: 45 }; let val = DebugWrapper::<u64>::x.with(&wrap, |val| *val); assert_eq!(wrap.x, val); let wrap = DebugWrapper::<String> { x: "pop".into() }; let val = DebugWrapper::<String>::x.with(&wrap, |val| val.clone()); assert_eq!(wrap.x, val) } #[derive(Lens)] struct LifetimeWrapper<'a, T: 'a> { x: T, phantom_a: PhantomData<&'a T>, } #[test] fn one_lifetime_param() { let wrap = LifetimeWrapper::<u64> { x: 45, phantom_a: Default::default(), }; let val = LifetimeWrapper::<u64>::x.with(&wrap, |val| *val); assert_eq!(wrap.x, val); let wrap = LifetimeWrapper::<String> { x: "pop".into(), phantom_a: Default::default(), }; let val = LifetimeWrapper::<String>::x.with(&wrap, |val| val.clone()); assert_eq!(wrap.x, val) } trait Xt { type I: Yt; } trait Yt { type P; } #[derive(Lens)] struct WhereWrapper<T, U, W> where T: Xt<I = U>, U: Yt, { t: T, u: U, w: W, } impl Xt for u64 { type I = i32; } impl Yt for i32 { type P = bool; } #[test] fn where_clause() { type Ww = WhereWrapper<u64, i32, bool>; let mut wrap = Ww { t: 45, u: 1_000_000, w: true, }; let ext = ( Ww::t.with(&wrap, |val| *val), Ww::u.with(&wrap, |val| *val), Ww::w.with(&wrap, |val| *val), ); assert_eq!((wrap.t, wrap.u, wrap.w), ext); Ww::t.with_mut(&mut wrap, |val| *val = 67); assert_eq!(wrap.t, 67) } #[derive(Lens)] struct ReservedParams<F, V> { f: F, // We were using V and F as method params v: V, } #[test] fn reserved() { let rp = ReservedParams::<u64, String> { f: 56, v: "Go".into(), }; let val = ReservedParams::<u64, String>::f.with(&rp, |val| *val); assert_eq!(rp.f, val); } #[derive(Lens)] struct Outer<T> { middle: Middle, t: T, } #[derive(Lens)] struct Middle { internal: usize, } #[test] fn then_inference() { let outer = Outer { t: -9i32, middle: Middle { internal: 89 }, }; let lens = Outer::<i32>::middle.then(Middle::internal); let val = lens.with(&outer, |val| *val); assert_eq!(outer.middle.internal, val); let outer = Outer { t: Middle { internal: 12 }, middle: Middle { internal: 567 }, }; let lens = Outer::<Middle>::t.then(Middle::internal); let val = lens.with(&outer, |val| *val); assert_eq!(outer.t.internal, val); let lt_wrapper = LifetimeWrapper { x: Middle { internal: 45 }, phantom_a: Default::default(), }; let lens = LifetimeWrapper::<'static, Middle>::x.then(Middle::internal); let val = lens.with(&lt_wrapper, |val| *val); assert_eq!(lt_wrapper.x.internal, val); //let outer = Outer }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui.rs
druid-derive/tests/ui.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 // https://github.com/dtolnay/trybuild // trybuild is a crate that essentially runs cargo on the provided files, and checks the output. // Tests may suddenly fail after a new compiler release, and there's not much we can do about that. // If the test suite fails because of trybuild: // - Update your compiler to the latest stable version. // - If it still fails, update the stderr snapshots. To do so, run the test suite with // env variable TRYBUILD=overwrite, and submit the file changes in a PR. use trybuild::TestCases; #[test] fn ui() { let t = TestCases::new(); t.pass("tests/ui/simple-lens.rs"); t.pass("tests/ui/lens-attributes.rs"); t.compile_fail("tests/ui/with-empty-struct.rs"); t.compile_fail("tests/ui/with-tuple-struct.rs"); t.compile_fail("tests/ui/with-enum.rs"); t.compile_fail("tests/ui/with-union.rs"); t.compile_fail("tests/ui/with-snake_case.rs"); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/data.rs
druid-derive/tests/data.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Test #[derive(Data)] use druid::Data; #[derive(Data, Clone)] struct PlainStruct; #[derive(Data, Clone)] struct EmptyTupleStruct(); #[derive(Data, Clone)] struct SingleTupleStruct(bool); #[derive(Data, Clone)] struct MultiTupleStruct(bool, i64, String); #[derive(Data, Clone)] struct EmptyFieldStruct {} #[derive(Data, Clone)] struct SingleFieldStruct { a: bool, } #[derive(Data, Clone)] struct MultiFieldStruct { a: bool, b: i64, c: String, } trait UserTrait {} #[derive(Clone, Data)] struct TypeParamForUserTraitStruct<T: UserTrait + Data> { a: T, } #[derive(Clone, Data)] struct TypeParamForUserTraitWithWhereClauseStruct<T> where T: UserTrait, { b: T, } #[derive(Clone, Data)] enum TypeParamForUserTraitAndLifetimeEnum<T: UserTrait + 'static> { V1(T), } #[test] fn test_data_derive_same() { let plain = PlainStruct; assert!(plain.same(&plain)); let empty_tuple = EmptyTupleStruct(); assert!(empty_tuple.same(&empty_tuple)); let singletuple = SingleTupleStruct(true); assert!(singletuple.same(&singletuple)); assert!(!singletuple.same(&SingleTupleStruct(false))); let multituple = MultiTupleStruct(false, 33, "Test".to_string()); assert!(multituple.same(&multituple)); assert!(!multituple.same(&MultiTupleStruct(true, 33, "Test".to_string()))); let empty_field = EmptyFieldStruct {}; assert!(empty_field.same(&empty_field)); let singlefield = SingleFieldStruct { a: true }; assert!(singlefield.same(&singlefield)); assert!(!singlefield.same(&SingleFieldStruct { a: false })); let multifield = MultiFieldStruct { a: false, b: 33, c: "Test".to_string(), }; assert!(multifield.same(&multifield)); assert!(!multifield.same(&MultiFieldStruct { a: false, b: 33, c: "Fail".to_string() })); #[derive(Clone, Data)] struct Value(u32); impl UserTrait for Value {} let v = TypeParamForUserTraitStruct { a: Value(1) }; assert!(v.same(&v)); assert!(!v.same(&TypeParamForUserTraitStruct { a: Value(2) })); let v = TypeParamForUserTraitWithWhereClauseStruct { b: Value(3) }; assert!(v.same(&v)); assert!(!v.same(&TypeParamForUserTraitWithWhereClauseStruct { b: Value(6) })); let v = TypeParamForUserTraitAndLifetimeEnum::V1(Value(10)); assert!(v.same(&v)); assert!(!v.same(&TypeParamForUserTraitAndLifetimeEnum::V1(Value(12)))); } #[derive(Data, Clone)] struct DataAttrEq { #[data(eq)] f: PanicOnPartialEq, } #[derive(Clone, Copy)] struct PanicOnPartialEq; impl PartialEq for PanicOnPartialEq { fn eq(&self, _other: &Self) -> bool { panic!("PartialEq::eq called"); } } #[test] #[should_panic = "PartialEq::eq called"] fn data_attr_eq() { DataAttrEq { f: PanicOnPartialEq, } .same(&DataAttrEq { f: PanicOnPartialEq, }); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/with-empty-struct.rs
druid-derive/tests/ui/with-empty-struct.rs
use druid::*; #[derive(Lens)] struct Foobar; fn main() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/with-union.rs
druid-derive/tests/ui/with-union.rs
use druid::*; #[derive(Lens)] union Foobar { foo: i32, bar: f64, } fn main() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/simple-lens.rs
druid-derive/tests/ui/simple-lens.rs
use druid::*; #[derive(Lens)] struct MyThing { field_1: i32, field_2: String, } fn main() { let _ = MyThing::field_1; let _ = MyThing::field_2; }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/with-snake_case.rs
druid-derive/tests/ui/with-snake_case.rs
#![allow(non_camel_case_types)] use druid::*; #[derive(Lens)] struct my_thing { field: i32 } fn main() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/with-enum.rs
druid-derive/tests/ui/with-enum.rs
use druid::*; #[derive(Lens)] enum Foobar { Foo(i32), Bar, } fn main() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/with-tuple-struct.rs
druid-derive/tests/ui/with-tuple-struct.rs
use druid::*; #[derive(Lens)] struct Foobar(i32, i64); fn main() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-derive/tests/ui/lens-attributes.rs
druid-derive/tests/ui/lens-attributes.rs
#![allow(dead_code)] use druid::*; #[derive(Lens)] struct Item { #[lens(name = "count_lens")] count: usize, #[lens(ignore)] complete: bool, } impl Item { fn count(&self) -> usize { self.count } fn complete(&mut self) { self.complete = true; } } fn main() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/build.rs
druid-shell/build.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #[cfg(not(any(feature = "x11", feature = "wayland")))] fn main() {} #[cfg(any(feature = "x11", feature = "wayland"))] fn main() { use pkg_config::probe_library; use std::env; use std::path::PathBuf; if env::var("CARGO_CFG_TARGET_OS").unwrap() != "freebsd" && env::var("CARGO_CFG_TARGET_OS").unwrap() != "linux" && env::var("CARGO_CFG_TARGET_OS").unwrap() != "openbsd" { return; } let xkbcommon = probe_library("xkbcommon").unwrap(); #[cfg(feature = "x11")] probe_library("xkbcommon-x11").unwrap(); let mut header = "\ #include <xkbcommon/xkbcommon-compose.h> #include <xkbcommon/xkbcommon-names.h> #include <xkbcommon/xkbcommon.h>" .to_string(); if cfg!(feature = "x11") { header += " #include <xkbcommon/xkbcommon-x11.h>"; } let bindings = bindgen::Builder::default() // The input header we would like to generate // bindings for. .header_contents("wrapper.h", &header) .clang_args( xkbcommon .include_paths .iter() .filter_map(|path| path.to_str().map(|s| format!("-I{s}"))), ) // Tell cargo to invalidate the built crate whenever any of the // included header files changed. .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .prepend_enum_name(false) .size_t_is_usize(true) .allowlist_function("xkb_.*") .allowlist_type("xkb_.*") .allowlist_var("XKB_.*") .allowlist_type("xcb_connection_t") // this needs var args .blocklist_function("xkb_context_set_log_fn") // we use FILE from libc .blocklist_type("FILE") .blocklist_type("va_list") .generate() .expect("Unable to generate bindings"); // Write the bindings to the $OUT_DIR/xkbcommon.rs file. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("xkbcommon_sys.rs")) .expect("Couldn't write bindings!"); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/lib.rs
druid-shell/src/lib.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Platform abstraction for Druid toolkit. //! //! `druid-shell` is an abstraction around a given platform UI & application //! framework. It provides common types, which then defer to a platform-defined //! implementation. //! //! # Env //! //! For testing and debugging, `druid-shell` can change its behavior based on environment //! variables. Here is a list of environment variables that `druid-shell` supports: //! //! - `DRUID_SHELL_DISABLE_X11_PRESENT`: if this is set and `druid-shell` is using the `x11` //! backend, it will avoid using the Present extension. #![warn(rustdoc::broken_intra_doc_links)] #![allow(clippy::new_without_default)] #![deny(clippy::trivially_copy_pass_by_ref)] #![doc( html_logo_url = "https://raw.githubusercontent.com/linebender/druid/screenshots/images/doc_logo.png" )] // This is overeager right now, see https://github.com/rust-lang/rust-clippy/issues/8494 #![allow(clippy::iter_overeager_cloned)] // Rename `gtk_rs` back to `gtk`. // This allows us to use `gtk` as the feature name. // The `target_os` requirement is there to exclude anything `wasm` like. #[cfg(all( any(target_os = "freebsd", target_os = "linux", target_os = "openbsd"), feature = "gtk" ))] extern crate gtk_rs as gtk; #[cfg(feature = "image")] pub use piet::image_crate as image; pub use piet::kurbo; pub use piet_common as piet; // Reexport the version of `raw_window_handle` we are using. #[cfg(feature = "raw-win-handle")] pub use raw_window_handle; #[macro_use] mod util; mod application; mod backend; mod clipboard; mod common_util; mod dialog; mod error; mod hotkey; mod keyboard; mod menu; mod mouse; mod region; mod scale; mod screen; mod window; pub mod platform; pub mod text; pub use application::{init_harness, AppHandler, Application}; pub use clipboard::{Clipboard, ClipboardFormat, FormatId}; pub use common_util::Counter; pub use dialog::{FileDialogOptions, FileInfo, FileSpec}; pub use error::Error; pub use hotkey::{HotKey, RawMods, SysMods}; pub use keyboard::{Code, IntoKey, KbKey, KeyEvent, KeyState, Location, Modifiers}; pub use menu::Menu; pub use mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent}; pub use region::Region; pub use scale::{Scalable, Scale, ScaledArea}; pub use screen::{Monitor, Screen}; pub use window::{ FileDialogToken, IdleHandle, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowBuilder, WindowHandle, WindowLevel, WindowState, }; pub use keyboard_types;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/region.rs
druid-shell/src/region.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::kurbo::{BezPath, Point, Rect, Shape, Vec2}; /// A union of rectangles, useful for describing an area that needs to be repainted. #[derive(Clone, Debug)] pub struct Region { rects: Vec<Rect>, } impl Region { /// The empty region. pub const EMPTY: Region = Region { rects: Vec::new() }; /// Returns the collection of rectangles making up this region. #[inline] pub fn rects(&self) -> &[Rect] { &self.rects } /// Adds a rectangle to this region. pub fn add_rect(&mut self, rect: Rect) { if rect.area() > 0.0 { self.rects.push(rect); } } /// Replaces this region with a single rectangle. pub fn set_rect(&mut self, rect: Rect) { self.clear(); self.add_rect(rect); } /// Sets this region to the empty region. pub fn clear(&mut self) { self.rects.clear(); } /// Returns a rectangle containing this region. pub fn bounding_box(&self) -> Rect { if self.rects.is_empty() { Rect::ZERO } else { self.rects[1..] .iter() .fold(self.rects[0], |r, s| r.union(*s)) } } #[doc(hidden)] #[deprecated(since = "0.7.0", note = "Use bounding_box() instead")] // this existed on the previous Region type, and I've bumped into it // a couple times while updating pub fn to_rect(&self) -> Rect { self.bounding_box() } /// Returns `true` if this region has a non-empty intersection with the given rectangle. pub fn intersects(&self, rect: Rect) -> bool { self.rects.iter().any(|r| r.intersect(rect).area() > 0.0) } /// Returns `true` if the given `point` is contained within any rectangle in the region. pub fn contains(&self, point: Point) -> bool { self.rects.iter().any(|r| r.contains(point)) } /// Returns `true` if this region is empty. pub fn is_empty(&self) -> bool { // Note that we only ever add non-empty rects to self.rects. self.rects.is_empty() } /// Converts into a Bezier path. Note that this just gives the concatenation of the rectangle /// paths, which is not the smartest possible thing. Also, it's not the right answer for an /// even/odd fill rule. pub fn to_bez_path(&self) -> BezPath { let mut ret = BezPath::new(); for rect in self.rects() { // Rect ignores the tolerance. ret.extend(rect.path_elements(0.0)); } ret } /// Modifies this region by including everything in the other region. pub fn union_with(&mut self, other: &Region) { self.rects.extend_from_slice(&other.rects); } /// Modifies this region by intersecting it with the given rectangle. pub fn intersect_with(&mut self, rect: Rect) { // TODO: this would be a good use of the nightly drain_filter function, if it stabilizes for r in &mut self.rects { *r = r.intersect(rect); } self.rects.retain(|r| r.area() > 0.0) } } impl std::ops::AddAssign<Vec2> for Region { fn add_assign(&mut self, rhs: Vec2) { for r in &mut self.rects { *r = *r + rhs; } } } impl std::ops::SubAssign<Vec2> for Region { fn sub_assign(&mut self, rhs: Vec2) { for r in &mut self.rects { *r = *r - rhs; } } } impl From<Rect> for Region { fn from(rect: Rect) -> Region { Region { rects: vec![rect] } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/mouse.rs
druid-shell/src/mouse.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Common types for representing mouse events and state use crate::backend; use crate::kurbo::{Point, Vec2}; use crate::piet::ImageBuf; use crate::Modifiers; /// Information about the mouse event. /// /// Every mouse event can have a new position. There is no guarantee of /// receiving a move event before another mouse event. #[derive(Debug, Clone, PartialEq)] pub struct MouseEvent { /// The location of the mouse in [display points] in relation to the current window. /// /// [display points]: crate::Scale pub pos: Point, /// Mouse buttons being held down during a move or after a click event. /// Thus it will contain the `button` that triggered a mouse-down event, /// and it will not contain the `button` that triggered a mouse-up event. pub buttons: MouseButtons, /// Keyboard modifiers at the time of the event. pub mods: Modifiers, /// The number of mouse clicks associated with this event. This will always /// be `0` for a mouse-up and mouse-move events. pub count: u8, /// Focus is `true` on macOS when the mouse-down event (or its companion mouse-up event) /// with `MouseButton::Left` was the event that caused the window to gain focus. pub focus: bool, /// The button that was pressed down in the case of mouse-down, /// or the button that was released in the case of mouse-up. /// This will always be `MouseButton::None` in the case of mouse-move. pub button: MouseButton, /// The wheel movement. /// /// The polarity is the amount to be added to the scroll position, /// in other words the opposite of the direction the content should /// move on scrolling. This polarity is consistent with the /// deltaX and deltaY values in a web [WheelEvent]. /// /// [WheelEvent]: https://w3c.github.io/uievents/#event-type-wheel pub wheel_delta: Vec2, } /// An indicator of which mouse button was pressed. #[derive(PartialEq, Eq, Clone, Copy, Debug)] #[repr(u8)] pub enum MouseButton { /// No mouse button. // MUST BE FIRST (== 0) None, /// Left mouse button. Left, /// Right mouse button. Right, /// Middle mouse button. Middle, /// First X button. X1, /// Second X button. X2, } impl MouseButton { /// Returns `true` if this is [`MouseButton::Left`]. /// /// [`MouseButton::Left`]: #variant.Left #[inline] pub fn is_left(self) -> bool { self == MouseButton::Left } /// Returns `true` if this is [`MouseButton::Right`]. /// /// [`MouseButton::Right`]: #variant.Right #[inline] pub fn is_right(self) -> bool { self == MouseButton::Right } /// Returns `true` if this is [`MouseButton::Middle`]. /// /// [`MouseButton::Middle`]: #variant.Middle #[inline] pub fn is_middle(self) -> bool { self == MouseButton::Middle } /// Returns `true` if this is [`MouseButton::X1`]. /// /// [`MouseButton::X1`]: #variant.X1 #[inline] pub fn is_x1(self) -> bool { self == MouseButton::X1 } /// Returns `true` if this is [`MouseButton::X2`]. /// /// [`MouseButton::X2`]: #variant.X2 #[inline] pub fn is_x2(self) -> bool { self == MouseButton::X2 } } /// A set of [`MouseButton`]s. #[derive(PartialEq, Eq, Clone, Copy, Default)] pub struct MouseButtons(u8); impl MouseButtons { /// Create a new empty set. #[inline] pub fn new() -> MouseButtons { MouseButtons(0) } /// Add the `button` to the set. #[inline] pub fn insert(&mut self, button: MouseButton) { self.0 |= 1.min(button as u8) << button as u8; } /// Remove the `button` from the set. #[inline] pub fn remove(&mut self, button: MouseButton) { self.0 &= !(1.min(button as u8) << button as u8); } /// Builder-style method for adding the `button` to the set. #[inline] pub fn with(mut self, button: MouseButton) -> MouseButtons { self.0 |= 1.min(button as u8) << button as u8; self } /// Builder-style method for removing the `button` from the set. #[inline] pub fn without(mut self, button: MouseButton) -> MouseButtons { self.0 &= !(1.min(button as u8) << button as u8); self } /// Returns `true` if the `button` is in the set. #[inline] pub fn contains(self, button: MouseButton) -> bool { (self.0 & (1.min(button as u8) << button as u8)) != 0 } /// Returns `true` if the set is empty. #[inline] pub fn is_empty(self) -> bool { self.0 == 0 } /// Returns `true` if all the `buttons` are in the set. #[inline] pub fn is_superset(self, buttons: MouseButtons) -> bool { self.0 & buttons.0 == buttons.0 } /// Returns `true` if [`MouseButton::Left`] is in the set. /// /// [`MouseButton::Left`]: enum.MouseButton.html#variant.Left #[inline] pub fn has_left(self) -> bool { self.contains(MouseButton::Left) } /// Returns `true` if [`MouseButton::Right`] is in the set. /// /// [`MouseButton::Right`]: enum.MouseButton.html#variant.Right #[inline] pub fn has_right(self) -> bool { self.contains(MouseButton::Right) } /// Returns `true` if [`MouseButton::Middle`] is in the set. /// /// [`MouseButton::Middle`]: enum.MouseButton.html#variant.Middle #[inline] pub fn has_middle(self) -> bool { self.contains(MouseButton::Middle) } /// Returns `true` if [`MouseButton::X1`] is in the set. /// /// [`MouseButton::X1`]: enum.MouseButton.html#variant.X1 #[inline] pub fn has_x1(self) -> bool { self.contains(MouseButton::X1) } /// Returns `true` if [`MouseButton::X2`] is in the set. /// /// [`MouseButton::X2`]: enum.MouseButton.html#variant.X2 #[inline] pub fn has_x2(self) -> bool { self.contains(MouseButton::X2) } /// Adds all the `buttons` to the set. pub fn extend(&mut self, buttons: MouseButtons) { self.0 |= buttons.0; } /// Returns a union of the values in `self` and `other`. #[inline] pub fn union(mut self, other: MouseButtons) -> MouseButtons { self.0 |= other.0; self } /// Clear the set. #[inline] pub fn clear(&mut self) { self.0 = 0; } /// Count the number of pressed buttons in the set. #[inline] pub fn count(self) -> u32 { self.0.count_ones() } } impl std::fmt::Debug for MouseButtons { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "MouseButtons({:05b})", self.0 >> 1) } } //NOTE: this currently only contains cursors that are included by default on //both Windows and macOS. We may want to provide polyfills for various additional cursors. /// Mouse cursors. #[derive(Clone, PartialEq, Eq)] pub enum Cursor { /// The default arrow cursor. Arrow, /// A vertical I-beam, for indicating insertion points in text. IBeam, Pointer, Crosshair, #[doc(hidden)] #[deprecated( since = "0.8.0", note = "This will be removed because it is not available on Windows." )] OpenHand, NotAllowed, ResizeLeftRight, ResizeUpDown, // The platform cursor should be small. Any image data that it uses should be shared (i.e. // behind an `Arc` or using a platform API that does the sharing). Custom(backend::window::CustomCursor), } /// A platform-independent description of a custom cursor. #[derive(Clone)] pub struct CursorDesc { #[allow(dead_code)] // Not yet used on all platforms. pub(crate) image: ImageBuf, #[allow(dead_code)] // Not yet used on all platforms. pub(crate) hot: Point, } impl CursorDesc { /// Creates a new `CursorDesc`. /// /// `hot` is the "hot spot" of the cursor, measured in terms of the pixels in `image` with /// `(0, 0)` at the top left. The hot spot is the logical position of the mouse cursor within /// the image. For example, if the image is a picture of a arrow, the hot spot might be the /// coordinates of the arrow's tip. pub fn new(image: ImageBuf, hot: impl Into<Point>) -> CursorDesc { CursorDesc { image, hot: hot.into(), } } } impl std::fmt::Debug for Cursor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { #[allow(deprecated)] match self { Cursor::Arrow => write!(f, "Cursor::Arrow"), Cursor::IBeam => write!(f, "Cursor::IBeam"), Cursor::Pointer => write!(f, "Cursor::Pointer"), Cursor::Crosshair => write!(f, "Cursor::Crosshair"), Cursor::OpenHand => write!(f, "Cursor::OpenHand"), Cursor::NotAllowed => write!(f, "Cursor::NotAllowed"), Cursor::ResizeLeftRight => write!(f, "Cursor::ResizeLeftRight"), Cursor::ResizeUpDown => write!(f, "Cursor::ResizeUpDown"), Cursor::Custom(_) => write!(f, "Cursor::Custom"), } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/dialog.rs
druid-shell/src/dialog.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! File open/save dialogs. use std::path::{Path, PathBuf}; /// Information about the path to be opened or saved. /// /// This path might point to a file or a directory. #[derive(Debug, Clone)] pub struct FileInfo { /// The path to the selected file. /// /// On macOS, this is already rewritten to use the extension that the user selected /// with the `file format` property. pub path: PathBuf, /// The selected file format. /// /// If there're multiple different formats available /// this allows understanding the kind of format that the user expects the file /// to be written in. Examples could be Blender 2.4 vs Blender 2.6 vs Blender 2.8. /// The `path` above will already contain the appropriate extension chosen in the /// `format` property, so it is not necessary to mutate `path` any further. pub format: Option<FileSpec>, } /// Type of file dialog. #[cfg(not(any( all( feature = "x11", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ), feature = "wayland" )))] #[derive(Clone, Copy, PartialEq, Eq)] pub enum FileDialogType { /// File open dialog. Open, /// File save dialog. Save, } /// Options for file dialogs. /// /// File dialogs let the user choose a specific path to open or save. /// /// By default the file dialogs operate in *files mode* where the user can only choose files. /// Importantly these are files from the user's perspective, but technically the returned path /// will be a directory when the user chooses a package. You can read more about [packages] below. /// It's also possible for users to manually specify a path which they might otherwise not be able /// to choose. Thus it is important to verify that all the returned paths match your expectations. /// /// The open dialog can also be switched to *directories mode* via [`select_directories`]. /// /// # Cross-platform compatibility /// /// You could write platform specific code that really makes the best use of each platform. /// However if you want to write universal code that will work on all platforms then /// you have to keep some restrictions in mind. /// /// ## Don't depend on directories with extensions /// /// Your application should avoid having to deal with directories that have extensions /// in their name, e.g. `my_stuff.pkg`. This clashes with [packages] on macOS and you /// will either need platform specific code or a degraded user experience on macOS /// via [`packages_as_directories`]. /// /// ## Use the save dialog only for new paths /// /// Don't direct the user to choose an existing file with the save dialog. /// Selecting existing files for overwriting is possible but extremely cumbersome on macOS. /// The much more optimized flow is to have the user select a file with the open dialog /// and then keep saving to that file without showing a save dialog. /// Use the save dialog only for selecting a new location. /// /// # macOS /// /// The file dialog works a bit differently on macOS. For a lot of applications this doesn't matter /// and you don't need to know the details. However if your application makes extensive use /// of file dialogs and you target macOS then you should understand the macOS specifics. /// /// ## Packages /// /// On macOS directories with known extensions are considered to be packages, e.g. `app_files.pkg`. /// Furthermore the packages are divided into two groups based on their extension. /// First there are packages that have been defined at the OS level, and secondly there are /// packages that are defined at the file dialog level based on [`allowed_types`]. /// These two types have slightly different behavior in the file dialogs. Generally packages /// behave similarly to regular files in many contexts, including the file dialogs. /// This package concept can be turned off in the file dialog via [`packages_as_directories`]. /// /// &#xFEFF; | Packages as files. File filters apply to packages. | Packages as directories. /// -------- | -------------------------------------------------- | ------------------------ /// Open directory | Not selectable. Not traversable. | Selectable. Traversable. /// Open file | Selectable. Not traversable. | Not selectable. Traversable. /// Save file | OS packages [clickable] but not traversable.<br/>Dialog packages traversable but not selectable. | Not selectable. Traversable. /// /// Keep in mind that the file dialog may start inside any package if the user has traversed /// into one just recently. The user might also manually specify a path inside a package. /// /// Generally this behavior should be kept, because it's least surprising to macOS users. /// However if your application requires selecting directories with extensions as directories /// or the user needs to be able to traverse into them to select a specific file, /// then you can change the default behavior via [`packages_as_directories`] /// to force macOS to behave like other platforms and not give special treatment to packages. /// /// ## Selecting files for overwriting in the save dialog is cumbersome /// /// Existing files can be clicked on in the save dialog, but that only copies their base file name. /// If the clicked file's extension is different than the first extension of the default type /// then the returned path does not actually match the path of the file that was clicked on. /// Clicking on a file doesn't change the base path either. Keep in mind that the macOS file dialog /// can have several directories open at once. So if a user has traversed into `/Users/Joe/foo/` /// and then clicks on an existing file `/Users/Joe/old.txt` in another directory then the returned /// path will actually be `/Users/Joe/foo/old.rtf` if the default type's first extension is `rtf`. /// /// [clickable]: #selecting-files-for-overwriting-in-the-save-dialog-is-cumbersome /// [packages]: #packages /// [`select_directories`]: #method.select_directories /// [`allowed_types`]: #method.allowed_types /// [`packages_as_directories`]: #method.packages_as_directories #[derive(Debug, Clone, Default)] pub struct FileDialogOptions { pub(crate) show_hidden: bool, pub(crate) allowed_types: Option<Vec<FileSpec>>, pub(crate) default_type: Option<FileSpec>, pub(crate) select_directories: bool, pub(crate) packages_as_directories: bool, pub(crate) multi_selection: bool, pub(crate) default_name: Option<String>, pub(crate) name_label: Option<String>, pub(crate) title: Option<String>, pub(crate) button_text: Option<String>, pub(crate) starting_directory: Option<PathBuf>, } /// A description of a filetype, for specifying allowed types in a file dialog. /// /// # Windows /// /// Each instance of this type is converted to a [`COMDLG_FILTERSPEC`] struct. /// /// # macOS /// /// These file types also apply to directories to define them as [packages]. /// /// [`COMDLG_FILTERSPEC`]: https://docs.microsoft.com/en-ca/windows/win32/api/shtypes/ns-shtypes-comdlg_filterspec /// [packages]: struct.FileDialogOptions.html#packages #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct FileSpec { /// A human readable name, describing this filetype. /// /// This is used in the Windows file dialog, where the user can select /// from a dropdown the type of file they would like to choose. /// /// This should not include the file extensions; they will be added automatically. /// For instance, if we are describing Word documents, the name would be "Word Document", /// and the displayed string would be "Word Document (*.doc)". pub name: &'static str, /// The file extensions used by this file type. /// /// This should not include the leading '.'. pub extensions: &'static [&'static str], } impl FileInfo { /// Returns the underlying path. pub fn path(&self) -> &Path { &self.path } } impl FileDialogOptions { /// Create a new set of options. pub fn new() -> FileDialogOptions { FileDialogOptions::default() } /// Set hidden files and directories to be visible. pub fn show_hidden(mut self) -> Self { self.show_hidden = true; self } /// Set directories to be selectable instead of files. /// /// This is only relevant for open dialogs. pub fn select_directories(mut self) -> Self { self.select_directories = true; self } /// Set [packages] to be treated as directories instead of files. /// /// This allows for writing more universal cross-platform code at the cost of user experience. /// /// This is only relevant on macOS. /// /// [packages]: #packages pub fn packages_as_directories(mut self) -> Self { self.packages_as_directories = true; self } /// Set multiple items to be selectable. /// /// This is only relevant for open dialogs. pub fn multi_selection(mut self) -> Self { self.multi_selection = true; self } /// Set the file types the user is allowed to select. /// /// This filter is only applied to files and [packages], but not to directories. /// /// An empty collection is treated as no filter. /// /// # macOS /// /// These file types also apply to directories to define [packages]. /// Which means the directories that match the filter are no longer considered directories. /// The packages are defined by this collection even in *directories mode*. /// /// [packages]: #packages pub fn allowed_types(mut self, types: Vec<FileSpec>) -> Self { // An empty vector can cause platform issues, so treat it as no filter if types.is_empty() { self.allowed_types = None; } else { self.allowed_types = Some(types); } self } /// Set the default file type. /// /// The provided `default_type` must also be present in [`allowed_types`]. /// /// If it's `None` then the first entry in [`allowed_types`] will be used as the default. /// /// This is only relevant in *files mode*. /// /// [`allowed_types`]: #method.allowed_types pub fn default_type(mut self, default_type: FileSpec) -> Self { self.default_type = Some(default_type); self } /// Set the default filename that appears in the dialog. pub fn default_name(mut self, default_name: impl Into<String>) -> Self { self.default_name = Some(default_name.into()); self } /// Set the text in the label next to the filename editbox. pub fn name_label(mut self, name_label: impl Into<String>) -> Self { self.name_label = Some(name_label.into()); self } /// Set the title text of the dialog. pub fn title(mut self, title: impl Into<String>) -> Self { self.title = Some(title.into()); self } /// Set the text of the Open/Save button. pub fn button_text(mut self, text: impl Into<String>) -> Self { self.button_text = Some(text.into()); self } /// Force the starting directory to the specified `path`. /// /// # User experience /// /// This should almost never be used because it overrides the OS choice, /// which will usually be a directory that the user recently visited. pub fn force_starting_directory(mut self, path: impl Into<PathBuf>) -> Self { self.starting_directory = Some(path.into()); self } } impl FileSpec { pub const TEXT: FileSpec = FileSpec::new("Text", &["txt"]); pub const JPG: FileSpec = FileSpec::new("Jpeg", &["jpg", "jpeg"]); pub const GIF: FileSpec = FileSpec::new("Gif", &["gif"]); pub const PNG: FileSpec = FileSpec::new("Portable network graphics (png)", &["png"]); pub const PDF: FileSpec = FileSpec::new("PDF", &["pdf"]); pub const HTML: FileSpec = FileSpec::new("Web Page", &["htm", "html"]); /// Create a new `FileSpec`. pub const fn new(name: &'static str, extensions: &'static [&'static str]) -> Self { FileSpec { name, extensions } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/clipboard.rs
druid-shell/src/clipboard.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interacting with the system pasteboard/clipboard. pub use crate::backend::clipboard as backend; /// A handle to the system clipboard. /// /// To get access to the global clipboard, call [`Application::clipboard`]. /// /// /// # Working with text /// /// Copying and pasting text is simple, using [`Clipboard::put_string`] and /// [`Clipboard::get_string`]. If this is all you need, you're in luck. /// /// # Advanced usage /// /// When working with data more complicated than plaintext, you will generally /// want to make that data available in multiple formats. /// /// For instance, if you are writing an image editor, you may have a preferred /// private format, that preserves metadata or layer information; but in order /// to interoperate with your user's other programs, you might also make your /// data available as an SVG, for other editors, and a bitmap image for applications /// that can accept general image data. /// /// ## `FormatId`entifiers /// /// In order for other applications to find data we put on the clipboard, /// (and for us to use data from other applications) we need to use agreed-upon /// identifiers for our data types. On macOS, these should be /// [`Universal Type Identifier`]s; on other platforms they appear to be /// mostly [MIME types]. Several common types are exposed as constants on /// [`ClipboardFormat`], these `const`s are set per-platform. /// /// When defining custom formats, you should use the correct identifier for /// the current platform. /// /// ## Setting custom data /// /// To put custom data on the clipboard, you create a [`ClipboardFormat`] for /// each type of data you support. You are responsible for ensuring that the /// data is already correctly serialized. /// /// /// ### `ClipboardFormat` for text /// /// If you wish to put text on the clipboard in addition to other formats, /// take special care to use `ClipboardFormat::TEXT` as the [`FormatId`]. On /// windows, we treat this identifier specially, and make sure the data is /// encoded as a wide string; all other data going into and out of the /// clipboard is treated as an array of bytes. /// /// # Examples /// /// ## Getting and setting text: /// /// ```no_run /// use druid_shell::{Application, Clipboard}; /// /// let mut clipboard = Application::global().clipboard(); /// clipboard.put_string("watch it there pal"); /// if let Some(contents) = clipboard.get_string() { /// assert_eq!("what it there pal", contents.as_str()); /// } /// /// ``` /// /// ## Copying multi-format data /// /// ```no_run /// use druid_shell::{Application, Clipboard, ClipboardFormat}; /// /// let mut clipboard = Application::global().clipboard(); /// /// let custom_type_id = "io.xieditor.path-clipboard-type"; /// /// let formats = [ /// ClipboardFormat::new(custom_type_id, make_custom_data()), /// ClipboardFormat::new(ClipboardFormat::SVG, make_svg_data()), /// ClipboardFormat::new(ClipboardFormat::PDF, make_pdf_data()), /// ]; /// /// clipboard.put_formats(&formats); /// /// # fn make_custom_data() -> Vec<u8> { unimplemented!() } /// # fn make_svg_data() -> Vec<u8> { unimplemented!() } /// # fn make_pdf_data() -> Vec<u8> { unimplemented!() } /// ``` /// ## Supporting multi-format paste /// /// ```no_run /// use druid_shell::{Application, Clipboard, ClipboardFormat}; /// /// let clipboard = Application::global().clipboard(); /// /// let custom_type_id = "io.xieditor.path-clipboard-type"; /// let supported_types = &[custom_type_id, ClipboardFormat::SVG, ClipboardFormat::PDF]; /// let best_available_type = clipboard.preferred_format(supported_types); /// /// if let Some(format) = best_available_type { /// let data = clipboard.get_format(format).expect("I promise not to unwrap in production"); /// do_something_with_data(format, data) /// } /// /// # fn do_something_with_data(_: &str, _: Vec<u8>) {} /// ``` /// /// [`Application::clipboard`]: crate::Application::clipboard /// [`Universal Type Identifier`]: https://escapetech.eu/manuals/qdrop/uti.html /// [MIME types]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types #[derive(Debug, Clone)] pub struct Clipboard(pub(crate) backend::Clipboard); impl Clipboard { /// Put a string onto the system clipboard. pub fn put_string(&mut self, s: impl AsRef<str>) { self.0.put_string(s); } /// Put multi-format data on the system clipboard. pub fn put_formats(&mut self, formats: &[ClipboardFormat]) { self.0.put_formats(formats) } /// Get a string from the system clipboard, if one is available. pub fn get_string(&self) -> Option<String> { self.0.get_string() } /// Given a list of supported clipboard types, returns the supported type which has /// highest priority on the system clipboard, or `None` if no types are supported. pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> { self.0.preferred_format(formats) } /// Return data in a given format, if available. /// /// It is recommended that the [`FormatId`] argument be a format returned by /// [`Clipboard::preferred_format`]. /// /// [`Clipboard::preferred_format`]: struct.Clipboard.html#method.preferred_format /// [`FormatId`]: type.FormatId.html pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> { self.0.get_format(format) } /// For debugging: print the resolved identifiers for each type currently /// on the clipboard. #[doc(hidden)] pub fn available_type_names(&self) -> Vec<String> { self.0.available_type_names() } } /// A type identifier for the system clipboard. /// /// These should be [`UTI` strings] on macOS, and (by convention?) [MIME types] elsewhere. /// /// [`UTI` strings]: https://escapetech.eu/manuals/qdrop/uti.html /// [MIME types]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types pub type FormatId = &'static str; /// Data coupled with a type identifier. #[derive(Debug, Clone)] #[cfg_attr(feature = "wayland", allow(dead_code))] #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub struct ClipboardFormat { pub(crate) identifier: FormatId, pub(crate) data: Vec<u8>, } impl ClipboardFormat { /// Create a new `ClipboardFormat` with the given `FormatId` and bytes. /// /// You are responsible for ensuring that this data can be interpreted /// as the provided format. pub fn new(identifier: FormatId, data: impl Into<Vec<u8>>) -> Self { let data = data.into(); ClipboardFormat { identifier, data } } } impl From<String> for ClipboardFormat { fn from(src: String) -> ClipboardFormat { let data = src.into_bytes(); ClipboardFormat::new(ClipboardFormat::TEXT, data) } } impl From<&str> for ClipboardFormat { fn from(src: &str) -> ClipboardFormat { src.to_string().into() } } impl From<backend::Clipboard> for Clipboard { fn from(src: backend::Clipboard) -> Clipboard { Clipboard(src) } } cfg_if::cfg_if! { if #[cfg(target_os = "macos")] { impl ClipboardFormat { pub const PDF: &'static str = "com.adobe.pdf"; pub const TEXT: &'static str = "public.utf8-plain-text"; pub const SVG: &'static str = "public.svg-image"; } } else { impl ClipboardFormat { cfg_if::cfg_if! { if #[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] { // trial and error; this is the most supported string type for gtk? pub const TEXT: &'static str = "UTF8_STRING"; } else { pub const TEXT: &'static str = "text/plain"; } } pub const PDF: &'static str = "application/pdf"; pub const SVG: &'static str = "image/svg+xml"; } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/menu.rs
druid-shell/src/menu.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::backend::menu as backend; use crate::hotkey::HotKey; /// A menu object. /// /// This may be a window menu, an application menu (macOS) or a context (right-click) /// menu. /// /// # Configuring menus /// /// Currently, a menu and its items cannot be changed once created. If you need /// to change anything about a menu (for instance, disabling or selecting items) /// you need to create a new menu with the desired properties. pub struct Menu(pub(crate) backend::Menu); impl Menu { /// Create a new empty window or application menu. pub fn new() -> Menu { Menu(backend::Menu::new()) } /// Create a new empty context menu. /// /// Some platforms distinguish between these types of menus, and some /// do not. pub fn new_for_popup() -> Menu { Menu(backend::Menu::new_for_popup()) } /// Consume this `Menu`, returning the platform menu object. pub(crate) fn into_inner(self) -> backend::Menu { self.0 } /// Add the provided `Menu` as a submenu of self, with the provided title. pub fn add_dropdown(&mut self, menu: Menu, text: &str, enabled: bool) { self.0.add_dropdown(menu.0, text, enabled) } /// Add an item to this menu. /// /// The `id` should uniquely identify this item. If the user selects this /// item, the responsible [`WinHandler`]'s [`command`] method will /// be called with this `id`. If the `enabled` argument is false, the menu /// item will be grayed out; the hotkey will also be disabled. /// If the `selected` argument is `true`, the menu will have a checkmark /// or platform appropriate equivalent indicating that it is currently selected. /// The `key` argument is an optional [`HotKey`] that will be registered /// with the system. /// /// /// [`WinHandler`]: crate::WinHandler /// [`command`]: crate::WinHandler::command pub fn add_item( &mut self, id: u32, text: &str, key: Option<&HotKey>, selected: Option<bool>, enabled: bool, ) { self.0.add_item(id, text, key, selected, enabled) } /// Add a separator to the menu. pub fn add_separator(&mut self) { self.0.add_separator() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/text.rs
druid-shell/src/text.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Types and functions for cross-platform text input. //! //! Text input is a notoriously difficult problem. Unlike many other aspects of //! user interfaces, text input can not be correctly modeled using discrete //! events passed from the platform to the application. For example, many mobile //! phones implement autocorrect: when the user presses the spacebar, the //! platform peeks at the word directly behind the caret, and potentially //! replaces it if it's misspelled. This means the platform needs to know the //! contents of a text field. On other devices, the platform may need to draw an //! emoji window under the caret, or look up the on-screen locations of letters //! for crossing out with a stylus, both of which require fetching on-screen //! coordinates from the application. //! //! This is all to say: text editing is a bidirectional conversation between the //! application and the platform. The application, when the platform asks for //! it, serves up text field coordinates and content. The platform looks at //! this information and combines it with input from keyboards (physical or //! onscreen), voice, styluses, the user's language settings, and then sends //! edit commands to the application. //! //! Many platforms have an additional complication: this input fusion often //! happens in a different process from your application. If we don't //! specifically account for this fact, we might get race conditions! In the //! autocorrect example, if I sloppily type "meoow" and press space, the //! platform might issue edits to "delete backwards one word and insert meow". //! However, if I concurrently click somewhere else in the document to move the //! caret, this will replace some *other* word with "meow", and leave the //! "meoow" disappointingly present. To mitigate this problem, we use locks, //! represented by the `InputHandler` trait. //! //! ## Lifecycle of a Text Input //! //! 1. The user clicks a link or switches tabs, and the window content now //! contains a new text field. The application registers this new field by //! calling `WindowHandle::add_text_field`, and gets a `TextFieldToken` that //! represents this new field. //! 2. The user clicks on that text field, focusing it. The application lets the //! platform know by calling `WindowHandle::set_focused_text_field` with that //! field's `TextFieldToken`. //! 3. The user presses a key on the keyboard. The platform first calls //! `WinHandler::key_down`. If this method returns `true`, the application //! has indicated the keypress was captured, and we skip the remaining steps. //! 4. If `key_down` returned `false`, `druid-shell` forwards the key event to the //! platform's text input system //! 5. The platform, in response to either this key event or some other user //! action, determines it's time for some text input. It calls //! `WinHandler::text_input` to acquire a lock on the text field's state. //! The application returns an `InputHandler` object corresponding to the //! requested text field. To prevent race conditions, your application may //! not make any changes //! to the text field's state until the platform drops the `InputHandler`. //! 6. The platform calls various `InputHandler` methods to inspect and edit the //! text field's state. Later, usually within a few milliseconds, the //! platform drops the `InputHandler`, allowing the application to once again //! make changes to the text field's state. These commands might be "insert //! `q`" for a smartphone user tapping on their virtual keyboard, or //! "move the caret one word left" for a user pressing the left arrow key //! while holding control. //! 7. Eventually, after many keypresses cause steps 3–6 to repeat, the user //! unfocuses the text field. The application indicates this to the platform //! by calling `set_focused_text_field`. Note that even though focus has //! shifted away from our text field, the platform may still send edits to it //! by calling `WinHandler::text_input`. //! 8. At some point, the user clicks a link or switches a tab, and the text //! field is no longer present in the window. The application calls //! `WindowHandle::remove_text_field`, and the platform may no longer call //! `WinHandler::text_input` to make changes to it. //! //! The application also has a series of steps it follows if it wants to make //! its own changes to the text field's state: //! //! 1. The application determines it would like to make a change to the text //! field; perhaps the user has scrolled and and the text field has changed //! its visible location on screen, or perhaps the user has clicked to move //! the caret to a new location. //! 2. The application first checks to see if there's an outstanding //! `InputHandler` lock for this text field; if so, it waits until the last //! `InputHandler` is dropped before continuing. //! 3. The application then makes the change to the text input. If the change //! would affect state visible from an `InputHandler`, the application must //! notify the platform via `WinHandler::update_text_field`. //! //! ## Supported Platforms //! //! Currently, `druid-shell` text input is fully implemented on macOS. Our goal //! is to have full support for all `druid-shell` targets, but for now, //! `InputHandler` calls are simulated from keypresses on other platforms, which //! doesn't allow for IME input, dead keys, etc. use crate::keyboard::{KbKey, KeyEvent}; use crate::kurbo::{Point, Rect}; use crate::piet::HitTestPoint; use crate::window::{TextFieldToken, WinHandler}; use std::borrow::Cow; use std::ops::Range; /// An event representing an application-initiated change in [`InputHandler`] /// state. /// /// When we change state that may have previously been retrieved from an /// [`InputHandler`], we notify the platform so that it can invalidate any /// data if necessary. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Event { /// Indicates the value returned by `InputHandler::selection` may have changed. SelectionChanged, /// Indicates the values returned by one or more of these methods may have changed: /// - `InputHandler::hit_test_point` /// - `InputHandler::line_range` /// - `InputHandler::bounding_box` /// - `InputHandler::slice_bounding_box` LayoutChanged, /// Indicates any value returned from any `InputHandler` method may have changed. Reset, } /// A range of selected text, or a caret. /// /// A caret is the blinking vertical bar where text is to be inserted. We /// represent it as a selection with zero length, where `anchor == active`. /// Indices are always expressed in UTF-8 bytes, and must be between 0 and the /// document length, inclusive. /// /// As an example, if the input caret is at the start of the document `hello /// world`, we would expect both `anchor` and `active` to be `0`. If the user /// holds shift and presses the right arrow key five times, we would expect the /// word `hello` to be selected, the `anchor` to still be `0`, and the `active` /// to now be `5`. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] pub struct Selection { /// The 'anchor' end of the selection. /// /// This is the end of the selection that stays unchanged while holding /// shift and pressing the arrow keys. pub anchor: usize, /// The 'active' end of the selection. /// /// This is the end of the selection that moves while holding shift and /// pressing the arrow keys. pub active: usize, /// The saved horizontal position, during vertical movement. /// /// This should not be set by the IME; it will be tracked and handled by /// the text field. pub h_pos: Option<f64>, } #[allow(clippy::len_without_is_empty)] impl Selection { /// Create a new `Selection` with the provided `anchor` and `active` positions. /// /// Both positions refer to UTF-8 byte indices in some text. /// /// If your selection is a caret, you can use [`Selection::caret`] instead. pub fn new(anchor: usize, active: usize) -> Selection { Selection { anchor, active, h_pos: None, } } /// Create a new caret (zero-length selection) at the provided UTF-8 byte index. /// /// `index` must be a grapheme cluster boundary. pub fn caret(index: usize) -> Selection { Selection { anchor: index, active: index, h_pos: None, } } /// Construct a new selection from this selection, with the provided h_pos. /// /// # Note /// /// `h_pos` is used to track the *pixel* location of the cursor when moving /// vertically; lines may have available cursor positions at different /// positions, and arrowing down and then back up should always result /// in a cursor at the original starting location; doing this correctly /// requires tracking this state. /// /// You *probably* don't need to use this, unless you are implementing a new /// text field, or otherwise implementing vertical cursor motion, in which /// case you will want to set this during vertical motion if it is not /// already set. pub fn with_h_pos(mut self, h_pos: Option<f64>) -> Self { self.h_pos = h_pos; self } /// Create a new selection that is guaranteed to be valid for the provided /// text. #[must_use = "constrained constructs a new Selection"] pub fn constrained(mut self, s: &str) -> Self { let s_len = s.len(); self.anchor = self.anchor.min(s_len); self.active = self.active.min(s_len); while !s.is_char_boundary(self.anchor) { self.anchor += 1; } while !s.is_char_boundary(self.active) { self.active += 1; } self } /// Return the position of the upstream end of the selection. /// /// This is end with the lesser byte index. /// /// Because of bidirectional text, this is not necessarily "left". pub fn min(&self) -> usize { usize::min(self.anchor, self.active) } /// Return the position of the downstream end of the selection. /// /// This is the end with the greater byte index. /// /// Because of bidirectional text, this is not necessarily "right". pub fn max(&self) -> usize { usize::max(self.anchor, self.active) } /// The sequential range of the document represented by this selection. /// /// This is the range that would be replaced if text were inserted at this /// selection. pub fn range(&self) -> Range<usize> { self.min()..self.max() } /// The length, in bytes of the selected region. /// /// If the selection is a caret, this is `0`. pub fn len(&self) -> usize { self.anchor.abs_diff(self.active) } /// Returns `true` if the selection's length is `0`. pub fn is_caret(&self) -> bool { self.len() == 0 } } /// A lock on a text field that allows the platform to retrieve state and make /// edits. /// /// This trait is implemented by the application or UI framework. The platform /// acquires this lock temporarily to apply edits corresponding to some user /// input. So long as the `InputHandler` has not been dropped, the only changes /// to the document state must come from calls to `InputHandler`. /// /// Some methods require a mutable lock, as indicated when acquiring the lock /// with `WinHandler::text_input`. If a mutable method is called on a immutable /// lock, `InputHandler` may panic. /// /// All ranges, lengths, and indices are specified in UTF-8 code units, unless /// specified otherwise. pub trait InputHandler { /// The document's current [`Selection`]. /// /// If the selection is a vertical caret bar, then `range.start == range.end`. /// Both `selection.anchor` and `selection.active` must be less than or /// equal to the value returned from `InputHandler::len()`, and must land on /// a extended grapheme cluster boundary in the document. fn selection(&self) -> Selection; /// Set the document's selection. /// /// If the selection is a vertical caret bar, then `range.start == range.end`. /// Both `selection.anchor` and `selection.active` must be less /// than or equal to the value returned from `InputHandler::len()`. /// /// Properties of the `Selection` *other* than `anchor` and `active` may /// be ignored by the handler. /// /// The `set_selection` implementation should round up (downstream) both /// `selection.anchor` and `selection.active` to the nearest extended /// grapheme cluster boundary. /// /// Requires a mutable lock. fn set_selection(&mut self, selection: Selection); /// The current composition region. /// /// This should be `Some` only if the IME is currently active, in which /// case it represents the range of text that may be modified by the IME. /// /// Both `range.start` and `range.end` must be less than or equal /// to the value returned from `InputHandler::len()`, and must land on a /// extended grapheme cluster boundary in the document. fn composition_range(&self) -> Option<Range<usize>>; /// Set the composition region. /// /// If this is `Some` it means that the IME is currently active for this /// region of the document. If it is `None` it means that the IME is not /// currently active. /// /// Both `range.start` and `range.end` must be less than or equal to the /// value returned from `InputHandler::len()`. /// /// The `set_selection` implementation should round up (downstream) both /// `range.start` and `range.end` to the nearest extended grapheme cluster /// boundary. /// /// Requires a mutable lock. fn set_composition_range(&mut self, range: Option<Range<usize>>); /// Check if the provided index is the first byte of a UTF-8 code point /// sequence, or is the end of the document. /// /// Equivalent in functionality to [`str::is_char_boundary`]. fn is_char_boundary(&self, i: usize) -> bool; /// The length of the document in UTF-8 code units. fn len(&self) -> usize; /// Returns `true` if the length of the document is `0`. fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the subslice of the document represented by `range`. /// /// # Panics /// /// Panics if the start or end of the range do not fall on a code point /// boundary. fn slice(&self, range: Range<usize>) -> Cow<'_, str>; /// Returns the number of UTF-16 code units in the provided UTF-8 range. /// /// Converts the document into UTF-8, looks up the range specified by /// `utf8_range` (in UTF-8 code units), reencodes that substring into /// UTF-16, and then returns the number of UTF-16 code units in that /// substring. /// /// This is automatically implemented, but you can override this if you have /// some faster system to determine string length. /// /// # Panics /// /// Panics if the start or end of the range do not fall on a code point /// boundary. fn utf8_to_utf16(&self, utf8_range: Range<usize>) -> usize { self.slice(utf8_range).encode_utf16().count() } /// Returns the number of UTF-8 code units in the provided UTF-16 range. /// /// Converts the document into UTF-16, looks up the range specified by /// `utf16_range` (in UTF-16 code units), reencodes that substring into /// UTF-8, and then returns the number of UTF-8 code units in that /// substring. /// /// This is automatically implemented, but you can override this if you have /// some faster system to determine string length. fn utf16_to_utf8(&self, utf16_range: Range<usize>) -> usize { if utf16_range.is_empty() { return 0; } let doc_range = 0..self.len(); let text = self.slice(doc_range); //FIXME: we can do this without allocating; there's an impl in piet let utf16: Vec<u16> = text .encode_utf16() .skip(utf16_range.start) .take(utf16_range.end) .collect(); String::from_utf16_lossy(&utf16).len() } /// Replaces a range of the text document with `text`. /// /// This method also sets the composition range to `None`, and updates the /// selection: /// /// - If both the selection's anchor and active are `< range.start`, then nothing is updated. /// - If both the selection's anchor and active are `> range.end`, then subtract `range.len()` /// from both, and add `text.len()`. /// - If neither of the previous two conditions are true, then set both anchor and active to /// `range.start + text.len()`. /// /// After the above update, if we increase each end of the selection if /// necessary to put it on a grapheme cluster boundary. /// /// Requires a mutable lock. /// /// # Panics /// /// Panics if either end of the range does not fall on a code point /// boundary. fn replace_range(&mut self, range: Range<usize>, text: &str); /// Given a `Point`, determine the corresponding text position. fn hit_test_point(&self, point: Point) -> HitTestPoint; /// Returns the range, in UTF-8 code units, of the line (soft- or hard-wrapped) /// containing the byte specified by `index`. fn line_range(&self, index: usize, affinity: Affinity) -> Range<usize>; /// Returns the bounding box, in window coordinates, of the visible text /// document. /// /// For instance, a text box's bounding box would be the rectangle /// of the border surrounding it, even if the text box is empty. If the /// text document is completely offscreen, return `None`. fn bounding_box(&self) -> Option<Rect>; /// Returns the bounding box, in window coordinates, of the range of text specified by `range`. /// /// Ranges will always be equal to or a subrange of some line range returned /// by `InputHandler::line_range`. If a range spans multiple lines, /// `slice_bounding_box` may panic. fn slice_bounding_box(&self, range: Range<usize>) -> Option<Rect>; /// Applies an [`Action`] to the text field. /// /// Requires a mutable lock. fn handle_action(&mut self, action: Action); } #[allow(dead_code)] /// Simulates `InputHandler` calls on `handler` for a given keypress `event`. /// /// This circumvents the platform, and so can't work with important features /// like input method editors! However, it's necessary while we build up our /// input support on various platforms, which takes a lot of time. We want /// applications to start building on the new `InputHandler` interface /// immediately, with a hopefully seamless upgrade process as we implement IME /// input on more platforms. pub fn simulate_input<H: WinHandler + ?Sized>( handler: &mut H, token: Option<TextFieldToken>, event: KeyEvent, ) -> bool { if handler.key_down(event.clone()) { return true; } let token = match token { Some(v) => v, None => return false, }; let mut input_handler = handler.acquire_input_lock(token, true); match event.key { KbKey::Character(c) if !event.mods.ctrl() && !event.mods.meta() && !event.mods.alt() => { let selection = input_handler.selection(); input_handler.replace_range(selection.range(), &c); let new_caret_index = selection.min() + c.len(); input_handler.set_selection(Selection::caret(new_caret_index)); } KbKey::ArrowLeft => { let movement = if event.mods.ctrl() { Movement::Word(Direction::Left) } else { Movement::Grapheme(Direction::Left) }; if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::ArrowRight => { let movement = if event.mods.ctrl() { Movement::Word(Direction::Right) } else { Movement::Grapheme(Direction::Right) }; if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::ArrowUp => { let movement = Movement::Vertical(VerticalMovement::LineUp); if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::ArrowDown => { let movement = Movement::Vertical(VerticalMovement::LineDown); if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::Backspace => { let movement = if event.mods.ctrl() { Movement::Word(Direction::Upstream) } else { Movement::Grapheme(Direction::Upstream) }; input_handler.handle_action(Action::Delete(movement)); } KbKey::Delete => { let movement = if event.mods.ctrl() { Movement::Word(Direction::Downstream) } else { Movement::Grapheme(Direction::Downstream) }; input_handler.handle_action(Action::Delete(movement)); } KbKey::Enter => { // I'm sorry windows, you'll get IME soon. input_handler.handle_action(Action::InsertNewLine { ignore_hotkey: false, newline_type: '\n', }); } KbKey::Tab => { let action = if event.mods.shift() { Action::InsertBacktab } else { Action::InsertTab { ignore_hotkey: false, } }; input_handler.handle_action(action); } KbKey::Home => { let movement = if event.mods.ctrl() { Movement::Vertical(VerticalMovement::DocumentStart) } else { Movement::Line(Direction::Upstream) }; if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::End => { let movement = if event.mods.ctrl() { Movement::Vertical(VerticalMovement::DocumentEnd) } else { Movement::Line(Direction::Downstream) }; if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::PageUp => { let movement = Movement::Vertical(VerticalMovement::PageUp); if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } KbKey::PageDown => { let movement = Movement::Vertical(VerticalMovement::PageDown); if event.mods.shift() { input_handler.handle_action(Action::MoveSelecting(movement)); } else { input_handler.handle_action(Action::Move(movement)); } } _ => { handler.release_input_lock(token); return false; } }; handler.release_input_lock(token); true } /// Indicates a movement that transforms a particular text position in a /// document. /// /// These movements transform only single indices — not selections. /// /// You'll note that a lot of these operations are idempotent, but you can get /// around this by first sending a `Grapheme` movement. If for instance, you /// want a `ParagraphStart` that is not idempotent, you can first send /// `Movement::Grapheme(Direction::Upstream)`, and then follow it with /// `ParagraphStart`. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Movement { /// A movement that stops when it reaches an extended grapheme cluster boundary. /// /// This movement is achieved on most systems by pressing the left and right /// arrow keys. For more information on grapheme clusters, see /// [Unicode Text Segmentation](https://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries). Grapheme(Direction), /// A movement that stops when it reaches a word boundary. /// /// This movement is achieved on most systems by pressing the left and right /// arrow keys while holding control. For more information on words, see /// [Unicode Text Segmentation](https://unicode.org/reports/tr29/#Word_Boundaries). Word(Direction), /// A movement that stops when it reaches a soft line break. /// /// This movement is achieved on macOS by pressing the left and right arrow /// keys while holding command. `Line` should be idempotent: if the /// position is already at the end of a soft-wrapped line, this movement /// should never push it onto another soft-wrapped line. /// /// In order to implement this properly, your text positions should remember /// their affinity. Line(Direction), /// An upstream movement that stops when it reaches a hard line break. /// /// `ParagraphStart` should be idempotent: if the position is already at the /// start of a hard-wrapped line, this movement should never push it onto /// the previous line. ParagraphStart, /// A downstream movement that stops when it reaches a hard line break. /// /// `ParagraphEnd` should be idempotent: if the position is already at the /// end of a hard-wrapped line, this movement should never push it onto the /// next line. ParagraphEnd, /// A vertical movement, see `VerticalMovement` for more details. Vertical(VerticalMovement), } /// Indicates a horizontal direction in the text. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Direction { /// The direction visually to the left. /// /// This may be byte-wise forwards or backwards in the document, depending /// on the text direction around the position being moved. Left, /// The direction visually to the right. /// /// This may be byte-wise forwards or backwards in the document, depending /// on the text direction around the position being moved. Right, /// Byte-wise backwards in the document. /// /// In a left-to-right context, this value is the same as `Left`. Upstream, /// Byte-wise forwards in the document. /// /// In a left-to-right context, this value is the same as `Right`. Downstream, } impl Direction { /// Returns `true` if this direction is byte-wise backwards for /// the provided [`WritingDirection`]. /// /// The provided direction *must not be* `WritingDirection::Natural`. pub fn is_upstream_for_direction(self, direction: WritingDirection) -> bool { assert!( !matches!(direction, WritingDirection::Natural), "writing direction must be resolved" ); match self { Direction::Upstream => true, Direction::Downstream => false, Direction::Left => matches!(direction, WritingDirection::LeftToRight), Direction::Right => matches!(direction, WritingDirection::RightToLeft), } } } /// Distinguishes between two visually distinct locations with the same byte /// index. /// /// Sometimes, a byte location in a document has two visual locations. For /// example, the end of a soft-wrapped line and the start of the subsequent line /// have different visual locations (and we want to be able to place an input /// caret in either place!) but the same byte-wise location. This also shows up /// in bidirectional text contexts. Affinity allows us to disambiguate between /// these two visual locations. pub enum Affinity { Upstream, Downstream, } /// Indicates a horizontal direction for writing text. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum WritingDirection { LeftToRight, RightToLeft, /// Indicates writing direction should be automatically detected based on /// the text contents. Natural, } /// Indicates a vertical movement in a text document. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum VerticalMovement { LineUp, LineDown, PageUp, PageDown, DocumentStart, DocumentEnd, } /// A special text editing command sent from the platform to the application. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Action { /// Moves the selection. /// /// Before moving, if the active and the anchor of the selection are not at /// the same position (it's a non-caret selection), then: /// /// 1. First set both active and anchor to the same position: the /// selection's upstream index if `Movement` is an upstream movement, or /// the downstream index if `Movement` is a downstream movement. /// /// 2. If `Movement` is `Grapheme`, then stop. Otherwise, apply the /// `Movement` as per the usual rules. Move(Movement), /// Moves just the selection's active edge. /// /// Equivalent to holding shift while performing movements or clicks on most /// operating systems. MoveSelecting(Movement), /// Select the entire document. SelectAll, /// Expands the selection to the entire soft-wrapped line. /// /// If multiple lines are already selected, expands the selection to /// encompass all soft-wrapped lines that intersected with the prior /// selection. If the selection is a caret is on a soft line break, uses /// the affinity of the caret to determine which of the two lines to select. /// `SelectLine` should be idempotent: it should never expand onto adjacent /// lines. SelectLine, /// Expands the selection to the entire hard-wrapped line. /// /// If multiple lines are already selected, expands the selection to /// encompass all hard-wrapped lines that intersected with the prior /// selection. `SelectParagraph` should be idempotent: it should never /// expand onto adjacent lines. SelectParagraph, /// Expands the selection to the entire word. /// /// If multiple words are already selected, expands the selection to /// encompass all words that intersected with the prior selection. If the /// selection is a caret is on a word boundary, selects the word downstream /// of the caret. `SelectWord` should be idempotent: it should never expand /// onto adjacent words. /// /// For more information on what these so-called "words" are, see /// [Unicode Text Segmentation](https://unicode.org/reports/tr29/#Word_Boundaries). SelectWord, /// Deletes some text. /// /// If some text is already selected, `Movement` is ignored, and the /// selection is deleted. If the selection's anchor is the same as the /// active, then first apply `MoveSelecting(Movement)` and then delete the /// resulting selection. Delete(Movement), /// Delete backwards, potentially breaking graphemes. /// /// A special kind of backspace that, instead of deleting the entire /// grapheme upstream of the caret, may in some cases and character sets /// delete a subset of that grapheme's code points. DecomposingBackspace, /// Maps the characters in the selection to uppercase. /// /// For more information on case mapping, see the /// [Unicode Case Mapping FAQ](https://unicode.org/faq/casemap_charprop.html#7) UppercaseSelection, /// Maps the characters in the selection to lowercase. ///
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/error.rs
druid-shell/src/error.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Errors at the application shell level. use std::fmt; use std::sync::Arc; use crate::backend::error as backend; /// Shell errors. #[derive(Debug, Clone)] pub enum Error { /// The Application instance has already been created. ApplicationAlreadyExists, /// Tried to use the application after it had been dropped. ApplicationDropped, /// The window has already been destroyed. WindowDropped, /// Platform specific error. Platform(backend::Error), /// Other miscellaneous error. Other(Arc<anyhow::Error>), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { Error::ApplicationAlreadyExists => { write!(f, "An application instance has already been created.") } Error::ApplicationDropped => { write!( f, "The application this operation requires has been dropped." ) } Error::Platform(err) => fmt::Display::fmt(err, f), Error::WindowDropped => write!(f, "The window has already been destroyed."), Error::Other(s) => write!(f, "{s}"), } } } impl std::error::Error for Error {} impl From<anyhow::Error> for Error { fn from(src: anyhow::Error) -> Error { Error::Other(Arc::new(src)) } } impl From<backend::Error> for Error { fn from(src: backend::Error) -> Error { Error::Platform(src) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/application.rs
druid-shell/src/application.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The top-level application type. use std::cell::RefCell; use std::rc::Rc; use std::sync::atomic::{AtomicBool, Ordering}; use crate::backend::application as backend; use crate::clipboard::Clipboard; use crate::error::Error; use crate::util; /// A top-level handler that is not associated with any window. /// /// This is most important on macOS, where it is entirely normal for /// an application to exist with no open windows. /// /// # Note /// /// This is currently very limited in its functionality, and is currently /// designed to address a single case, which is handling menu commands when /// no window is open. /// /// It is possible that this will expand to cover additional functionality /// in the future. pub trait AppHandler { /// Called when a menu item is selected. #[allow(unused_variables)] fn command(&mut self, id: u32) {} } /// The top level application object. /// /// This can be thought of as a reference and it can be safely cloned. #[derive(Clone)] pub struct Application { pub(crate) backend_app: backend::Application, state: Rc<RefCell<State>>, } /// Platform-independent `Application` state. struct State { running: bool, } /// Used to ensure only one Application instance is ever created. static APPLICATION_CREATED: AtomicBool = AtomicBool::new(false); thread_local! { /// A reference object to the current `Application`, if any. static GLOBAL_APP: RefCell<Option<Application>> = const { RefCell::new(None) }; } impl Application { /// Create a new `Application`. /// /// # Errors /// /// Errors if an `Application` has already been created. /// /// This may change in the future. See [druid#771] for discussion. /// /// [druid#771]: https://github.com/linebender/druid/issues/771 pub fn new() -> Result<Application, Error> { APPLICATION_CREATED .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .map_err(|_| Error::ApplicationAlreadyExists)?; util::claim_main_thread(); let backend_app = backend::Application::new()?; let state = Rc::new(RefCell::new(State { running: false })); let app = Application { backend_app, state }; GLOBAL_APP.with(|global_app| { *global_app.borrow_mut() = Some(app.clone()); }); Ok(app) } /// Get the current globally active `Application`. /// /// A globally active `Application` exists /// after [`new`] is called and until [`run`] returns. /// /// # Panics /// /// Panics if there is no globally active `Application`. /// For a non-panicking function use [`try_global`]. /// /// This function will also panic if called from a non-main thread. /// /// [`new`]: #method.new /// [`run`]: #method.run /// [`try_global`]: #method.try_global #[inline] pub fn global() -> Application { // Main thread assertion takes place in try_global() Application::try_global().expect("There is no globally active Application") } /// Get the current globally active `Application`. /// /// A globally active `Application` exists /// after [`new`] is called and until [`run`] returns. /// /// # Panics /// /// Panics if called from a non-main thread. /// /// [`new`]: #method.new /// [`run`]: #method.run pub fn try_global() -> Option<Application> { util::assert_main_thread_or_main_unclaimed(); GLOBAL_APP.with(|global_app| global_app.borrow().clone()) } /// Start the `Application` runloop. /// /// The provided `handler` will be used to inform of events. /// /// This will consume the `Application` and block the current thread /// until the `Application` has finished executing. /// /// # Panics /// /// Panics if the `Application` is already running. pub fn run(self, handler: Option<Box<dyn AppHandler>>) { // Make sure this application hasn't run() yet. if let Ok(mut state) = self.state.try_borrow_mut() { if state.running { panic!("Application is already running"); } state.running = true; } else { panic!("Application state already borrowed"); } // Run the platform application self.backend_app.run(handler); // This application is no longer active, so clear the global reference GLOBAL_APP.with(|global_app| { *global_app.borrow_mut() = None; }); // .. and release the main thread util::release_main_thread(); // .. and mark as done so a new sequence can start APPLICATION_CREATED .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire) .expect("Application marked as not created while still running."); } /// Quit the `Application`. /// /// This will cause [`run`] to return control back to the calling function. /// /// [`run`]: #method.run pub fn quit(&self) { self.backend_app.quit() } /// Returns a handle to the system clipboard. pub fn clipboard(&self) -> Clipboard { self.backend_app.clipboard().into() } /// Returns the current locale string. /// /// This should a [Unicode language identifier]. /// /// [Unicode language identifier]: https://unicode.org/reports/tr35/#Unicode_language_identifier pub fn get_locale() -> String { backend::Application::get_locale() } } /// Perform any initialization needed for the testing harness. pub fn init_harness() { backend::init_harness(); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/scale.rs
druid-shell/src/scale.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Resolution scale related helpers. use crate::kurbo::{Insets, Line, Point, Rect, Size, Vec2}; /// Coordinate scaling between pixels and display points. /// /// This holds the platform scale factors. /// /// ## Pixels and Display Points /// /// A pixel (**px**) represents the smallest controllable area of color on the platform. /// A display point (**dp**) is a resolution independent logical unit. /// When developing your application you should primarily be thinking in display points. /// These display points will be automatically converted into pixels under the hood. /// One pixel is equal to one display point when the platform scale factor is `1.0`. /// /// Read more about pixels and display points [in the Druid book]. /// /// ## Converting with `Scale` /// /// To translate coordinates between pixels and display points you should use one of the /// helper conversion methods of `Scale` or for manual conversion [`x`] / [`y`]. /// /// `Scale` is designed for responsive applications, including responding to platform scale changes. /// The platform scale can change quickly, e.g. when moving a window from one monitor to another. /// /// A copy of `Scale` will be stale as soon as the platform scale changes. /// /// [`x`]: #method.x /// [`y`]: #method.y /// [in the Druid book]: https://linebender.org/druid/07_resolution_independence.html #[derive(Copy, Clone, PartialEq, Debug)] pub struct Scale { /// The scale factor on the x axis. x: f64, /// The scale factor on the y axis. y: f64, } /// A specific area scaling state. /// /// This holds the platform area size in pixels and the logical area size in display points. /// /// The platform area size in pixels tends to be limited to integers and `ScaledArea` works /// under that assumption. /// /// The logical area size in display points is an unrounded conversion, which means that it is /// often not limited to integers. This allows for accurate calculations of /// the platform area pixel boundaries from the logical area using a [`Scale`]. /// /// Even though the logical area size can be fractional, the integer boundaries of that logical area /// will still match up with the platform area pixel boundaries as often as the scale factor allows. /// /// A copy of `ScaledArea` will be stale as soon as the platform area size changes. /// /// [`Scale`]: struct.Scale.html #[derive(Copy, Clone, PartialEq, Debug)] pub struct ScaledArea { /// The size of the scaled area in display points. size_dp: Size, /// The size of the scaled area in pixels. size_px: Size, } /// The `Scalable` trait describes how coordinates should be translated /// from display points into pixels and vice versa using a [`Scale`]. /// /// [`Scale`]: struct.Scale.html pub trait Scalable { /// Converts the scalable item from display points into pixels, /// using the x axis scale factor for coordinates on the x axis /// and the y axis scale factor for coordinates on the y axis. fn to_px(&self, scale: Scale) -> Self; /// Converts the scalable item from pixels into display points, /// using the x axis scale factor for coordinates on the x axis /// and the y axis scale factor for coordinates on the y axis. fn to_dp(&self, scale: Scale) -> Self; } impl Default for Scale { fn default() -> Scale { Scale { x: 1.0, y: 1.0 } } } impl Scale { /// Create a new `Scale` based on the specified axis factors. /// /// Units: none (scale relative to "standard" scale) pub fn new(x: f64, y: f64) -> Scale { Scale { x, y } } /// Returns the x axis scale factor. #[inline] pub fn x(self) -> f64 { self.x } /// Returns the y axis scale factor. #[inline] pub fn y(self) -> f64 { self.y } /// Converts from pixels into display points, using the x axis scale factor. #[inline] pub fn px_to_dp_x<T: Into<f64>>(self, x: T) -> f64 { x.into() / self.x } /// Converts from pixels into display points, using the y axis scale factor. #[inline] pub fn px_to_dp_y<T: Into<f64>>(self, y: T) -> f64 { y.into() / self.y } /// Converts from pixels into display points, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] pub fn px_to_dp_xy<T: Into<f64>>(self, x: T, y: T) -> (f64, f64) { (x.into() / self.x, y.into() / self.y) } } impl Scalable for Vec2 { /// Converts a `Vec2` from display points into pixels, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] fn to_px(&self, scale: Scale) -> Vec2 { Vec2::new(self.x * scale.x, self.y * scale.y) } /// Converts a `Vec2` from pixels into display points, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] fn to_dp(&self, scale: Scale) -> Vec2 { Vec2::new(self.x / scale.x, self.y / scale.y) } } impl Scalable for Point { /// Converts a `Point` from display points into pixels, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] fn to_px(&self, scale: Scale) -> Point { Point::new(self.x * scale.x, self.y * scale.y) } /// Converts a `Point` from pixels into display points, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] fn to_dp(&self, scale: Scale) -> Point { Point::new(self.x / scale.x, self.y / scale.y) } } impl Scalable for Line { /// Converts a `Line` from display points into pixels, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] fn to_px(&self, scale: Scale) -> Line { Line::new(self.p0.to_px(scale), self.p1.to_px(scale)) } /// Converts a `Line` from pixels into display points, /// using the x axis scale factor for `x` and the y axis scale factor for `y`. #[inline] fn to_dp(&self, scale: Scale) -> Line { Line::new(self.p0.to_dp(scale), self.p1.to_dp(scale)) } } impl Scalable for Size { /// Converts a `Size` from display points into pixels, /// using the x axis scale factor for `width` /// and the y axis scale factor for `height`. #[inline] fn to_px(&self, scale: Scale) -> Size { Size::new(self.width * scale.x, self.height * scale.y) } /// Converts a `Size` from pixels into points, /// using the x axis scale factor for `width` /// and the y axis scale factor for `height`. #[inline] fn to_dp(&self, scale: Scale) -> Size { Size::new(self.width / scale.x, self.height / scale.y) } } impl Scalable for Rect { /// Converts a `Rect` from display points into pixels, /// using the x axis scale factor for `x0` and `x1` /// and the y axis scale factor for `y0` and `y1`. #[inline] fn to_px(&self, scale: Scale) -> Rect { Rect::new( self.x0 * scale.x, self.y0 * scale.y, self.x1 * scale.x, self.y1 * scale.y, ) } /// Converts a `Rect` from pixels into display points, /// using the x axis scale factor for `x0` and `x1` /// and the y axis scale factor for `y0` and `y1`. #[inline] fn to_dp(&self, scale: Scale) -> Rect { Rect::new( self.x0 / scale.x, self.y0 / scale.y, self.x1 / scale.x, self.y1 / scale.y, ) } } impl Scalable for Insets { /// Converts `Insets` from display points into pixels, /// using the x axis scale factor for `x0` and `x1` /// and the y axis scale factor for `y0` and `y1`. #[inline] fn to_px(&self, scale: Scale) -> Insets { Insets::new( self.x0 * scale.x, self.y0 * scale.y, self.x1 * scale.x, self.y1 * scale.y, ) } /// Converts `Insets` from pixels into display points, /// using the x axis scale factor for `x0` and `x1` /// and the y axis scale factor for `y0` and `y1`. #[inline] fn to_dp(&self, scale: Scale) -> Insets { Insets::new( self.x0 / scale.x, self.y0 / scale.y, self.x1 / scale.x, self.y1 / scale.y, ) } } impl Default for ScaledArea { fn default() -> ScaledArea { ScaledArea { size_dp: Size::ZERO, size_px: Size::ZERO, } } } impl ScaledArea { /// Create a new scaled area from pixels. pub fn from_px<T: Into<Size>>(size: T, scale: Scale) -> ScaledArea { let size_px = size.into(); let size_dp = size_px.to_dp(scale); ScaledArea { size_dp, size_px } } /// Create a new scaled area from display points. /// /// The calculated size in pixels is rounded away from zero to integers. /// That means that the scaled area size in display points isn't always the same /// as the `size` given to this function. To find out the new size in points use [`size_dp`]. /// /// [`size_dp`]: #method.size_dp pub fn from_dp<T: Into<Size>>(size: T, scale: Scale) -> ScaledArea { let size_px = size.into().to_px(scale).expand(); let size_dp = size_px.to_dp(scale); ScaledArea { size_dp, size_px } } /// Returns the scaled area size in display points. #[inline] pub fn size_dp(&self) -> Size { self.size_dp } /// Returns the scaled area size in pixels. #[inline] pub fn size_px(&self) -> Size { self.size_px } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/util.rs
druid-shell/src/util.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Utility functions for determining the main thread. use std::mem; use std::sync::atomic::{AtomicU64, Ordering}; use std::thread; static MAIN_THREAD_ID: AtomicU64 = AtomicU64::new(0); #[inline] fn current_thread_id() -> u64 { // TODO: Use .as_u64() instead of mem::transmute // when .as_u64() or something similar gets stabilized. unsafe { mem::transmute(thread::current().id()) } } /// Assert that the current thread is the registered main thread or main thread is not claimed. /// /// # Panics /// /// Panics when called from a non-main thread and main thread is claimed. pub(crate) fn assert_main_thread_or_main_unclaimed() { let thread_id = current_thread_id(); let main_thread_id = MAIN_THREAD_ID.load(Ordering::Acquire); if thread_id != main_thread_id && main_thread_id != 0 { panic!("Main thread assertion failed {thread_id} != {main_thread_id}"); } } /// Register the current thread as the main thread. /// /// # Panics /// /// Panics if the main thread has already been claimed by another thread. pub(crate) fn claim_main_thread() { let thread_id = current_thread_id(); let old_thread_id = MAIN_THREAD_ID.compare_exchange(0, thread_id, Ordering::AcqRel, Ordering::Acquire); match old_thread_id { Ok(0) => (), Ok(_) => unreachable!(), // not possible per the docs Err(0) => { tracing::warn!("The main thread status was already claimed by the current thread.") } Err(k) => panic!("The main thread status has already been claimed by thread {k}"), } } /// Removes the main thread status of the current thread. /// /// # Panics /// /// Panics if the main thread status is owned by another thread. pub(crate) fn release_main_thread() { let thread_id = current_thread_id(); let old_thread_id = MAIN_THREAD_ID.compare_exchange(thread_id, 0, Ordering::AcqRel, Ordering::Acquire); match old_thread_id { Ok(n) if n == thread_id => (), Ok(_) => unreachable!(), // not possible per the docs Err(0) => tracing::warn!("The main thread status was already vacant."), Err(k) => panic!("The main thread status has already been claimed by thread {k}"), } } /// Wrapper around `RefCell::borrow` that provides error context. // These are currently only used in the X11 backend, so suppress the unused warning in other // backends. #[allow(unused_macros)] macro_rules! borrow { ($val:expr) => {{ use anyhow::Context; $val.try_borrow().with_context(|| { format!( "[{}:{}] {}", std::file!(), std::line!(), std::stringify!($val) ) }) }}; } /// Wrapper around `RefCell::borrow_mut` that provides error context. #[allow(unused_macros)] macro_rules! borrow_mut { ($val:expr) => {{ use anyhow::Context; $val.try_borrow_mut().with_context(|| { format!( "[{}:{}] {}", std::file!(), std::line!(), std::stringify!($val) ) }) }}; } /// This is a useful way to clone some values into a `move` closure. Currently only used in the /// Wayland backend. #[allow(unused_macros)] macro_rules! with_cloned { ($($val:ident),* ; $($rest:tt)*) => { { $( let $val = $val.clone(); )* $($rest)* } }; }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/hotkey.rs
druid-shell/src/hotkey.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Hotkeys and helpers for parsing keyboard shortcuts. use std::borrow::Borrow; use tracing::warn; use crate::{IntoKey, KbKey, KeyEvent, Modifiers}; // TODO: fix docstring /// A description of a keyboard shortcut. /// /// This type is only intended to be used to describe shortcuts, /// and recognize them when they arrive. /// /// # Examples /// /// [`SysMods`] matches the Command key on macOS and Ctrl elsewhere: /// /// ``` /// use druid_shell::{HotKey, KbKey, KeyEvent, RawMods, SysMods}; /// /// let hotkey = HotKey::new(SysMods::Cmd, "a"); /// /// #[cfg(target_os = "macos")] /// assert!(hotkey.matches(KeyEvent::for_test(RawMods::Meta, "a"))); /// /// #[cfg(target_os = "windows")] /// assert!(hotkey.matches(KeyEvent::for_test(RawMods::Ctrl, "a"))); /// ``` /// /// `None` matches only the key without modifiers: /// /// ``` /// use druid_shell::{HotKey, KbKey, KeyEvent, RawMods, SysMods}; /// /// let hotkey = HotKey::new(None, KbKey::ArrowLeft); /// /// assert!(hotkey.matches(KeyEvent::for_test(RawMods::None, KbKey::ArrowLeft))); /// assert!(!hotkey.matches(KeyEvent::for_test(RawMods::Ctrl, KbKey::ArrowLeft))); /// ``` /// /// [`SysMods`]: enum.SysMods.html #[derive(Debug, Clone, PartialEq, Eq)] pub struct HotKey { pub(crate) mods: RawMods, pub(crate) key: KbKey, } impl HotKey { /// Create a new hotkey. /// /// The first argument describes the keyboard modifiers. This can be `None`, /// or an instance of either [`SysMods`], or [`RawMods`]. [`SysMods`] unify the /// 'Command' key on macOS with the 'Ctrl' key on other platforms. /// /// The second argument describes the non-modifier key. This can be either /// a `&str` or a [`KbKey`]; the former is merely a convenient /// shorthand for `KbKey::Character()`. /// /// # Examples /// ``` /// use druid_shell::{HotKey, KbKey, RawMods, SysMods}; /// /// let select_all = HotKey::new(SysMods::Cmd, "a"); /// let esc = HotKey::new(None, KbKey::Escape); /// let macos_fullscreen = HotKey::new(RawMods::CtrlMeta, "f"); /// ``` /// /// [`Key`]: keyboard_types::Key /// [`SysMods`]: enum.SysMods.html /// [`RawMods`]: enum.RawMods.html pub fn new(mods: impl Into<Option<RawMods>>, key: impl IntoKey) -> Self { HotKey { mods: mods.into().unwrap_or(RawMods::None), key: key.into_key(), } .warn_if_needed() } //TODO: figure out if we need to be normalizing case or something? fn warn_if_needed(self) -> Self { if let KbKey::Character(s) = &self.key { let km: Modifiers = self.mods.into(); if km.shift() && s.chars().any(|c| c.is_lowercase()) { warn!( "warning: HotKey {:?} includes shift, but text is lowercase. \ Text is matched literally; this may cause problems.", &self ); } } self } /// Returns `true` if this [`KeyEvent`] matches this `HotKey`. /// /// [`KeyEvent`]: KeyEvent pub fn matches(&self, event: impl Borrow<KeyEvent>) -> bool { // Should be a const but const bit_or doesn't work here. let base_mods = Modifiers::SHIFT | Modifiers::CONTROL | Modifiers::ALT | Modifiers::META; let event = event.borrow(); self.mods == event.mods & base_mods && self.key == event.key } } /// A platform-agnostic representation of keyboard modifiers, for command handling. /// /// This does one thing: it allows specifying hotkeys that use the Command key /// on macOS, but use the Ctrl key on other platforms. #[derive(Debug, Clone, Copy)] pub enum SysMods { None, Shift, /// Command on macOS, and Ctrl on Windows/Linux/OpenBSD/FreeBSD Cmd, /// Command + Alt on macOS, Ctrl + Alt on Windows/Linux/OpenBSD/FreeBSD AltCmd, /// Command + Shift on macOS, Ctrl + Shift on Windows/Linux/OpenBSD/FreeBSD CmdShift, /// Command + Alt + Shift on macOS, Ctrl + Alt + Shift on Windows/Linux/OpenBSD/FreeBSD AltCmdShift, } //TODO: should something like this just _replace_ keymodifiers? /// A representation of the active modifier keys. /// /// This is intended to be clearer than `Modifiers`, when describing hotkeys. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RawMods { None, Alt, Ctrl, Meta, Shift, AltCtrl, AltMeta, AltShift, CtrlShift, CtrlMeta, MetaShift, AltCtrlMeta, AltCtrlShift, AltMetaShift, CtrlMetaShift, AltCtrlMetaShift, } impl std::cmp::PartialEq<Modifiers> for RawMods { fn eq(&self, other: &Modifiers) -> bool { let mods: Modifiers = (*self).into(); mods == *other } } impl std::cmp::PartialEq<RawMods> for Modifiers { fn eq(&self, other: &RawMods) -> bool { other == self } } impl std::cmp::PartialEq<Modifiers> for SysMods { fn eq(&self, other: &Modifiers) -> bool { let mods: RawMods = (*self).into(); mods == *other } } impl std::cmp::PartialEq<SysMods> for Modifiers { fn eq(&self, other: &SysMods) -> bool { let other: RawMods = (*other).into(); &other == self } } impl From<RawMods> for Modifiers { fn from(src: RawMods) -> Modifiers { let (alt, ctrl, meta, shift) = match src { RawMods::None => (false, false, false, false), RawMods::Alt => (true, false, false, false), RawMods::Ctrl => (false, true, false, false), RawMods::Meta => (false, false, true, false), RawMods::Shift => (false, false, false, true), RawMods::AltCtrl => (true, true, false, false), RawMods::AltMeta => (true, false, true, false), RawMods::AltShift => (true, false, false, true), RawMods::CtrlMeta => (false, true, true, false), RawMods::CtrlShift => (false, true, false, true), RawMods::MetaShift => (false, false, true, true), RawMods::AltCtrlMeta => (true, true, true, false), RawMods::AltMetaShift => (true, false, true, true), RawMods::AltCtrlShift => (true, true, false, true), RawMods::CtrlMetaShift => (false, true, true, true), RawMods::AltCtrlMetaShift => (true, true, true, true), }; let mut mods = Modifiers::empty(); mods.set(Modifiers::ALT, alt); mods.set(Modifiers::CONTROL, ctrl); mods.set(Modifiers::META, meta); mods.set(Modifiers::SHIFT, shift); mods } } // we do this so that HotKey::new can accept `None` as an initial argument. impl From<SysMods> for Option<RawMods> { fn from(src: SysMods) -> Option<RawMods> { Some(src.into()) } } impl From<SysMods> for RawMods { fn from(src: SysMods) -> RawMods { #[cfg(target_os = "macos")] match src { SysMods::None => RawMods::None, SysMods::Shift => RawMods::Shift, SysMods::Cmd => RawMods::Meta, SysMods::AltCmd => RawMods::AltMeta, SysMods::CmdShift => RawMods::MetaShift, SysMods::AltCmdShift => RawMods::AltMetaShift, } #[cfg(not(target_os = "macos"))] match src { SysMods::None => RawMods::None, SysMods::Shift => RawMods::Shift, SysMods::Cmd => RawMods::Ctrl, SysMods::AltCmd => RawMods::AltCtrl, SysMods::CmdShift => RawMods::CtrlShift, SysMods::AltCmdShift => RawMods::AltCtrlShift, } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/window.rs
druid-shell/src/window.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Platform independent window types. use std::any::Any; use std::time::Duration; use crate::application::Application; use crate::backend::window as backend; use crate::common_util::Counter; use crate::dialog::{FileDialogOptions, FileInfo}; use crate::error::Error; use crate::keyboard::KeyEvent; use crate::kurbo::{Insets, Point, Rect, Size}; use crate::menu::Menu; use crate::mouse::{Cursor, CursorDesc, MouseEvent}; use crate::region::Region; use crate::scale::Scale; use crate::text::{Event, InputHandler}; use piet_common::PietText; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; /// A token that uniquely identifies a running timer. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)] pub struct TimerToken(u64); impl TimerToken { /// A token that does not correspond to any timer. pub const INVALID: TimerToken = TimerToken(0); /// Create a new token. pub fn next() -> TimerToken { static TIMER_COUNTER: Counter = Counter::new(); TimerToken(TIMER_COUNTER.next()) } /// Create a new token from a raw value. pub const fn from_raw(id: u64) -> TimerToken { TimerToken(id) } /// Get the raw value for a token. pub const fn into_raw(self) -> u64 { self.0 } } /// Uniquely identifies a text input field inside a window. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)] pub struct TextFieldToken(u64); impl TextFieldToken { /// A token that does not correspond to any text input. pub const INVALID: TextFieldToken = TextFieldToken(0); /// Create a new token; this should for the most part be called only by platform code. pub fn next() -> TextFieldToken { static TEXT_FIELD_COUNTER: Counter = Counter::new(); TextFieldToken(TEXT_FIELD_COUNTER.next()) } /// Create a new token from a raw value. pub const fn from_raw(id: u64) -> TextFieldToken { TextFieldToken(id) } /// Get the raw value for a token. pub const fn into_raw(self) -> u64 { self.0 } } //NOTE: this has a From<backend::Handle> impl for construction /// A handle that can enqueue tasks on the window loop. #[derive(Clone)] pub struct IdleHandle(backend::IdleHandle); impl IdleHandle { /// Add an idle handler, which is called (once) when the message loop /// is empty. The idle handler will be run from the main UI thread, and /// won't be scheduled if the associated view has been dropped. /// /// Note: the name "idle" suggests that it will be scheduled with a lower /// priority than other UI events, but that's not necessarily the case. pub fn add_idle<F>(&self, callback: F) where F: FnOnce(&mut dyn WinHandler) + Send + 'static, { self.0.add_idle_callback(callback) } /// Request a callback from the runloop. Your `WinHander::idle` method will /// be called with the `token` that was passed in. pub fn schedule_idle(&mut self, token: IdleToken) { self.0.add_idle_token(token) } } /// A token that uniquely identifies a idle schedule. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)] pub struct IdleToken(usize); impl IdleToken { /// Create a new `IdleToken` with the given raw `usize` id. pub const fn new(raw: usize) -> IdleToken { IdleToken(raw) } } /// A token that uniquely identifies a file dialog request. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)] pub struct FileDialogToken(u64); impl FileDialogToken { /// A token that does not correspond to any file dialog. pub const INVALID: FileDialogToken = FileDialogToken(0); /// Create a new token. pub fn next() -> FileDialogToken { static COUNTER: Counter = Counter::new(); FileDialogToken(COUNTER.next()) } /// Create a new token from a raw value. pub const fn from_raw(id: u64) -> FileDialogToken { FileDialogToken(id) } /// Get the raw value for a token. pub const fn into_raw(self) -> u64 { self.0 } } /// Levels in the window system - Z order for display purposes. /// Describes the purpose of a window and should be mapped appropriately to match platform /// conventions. #[derive(Clone, PartialEq, Eq)] pub enum WindowLevel { /// A top level app window. AppWindow, /// A window that should stay above app windows - like a tooltip Tooltip(WindowHandle), /// A user interface element such as a dropdown menu or combo box DropDown(WindowHandle), /// A modal dialog Modal(WindowHandle), } /// Contains the different states a Window can be in. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WindowState { Maximized, Minimized, Restored, } /// A handle to a platform window object. #[derive(Clone, Default, PartialEq, Eq)] pub struct WindowHandle(pub(crate) backend::WindowHandle); impl WindowHandle { /// Make this window visible. pub fn show(&self) { self.0.show() } /// Close the window. pub fn close(&self) { self.0.close() } /// Hide the window pub fn hide(&self) { self.0.hide() } /// Set whether the window should be resizable pub fn resizable(&self, resizable: bool) { self.0.resizable(resizable) } /// Sets the state of the window. pub fn set_window_state(&mut self, state: WindowState) { self.0.set_window_state(state); } /// Gets the state of the window. pub fn get_window_state(&self) -> WindowState { self.0.get_window_state() } /// Informs the system that the current location of the mouse should be treated as part of the /// window's titlebar. This can be used to implement a custom titlebar widget. Note that /// because this refers to the current location of the mouse, you should probably call this /// function in response to every relevant [`WinHandler::mouse_move`]. /// /// This is currently only implemented on Windows and GTK. pub fn handle_titlebar(&self, val: bool) { self.0.handle_titlebar(val); } /// Set whether the window should show titlebar. pub fn show_titlebar(&self, show_titlebar: bool) { self.0.show_titlebar(show_titlebar) } /// Sets the position of the window. /// /// The position is given in [display points], measured relative to the parent window if there /// is one, or the origin of the virtual screen if there is no parent. /// /// [display points]: crate::Scale pub fn set_position(&self, position: impl Into<Point>) { self.0.set_position(position.into()) } /// Sets whether the window is always on top of other windows. /// /// How and if this works is system dependent, by either setting a flag, or setting the level. /// On Wayland systems, the user needs to manually set this in the titlebar. pub fn set_always_on_top(&self, always_on_top: bool) { self.0.set_always_on_top(always_on_top); } /// Sets whether the mouse passes through the window to whatever is behind. pub fn set_mouse_pass_through(&self, mouse_pass_through: bool) { self.0.set_mouse_pass_through(mouse_pass_through); } /// Sets where in the window the user can interact with the program. /// /// This enables irregularly shaped windows. For example, you can make it simply /// not rectangular or you can make a sub-window which can be moved even on Wayland. /// /// The contents of `region` are added together, and are specified in [display points], so /// you do not need to deal with scale yourself. /// /// On GTK and Wayland, this is specified as where the user can interact with the program. /// On Windows, this is specified as both where you can interact, and where the window is /// visible. So on Windows it will hide all regions not specified. /// On macOS, this does nothing, but you can make the window transparent for the same effect. /// On Web, this does nothing. /// /// [display points]: crate::Scale pub fn set_input_region(&self, region: Option<Region>) { self.0.set_input_region(region) } /// Returns true if the window is the foreground window or this is unknown. /// Returns false if a different window is known to be the foreground window. pub fn is_foreground_window(&self) -> bool { self.0.is_foreground_window() } /// Returns the position of the top left corner of the window. /// /// The position is returned in [display points], measured relative to the parent window if /// there is one, of the origin of the virtual screen if there is no parent. /// /// [display points]: crate::Scale pub fn get_position(&self) -> Point { self.0.get_position() } /// Returns the insets of the window content from its position and size in [display points]. /// /// This is to account for any window system provided chrome, e.g. title bars. For example, if /// you want your window to have room for contents of size `contents`, then you should call /// [`WindowHandle::get_size`] with an argument of `(contents.to_rect() + insets).size()`, /// where `insets` is the return value of this function. /// /// The details of this function are somewhat platform-dependent. For example, on Windows both /// the insets and the window size include the space taken up by the title bar and window /// decorations; on GTK neither the insets nor the window size include the title bar or window /// decorations. /// /// [display points]: crate::Scale pub fn content_insets(&self) -> Insets { self.0.content_insets() } /// Set the window's size in [display points]. /// /// The actual window size in pixels will depend on the platform DPI settings. /// /// This should be considered a request to the platform to set the size of the window. The /// platform might choose a different size depending on its DPI or other platform-dependent /// configuration. To know the actual size of the window you should handle the /// [`WinHandler::size`] method. /// /// [display points]: crate::Scale pub fn set_size(&self, size: impl Into<Size>) { self.0.set_size(size.into()) } /// Gets the window size, in [display points]. /// /// [display points]: crate::Scale pub fn get_size(&self) -> Size { self.0.get_size() } /// Bring this window to the front of the window stack and give it focus. pub fn bring_to_front_and_focus(&self) { self.0.bring_to_front_and_focus() } /// Request that [`prepare_paint`] and [`paint`] be called next time there's the opportunity to /// render another frame. This differs from [`invalidate`] and [`invalidate_rect`] in that it /// doesn't invalidate any part of the window. /// /// [`invalidate`]: WindowHandle::invalidate /// [`invalidate_rect`]: WindowHandle::invalidate_rect /// [`paint`]: WinHandler::paint /// [`prepare_paint`]: WinHandler::prepare_paint pub fn request_anim_frame(&self) { self.0.request_anim_frame(); } /// Request invalidation of the entire window contents. pub fn invalidate(&self) { self.0.invalidate(); } /// Request invalidation of a region of the window. pub fn invalidate_rect(&self, rect: Rect) { self.0.invalidate_rect(rect); } /// Set the title for this menu. pub fn set_title(&self, title: &str) { self.0.set_title(title) } /// Set the top-level menu for this window. pub fn set_menu(&self, menu: Menu) { self.0.set_menu(menu.into_inner()) } /// Get access to a type that can perform text layout. pub fn text(&self) -> PietText { self.0.text() } /// Register a new text input receiver for this window. /// /// This method should be called any time a new editable text field is /// created inside a window. Any text field with a `TextFieldToken` that /// has not yet been destroyed with `remove_text_field` *must* be ready to /// accept input from the platform via `WinHandler::text_input` at any time, /// even if it is not currently focused. /// /// Returns the `TextFieldToken` associated with this new text input. pub fn add_text_field(&self) -> TextFieldToken { self.0.add_text_field() } /// Unregister a previously registered text input receiver. /// /// If `token` is the text field currently focused, the platform automatically /// sets the focused field to `None`. pub fn remove_text_field(&self, token: TextFieldToken) { self.0.remove_text_field(token) } /// Notify the platform that the focused text input receiver has changed. /// /// This must be called any time focus changes to a different text input, or /// when focus switches away from a text input. pub fn set_focused_text_field(&self, active_field: Option<TextFieldToken>) { self.0.set_focused_text_field(active_field) } /// Notify the platform that some text input state has changed, such as the /// selection, contents, etc. /// /// This method should *never* be called in response to edits from a /// `InputHandler`; only in response to changes from the application: /// scrolling, remote edits, etc. pub fn update_text_field(&self, token: TextFieldToken, update: Event) { self.0.update_text_field(token, update) } /// Schedule a timer. /// /// This causes a [`WinHandler::timer`] call at the deadline. The /// return value is a token that can be used to associate the request /// with the handler call. /// /// Note that this is not a precise timer. On Windows, the typical /// resolution is around 10ms. Therefore, it's best used for things /// like blinking a cursor or triggering tooltips, not for anything /// requiring precision. pub fn request_timer(&self, deadline: Duration) -> TimerToken { self.0.request_timer(instant::Instant::now() + deadline) } /// Set the cursor icon. pub fn set_cursor(&mut self, cursor: &Cursor) { self.0.set_cursor(cursor) } pub fn make_cursor(&self, desc: &CursorDesc) -> Option<Cursor> { self.0.make_cursor(desc) } /// Prompt the user to choose a file to open. /// /// This won't block immediately; the file dialog will be shown whenever control returns to /// `druid-shell`, and the [`WinHandler::open_file`] method will be called when the dialog is /// closed. pub fn open_file(&mut self, options: FileDialogOptions) -> Option<FileDialogToken> { self.0.open_file(options) } /// Prompt the user to choose a path for saving. /// /// This won't block immediately; the file dialog will be shown whenever control returns to /// `druid-shell`, and the [`WinHandler::save_as`] method will be called when the dialog is /// closed. pub fn save_as(&mut self, options: FileDialogOptions) -> Option<FileDialogToken> { self.0.save_as(options) } /// Display a pop-up menu at the given position. /// /// `pos` is in the coordinate space of the window. pub fn show_context_menu(&self, menu: Menu, pos: Point) { self.0.show_context_menu(menu.into_inner(), pos) } /// Get a handle that can be used to schedule an idle task. pub fn get_idle_handle(&self) -> Option<IdleHandle> { self.0.get_idle_handle().map(IdleHandle) } /// Get the DPI scale of the window. /// /// The returned [`Scale`] is a copy and thus its information will be stale after /// the platform DPI changes. This means you should not stash it and rely on it later; it is /// only guaranteed to be valid for the current pass of the runloop. // TODO: Can we get rid of the Result/Error for ergonomics? pub fn get_scale(&self) -> Result<Scale, Error> { self.0.get_scale() } } #[cfg(feature = "raw-win-handle")] unsafe impl HasRawWindowHandle for WindowHandle { fn raw_window_handle(&self) -> RawWindowHandle { self.0.raw_window_handle() } } /// A builder type for creating new windows. pub struct WindowBuilder(backend::WindowBuilder); impl WindowBuilder { /// Create a new `WindowBuilder`. /// /// Takes the [`Application`] that this window is for. pub fn new(app: Application) -> WindowBuilder { WindowBuilder(backend::WindowBuilder::new(app.backend_app)) } /// Set the [`WinHandler`] for this window. /// /// This is the object that will receive callbacks from this window. pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.0.set_handler(handler) } /// Set the window's initial drawing area size in [display points]. /// /// The actual window size in pixels will depend on the platform DPI settings. /// /// This should be considered a request to the platform to set the size of the window. The /// platform might choose a different size depending on its DPI or other platform-dependent /// configuration. To know the actual size of the window you should handle the /// [`WinHandler::size`] method. /// /// [display points]: crate::Scale pub fn set_size(&mut self, size: Size) { self.0.set_size(size) } /// Set the window's minimum drawing area size in [display points]. /// /// The actual minimum window size in pixels will depend on the platform DPI settings. /// /// This should be considered a request to the platform to set the minimum size of the window. /// The platform might increase the size a tiny bit due to DPI. /// /// [display points]: crate::Scale pub fn set_min_size(&mut self, size: Size) { self.0.set_min_size(size) } /// Set whether the window should be resizable. pub fn resizable(&mut self, resizable: bool) { self.0.resizable(resizable) } /// Set whether the window should have a titlebar and decorations. pub fn show_titlebar(&mut self, show_titlebar: bool) { self.0.show_titlebar(show_titlebar) } /// Set whether the window should be always positioned above all other windows. pub fn set_always_on_top(&mut self, always_on_top: bool) { self.0.set_always_on_top(always_on_top); } /// Set whether the window background should be transparent pub fn set_transparent(&mut self, transparent: bool) { self.0.set_transparent(transparent) } /// Sets the initial window position in display points. /// For windows with a parent, the position is relative to the parent. /// For windows without a parent, it is relative to the origin of the virtual screen. /// See also [set_level] /// /// [set_level]: crate::WindowBuilder::set_level pub fn set_position(&mut self, position: Point) { self.0.set_position(position); } /// Sets the initial [`WindowLevel`]. pub fn set_level(&mut self, level: WindowLevel) { self.0.set_level(level); } /// Set the window's initial title. pub fn set_title(&mut self, title: impl Into<String>) { self.0.set_title(title) } /// Set the window's menu. pub fn set_menu(&mut self, menu: Menu) { self.0.set_menu(menu.into_inner()) } /// Sets the initial state of the window. pub fn set_window_state(&mut self, state: WindowState) { self.0.set_window_state(state); } /// Attempt to construct the platform window. /// /// If this fails, your application should exit. pub fn build(self) -> Result<WindowHandle, Error> { #[allow(clippy::useless_conversion)] // Platform-dependant self.0.build().map(WindowHandle).map_err(Into::into) } } /// App behavior, supplied by the app. /// /// Many of the "window procedure" messages map to calls to this trait. /// The methods are non-mut because the window procedure can be called /// recursively; implementers are expected to use `RefCell` or the like, /// but should be careful to keep the lifetime of the borrow short. pub trait WinHandler { /// Provide the handler with a handle to the window so that it can /// invalidate or make other requests. /// /// This method passes the `WindowHandle` directly, because the handler may /// wish to stash it. fn connect(&mut self, handle: &WindowHandle); /// Called when the size of the window has changed. /// /// The `size` parameter is the new size in [display points](crate::Scale). #[allow(unused_variables)] fn size(&mut self, size: Size) {} /// Called when the [scale](crate::Scale) of the window has changed. /// /// This is always called before the accompanying [`size`](WinHandler::size). #[allow(unused_variables)] fn scale(&mut self, scale: Scale) {} /// Request the handler to prepare to paint the window contents. In particular, if there are /// any regions that need to be repainted on the next call to `paint`, the handler should /// invalidate those regions by calling [`WindowHandle::invalidate_rect`] or /// [`WindowHandle::invalidate`]. fn prepare_paint(&mut self); /// Request the handler to paint the window contents. `invalid` is the region in [display /// points](crate::Scale) that needs to be repainted; painting outside the invalid region will /// have no effect. fn paint(&mut self, piet: &mut piet_common::Piet, invalid: &Region); /// Called when the resources need to be rebuilt. /// /// Discussion: this function is mostly motivated by using /// `GenericRenderTarget` on Direct2D. If we move to `DeviceContext` /// instead, then it's possible we don't need this. #[allow(unused_variables)] fn rebuild_resources(&mut self) {} /// Called when a menu item is selected. #[allow(unused_variables)] fn command(&mut self, id: u32) {} /// Called when a "Save As" dialog is closed. /// /// `token` is the value returned by [`WindowHandle::save_as`]. `file` contains the information /// of the chosen path, or `None` if the save dialog was cancelled. #[allow(unused_variables)] fn save_as(&mut self, token: FileDialogToken, file: Option<FileInfo>) {} /// Called when an "Open" dialog is closed. /// /// `token` is the value returned by [`WindowHandle::open_file`]. `file` contains the information /// of the chosen path, or `None` if the save dialog was cancelled. #[allow(unused_variables)] fn open_file(&mut self, token: FileDialogToken, file: Option<FileInfo>) {} /// Called when an "Open" dialog with multiple selection is closed. /// /// `token` is the value returned by [`WindowHandle::open_file`]. `files` contains the information /// of the chosen paths, or `None` if the save dialog was cancelled. #[allow(unused_variables)] fn open_files(&mut self, token: FileDialogToken, files: Vec<FileInfo>) {} /// Called on a key down event. /// /// Return `true` if the event is handled. #[allow(unused_variables)] fn key_down(&mut self, event: KeyEvent) -> bool { false } /// Called when a key is released. This corresponds to the WM_KEYUP message /// on Windows, or keyUp(withEvent:) on macOS. #[allow(unused_variables)] fn key_up(&mut self, event: KeyEvent) {} /// Take a lock for the text document specified by `token`. /// /// All calls to this method must be balanced with a call to /// [`release_input_lock`]. /// /// If `mutable` is true, the lock should be a write lock, and allow calling /// mutating methods on InputHandler. This method is called from the top /// level of the event loop and expects to acquire a lock successfully. /// /// For more information, see [the text input documentation](crate::text). /// /// [`release_input_lock`]: WinHandler::release_input_lock #[allow(unused_variables)] fn acquire_input_lock( &mut self, token: TextFieldToken, mutable: bool, ) -> Box<dyn InputHandler> { panic!("acquire_input_lock was called on a WinHandler that did not expect text input.") } /// Release a lock previously acquired by [`acquire_input_lock`]. /// /// [`acquire_input_lock`]: WinHandler::acquire_input_lock #[allow(unused_variables)] fn release_input_lock(&mut self, token: TextFieldToken) { panic!("release_input_lock was called on a WinHandler that did not expect text input.") } /// Called on a mouse wheel event. /// /// The polarity is the amount to be added to the scroll position, /// in other words the opposite of the direction the content should /// move on scrolling. This polarity is consistent with the /// deltaX and deltaY values in a web [WheelEvent]. /// /// [WheelEvent]: https://w3c.github.io/uievents/#event-type-wheel #[allow(unused_variables)] fn wheel(&mut self, event: &MouseEvent) {} /// Called when a platform-defined zoom gesture occurs (such as pinching /// on the trackpad). #[allow(unused_variables)] fn zoom(&mut self, delta: f64) {} /// Called when the mouse moves. #[allow(unused_variables)] fn mouse_move(&mut self, event: &MouseEvent) {} /// Called on mouse button down. #[allow(unused_variables)] fn mouse_down(&mut self, event: &MouseEvent) {} /// Called on mouse button up. #[allow(unused_variables)] fn mouse_up(&mut self, event: &MouseEvent) {} /// Called when the mouse cursor has left the application window fn mouse_leave(&mut self) {} /// Called on timer event. /// /// This is called at (approximately) the requested deadline by a /// [`WindowHandle::request_timer()`] call. The token argument here is the same /// as the return value of that call. #[allow(unused_variables)] fn timer(&mut self, token: TimerToken) {} /// Called when this window becomes the focused window. #[allow(unused_variables)] fn got_focus(&mut self) {} /// Called when this window stops being the focused window. #[allow(unused_variables)] fn lost_focus(&mut self) {} /// Called when the shell requests to close the window, for example because the user clicked /// the little "X" in the titlebar. /// /// If you want to actually close the window in response to this request, call /// [`WindowHandle::close`]. If you don't implement this method, clicking the titlebar "X" will /// have no effect. fn request_close(&mut self) {} /// Called when the window is being destroyed. Note that this happens /// earlier in the sequence than drop (at WM_DESTROY, while the latter is /// WM_NCDESTROY). #[allow(unused_variables)] fn destroy(&mut self) {} /// Called when a idle token is requested by [`IdleHandle::schedule_idle()`] call. #[allow(unused_variables)] fn idle(&mut self, token: IdleToken) {} /// Get a reference to the handler state. Used mostly by idle handlers. fn as_any(&mut self) -> &mut dyn Any; } impl From<backend::WindowHandle> for WindowHandle { fn from(src: backend::WindowHandle) -> WindowHandle { WindowHandle(src) } } #[cfg(test)] mod test { use super::*; use static_assertions as sa; sa::assert_not_impl_any!(WindowHandle: Send, Sync); sa::assert_impl_all!(IdleHandle: Send, Sync); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/common_util.rs
druid-shell/src/common_util.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Common functions used by the backends use std::cell::Cell; use std::num::NonZeroU64; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use instant::Instant; use crate::kurbo::Point; use crate::WinHandler; // This is the default timing on windows. const MULTI_CLICK_INTERVAL: Duration = Duration::from_millis(500); // the max distance between two clicks for them to count as a multi-click const MULTI_CLICK_MAX_DISTANCE: f64 = 5.0; /// Strip the access keys from the menu string. /// /// Changes "E&xit" to "Exit". Actual ampersands are escaped as "&&". #[allow(dead_code)] pub fn strip_access_key(raw_menu_text: &str) -> String { let mut saw_ampersand = false; let mut result = String::new(); for c in raw_menu_text.chars() { if c == '&' { if saw_ampersand { result.push(c); } saw_ampersand = !saw_ampersand; } else { result.push(c); saw_ampersand = false; } } result } /// A trait for implementing the boxed callback hack. pub(crate) trait IdleCallback: Send { fn call(self: Box<Self>, a: &mut dyn WinHandler); } impl<F: FnOnce(&mut dyn WinHandler) + Send> IdleCallback for F { fn call(self: Box<F>, a: &mut dyn WinHandler) { (*self)(a) } } /// An incrementing counter for generating unique ids. /// /// This can be used safely from multiple threads. /// /// The counter will overflow if `next()` is called 2^64 - 2 times. /// If this is possible for your application, and reuse would be undesirable, /// use something else. pub struct Counter(AtomicU64); impl Counter { /// Create a new counter. pub const fn new() -> Counter { Counter(AtomicU64::new(1)) } /// Creates a new counter with a given starting value. /// /// # Safety /// /// The value must not be zero. pub const unsafe fn new_unchecked(init: u64) -> Counter { Counter(AtomicU64::new(init)) } /// Return the next value. pub fn next(&self) -> u64 { self.0.fetch_add(1, Ordering::Relaxed) } /// Return the next value, as a `NonZeroU64`. pub fn next_nonzero(&self) -> NonZeroU64 { // safe because our initial value is 1 and can only be incremented. unsafe { NonZeroU64::new_unchecked(self.0.fetch_add(1, Ordering::Relaxed)) } } } /// A small helper for determining the click-count of a mouse-down event. /// /// Click-count is incremented if both the duration and distance between a pair /// of clicks are below some threshold. #[derive(Debug, Clone)] pub struct ClickCounter { max_interval: Cell<Duration>, max_distance: Cell<f64>, last_click: Cell<Instant>, last_pos: Cell<Point>, click_count: Cell<u8>, } #[allow(dead_code)] impl ClickCounter { /// Create a new ClickCounter with the given interval and distance. pub fn new(max_interval: Duration, max_distance: f64) -> ClickCounter { ClickCounter { max_interval: Cell::new(max_interval), max_distance: Cell::new(max_distance), last_click: Cell::new(Instant::now()), click_count: Cell::new(0), last_pos: Cell::new(Point::new(f64::MAX, 0.0)), } } pub fn set_interval_ms(&self, millis: u64) { self.max_interval.set(Duration::from_millis(millis)) } pub fn set_distance(&self, distance: f64) { self.max_distance.set(distance) } /// Return the click count for a click occurring now, at the provided position. pub fn count_for_click(&self, click_pos: Point) -> u8 { let click_time = Instant::now(); let last_time = self.last_click.replace(click_time); let last_pos = self.last_pos.replace(click_pos); let elapsed = click_time - last_time; let distance = last_pos.distance(click_pos); if elapsed > self.max_interval.get() || distance > self.max_distance.get() { self.click_count.set(0); } let click_count = self.click_count.get().saturating_add(1); self.click_count.set(click_count); click_count } } impl Default for ClickCounter { fn default() -> Self { ClickCounter::new(MULTI_CLICK_INTERVAL, MULTI_CLICK_MAX_DISTANCE) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/keyboard.rs
druid-shell/src/keyboard.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Keyboard types. // This is a reasonable lint, but we keep signatures in sync with the // bitflags implementation of the inner Modifiers type. #![allow(clippy::trivially_copy_pass_by_ref)] use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}; pub use keyboard_types::{Code, KeyState, Location}; /// The meaning (mapped value) of a keypress. pub type KbKey = keyboard_types::Key; /// Information about a keyboard event. /// /// Note that this type is similar to [`KeyboardEvent`] in keyboard-types, /// but has a few small differences for convenience. /// /// [`KeyboardEvent`]: keyboard_types::KeyboardEvent #[non_exhaustive] #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct KeyEvent { /// Whether the key is pressed or released. pub state: KeyState, /// Logical key value. pub key: KbKey, /// Physical key position. pub code: Code, /// Location for keys with multiple instances on common keyboards. pub location: Location, /// Flags for pressed modifier keys. pub mods: Modifiers, /// True if the key is currently auto-repeated. pub repeat: bool, /// Events with this flag should be ignored in a text editor /// and instead composition events should be used. pub is_composing: bool, } /// The modifiers. /// /// This type is a thin wrappers around [`keyboard_types::Modifiers`], /// mostly for the convenience methods. If those get upstreamed, it /// will simply become that type. /// /// [`keyboard_types::Modifiers`]: keyboard_types::Modifiers #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub struct Modifiers(keyboard_types::Modifiers); /// A convenience trait for creating Key objects. /// /// This trait is implemented by [`KbKey`] itself and also strings, which are /// converted into the `Character` variant. It is defined this way and not /// using the standard `Into` mechanism because `KbKey` is a type in an external /// crate. /// /// [`KbKey`]: KbKey pub trait IntoKey { fn into_key(self) -> KbKey; } impl KeyEvent { #[doc(hidden)] /// Create a key event for testing purposes. pub fn for_test(mods: impl Into<Modifiers>, key: impl IntoKey) -> KeyEvent { let mods = mods.into(); let key = key.into_key(); KeyEvent { key, code: Code::Unidentified, location: Location::Standard, state: KeyState::Down, mods, is_composing: false, repeat: false, } } } impl Modifiers { pub const ALT: Modifiers = Modifiers(keyboard_types::Modifiers::ALT); pub const ALT_GRAPH: Modifiers = Modifiers(keyboard_types::Modifiers::ALT_GRAPH); pub const CAPS_LOCK: Modifiers = Modifiers(keyboard_types::Modifiers::CAPS_LOCK); pub const CONTROL: Modifiers = Modifiers(keyboard_types::Modifiers::CONTROL); pub const FN: Modifiers = Modifiers(keyboard_types::Modifiers::FN); pub const FN_LOCK: Modifiers = Modifiers(keyboard_types::Modifiers::FN_LOCK); pub const META: Modifiers = Modifiers(keyboard_types::Modifiers::META); pub const NUM_LOCK: Modifiers = Modifiers(keyboard_types::Modifiers::NUM_LOCK); pub const SCROLL_LOCK: Modifiers = Modifiers(keyboard_types::Modifiers::SCROLL_LOCK); pub const SHIFT: Modifiers = Modifiers(keyboard_types::Modifiers::SHIFT); pub const SYMBOL: Modifiers = Modifiers(keyboard_types::Modifiers::SYMBOL); pub const SYMBOL_LOCK: Modifiers = Modifiers(keyboard_types::Modifiers::SYMBOL_LOCK); pub const HYPER: Modifiers = Modifiers(keyboard_types::Modifiers::HYPER); pub const SUPER: Modifiers = Modifiers(keyboard_types::Modifiers::SUPER); /// Get the inner value. /// /// Note that this function might go away if our changes are upstreamed. pub fn raw(&self) -> keyboard_types::Modifiers { self.0 } /// Determine whether Shift is set. pub fn shift(&self) -> bool { self.contains(Modifiers::SHIFT) } /// Determine whether Ctrl is set. pub fn ctrl(&self) -> bool { self.contains(Modifiers::CONTROL) } /// Determine whether Alt is set. pub fn alt(&self) -> bool { self.contains(Modifiers::ALT) } /// Determine whether Meta is set. pub fn meta(&self) -> bool { self.contains(Modifiers::META) } /// Returns an empty set of modifiers. pub fn empty() -> Modifiers { Default::default() } /// Returns `true` if no modifiers are set. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns `true` if all the modifiers in `other` are set. pub fn contains(&self, other: Modifiers) -> bool { self.0.contains(other.0) } /// Inserts or removes the specified modifiers depending on the passed value. pub fn set(&mut self, other: Modifiers, value: bool) { self.0.set(other.0, value) } } impl BitAnd for Modifiers { type Output = Self; fn bitand(self, rhs: Self) -> Self { Modifiers(self.0 & rhs.0) } } impl BitAndAssign for Modifiers { // rhs is the "right-hand side" of the expression `a &= b` fn bitand_assign(&mut self, rhs: Self) { *self = Modifiers(self.0 & rhs.0) } } impl BitOr for Modifiers { type Output = Self; fn bitor(self, rhs: Self) -> Self { Modifiers(self.0 | rhs.0) } } impl BitOrAssign for Modifiers { // rhs is the "right-hand side" of the expression `a &= b` fn bitor_assign(&mut self, rhs: Self) { *self = Modifiers(self.0 | rhs.0) } } impl BitXor for Modifiers { type Output = Self; fn bitxor(self, rhs: Self) -> Self { Modifiers(self.0 ^ rhs.0) } } impl BitXorAssign for Modifiers { // rhs is the "right-hand side" of the expression `a &= b` fn bitxor_assign(&mut self, rhs: Self) { *self = Modifiers(self.0 ^ rhs.0) } } impl Not for Modifiers { type Output = Self; fn not(self) -> Self { Modifiers(!self.0) } } impl IntoKey for KbKey { fn into_key(self) -> KbKey { self } } impl IntoKey for &str { fn into_key(self) -> KbKey { KbKey::Character(self.into()) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/screen.rs
druid-shell/src/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Module to get information about monitors use crate::backend; use crate::kurbo::Rect; use std::fmt; use std::fmt::Display; /// Monitor struct containing data about a monitor on the system /// /// Use [`Screen::get_monitors`] to return a `Vec<Monitor>` of all the monitors on the system /// /// [`Screen::get_monitors`]: Screen::get_monitors #[derive(Clone, Debug, PartialEq)] pub struct Monitor { primary: bool, rect: Rect, // TODO: Work area, cross_platform // https://developer.apple.com/documentation/appkit/nsscreen/1388369-visibleframe // https://developer.gnome.org/gdk3/stable/GdkMonitor.html#gdk-monitor-get-workarea // https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-monitorinfo // Unsure about x11 work_rect: Rect, } impl Monitor { #[allow(dead_code)] pub(crate) fn new(primary: bool, rect: Rect, work_rect: Rect) -> Self { Monitor { primary, rect, work_rect, } } /// Returns true if the monitor is the primary monitor. /// The primary monitor has its origin at (0, 0) in virtual screen coordinates. pub fn is_primary(&self) -> bool { self.primary } /// Returns the monitor rectangle in virtual screen coordinates. pub fn virtual_rect(&self) -> Rect { self.rect } /// Returns the monitor working rectangle in virtual screen coordinates. /// The working rectangle excludes certain things like the dock and menubar on mac, /// and the taskbar on windows. pub fn virtual_work_rect(&self) -> Rect { self.work_rect } } impl Display for Monitor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.primary { write!(f, "Primary ")?; } else { write!(f, "Secondary ")?; } write!( f, "({}, {})({}, {})", self.rect.x0, self.rect.x1, self.rect.y0, self.rect.y1 )?; Ok(()) } } /// Information about the screen and monitors pub struct Screen {} impl Screen { /// Returns a vector of all the [`monitors`] on the system. /// /// [`monitors`]: Monitor pub fn get_monitors() -> Vec<Monitor> { backend::screen::get_monitors() } /// Returns the bounding rectangle of the total virtual screen space in pixels. pub fn get_display_rect() -> Rect { Self::get_monitors() .iter() .map(|x| x.virtual_rect()) .fold(Rect::ZERO, |a, b| a.union(b)) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mod.rs
druid-shell/src/backend/mod.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Platform specific implementations. // It would be clearer to use cfg_if! macros here, but that breaks rustfmt. #[cfg(target_os = "windows")] mod windows; #[cfg(target_os = "windows")] pub use windows::*; #[cfg(target_os = "macos")] mod mac; #[cfg(target_os = "macos")] pub use mac::*; #[cfg(target_os = "macos")] pub(crate) mod shared; #[cfg(all( feature = "x11", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] mod x11; #[cfg(all( feature = "x11", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub use x11::*; #[cfg(all( feature = "x11", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub(crate) mod shared; #[cfg(all( feature = "wayland", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] mod wayland; #[cfg(all( feature = "wayland", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub use wayland::*; #[cfg(all( feature = "wayland", any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub(crate) mod shared; #[cfg(all( not(feature = "x11"), not(feature = "wayland"), any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] mod gtk; #[cfg(all( not(feature = "x11"), not(feature = "wayland"), any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub use self::gtk::*; #[cfg(all( not(feature = "x11"), not(feature = "wayland"), any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub(crate) mod shared; #[cfg(target_arch = "wasm32")] mod web; #[cfg(target_arch = "wasm32")] pub use web::*;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/dialog.rs
druid-shell/src/backend/x11/dialog.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! This module contains functions for opening file dialogs using DBus. use ashpd::desktop::file_chooser; use ashpd::{zbus, WindowIdentifier}; use futures::executor::block_on; use tracing::warn; use crate::{FileDialogOptions, FileDialogToken, FileInfo}; use super::window::IdleHandle; pub(crate) fn open_file( window: u32, idle: IdleHandle, options: FileDialogOptions, ) -> FileDialogToken { dialog(window, idle, options, true) } pub(crate) fn save_file( window: u32, idle: IdleHandle, options: FileDialogOptions, ) -> FileDialogToken { dialog(window, idle, options, false) } fn dialog( window: u32, idle: IdleHandle, mut options: FileDialogOptions, open: bool, ) -> FileDialogToken { let tok = FileDialogToken::next(); std::thread::spawn(move || { if let Err(e) = block_on(async { let conn = zbus::Connection::session().await?; let proxy = file_chooser::FileChooserProxy::new(&conn).await?; let id = WindowIdentifier::from_xid(window as u64); let multi = options.multi_selection; let title_owned = options.title.take(); let title = match (open, options.select_directories) { (true, true) => "Open Folder", (true, false) => "Open File", (false, _) => "Save File", }; let title = title_owned.as_deref().unwrap_or(title); let open_result; let save_result; let uris = if open { open_result = proxy.open_file(&id, title, options.into()).await?; open_result.uris() } else { save_result = proxy.save_file(&id, title, options.into()).await?; save_result.uris() }; let mut paths = uris.iter().filter_map(|s| { s.strip_prefix("file://").or_else(|| { warn!("expected path '{}' to start with 'file://'", s); None }) }); if multi && open { let infos = paths .map(|p| FileInfo { path: p.into(), format: None, }) .collect(); idle.add_idle_callback(move |handler| handler.open_files(tok, infos)); } else if !multi { if uris.len() > 2 { warn!( "expected one path (got {}), returning only the first", uris.len() ); } let info = paths.next().map(|p| FileInfo { path: p.into(), format: None, }); if open { idle.add_idle_callback(move |handler| handler.open_file(tok, info)); } else { idle.add_idle_callback(move |handler| handler.save_as(tok, info)); } } else { warn!("cannot save multiple paths"); } Ok(()) as ashpd::Result<()> }) { warn!("error while opening file dialog: {}", e); } }); tok } impl From<crate::FileSpec> for file_chooser::FileFilter { fn from(spec: crate::FileSpec) -> file_chooser::FileFilter { let mut filter = file_chooser::FileFilter::new(spec.name); for ext in spec.extensions { filter = filter.glob(&format!("*.{ext}")); } filter } } impl From<crate::FileDialogOptions> for file_chooser::OpenFileOptions { fn from(opts: crate::FileDialogOptions) -> file_chooser::OpenFileOptions { let mut fc = file_chooser::OpenFileOptions::default() .modal(true) .multiple(opts.multi_selection) .directory(opts.select_directories); if let Some(label) = &opts.button_text { fc = fc.accept_label(label); } if let Some(filters) = opts.allowed_types { for f in filters { fc = fc.add_filter(f.into()); } } if let Some(filter) = opts.default_type { fc = fc.current_filter(filter.into()); } fc } } impl From<crate::FileDialogOptions> for file_chooser::SaveFileOptions { fn from(opts: crate::FileDialogOptions) -> file_chooser::SaveFileOptions { let mut fc = file_chooser::SaveFileOptions::default().modal(true); if let Some(name) = &opts.default_name { fc = fc.current_name(name); } if let Some(label) = &opts.button_text { fc = fc.accept_label(label); } if let Some(filters) = opts.allowed_types { for f in filters { fc = fc.add_filter(f.into()); } } if let Some(filter) = opts.default_type { fc = fc.current_filter(filter.into()); } if let Some(dir) = &opts.starting_directory { fc = fc.current_folder(dir); } fc } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/clipboard.rs
druid-shell/src/backend/x11/clipboard.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interactions with the system pasteboard on X11. use std::cell::{Cell, RefCell}; use std::collections::VecDeque; use std::convert::TryFrom; use std::rc::Rc; use std::time::{Duration, Instant}; use x11rb::connection::{Connection, RequestConnection}; use x11rb::errors::{ConnectionError, ReplyError, ReplyOrIdError}; use x11rb::protocol::xproto::{ Atom, AtomEnum, ChangeWindowAttributesAux, ConnectionExt, EventMask, GetPropertyReply, GetPropertyType, PropMode, Property, PropertyNotifyEvent, SelectionClearEvent, SelectionNotifyEvent, SelectionRequestEvent, Timestamp, Window, WindowClass, SELECTION_NOTIFY_EVENT, }; use x11rb::protocol::Event; use x11rb::wrapper::ConnectionExt as _; use x11rb::xcb_ffi::XCBConnection; use super::application::AppAtoms; use crate::clipboard::{ClipboardFormat, FormatId}; use tracing::{debug, error, warn}; // We can pick an arbitrary atom that is used for the transfer. This is our pick. const TRANSFER_ATOM: AtomEnum = AtomEnum::CUT_BUFFE_R4; const STRING_TARGETS: [&str; 5] = [ "UTF8_STRING", "TEXT", "STRING", "text/plain;charset=utf-8", "text/plain", ]; #[derive(Debug, Clone)] pub struct Clipboard(Rc<RefCell<ClipboardState>>); impl Clipboard { pub(crate) fn new( connection: Rc<XCBConnection>, screen_num: usize, atoms: Rc<AppAtoms>, selection_name: Atom, event_queue: Rc<RefCell<VecDeque<Event>>>, timestamp: Rc<Cell<Timestamp>>, ) -> Self { Self(Rc::new(RefCell::new(ClipboardState::new( connection, screen_num, atoms, selection_name, event_queue, timestamp, )))) } pub(crate) fn handle_clear(&self, event: SelectionClearEvent) -> Result<(), ConnectionError> { self.0.borrow_mut().handle_clear(event) } pub(crate) fn handle_request( &self, event: &SelectionRequestEvent, ) -> Result<(), ReplyOrIdError> { self.0.borrow_mut().handle_request(event) } pub(crate) fn handle_property_notify( &self, event: PropertyNotifyEvent, ) -> Result<(), ReplyOrIdError> { self.0.borrow_mut().handle_property_notify(event) } pub fn put_string(&mut self, s: impl AsRef<str>) { let bytes = s.as_ref().as_bytes(); let formats = STRING_TARGETS .iter() .map(|format| ClipboardFormat::new(format, bytes)) .collect::<Vec<_>>(); self.put_formats(&formats); } pub fn put_formats(&mut self, formats: &[ClipboardFormat]) { if let Err(err) = self.0.borrow_mut().put_formats(formats) { error!("Error in Clipboard::put_formats: {:?}", err); } } pub fn get_string(&self) -> Option<String> { self.0.borrow().get_string() } pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> { self.0.borrow().preferred_format(formats) } pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> { self.0.borrow().get_format(format) } pub fn available_type_names(&self) -> Vec<String> { self.0.borrow().available_type_names() } } #[derive(Debug)] struct ClipboardState { connection: Rc<XCBConnection>, screen_num: usize, atoms: Rc<AppAtoms>, selection_name: Atom, event_queue: Rc<RefCell<VecDeque<Event>>>, timestamp: Rc<Cell<Timestamp>>, contents: Option<ClipboardContents>, incremental: Vec<IncrementalTransfer>, } impl ClipboardState { fn new( connection: Rc<XCBConnection>, screen_num: usize, atoms: Rc<AppAtoms>, selection_name: Atom, event_queue: Rc<RefCell<VecDeque<Event>>>, timestamp: Rc<Cell<Timestamp>>, ) -> Self { Self { connection, screen_num, atoms, selection_name, event_queue, timestamp, contents: None, incremental: Vec::new(), } } fn put_formats(&mut self, formats: &[ClipboardFormat]) -> Result<(), ReplyOrIdError> { let conn = &*self.connection; // Create a window for selection ownership and save the necessary state let contents = ClipboardContents::new(conn, self.screen_num, formats)?; // Become selection owner of our selection conn.set_selection_owner( contents.owner_window, self.selection_name, self.timestamp.get(), )?; // Check if we really are the selection owner; this might e.g. fail if our timestamp is too // old and some other program became the selection owner with a newer timestamp let owner = conn.get_selection_owner(self.selection_name)?.reply()?; if owner.owner == contents.owner_window { // We are the new selection owner! Remember our contents for later. debug!("put_formats(): became selection owner"); if let Some(mut old_owner) = self.contents.replace(contents) { // We already where the owner before. Destroy the old contents. old_owner.destroy(conn)?; } } else { debug!("put_formats(): failed to become selection owner"); } Ok(()) } fn get_string(&self) -> Option<String> { STRING_TARGETS.iter().find_map(|target| { self.get_format(target) .and_then(|data| String::from_utf8(data).ok()) }) } fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> { let available = self.available_type_names(); formats .iter() .find(|f1| available.iter().any(|f2| *f1 == f2)) .copied() } fn get_format(&self, format: FormatId) -> Option<Vec<u8>> { if let Some(contents) = self.contents.as_ref() { // We are the selection owner and can directly return the result contents .data .iter() .find(|(_, fmt, _)| fmt == format) .map(|(_, _, data)| data.to_vec()) } else { self.do_transfer(format, |prop| prop.value) } } #[allow(clippy::needless_collect)] fn available_type_names(&self) -> Vec<String> { if let Some(contents) = self.contents.as_ref() { // We are the selection owner and can directly return the result return contents .data .iter() .map(|(_, format, _)| format.to_string()) .collect(); } let requests = self .do_transfer("TARGETS", |prop| { prop.value32() .map(|iter| iter.collect()) .unwrap_or_default() }) .unwrap_or_default() .into_iter() .filter_map(|atom| self.connection.get_atom_name(atom).ok()) .collect::<Vec<_>>(); // We first send all requests above and then fetch the replies with only one round-trip to // the X11 server. Hence, the collect() above is not unnecessary! requests .into_iter() .filter_map(|req| req.reply().ok()) .filter_map(|reply| String::from_utf8(reply.name).ok()) .collect() } fn do_transfer<R, F>(&self, format: FormatId, converter: F) -> Option<Vec<R>> where R: Clone, F: FnMut(GetPropertyReply) -> Vec<R>, { match self.do_transfer_impl(format, converter) { Ok(result) => result, Err(error) => { warn!("Error in Clipboard::do_transfer: {:?}", error); None } } } fn do_transfer_impl<R, F>( &self, format: FormatId, mut converter: F, ) -> Result<Option<Vec<R>>, ReplyOrIdError> where R: Clone, F: FnMut(GetPropertyReply) -> Vec<R>, { debug!("Getting clipboard contents in format {}", format); let deadline = Instant::now() + Duration::from_secs(5); let conn = &*self.connection; let format_atom = conn.intern_atom(false, format.as_bytes())?.reply()?.atom; // Create a window for the transfer let window = WindowContainer::new(conn, self.screen_num)?; conn.convert_selection( window.window, self.selection_name, format_atom, TRANSFER_ATOM, self.timestamp.get(), )?; // Now wait for the selection notify event conn.flush()?; let notify = loop { match wait_for_event_with_deadline(conn, deadline)? { Event::SelectionNotify(notify) if notify.requestor == window.window => { break notify } Event::SelectionRequest(request) if request.requestor == window.window => { // The callers should catch this situation before and not even call us // do_transfer() error!("BUG! We are doing a selection transfer while we are the selection owner. This will hang!"); } event => self.event_queue.borrow_mut().push_back(event), } }; if notify.property == x11rb::NONE { // Selection is empty debug!("Selection transfer was rejected"); return Ok(None); } conn.change_window_attributes( window.window, &ChangeWindowAttributesAux::default().event_mask(EventMask::PROPERTY_CHANGE), )?; let property = conn .get_property( true, window.window, TRANSFER_ATOM, GetPropertyType::ANY, 0, u32::MAX, )? .reply()?; if property.type_ != self.atoms.INCR { debug!("Got selection contents directly"); return Ok(Some(converter(property))); } // The above GetProperty with delete=true indicated that the INCR transfer starts // now, wait for the property notifies debug!("Doing an INCR transfer for the selection"); conn.flush()?; let mut value = Vec::new(); loop { match wait_for_event_with_deadline(conn, deadline)? { Event::PropertyNotify(notify) if (notify.window, notify.state) == (window.window, Property::NEW_VALUE) => { let property = conn .get_property( true, window.window, TRANSFER_ATOM, GetPropertyType::ANY, 0, u32::MAX, )? .reply()?; if property.value.is_empty() { debug!("INCR transfer finished"); return Ok(Some(value)); } else { value.extend_from_slice(&converter(property)); } } event => self.event_queue.borrow_mut().push_back(event), } } } fn handle_clear(&mut self, event: SelectionClearEvent) -> Result<(), ConnectionError> { if event.selection != self.selection_name { // This event is meant for another Clipboard instance return Ok(()); } let window = self.contents.as_ref().map(|c| c.owner_window); if Some(event.owner) == window { // We lost ownership of the selection, clean up if let Some(mut contents) = self.contents.take() { contents.destroy(&self.connection)?; } } Ok(()) } fn handle_request(&mut self, event: &SelectionRequestEvent) -> Result<(), ReplyOrIdError> { if event.selection != self.selection_name { // This request is meant for another Clipboard instance return Ok(()); } let conn = &*self.connection; let contents = match &self.contents { Some(contents) if contents.owner_window == event.owner => contents, _ => { // We do not know what to do with this transfer debug!("Got non-matching selection request event"); reject_transfer(conn, event)?; return Ok(()); } }; // TODO: ICCCM has TIMESTAMP as a required target (but no one uses it...?) if event.target == self.atoms.TARGETS { // TARGETS is a special case: reply is list of u32 let mut atoms = contents .data .iter() .map(|(atom, _, _)| *atom) .collect::<Vec<_>>(); atoms.push(self.atoms.TARGETS); conn.change_property32( PropMode::REPLACE, event.requestor, event.property, AtomEnum::ATOM, &atoms, )?; } else { // Find the request target let content = contents .data .iter() .find(|(atom, _, _)| *atom == event.target); match content { None => { reject_transfer(conn, event)?; return Ok(()); } Some((atom, _, data)) => { if data.len() > maximum_property_length(conn) { // We need to do an INCR transfer. debug!("Starting new INCR transfer"); let transfer = IncrementalTransfer::new(conn, event, Rc::clone(data), self.atoms.INCR); match transfer { Ok(transfer) => self.incremental.push(transfer), Err(err) => { reject_transfer(conn, event)?; return Err(err.into()); } } } else { // We can provide the data directly conn.change_property8( PropMode::REPLACE, event.requestor, event.property, *atom, data, )?; } } } } // Inform the requestor that we sent the data debug!("Replying to selection request event"); let event = SelectionNotifyEvent { response_type: SELECTION_NOTIFY_EVENT, sequence: 0, requestor: event.requestor, selection: event.selection, target: event.target, property: event.property, time: event.time, }; conn.send_event(false, event.requestor, EventMask::NO_EVENT, event)?; Ok(()) } fn handle_property_notify(&mut self, event: PropertyNotifyEvent) -> Result<(), ReplyOrIdError> { fn matches(transfer: &IncrementalTransfer, event: PropertyNotifyEvent) -> bool { transfer.requestor == event.window && transfer.property == event.atom } if event.state != Property::DELETE { return Ok(()); } // Deleting the target property indicates that an INCR transfer should continue. Find that // transfer if let Some(transfer) = self .incremental .iter_mut() .find(|transfer| matches(transfer, event)) { let done = transfer.continue_incremental(&self.connection)?; if done { debug!("INCR transfer finished"); // Remove the transfer self.incremental .retain(|transfer| !matches(transfer, event)); } } Ok(()) } } #[derive(Debug)] struct ClipboardContents { owner_window: Window, data: Vec<(Atom, String, Rc<[u8]>)>, } impl ClipboardContents { fn new( conn: &XCBConnection, screen_num: usize, formats: &[ClipboardFormat], ) -> Result<Self, ReplyOrIdError> { // Send InternAtom requests for all formats let data = formats .iter() .map(|format| { conn.intern_atom(false, format.identifier.as_bytes()) .map(|cookie| (cookie, format)) }) .collect::<Result<Vec<_>, ConnectionError>>()?; // Get the replies for all InternAtom requests let data = data .into_iter() .map(|(cookie, format)| { cookie.reply().map(|reply| { ( reply.atom, format.identifier.to_string(), format.data[..].into(), ) }) }) .collect::<Result<Vec<_>, ReplyError>>()?; let owner_window = conn.generate_id()?; conn.create_window( x11rb::COPY_DEPTH_FROM_PARENT, owner_window, conn.setup().roots[screen_num].root, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, x11rb::COPY_FROM_PARENT, &Default::default(), )?; Ok(Self { owner_window, data }) } fn destroy(&mut self, conn: &XCBConnection) -> Result<(), ConnectionError> { conn.destroy_window(std::mem::replace(&mut self.owner_window, x11rb::NONE))?; Ok(()) } } #[derive(Debug)] struct IncrementalTransfer { requestor: Window, target: Atom, property: Atom, data: Rc<[u8]>, data_offset: usize, } impl IncrementalTransfer { fn new( conn: &XCBConnection, event: &SelectionRequestEvent, data: Rc<[u8]>, incr: Atom, ) -> Result<Self, ConnectionError> { // We need PropertyChange events on the window conn.change_window_attributes( event.requestor, &ChangeWindowAttributesAux::new().event_mask(EventMask::PROPERTY_CHANGE), )?; // Indicate that we are doing an INCR transfer let length = u32::try_from(data.len()).unwrap_or(u32::MAX); conn.change_property32( PropMode::REPLACE, event.requestor, event.property, incr, &[length], )?; Ok(Self { requestor: event.requestor, target: event.target, property: event.property, data, data_offset: 0, }) } /// Continue an incremental transfer, returning true if the transfer is finished fn continue_incremental(&mut self, conn: &XCBConnection) -> Result<bool, ConnectionError> { let remaining = &self.data[self.data_offset..]; let next_length = remaining.len().min(maximum_property_length(conn)); conn.change_property8( PropMode::REPLACE, self.requestor, self.property, self.target, &remaining[..next_length], )?; self.data_offset += next_length; Ok(remaining.is_empty()) } } struct WindowContainer<'a> { window: u32, conn: &'a XCBConnection, } impl<'a> WindowContainer<'a> { fn new(conn: &'a XCBConnection, screen_num: usize) -> Result<Self, ReplyOrIdError> { let window = conn.generate_id()?; conn.create_window( x11rb::COPY_DEPTH_FROM_PARENT, window, conn.setup().roots[screen_num].root, 0, 0, 1, 1, 0, WindowClass::INPUT_OUTPUT, x11rb::COPY_FROM_PARENT, &Default::default(), )?; Ok(WindowContainer { window, conn }) } } impl Drop for WindowContainer<'_> { fn drop(&mut self) { let _ = self.conn.destroy_window(self.window); } } fn maximum_property_length(connection: &XCBConnection) -> usize { let change_property_header_size = 24; // Apply an arbitrary limit to the property size to not stress the server too much let max_request_length = connection .maximum_request_bytes() .min(usize::from(u16::MAX)); max_request_length - change_property_header_size } fn reject_transfer( conn: &XCBConnection, event: &SelectionRequestEvent, ) -> Result<(), ConnectionError> { let event = SelectionNotifyEvent { response_type: SELECTION_NOTIFY_EVENT, sequence: 0, requestor: event.requestor, selection: event.selection, target: event.target, property: x11rb::NONE, time: event.time, }; conn.send_event(false, event.requestor, EventMask::NO_EVENT, event)?; Ok(()) } /// Wait for an X11 event or return a timeout error if the given deadline is in the past. fn wait_for_event_with_deadline( conn: &XCBConnection, deadline: Instant, ) -> Result<Event, ConnectionError> { use nix::poll::{poll, PollFd, PollFlags}; use std::os::raw::c_int; use std::os::unix::io::AsRawFd; loop { // Is there already an event? if let Some(event) = conn.poll_for_event()? { return Ok(event); } // Are we past the deadline? let now = Instant::now(); if deadline <= now { return Err(std::io::Error::new( std::io::ErrorKind::TimedOut, "Timeout while waiting for selection owner to reply", ) .into()); } // Use poll() to wait for the socket to become readable. let mut poll_fds = [PollFd::new(conn.as_raw_fd(), PollFlags::POLLIN)]; let poll_timeout = c_int::try_from(deadline.duration_since(now).as_millis()) .unwrap_or(c_int::MAX - 1) // The above rounds down, but we don't want to wake up to early, so add one .saturating_add(1); // Wait for the socket to be readable via poll() and try again match poll(&mut poll_fds, poll_timeout) { Ok(_) => {} Err(nix::errno::Errno::EINTR) => {} Err(e) => return Err(std::io::Error::from(e).into()), } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/menu.rs
druid-shell/src/backend/x11/menu.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! X11 menus implementation. use crate::hotkey::HotKey; pub struct Menu; impl Menu { pub fn new() -> Menu { // TODO(x11/menus): implement Menu::new (currently a no-op) tracing::warn!("Menu::new is currently unimplemented for X11 backend."); Menu {} } pub fn new_for_popup() -> Menu { // TODO(x11/menus): implement Menu::new_for_popup (currently a no-op) tracing::warn!("Menu::new_for_popup is currently unimplemented for X11 backend."); Menu {} } pub fn add_dropdown(&mut self, mut _menu: Menu, _text: &str, _enabled: bool) { // TODO(x11/menus): implement Menu::add_dropdown (currently a no-op) tracing::warn!("Menu::add_dropdown is currently unimplemented for X11 backend."); } pub fn add_item( &mut self, _id: u32, _text: &str, _key: Option<&HotKey>, _selected: Option<bool>, _enabled: bool, ) { // TODO(x11/menus): implement Menu::add_item (currently a no-op) tracing::warn!("Menu::add_item is currently unimplemented for X11 backend."); } pub fn add_separator(&mut self) { // TODO(x11/menus): implement Menu::add_separator (currently a no-op) tracing::warn!("Menu::add_separator is currently unimplemented for X11 backend."); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/error.rs
druid-shell/src/backend/x11/error.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Errors at the application shell level. use std::fmt; use std::sync::Arc; #[derive(Debug, Clone)] pub enum Error { XError(Arc<x11rb::errors::ReplyError>), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let Error::XError(e) = self; e.fmt(f) } } impl std::error::Error for Error {} impl From<x11rb::x11_utils::X11Error> for Error { fn from(err: x11rb::x11_utils::X11Error) -> Error { Error::XError(Arc::new(x11rb::errors::ReplyError::X11Error(err))) } } impl From<x11rb::errors::ReplyError> for Error { fn from(err: x11rb::errors::ReplyError) -> Error { Error::XError(Arc::new(err)) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/application.rs
druid-shell/src/backend/x11/application.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! X11 implementation of features at the application scope. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; use std::convert::{TryFrom, TryInto}; use std::os::unix::io::RawFd; use std::rc::Rc; use std::time::{Duration, Instant}; use anyhow::{anyhow, Context, Error}; use x11rb::connection::{Connection, RequestConnection}; use x11rb::protocol::present::ConnectionExt as _; use x11rb::protocol::render::{self, ConnectionExt as _, Pictformat}; use x11rb::protocol::xfixes::ConnectionExt as _; use x11rb::protocol::xproto::{ self, ConnectionExt, CreateWindowAux, EventMask, Timestamp, Visualtype, WindowClass, }; use x11rb::protocol::Event; use x11rb::resource_manager::{ new_from_default as new_resource_db_from_default, Database as ResourceDb, }; use x11rb::xcb_ffi::XCBConnection; use crate::application::AppHandler; use super::clipboard::Clipboard; use super::util; use super::window::Window; use crate::backend::shared::linux; use crate::backend::shared::xkb; // This creates a `struct WindowAtoms` containing the specified atoms as members (along with some // convenience methods to intern and query those atoms). We use the following atoms: // // WM_PROTOCOLS // // List of atoms that identify the communications protocols between // the client and window manager in which the client is willing to participate. // // https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#wm_protocols_property // // WM_DELETE_WINDOW // // Including this atom in the WM_PROTOCOLS property on each window makes sure that // if the window manager respects WM_DELETE_WINDOW it will send us the event. // // The WM_DELETE_WINDOW event is sent when there is a request to close the window. // Registering for but ignoring this event means that the window will remain open. // // https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#window_deletion // // _NET_WM_PID // // A property containing the PID of the process that created the window. // // https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html#idm45805407915360 // // _NET_WM_NAME // // A version of WM_NAME supporting UTF8 text. // // https://specifications.freedesktop.org/wm-spec/wm-spec-1.3.html#idm45805407982336 // // UTF8_STRING // // The type of _NET_WM_NAME // // CLIPBOARD // // The name of the clipboard selection; used for implementing copy&paste // // PRIMARY // // The name of the primary selection; used for implementing "paste the currently selected text" // // TARGETS // // A target for getting the selection contents that answers with a list of supported targets // // INCR // // Type used for incremental selection transfers x11rb::atom_manager! { pub(crate) AppAtoms: AppAtomsCookie { WM_PROTOCOLS, WM_DELETE_WINDOW, _NET_WM_PID, _NET_WM_NAME, UTF8_STRING, _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_NORMAL, _NET_WM_WINDOW_TYPE_DROPDOWN_MENU, _NET_WM_WINDOW_TYPE_TOOLTIP, _NET_WM_WINDOW_TYPE_DIALOG, CLIPBOARD, PRIMARY, TARGETS, INCR, } } #[derive(Clone)] pub(crate) struct Application { /// The connection to the X server. /// /// This connection is associated with a single display. /// The X server might also host other displays. /// /// A display is a collection of screens. connection: Rc<XCBConnection>, /// An `XCBConnection` is *technically* safe to use from other threads, but there are /// subtleties; see [x11rb event loop integration notes][1] for more details. /// Let's just avoid the issue altogether. As far as public API is concerned, this causes /// `druid_shell::WindowHandle` to be `!Send` and `!Sync`. /// /// [1]: https://github.com/psychon/x11rb/blob/41ab6610f44f5041e112569684fc58cd6d690e57/src/event_loop_integration.rs. marker: std::marker::PhantomData<*mut XCBConnection>, /// The type of visual used by the root window root_visual_type: Visualtype, /// The visual for windows with transparent backgrounds, if supported argb_visual_type: Option<Visualtype>, /// Pending events that need to be handled later pending_events: Rc<RefCell<VecDeque<Event>>>, /// The atoms that we need atoms: Rc<AppAtoms>, /// The X11 resource database used to query dpi. pub(crate) rdb: Rc<ResourceDb>, pub(crate) cursors: Cursors, /// The clipboard implementation clipboard: Clipboard, /// The clipboard implementation for the primary selection primary: Clipboard, /// The default screen of the connected display. /// /// The connected display may also have additional screens. /// Moving windows between multiple screens is difficult and there is no support for it. /// The application would have to create a clone of its window on multiple screens /// and then fake the visual transfer. /// /// In practice multiple physical monitor drawing areas are present on a single screen. /// This is achieved via various X server extensions (XRandR/Xinerama/TwinView), /// with XRandR seeming like the best choice. screen_num: usize, // Needs a container when no longer const /// The X11 window id of this `Application`. /// /// This is an input-only non-visual X11 window that is created first during initialization, /// and it is destroyed last during `Application::finalize_quit`. /// This window is useful for receiving application level events without any real windows. /// /// This is constant for the lifetime of the `Application`. window_id: u32, /// The mutable `Application` state. state: Rc<RefCell<State>>, /// The read end of the "idle pipe", a pipe that allows the event loop to be woken up from /// other threads. idle_read: RawFd, /// The write end of the "idle pipe", a pipe that allows the event loop to be woken up from /// other threads. idle_write: RawFd, /// The major opcode of the Present extension, if it is supported. present_opcode: Option<u8>, /// Support for the render extension in at least version 0.5? render_argb32_pictformat_cursor: Option<Pictformat>, /// Newest timestamp that we received timestamp: Rc<Cell<Timestamp>>, } /// The mutable `Application` state. struct State { /// Whether `Application::quit` has already been called. quitting: bool, /// A collection of all the `Application` windows. windows: HashMap<u32, Rc<Window>>, xkb_state: xkb::State, } #[derive(Clone, Debug)] pub(crate) struct Cursors { pub default: Option<xproto::Cursor>, pub text: Option<xproto::Cursor>, pub pointer: Option<xproto::Cursor>, pub crosshair: Option<xproto::Cursor>, pub not_allowed: Option<xproto::Cursor>, pub row_resize: Option<xproto::Cursor>, pub col_resize: Option<xproto::Cursor>, } impl Application { pub fn new() -> Result<Application, Error> { // If we want to support OpenGL, we will need to open a connection with Xlib support (see // https://xcb.freedesktop.org/opengl/ for background). There is some sample code for this // in the `rust-xcb` crate (see `connect_with_xlib_display`), although it may be missing // something: according to the link below, If you want to handle events through x11rb and // libxcb, you should call XSetEventQueueOwner(dpy, XCBOwnsEventQueue). Otherwise, libX11 // might randomly eat your events / move them to its own event queue. // // https://github.com/linebender/druid/pull/1025#discussion_r442777892 let (conn, screen_num) = XCBConnection::connect(None)?; let rdb = Rc::new(new_resource_db_from_default(&conn)?); let xkb_context = xkb::Context::new(); xkb_context.set_log_level(tracing::Level::DEBUG); use x11rb::protocol::xkb::ConnectionExt; conn.xkb_use_extension(1, 0)? .reply() .context("init xkb extension")?; let device_id = xkb_context .core_keyboard_device_id(&conn) .context("get core keyboard device id")?; let keymap = xkb_context .keymap_from_device(&conn, device_id) .context("key map from device")?; let xkb_state = keymap.state(); let connection = Rc::new(conn); let window_id = Application::create_event_window(&connection, screen_num)?; let state = Rc::new(RefCell::new(State { quitting: false, windows: HashMap::new(), xkb_state, })); let (idle_read, idle_write) = nix::unistd::pipe2(nix::fcntl::OFlag::O_NONBLOCK)?; let present_opcode = if std::env::var_os("DRUID_SHELL_DISABLE_X11_PRESENT").is_some() { // Allow disabling Present with an environment variable. None } else { match Application::query_present_opcode(&connection) { Ok(p) => p, Err(e) => { tracing::info!("failed to find Present extension: {}", e); None } } }; let pictformats = connection.render_query_pict_formats()?; let render_create_cursor_supported = matches!(connection .extension_information(render::X11_EXTENSION_NAME)? .and_then(|_| connection.render_query_version(0, 5).ok()) .map(|cookie| cookie.reply()) .transpose()?, Some(version) if version.major_version >= 1 || version.minor_version >= 5); let render_argb32_pictformat_cursor = if render_create_cursor_supported { pictformats .reply()? .formats .iter() .find(|format| { format.type_ == render::PictType::DIRECT && format.depth == 32 && format.direct.red_shift == 16 && format.direct.red_mask == 0xff && format.direct.green_shift == 8 && format.direct.green_mask == 0xff && format.direct.blue_shift == 0 && format.direct.blue_mask == 0xff && format.direct.alpha_shift == 24 && format.direct.alpha_mask == 0xff }) .map(|format| format.id) } else { drop(pictformats); None }; let handle = x11rb::cursor::Handle::new(connection.as_ref(), screen_num, &rdb)?.reply()?; let load_cursor = |cursor| { handle .load_cursor(connection.as_ref(), cursor) .map_err(|e| tracing::warn!("Unable to load cursor {}, error: {}", cursor, e)) .ok() }; let cursors = Cursors { default: load_cursor("default"), text: load_cursor("text"), pointer: load_cursor("pointer"), crosshair: load_cursor("crosshair"), not_allowed: load_cursor("not-allowed"), row_resize: load_cursor("row-resize"), col_resize: load_cursor("col-resize"), }; let atoms = Rc::new( AppAtoms::new(&*connection)? .reply() .context("get X11 atoms")?, ); let screen = connection .setup() .roots .get(screen_num) .ok_or_else(|| anyhow!("Invalid screen num: {}", screen_num))?; let root_visual_type = util::get_visual_from_screen(screen) .ok_or_else(|| anyhow!("Couldn't get visual from screen"))?; let argb_visual_type = util::get_argb_visual_type(&connection, screen)?; let timestamp = Rc::new(Cell::new(x11rb::CURRENT_TIME)); let pending_events = Default::default(); let clipboard = Clipboard::new( Rc::clone(&connection), screen_num, Rc::clone(&atoms), atoms.CLIPBOARD, Rc::clone(&pending_events), Rc::clone(&timestamp), ); let primary = Clipboard::new( Rc::clone(&connection), screen_num, Rc::clone(&atoms), atoms.PRIMARY, Rc::clone(&pending_events), Rc::clone(&timestamp), ); Ok(Application { connection, rdb, screen_num, window_id, state, idle_read, cursors, clipboard, primary, idle_write, present_opcode, root_visual_type, argb_visual_type, atoms, pending_events: Default::default(), marker: std::marker::PhantomData, render_argb32_pictformat_cursor, timestamp, }) } // Check if the Present extension is supported, returning its opcode if it is. fn query_present_opcode(conn: &Rc<XCBConnection>) -> Result<Option<u8>, Error> { let query = conn .query_extension(b"Present")? .reply() .context("query Present extension")?; if !query.present { return Ok(None); } let opcode = Some(query.major_opcode); // If Present is there at all, version 1.0 should be supported. This code // shouldn't have a real effect; it's just a sanity check. let version = conn .present_query_version(1, 0)? .reply() .context("query Present version")?; tracing::info!( "X server supports Present version {}.{}", version.major_version, version.minor_version, ); // We need the XFIXES extension to use regions. This code looks like it's just doing a // sanity check but it is *necessary*: XFIXES doesn't work until we've done version // negotiation // (https://www.x.org/releases/X11R7.7/doc/fixesproto/fixesproto.txt) let version = conn .xfixes_query_version(5, 0)? .reply() .context("query XFIXES version")?; tracing::info!( "X server supports XFIXES version {}.{}", version.major_version, version.minor_version, ); Ok(opcode) } #[inline] pub(crate) fn present_opcode(&self) -> Option<u8> { self.present_opcode } /// Return the ARGB32 pictformat of the server, but only if RENDER's CreateCursor is supported #[inline] pub(crate) fn render_argb32_pictformat_cursor(&self) -> Option<Pictformat> { self.render_argb32_pictformat_cursor } fn create_event_window(conn: &Rc<XCBConnection>, screen_num: usize) -> Result<u32, Error> { let id = conn.generate_id()?; let setup = conn.setup(); let screen = setup .roots .get(screen_num) .ok_or_else(|| anyhow!("invalid screen num: {}", screen_num))?; // Create the actual window conn.create_window( // Window depth x11rb::COPY_FROM_PARENT.try_into().unwrap(), // The new window's ID id, // Parent window of this new window screen.root, // X-coordinate of the new window 0, // Y-coordinate of the new window 0, // Width of the new window 1, // Height of the new window 1, // Border width 0, // Window class type WindowClass::INPUT_ONLY, // Visual ID x11rb::COPY_FROM_PARENT, // Window properties mask &CreateWindowAux::new().event_mask(EventMask::STRUCTURE_NOTIFY), )? .check() .context("create input-only window")?; Ok(id) } pub(crate) fn add_window(&self, id: u32, window: Rc<Window>) -> Result<(), Error> { borrow_mut!(self.state)?.windows.insert(id, window); Ok(()) } /// Remove the specified window from the `Application` and return the number of windows left. fn remove_window(&self, id: u32) -> Result<usize, Error> { let mut state = borrow_mut!(self.state)?; state.windows.remove(&id); Ok(state.windows.len()) } fn window(&self, id: u32) -> Result<Rc<Window>, Error> { borrow!(self.state)? .windows .get(&id) .cloned() .ok_or_else(|| anyhow!("No window with id {}", id)) } #[inline] pub(crate) fn connection(&self) -> &Rc<XCBConnection> { &self.connection } #[inline] pub(crate) fn screen_num(&self) -> usize { self.screen_num } #[inline] pub(crate) fn argb_visual_type(&self) -> Option<Visualtype> { // Check if a composite manager is running let atom_name = format!("_NET_WM_CM_S{}", self.screen_num); let owner = self .connection .intern_atom(false, atom_name.as_bytes()) .ok() .and_then(|cookie| cookie.reply().ok()) .map(|reply| reply.atom) .and_then(|atom| self.connection.get_selection_owner(atom).ok()) .and_then(|cookie| cookie.reply().ok()) .map(|reply| reply.owner); if Some(x11rb::NONE) == owner { tracing::debug!("_NET_WM_CM_Sn selection is unowned, not providing ARGB visual"); None } else { self.argb_visual_type } } #[inline] pub(crate) fn root_visual_type(&self) -> Visualtype { self.root_visual_type } #[inline] pub(crate) fn atoms(&self) -> &AppAtoms { &self.atoms } /// Returns `Ok(true)` if we want to exit the main loop. fn handle_event(&self, ev: &Event) -> Result<bool, Error> { if ev.server_generated() { // Update our latest timestamp let timestamp = match ev { Event::KeyPress(ev) => ev.time, Event::KeyRelease(ev) => ev.time, Event::ButtonPress(ev) => ev.time, Event::ButtonRelease(ev) => ev.time, Event::MotionNotify(ev) => ev.time, Event::EnterNotify(ev) => ev.time, Event::LeaveNotify(ev) => ev.time, Event::PropertyNotify(ev) => ev.time, _ => self.timestamp.get(), }; self.timestamp.set(timestamp); } match ev { // NOTE: When adding handling for any of the following events, // there must be a check against self.window_id // to know if the event must be ignored. // Otherwise there will be a "failed to get window" error. // // CIRCULATE_NOTIFY, GRAVITY_NOTIFY // MAP_NOTIFY, REPARENT_NOTIFY, UNMAP_NOTIFY Event::Expose(ev) => { let w = self .window(ev.window) .context("EXPOSE - failed to get window")?; w.handle_expose(ev).context("EXPOSE - failed to handle")?; } Event::KeyPress(ev) => { let w = self .window(ev.event) .context("KEY_PRESS - failed to get window")?; let hw_keycode = ev.detail; let mut state = borrow_mut!(self.state)?; let key_event = state.xkb_state.key_event( hw_keycode as _, keyboard_types::KeyState::Down, false, ); w.handle_key_event(key_event); } Event::KeyRelease(ev) => { let w = self .window(ev.event) .context("KEY_PRESS - failed to get window")?; let hw_keycode = ev.detail; let mut state = borrow_mut!(self.state)?; let key_event = state .xkb_state .key_event(hw_keycode as _, keyboard_types::KeyState::Up, false); w.handle_key_event(key_event); } Event::ButtonPress(ev) => { let w = self .window(ev.event) .context("BUTTON_PRESS - failed to get window")?; // X doesn't have dedicated scroll events: it uses mouse buttons instead. // Buttons 4/5 are vertical; 6/7 are horizontal. if ev.detail >= 4 && ev.detail <= 7 { w.handle_wheel(ev) .context("BUTTON_PRESS - failed to handle wheel")?; } else { w.handle_button_press(ev)?; } } Event::ButtonRelease(ev) => { let w = self .window(ev.event) .context("BUTTON_RELEASE - failed to get window")?; if ev.detail >= 4 && ev.detail <= 7 { // This is the release event corresponding to a mouse wheel. // Ignore it: we already handled the press event. } else { w.handle_button_release(ev)?; } } Event::MotionNotify(ev) => { let w = self .window(ev.event) .context("MOTION_NOTIFY - failed to get window")?; w.handle_motion_notify(ev)?; } Event::ClientMessage(ev) => { let w = self .window(ev.window) .context("CLIENT_MESSAGE - failed to get window")?; w.handle_client_message(ev); } Event::DestroyNotify(ev) => { if ev.window == self.window_id { // The destruction of the Application window means that // we need to quit the run loop. return Ok(true); } let w = self .window(ev.window) .context("DESTROY_NOTIFY - failed to get window")?; w.handle_destroy_notify(ev); // Remove our reference to the Window and allow it to be dropped let windows_left = self .remove_window(ev.window) .context("DESTROY_NOTIFY - failed to remove window")?; // Check if we need to finalize a quit request if windows_left == 0 && borrow!(self.state)?.quitting { self.finalize_quit(); } } Event::ConfigureNotify(ev) => { if ev.window != self.window_id { let w = self .window(ev.window) .context("CONFIGURE_NOTIFY - failed to get window")?; w.handle_configure_notify(ev) .context("CONFIGURE_NOTIFY - failed to handle")?; } } Event::PresentCompleteNotify(ev) => { let w = self .window(ev.window) .context("COMPLETE_NOTIFY - failed to get window")?; w.handle_complete_notify(ev) .context("COMPLETE_NOTIFY - failed to handle")?; } Event::PresentIdleNotify(ev) => { let w = self .window(ev.window) .context("IDLE_NOTIFY - failed to get window")?; w.handle_idle_notify(ev) .context("IDLE_NOTIFY - failed to handle")?; } Event::SelectionClear(ev) => { self.clipboard .handle_clear(*ev) .context("SELECTION_CLEAR event handling for clipboard")?; self.primary .handle_clear(*ev) .context("SELECTION_CLEAR event handling for primary")?; } Event::SelectionRequest(ev) => { self.clipboard .handle_request(ev) .context("SELECTION_REQUEST event handling for clipboard")?; self.primary .handle_request(ev) .context("SELECTION_REQUEST event handling for primary")?; } Event::PropertyNotify(ev) => { self.clipboard .handle_property_notify(*ev) .context("PROPERTY_NOTIFY event handling for clipboard")?; self.primary .handle_property_notify(*ev) .context("PROPERTY_NOTIFY event handling for primary")?; } Event::FocusIn(ev) => { let w = self .window(ev.event) .context("FOCUS_IN - failed to get window")?; w.handle_got_focus(); } Event::FocusOut(ev) => { let w = self .window(ev.event) .context("FOCUS_OUT - failed to get window")?; w.handle_lost_focus(); } Event::Error(e) => { // TODO: if an error is caused by the present extension, disable it and fall back // to copying pixels. This was blocked on // https://github.com/psychon/x11rb/issues/503 but no longer is return Err(x11rb::errors::ReplyError::from(e.clone()).into()); } _ => {} } Ok(false) } fn run_inner(self) -> Result<(), Error> { // Try to figure out the refresh rate of the current screen. We run the idle loop at that // rate. The rate-limiting of the idle loop has two purposes: // - When the present extension is disabled, we paint in the idle loop. By limiting the // idle loop to the monitor's refresh rate, we aren't painting unnecessarily. // - By running idle commands at a limited rate, we limit spurious wake-ups: if the X11 // connection is otherwise idle, we'll wake up at most once per frame, run *all* the // pending idle commands, and then go back to sleep. let refresh_rate = util::refresh_rate(self.connection(), self.window_id).unwrap_or(60.0); let timeout = Duration::from_millis((1000.0 / refresh_rate) as u64); let mut last_idle_time = Instant::now(); loop { // Figure out when the next wakeup needs to happen let next_timeout = if let Ok(state) = self.state.try_borrow() { state .windows .values() .filter_map(|w| w.next_timeout()) .min() } else { tracing::error!("Getting next timeout, application state already borrowed"); None }; let next_idle_time = last_idle_time + timeout; self.connection.flush()?; // Deal with pending events let mut event = self.pending_events.borrow_mut().pop_front(); // Before we poll on the connection's file descriptor, check whether there are any // events ready. It could be that XCB has some events in its internal buffers because // of something that happened during the idle loop. if event.is_none() { event = self.connection.poll_for_event()?; } if event.is_none() { poll_with_timeout( &self.connection, self.idle_read, next_timeout, next_idle_time, ) .context("Error while waiting for X11 connection")?; } while let Some(ev) = event { match self.handle_event(&ev) { Ok(quit) => { if quit { return Ok(()); } } Err(e) => { tracing::error!("Error handling event: {:#}", e); } } event = self.connection.poll_for_event()?; } let now = Instant::now(); if let Some(timeout) = next_timeout { if timeout <= now { if let Ok(state) = self.state.try_borrow() { let values = state.windows.values().cloned().collect::<Vec<_>>(); drop(state); for w in values { w.run_timers(now); } } else { tracing::error!("In timer loop, application state already borrowed"); } } } if now >= next_idle_time { last_idle_time = now; drain_idle_pipe(self.idle_read)?; if let Ok(state) = self.state.try_borrow() { for w in state.windows.values() { w.run_idle(); } } else { tracing::error!("In idle loop, application state already borrowed"); } } } } pub fn run(self, _handler: Option<Box<dyn AppHandler>>) { if let Err(e) = self.run_inner() { tracing::error!("{}", e); } } pub fn quit(&self) { if let Ok(mut state) = self.state.try_borrow_mut() { if !state.quitting { state.quitting = true; if state.windows.is_empty() { // There are no windows left, so we can immediately finalize the quit. self.finalize_quit(); } else { // We need to queue up the destruction of all our windows. // Failure to do so will lead to resource leaks. for window in state.windows.values() { window.destroy(); } } } } else { tracing::error!("Application state already borrowed"); } } fn finalize_quit(&self) { log_x11!(self.connection.destroy_window(self.window_id)); if let Err(e) = nix::unistd::close(self.idle_read) { tracing::error!("Error closing idle_read: {}", e); } if let Err(e) = nix::unistd::close(self.idle_write) { tracing::error!("Error closing idle_write: {}", e); } } pub fn clipboard(&self) -> Clipboard { self.clipboard.clone() } pub fn get_locale() -> String { linux::env::locale() } pub(crate) fn idle_pipe(&self) -> RawFd { self.idle_write } } impl crate::platform::linux::ApplicationExt for crate::Application { fn primary_clipboard(&self) -> crate::Clipboard { self.backend_app.primary.clone().into() } } /// Clears out our idle pipe; `idle_read` should be the reading end of a pipe that was opened with /// O_NONBLOCK. fn drain_idle_pipe(idle_read: RawFd) -> Result<(), Error> { // Each write to the idle pipe adds one byte; it's unlikely that there will be much in it, but // read it 16 bytes at a time just in case. let mut read_buf = [0u8; 16]; loop { match nix::unistd::read(idle_read, &mut read_buf[..]) { Err(nix::errno::Errno::EINTR) => {} // According to write(2), this is the outcome of reading an empty, O_NONBLOCK // pipe. Err(nix::errno::Errno::EAGAIN) => { break; } Err(e) => { return Err(e).context("Failed to read from idle pipe"); } // According to write(2), this is the outcome of reading an O_NONBLOCK pipe // when the other end has been closed. This shouldn't happen to us because we // own both ends, but just in case. Ok(0) => { break; } Ok(_) => {} } } Ok(()) } /// Returns when there is an event ready to read from `conn`, or we got signalled by another thread /// writing into our idle pipe and the `timeout` has passed. // This was taken, with minor modifications, from the xclock_utc example in the x11rb crate.
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/util.rs
druid-shell/src/backend/x11/util.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Miscellaneous utility functions for working with X11. use std::rc::Rc; use anyhow::{anyhow, Error}; use x11rb::connection::RequestConnection; use x11rb::errors::ReplyError; use x11rb::protocol::randr::{ConnectionExt, ModeFlag}; use x11rb::protocol::render::{self, ConnectionExt as _}; use x11rb::protocol::xproto::{Screen, Visualid, Visualtype, Window}; use x11rb::xcb_ffi::XCBConnection; // See: https://github.com/rtbo/rust-xcb/blob/master/examples/randr_screen_modes.rs pub fn refresh_rate(conn: &Rc<XCBConnection>, window_id: Window) -> Option<f64> { let try_refresh_rate = || -> Result<f64, Error> { let reply = conn.randr_get_screen_resources(window_id)?.reply()?; // TODO(x11/render_improvements): Figure out a more correct way of getting the screen's refresh rate. // Or maybe we don't even need this function if I figure out a better way to schedule redraws? // Assuming the first mode is the one we want to use. This is probably a bug on some setups. // Any better way to find the correct one? reply .modes .first() .ok_or_else(|| anyhow!("didn't get any modes")) .and_then(|mode_info| { let flags = mode_info.mode_flags; let vtotal = { let mut val = mode_info.vtotal; if (flags & u32::from(ModeFlag::DOUBLE_SCAN)) != 0 { val *= 2; } if (flags & u32::from(ModeFlag::INTERLACE)) != 0 { val /= 2; } val }; if vtotal != 0 && mode_info.htotal != 0 { Ok((mode_info.dot_clock as f64) / (vtotal as f64 * mode_info.htotal as f64)) } else { Err(anyhow!("got nonsensical mode values")) } }) }; match try_refresh_rate() { Err(e) => { tracing::error!("failed to find refresh rate: {}", e); None } Ok(r) => Some(r), } } // Apparently you have to get the visualtype this way :| fn find_visual_from_screen(screen: &Screen, visual_id: u32) -> Option<Visualtype> { for depth in &screen.allowed_depths { for visual in &depth.visuals { if visual.visual_id == visual_id { return Some(*visual); } } } None } pub fn get_visual_from_screen(screen: &Screen) -> Option<Visualtype> { find_visual_from_screen(screen, screen.root_visual) } pub fn get_argb_visual_type( conn: &XCBConnection, screen: &Screen, ) -> Result<Option<Visualtype>, ReplyError> { fn find_visual_for_format( reply: &render::QueryPictFormatsReply, id: render::Pictformat, ) -> Option<Visualid> { let find_in_depth = |depth: &render::Pictdepth| { depth .visuals .iter() .find(|visual| visual.format == id) .map(|visual| visual.visual) }; let find_in_screen = |screen: &render::Pictscreen| screen.depths.iter().find_map(find_in_depth); reply.screens.iter().find_map(find_in_screen) } // Getting a visual is already funny, but finding the ARGB32 visual is even more fun. // RENDER has picture formats. Each format corresponds to a visual. Thus, we first find the // right picture format, then find the corresponding visual id, then the Visualtype. if conn .extension_information(render::X11_EXTENSION_NAME)? .is_none() { // RENDER not supported Ok(None) } else { let pict_formats = conn.render_query_pict_formats()?.reply()?; // Find the ARGB32 standard format let res = pict_formats .formats .iter() .find(|format| { format.type_ == render::PictType::DIRECT && format.depth == 32 && format.direct.red_shift == 16 && format.direct.red_mask == 0xff && format.direct.green_shift == 8 && format.direct.green_mask == 0xff && format.direct.blue_shift == 0 && format.direct.blue_mask == 0xff && format.direct.alpha_shift == 24 && format.direct.alpha_mask == 0xff }) // Now find the corresponding visual ID .and_then(|format| find_visual_for_format(&pict_formats, format.id)) // And finally, we can find the visual .and_then(|visual_id| find_visual_from_screen(screen, visual_id)); Ok(res) } } macro_rules! log_x11 { ($val:expr) => { if let Err(e) = $val { // We probably don't want to include file/line numbers. This logging is done in // a context where X11 errors probably just mean that the connection to the X server // was lost. In particular, it doesn't represent a druid-shell bug for which we want // more context. tracing::error!("X11 error: {}", e); } }; }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/mod.rs
druid-shell/src/backend/x11/mod.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! X11 implementation of `druid-shell`. // TODO(x11/render_improvements): screen is currently flashing when resizing in perftest. // Might be related to the "sleep scheduler" in XWindow::render()? // TODO(x11/render_improvements): double-buffering / present strategies / etc? // # Notes on error handling in X11 // // In XCB, errors are reported asynchronously by default, by sending them to the event // loop. You can also request a synchronous error for a given call; we use this in // window initialization, but otherwise we take the async route. // // When checking for X11 errors synchronously, there are two places where the error could // happen. An error on the request means the connection is broken. There's no need for // extra error context here, because the fact that the connection broke has nothing to do // with what we're trying to do. An error on the reply means there was something wrong with // the request, and so we add context. This convention is used throughout the x11 backend. #[macro_use] mod util; pub mod application; pub mod clipboard; pub mod dialog; pub mod error; pub mod menu; pub mod screen; pub mod window;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/window.rs
druid-shell/src/backend/x11/window.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! X11 window creation and window management. use std::cell::{Cell, RefCell}; use std::collections::BinaryHeap; use std::convert::{TryFrom, TryInto}; use std::os::unix::io::RawFd; use std::panic::Location; use std::rc::{Rc, Weak}; use std::sync::{Arc, Mutex}; use std::time::Instant; use crate::scale::Scalable; use anyhow::{anyhow, Context, Error}; use cairo::{XCBConnection as CairoXCBConnection, XCBDrawable, XCBSurface, XCBVisualType}; use tracing::{error, info, warn}; use x11rb::connection::Connection; use x11rb::errors::ReplyOrIdError; use x11rb::properties::{WmHints, WmHintsState, WmSizeHints}; use x11rb::protocol::present::{CompleteNotifyEvent, ConnectionExt as _, IdleNotifyEvent}; use x11rb::protocol::render::{ConnectionExt as _, Pictformat}; use x11rb::protocol::xfixes::{ConnectionExt as _, Region as XRegion}; use x11rb::protocol::xproto::{ self, AtomEnum, ChangeWindowAttributesAux, ColormapAlloc, ConfigureNotifyEvent, ConfigureWindowAux, ConnectionExt, CreateGCAux, EventMask, Gcontext, ImageFormat, ImageOrder as X11ImageOrder, Pixmap, PropMode, Rectangle, Visualtype, WindowClass, }; use x11rb::wrapper::ConnectionExt as _; use x11rb::xcb_ffi::XCBConnection; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, XcbWindowHandle}; use crate::backend::shared::Timer; use crate::common_util::IdleCallback; use crate::dialog::FileDialogOptions; use crate::error::Error as ShellError; use crate::keyboard::{KeyState, Modifiers}; use crate::kurbo::{Insets, Point, Rect, Size, Vec2}; use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent}; use crate::piet::{Piet, PietText, RenderContext}; use crate::region::Region; use crate::scale::Scale; use crate::text::{simulate_input, Event}; use crate::window::{ FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel, }; use crate::{window, KeyEvent, ScaledArea}; use super::application::Application; use super::dialog; use super::menu::Menu; /// A version of XCB's `xcb_visualtype_t` struct. This was copied from the [example] in x11rb; it /// is used to interoperate with cairo. /// /// The official upstream reference for this struct definition is [here]. /// /// [example]: https://github.com/psychon/x11rb/blob/master/cairo-example/src/main.rs /// [here]: https://xcb.freedesktop.org/manual/structxcb__visualtype__t.html #[derive(Debug, Clone, Copy)] #[repr(C)] pub struct xcb_visualtype_t { pub visual_id: u32, pub class: u8, pub bits_per_rgb_value: u8, pub colormap_entries: u16, pub red_mask: u32, pub green_mask: u32, pub blue_mask: u32, pub pad0: [u8; 4], } impl From<Visualtype> for xcb_visualtype_t { fn from(value: Visualtype) -> xcb_visualtype_t { xcb_visualtype_t { visual_id: value.visual_id, class: value.class.into(), bits_per_rgb_value: value.bits_per_rgb_value, colormap_entries: value.colormap_entries, red_mask: value.red_mask, green_mask: value.green_mask, blue_mask: value.blue_mask, pad0: [0; 4], } } } fn size_hints(resizable: bool, size: Size, min_size: Size) -> WmSizeHints { let mut size_hints = WmSizeHints::new(); if resizable { size_hints.min_size = Some((min_size.width as i32, min_size.height as i32)); } else { size_hints.min_size = Some((size.width as i32, size.height as i32)); size_hints.max_size = Some((size.width as i32, size.height as i32)); } size_hints } pub(crate) struct WindowBuilder { app: Application, handler: Option<Box<dyn WinHandler>>, title: String, transparent: bool, position: Option<Point>, size: Size, min_size: Size, resizable: bool, level: WindowLevel, always_on_top: bool, state: Option<window::WindowState>, } impl WindowBuilder { pub fn new(app: Application) -> WindowBuilder { WindowBuilder { app, handler: None, title: String::new(), transparent: false, position: None, size: Size::new(500.0, 400.0), min_size: Size::new(0.0, 0.0), resizable: true, level: WindowLevel::AppWindow, always_on_top: false, state: None, } } pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.handler = Some(handler); } pub fn set_size(&mut self, size: Size) { // zero sized window results in server error self.size = if size.width == 0. || size.height == 0. { Size::new(1., 1.) } else { size }; } pub fn set_min_size(&mut self, min_size: Size) { self.min_size = min_size; } pub fn resizable(&mut self, resizable: bool) { self.resizable = resizable; } pub fn show_titlebar(&mut self, _show_titlebar: bool) { // not sure how to do this, maybe _MOTIF_WM_HINTS? warn!("WindowBuilder::show_titlebar is currently unimplemented for X11 backend."); } pub fn set_transparent(&mut self, transparent: bool) { self.transparent = transparent; } pub fn set_position(&mut self, position: Point) { self.position = Some(position); } pub fn set_always_on_top(&mut self, always_on_top: bool) { self.always_on_top = always_on_top; } pub fn set_level(&mut self, level: window::WindowLevel) { self.level = level; } pub fn set_window_state(&mut self, state: window::WindowState) { self.state = Some(state); } pub fn set_title<S: Into<String>>(&mut self, title: S) { self.title = title.into(); } pub fn set_menu(&mut self, _menu: Menu) { // TODO(x11/menus): implement WindowBuilder::set_menu (currently a no-op) } fn create_cairo_surface( &self, window_id: u32, visual_type: &Visualtype, ) -> Result<XCBSurface, Error> { let conn = self.app.connection(); let cairo_xcb_connection = unsafe { CairoXCBConnection::from_raw_none( conn.get_raw_xcb_connection() as *mut cairo::ffi::xcb_connection_t ) }; let cairo_drawable = XCBDrawable(window_id); let mut xcb_visual = xcb_visualtype_t::from(*visual_type); let cairo_visual_type = unsafe { XCBVisualType::from_raw_none( &mut xcb_visual as *mut xcb_visualtype_t as *mut cairo::ffi::xcb_visualtype_t, ) }; let cairo_surface = XCBSurface::create( &cairo_xcb_connection, &cairo_drawable, &cairo_visual_type, self.size.width as i32, self.size.height as i32, ) .map_err(|status| anyhow!("Failed to create cairo surface: {}", status))?; Ok(cairo_surface) } // TODO(x11/menus): make menus if requested pub fn build(self) -> Result<WindowHandle, Error> { let conn = self.app.connection(); let screen_num = self.app.screen_num(); let id = conn.generate_id()?; let setup = conn.setup(); let env_dpi = std::env::var("DRUID_X11_DPI") .ok() .map(|x| x.parse::<f64>()); let scale = match env_dpi.or_else(|| self.app.rdb.get_value("Xft.dpi", "").transpose()) { Some(Ok(dpi)) => { let scale = dpi / 96.; Scale::new(scale, scale) } None => Scale::default(), Some(Err(err)) => { let default = Scale::default(); warn!( "Unable to parse dpi: {:?}, defaulting to {:?}", err, default ); default } }; let size_px = self.size.to_px(scale); let screen = setup .roots .get(screen_num) .ok_or_else(|| anyhow!("Invalid screen num: {}", screen_num))?; let visual_type = if self.transparent { self.app.argb_visual_type() } else { None }; let (transparent, visual_type) = match visual_type { Some(visual) => (true, visual), None => (false, self.app.root_visual_type()), }; if transparent != self.transparent { warn!("Windows with transparent backgrounds do not work"); } let mut cw_values = xproto::CreateWindowAux::new().event_mask( EventMask::EXPOSURE | EventMask::STRUCTURE_NOTIFY | EventMask::KEY_PRESS | EventMask::KEY_RELEASE | EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE | EventMask::POINTER_MOTION | EventMask::FOCUS_CHANGE, ); if transparent { let colormap = conn.generate_id()?; conn.create_colormap( ColormapAlloc::NONE, colormap, screen.root, visual_type.visual_id, )?; cw_values = cw_values .border_pixel(screen.white_pixel) .colormap(colormap); }; let (parent, parent_origin) = match &self.level { WindowLevel::AppWindow => (Weak::new(), Vec2::ZERO), WindowLevel::Tooltip(parent) | WindowLevel::DropDown(parent) | WindowLevel::Modal(parent) => { let handle = parent.0.window.clone(); let origin = handle .upgrade() .map(|x| x.get_position()) .unwrap_or_default() .to_vec2(); (handle, origin) } }; let pos = (self.position.unwrap_or_default() + parent_origin).to_px(scale); // Create the actual window let (width_px, height_px) = (size_px.width as u16, size_px.height as u16); let depth = if transparent { 32 } else { screen.root_depth }; conn.create_window( // Window depth depth, // The new window's ID id, // Parent window of this new window // TODO(#468): either `screen.root()` (no parent window) or pass parent here to attach screen.root, // X-coordinate of the new window pos.x as _, // Y-coordinate of the new window pos.y as _, // Width of the new window width_px, // Height of the new window height_px, // Border width 0, // Window class type WindowClass::INPUT_OUTPUT, // Visual ID visual_type.visual_id, // Window properties mask &cw_values, )? .check() .context("create window")?; if let Some(colormap) = cw_values.colormap { conn.free_colormap(colormap)?; } // Allocate a graphics context (currently used only for copying pixels when present is // unavailable). let gc = conn.generate_id()?; conn.create_gc(gc, id, &CreateGCAux::new())? .check() .context("create graphics context")?; // TODO(x11/errors): Should do proper cleanup (window destruction etc) in case of error let cairo_surface = RefCell::new(self.create_cairo_surface(id, &visual_type)?); let present_data = match self.initialize_present_data(id) { Ok(p) => Some(p), Err(e) => { info!("Failed to initialize present extension: {}", e); None } }; let handler = RefCell::new(self.handler.unwrap()); // When using present, we generally need two buffers (because after we present, we aren't // allowed to use that buffer for a little while, and so we might want to render to the // other one). Otherwise, we only need one. let buf_count = if present_data.is_some() { 2 } else { 1 }; let buffers = RefCell::new(Buffers::new( conn, id, buf_count, width_px, height_px, depth, )?); // Initialize some properties let atoms = self.app.atoms(); let pid = nix::unistd::Pid::this().as_raw(); if let Ok(pid) = u32::try_from(pid) { conn.change_property32( xproto::PropMode::REPLACE, id, atoms._NET_WM_PID, AtomEnum::CARDINAL, &[pid], )? .check() .context("set _NET_WM_PID")?; } if let Some(name) = std::env::args_os().next() { // ICCCM § 4.1.2.5: // The WM_CLASS property (of type STRING without control characters) contains two // consecutive null-terminated strings. These specify the Instance and Class names. // // The code below just imitates what happens on the gtk backend: // - instance: The program's name // - class: The program's name with first letter in upper case // Get the name of the running binary let path: &std::path::Path = name.as_ref(); let name = path .file_name() .and_then(|name| name.to_str()) .unwrap_or(""); // Build the contents of WM_CLASS let mut wm_class = Vec::with_capacity(2 * (name.len() + 1)); wm_class.extend(name.as_bytes()); wm_class.push(0); if let Some(&first) = wm_class.first() { wm_class.push(first.to_ascii_uppercase()); wm_class.extend(&name.as_bytes()[1..]); } wm_class.push(0); conn.change_property8( PropMode::REPLACE, id, AtomEnum::WM_CLASS, AtomEnum::STRING, &wm_class, )?; } else { // GTK (actually glib) goes fishing in /proc (platform_get_argv0()). We pass. } // Replace the window's WM_PROTOCOLS with the following. let protocols = [atoms.WM_DELETE_WINDOW]; conn.change_property32( PropMode::REPLACE, id, atoms.WM_PROTOCOLS, AtomEnum::ATOM, &protocols, )? .check() .context("set WM_PROTOCOLS")?; let min_size = self.min_size.to_px(scale); log_x11!(size_hints(self.resizable, size_px, min_size) .set_normal_hints(conn.as_ref(), id) .context("set wm normal hints")); // TODO: set _NET_WM_STATE let mut hints = WmHints::new(); if let Some(state) = self.state { hints.initial_state = Some(match state { window::WindowState::Maximized => WmHintsState::Normal, window::WindowState::Minimized => WmHintsState::Iconic, window::WindowState::Restored => WmHintsState::Normal, }); } log_x11!(hints.set(conn.as_ref(), id).context("set wm hints")); // set level { let window_type = match self.level { WindowLevel::AppWindow => atoms._NET_WM_WINDOW_TYPE_NORMAL, WindowLevel::Tooltip(_) => atoms._NET_WM_WINDOW_TYPE_TOOLTIP, WindowLevel::Modal(_) => atoms._NET_WM_WINDOW_TYPE_DIALOG, WindowLevel::DropDown(_) => atoms._NET_WM_WINDOW_TYPE_DROPDOWN_MENU, }; let conn = self.app.connection(); log_x11!(conn.change_property32( xproto::PropMode::REPLACE, id, atoms._NET_WM_WINDOW_TYPE, AtomEnum::ATOM, &[window_type], )); if matches!( self.level, WindowLevel::DropDown(_) | WindowLevel::Modal(_) | WindowLevel::Tooltip(_) ) { log_x11!(conn.change_window_attributes( id, &ChangeWindowAttributesAux::new().override_redirect(1), )); } } let window = Rc::new(Window { id, gc, app: self.app.clone(), handler, cairo_surface, area: Cell::new(ScaledArea::from_px(size_px, scale)), scale: Cell::new(scale), min_size, invalid: RefCell::new(Region::EMPTY), destroyed: Cell::new(false), timer_queue: Mutex::new(BinaryHeap::new()), idle_queue: Arc::new(Mutex::new(Vec::new())), idle_pipe: self.app.idle_pipe(), present_data: RefCell::new(present_data), buffers, active_text_field: Cell::new(None), parent, }); window.set_title(&self.title); if let Some(pos) = self.position { window.set_position(pos); } let handle = WindowHandle::new(id, visual_type.visual_id, Rc::downgrade(&window)); window.connect(handle.clone())?; self.app.add_window(id, window)?; Ok(handle) } fn initialize_present_data(&self, window_id: u32) -> Result<PresentData, Error> { if self.app.present_opcode().is_some() { let conn = self.app.connection(); // We use the CompleteNotify events to schedule the next frame, and the IdleNotify // events to manage our buffers. let id = conn.generate_id()?; use x11rb::protocol::present::EventMask; conn.present_select_input( id, window_id, EventMask::COMPLETE_NOTIFY | EventMask::IDLE_NOTIFY, )? .check() .context("set present event mask")?; let region_id = conn.generate_id()?; conn.xfixes_create_region(region_id, &[]) .context("create region")?; Ok(PresentData { serial: 0, region: region_id, waiting_on: None, needs_present: false, last_msc: None, last_ust: None, }) } else { Err(anyhow!("no present opcode")) } } } /// An X11 window. // // We use lots of RefCells here, so to avoid panics we need some rules. The basic observation is // that there are two ways we can end up calling the code in this file: // // 1) it either comes from the system (e.g. through some X11 event), or // 2) from the client (e.g. druid, calling a method on its `WindowHandle`). // // Note that 2 only ever happens as a result of 1 (i.e., the system calls us, we call the client // using the `WinHandler`, and it calls us back). The rules are: // // a) We never call into the system as a result of 2. As a consequence, we never get 1 // re-entrantly. // b) We *almost* never call into the `WinHandler` while holding any of the other RefCells. There's // an exception for `paint`. This is enforced by the `with_handler` method. // (TODO: we could try to encode this exception statically, by making the data accessible in // case 2 smaller than the data accessible in case 1). pub(crate) struct Window { id: u32, gc: Gcontext, app: Application, handler: RefCell<Box<dyn WinHandler>>, cairo_surface: RefCell<XCBSurface>, area: Cell<ScaledArea>, scale: Cell<Scale>, // min size in px min_size: Size, /// We've told X11 to destroy this window, so don't do any more X requests with this window id. destroyed: Cell<bool>, /// The region that was invalidated since the last time we rendered. invalid: RefCell<Region>, /// Timers, sorted by "earliest deadline first" timer_queue: Mutex<BinaryHeap<Timer<()>>>, idle_queue: Arc<Mutex<Vec<IdleKind>>>, // Writing to this wakes up the event loop, so that it can run idle handlers. idle_pipe: RawFd, /// When this is `Some(_)`, we use the X11 Present extension to present windows. This syncs all /// presentation to vblank and it appears to prevent tearing (subject to various caveats /// regarding broken video drivers). /// /// The Present extension works roughly like this: we submit a pixmap for presentation. It will /// get drawn at the next vblank, and some time shortly after that we'll get a notification /// that the drawing was completed. /// /// There are three ways that rendering can get triggered: /// 1) We render a frame, and it signals to us that an animation is requested. In this case, we /// will render the next frame as soon as we get a notification that the just-presented /// frame completed. In other words, we use `CompleteNotifyEvent` to schedule rendering. /// 2) We get an expose event telling us that a region got invalidated. In /// this case, we will render the next frame immediately unless we're already waiting for a /// completion notification. (If we are waiting for a completion notification, we just make /// a note to schedule a new frame once we get it.) /// 3) Someone calls `invalidate` or `invalidate_rect` on us. We schedule ourselves to repaint /// in the idle loop. This is better than rendering straight away, because for example they /// might have called `invalidate` from their paint callback, and then we'd end up painting /// re-entrantively. /// /// This is probably not the best (or at least, not the lowest-latency) scheme we can come up /// with, because invalidations that happen shortly after a vblank might need to wait 2 frames /// before they appear. If we're getting lots of invalidations, it might be better to render more /// than once per frame. Note that if we do, it will require some changes to part 1) above, /// because if we render twice in a frame then we will get two completion notifications in a /// row, so we don't want to present on both of them. The `msc` field of the completion /// notification might be useful here, because it allows us to check how many frames have /// actually been presented. present_data: RefCell<Option<PresentData>>, buffers: RefCell<Buffers>, active_text_field: Cell<Option<TextFieldToken>>, parent: Weak<Window>, } /// A collection of pixmaps for rendering to. This gets used in two different ways: if the present /// extension is enabled, we render to a pixmap and then present it. If the present extension is /// disabled, we render to a pixmap and then call `copy_area` on it (this probably isn't the best /// way to imitate double buffering, but it's the fallback anyway). struct Buffers { /// A list of idle pixmaps. We take a pixmap from here for rendering to. /// /// When we're not using the present extension, all pixmaps belong in here; as soon as we copy /// from one, we can use it again. /// /// When we submit a pixmap to present, we're not allowed to touch it again until we get a /// corresponding IDLE_NOTIFY event. In my limited experiments this happens shortly after /// vsync, meaning that we may want to start rendering the next pixmap before we get the old /// one back. Therefore, we keep a list of pixmaps. We pop one each time we render, and push /// one when we get IDLE_NOTIFY. /// /// Since the current code only renders at most once per vsync, two pixmaps seems to always be /// enough. Nevertheless, we will allocate more on the fly if we need them. Note that rendering /// more than once per vsync can only improve latency, because only the most recently-presented /// pixmap will get rendered. idle_pixmaps: Vec<Pixmap>, /// A list of all the allocated pixmaps (including the idle ones). all_pixmaps: Vec<Pixmap>, /// The sizes of the pixmaps (they all have the same size). In order to avoid repeatedly /// reallocating as the window size changes, we allow these to be bigger than the window. width: u16, height: u16, /// The depth of the currently allocated pixmaps. depth: u8, } /// The state involved in using X's [Present] extension. /// /// [Present]: https://cgit.freedesktop.org/xorg/proto/presentproto/tree/presentproto.txt #[derive(Debug)] struct PresentData { /// A monotonically increasing present request counter. serial: u32, /// The region that we use for telling X what to present. region: XRegion, /// Did we submit a present that hasn't completed yet? If so, this is its serial number. waiting_on: Option<u32>, /// We need to render another frame as soon as the current one is done presenting. needs_present: bool, /// The last MSC (media stream counter) that was completed. This can be used to diagnose /// latency problems, because MSC is a frame counter: it increments once per frame. We should /// be presenting on every frame, and storing the last completed MSC lets us know if we missed /// one. last_msc: Option<u64>, /// The time at which the last frame was completed. The present protocol documentation doesn't /// define the units, but it appears to be in microseconds. last_ust: Option<u64>, } #[derive(Clone, PartialEq, Eq)] pub struct CustomCursor(xproto::Cursor); impl Window { #[track_caller] fn with_handler<T, F: FnOnce(&mut dyn WinHandler) -> T>(&self, f: F) -> Option<T> { if self.cairo_surface.try_borrow_mut().is_err() || self.invalid.try_borrow_mut().is_err() || self.present_data.try_borrow_mut().is_err() || self.buffers.try_borrow_mut().is_err() { error!("other RefCells were borrowed when calling into the handler"); return None; } self.with_handler_and_dont_check_the_other_borrows(f) } #[track_caller] fn with_handler_and_dont_check_the_other_borrows<T, F: FnOnce(&mut dyn WinHandler) -> T>( &self, f: F, ) -> Option<T> { match self.handler.try_borrow_mut() { Ok(mut h) => Some(f(&mut **h)), Err(_) => { error!("failed to borrow WinHandler at {}", Location::caller()); None } } } fn connect(&self, handle: WindowHandle) -> Result<(), Error> { let size = self.size().size_dp(); let scale = self.scale.get(); self.with_handler(|h| { h.connect(&handle.into()); h.scale(scale); h.size(size); }); Ok(()) } /// Start the destruction of the window. pub fn destroy(&self) { if !self.destroyed() { self.destroyed.set(true); log_x11!(self.app.connection().destroy_window(self.id)); } } fn destroyed(&self) -> bool { self.destroyed.get() } fn size(&self) -> ScaledArea { self.area.get() } // note: size is in px fn size_changed(&self, size: Size) -> Result<(), Error> { let scale = self.scale.get(); let new_size = { if size != self.area.get().size_px() { self.area.set(ScaledArea::from_px(size, scale)); true } else { false } }; if new_size { borrow_mut!(self.buffers)?.set_size( self.app.connection(), self.id, size.width as u16, size.height as u16, ); borrow_mut!(self.cairo_surface)? .set_size(size.width as i32, size.height as i32) .map_err(|status| { anyhow!( "Failed to update cairo surface size to {:?}: {}", size, status ) })?; self.add_invalid_rect(size.to_dp(scale).to_rect())?; self.with_handler(|h| h.size(size.to_dp(scale))); self.with_handler(|h| h.scale(scale)); } Ok(()) } // Ensure that our cairo context is targeting the right drawable, allocating one if necessary. fn update_cairo_surface(&self) -> Result<(), Error> { let mut buffers = borrow_mut!(self.buffers)?; let pixmap = if let Some(p) = buffers.idle_pixmaps.last() { *p } else { info!("ran out of idle pixmaps, creating a new one"); buffers.create_pixmap(self.app.connection(), self.id)? }; let drawable = XCBDrawable(pixmap); borrow_mut!(self.cairo_surface)? .set_drawable(&drawable, buffers.width as i32, buffers.height as i32) .map_err(|e| anyhow!("Failed to update cairo drawable: {}", e))?; Ok(()) } fn render(&self) -> Result<(), Error> { self.with_handler(|h| h.prepare_paint()); if self.destroyed() { return Ok(()); } self.update_cairo_surface()?; let invalid = std::mem::replace(&mut *borrow_mut!(self.invalid)?, Region::EMPTY); { let surface = borrow!(self.cairo_surface)?; let cairo_ctx = cairo::Context::new(&*surface).unwrap(); let scale = self.scale.get(); for rect in invalid.rects() { let rect = rect.to_px(scale).round(); cairo_ctx.rectangle(rect.x0, rect.y0, rect.width(), rect.height()); } cairo_ctx.clip(); cairo_ctx.scale(scale.x(), scale.y()); let mut piet_ctx = Piet::new(&cairo_ctx); // We need to be careful with earlier returns here, because piet_ctx // can panic if it isn't finish()ed. Also, we want to reset cairo's clip // even on error. // // Note that we're borrowing the surface while calling the handler. This is ok, because // we don't return control to the system or re-borrow the surface from any code that // the client can call. let result = self.with_handler_and_dont_check_the_other_borrows(|handler| { handler.paint(&mut piet_ctx, &invalid); piet_ctx .finish() .map_err(|e| anyhow!("Window::render - piet finish failed: {}", e)) }); let err = match result { None => { // The handler borrow failed, so finish didn't get called. piet_ctx .finish() .map_err(|e| anyhow!("Window::render - piet finish failed: {}", e)) } Some(e) => { // Finish might have errored, in which case we want to propagate it. e } }; cairo_ctx.reset_clip(); err?; } self.set_needs_present(false)?; let mut buffers = borrow_mut!(self.buffers)?; let pixmap = *buffers .idle_pixmaps .last() .ok_or_else(|| anyhow!("after rendering, no pixmap to present"))?; let scale = self.scale.get(); if let Some(present) = borrow_mut!(self.present_data)?.as_mut() { present.present(self.app.connection(), pixmap, self.id, &invalid, scale)?; buffers.idle_pixmaps.pop(); } else { for rect in invalid.rects() { let rect = rect.to_px(scale).round(); let (x, y) = (rect.x0 as i16, rect.y0 as i16); let (w, h) = (rect.width() as u16, rect.height() as u16); self.app .connection() .copy_area(pixmap, self.id, self.gc, x, y, x, y, w, h)?; } } Ok(()) } fn show(&self) { if !self.destroyed() { log_x11!(self.app.connection().map_window(self.id)); } } fn hide(&self) { if !self.destroyed() { log_x11!(self.app.connection().unmap_window(self.id)); } } fn close(&self) { self.destroy(); } /// Set whether the window should be resizable fn resizable(&self, resizable: bool) { let conn = self.app.connection().as_ref(); log_x11!(size_hints(resizable, self.size().size_px(), self.min_size) .set_normal_hints(conn, self.id) .context("set normal hints")); } /// Set whether the window should show titlebar
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/x11/screen.rs
druid-shell/src/backend/x11/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! X11 Monitors and Screen information. use x11rb::connection::Connection; use x11rb::errors::ReplyOrIdError; use x11rb::protocol::randr::{self, ConnectionExt as _, Crtc}; use x11rb::protocol::xproto::{Screen, Timestamp}; use crate::kurbo::Rect; use crate::screen::Monitor; fn monitor<Pos>(primary: bool, (x, y): (Pos, Pos), (width, height): (u16, u16)) -> Monitor where Pos: Into<i32>, { let rect = Rect::from_points( (x.into() as f64, y.into() as f64), (width as f64, height as f64), ); // TODO: Support for work_rect. It's complicated... Monitor::new(primary, rect, rect) } pub(crate) fn get_monitors() -> Vec<Monitor> { let result = if let Some(app) = crate::Application::try_global() { let app = app.backend_app; get_monitors_impl(app.connection().as_ref(), app.screen_num()) } else { let (conn, screen_num) = match x11rb::connect(None) { Ok(res) => res, Err(err) => { tracing::error!("Error in Screen::get_monitors(): {:?}", err); return Vec::new(); } }; get_monitors_impl(&conn, screen_num) }; match result { Ok(monitors) => monitors, Err(err) => { tracing::error!("Error in Screen::get_monitors(): {:?}", err); Vec::new() } } } fn get_monitors_impl( conn: &impl Connection, screen_num: usize, ) -> Result<Vec<Monitor>, ReplyOrIdError> { let screen = &conn.setup().roots[screen_num]; if conn .extension_information(randr::X11_EXTENSION_NAME)? .is_none() { return get_monitors_core(screen); } // Monitor support was added in RandR 1.5 let version = conn.randr_query_version(1, 5)?.reply()?; match (version.major_version, version.minor_version) { (major, _) if major >= 2 => get_monitors_randr_monitors(conn, screen), (1, minor) if minor >= 5 => get_monitors_randr_monitors(conn, screen), (1, minor) if minor >= 3 => get_monitors_randr_screen_resources_current(conn, screen), (1, minor) if minor >= 2 => get_monitors_randr_screen_resources(conn, screen), _ => get_monitors_core(screen), } } fn get_monitors_core(screen: &Screen) -> Result<Vec<Monitor>, ReplyOrIdError> { Ok(vec![monitor( true, (0, 0), (screen.width_in_pixels, screen.height_in_pixels), )]) } fn get_monitors_randr_monitors( conn: &impl Connection, screen: &Screen, ) -> Result<Vec<Monitor>, ReplyOrIdError> { let result = conn .randr_get_monitors(screen.root, true)? .reply()? .monitors .iter() .map(|info| monitor(info.primary, (info.x, info.y), (info.width, info.height))) .collect(); Ok(result) } fn get_monitors_randr_screen_resources_current( conn: &impl Connection, screen: &Screen, ) -> Result<Vec<Monitor>, ReplyOrIdError> { let reply = conn .randr_get_screen_resources_current(screen.root)? .reply()?; get_monitors_randr_crtcs_timestamp(conn, &reply.crtcs, reply.config_timestamp) } fn get_monitors_randr_screen_resources( conn: &impl Connection, screen: &Screen, ) -> Result<Vec<Monitor>, ReplyOrIdError> { let reply = conn.randr_get_screen_resources(screen.root)?.reply()?; get_monitors_randr_crtcs_timestamp(conn, &reply.crtcs, reply.config_timestamp) } // This function first sends a number of requests, collect()ing them into a Vec and then gets the // replies. This saves round-trips. Without the collect(), there would be one round-trip per CRTC. #[allow(clippy::needless_collect)] fn get_monitors_randr_crtcs_timestamp( conn: &impl Connection, crtcs: &[Crtc], config_timestamp: Timestamp, ) -> Result<Vec<Monitor>, ReplyOrIdError> { // Request information about all CRTCs let requests = crtcs .iter() .map(|&crtc| conn.randr_get_crtc_info(crtc, config_timestamp)) .collect::<Vec<_>>(); // Deal with CRTC information let mut result = Vec::new(); for request in requests.into_iter() { let reply = request?.reply()?; if reply.width != 0 && reply.height != 0 { // First CRTC is assumed to be the primary output let primary = result.is_empty(); result.push(monitor( primary, (reply.x, reply.y), (reply.width, reply.height), )); } } // TODO: I think we need to deduplicate monitors. In clone mode, each "clone" appears as its // own monitor otherwise. Ok(result) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/keycodes.rs
druid-shell/src/backend/gtk/keycodes.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK code handling. use gtk::gdk::keys::constants::*; pub use super::super::shared::hardware_keycode_to_code; use crate::keyboard_types::{Key, Location}; pub type RawKey = gtk::gdk::keys::Key; #[allow(clippy::just_underscores_and_digits, non_upper_case_globals)] pub fn raw_key_to_key(raw: RawKey) -> Option<Key> { // changes from x11 backend keycodes: // * XKB_KEY_ prefix removed // * 3270 is replaced with _3270 // * XF86 prefix is removed // * Sun* Keys are gone Some(match raw { BackSpace => Key::Backspace, Tab | KP_Tab | ISO_Left_Tab => Key::Tab, Clear | KP_Begin => Key::Clear, Return | KP_Enter => Key::Enter, Linefeed => Key::Enter, Pause => Key::Pause, Scroll_Lock => Key::ScrollLock, Escape => Key::Escape, Multi_key => Key::Compose, Kanji => Key::KanjiMode, Muhenkan => Key::NonConvert, Henkan_Mode => Key::Convert, Romaji => Key::Romaji, Hiragana => Key::Hiragana, Katakana => Key::Katakana, Hiragana_Katakana => Key::HiraganaKatakana, Zenkaku => Key::Zenkaku, Hankaku => Key::Hankaku, Zenkaku_Hankaku => Key::ZenkakuHankaku, Kana_Lock => Key::KanaMode, Eisu_Shift | Eisu_toggle => Key::Alphanumeric, Hangul => Key::HangulMode, Hangul_Hanja => Key::HanjaMode, Codeinput => Key::CodeInput, SingleCandidate => Key::SingleCandidate, MultipleCandidate => Key::AllCandidates, PreviousCandidate => Key::PreviousCandidate, Home | KP_Home => Key::Home, Left | KP_Left => Key::ArrowLeft, Up | KP_Up => Key::ArrowUp, Right | KP_Right => Key::ArrowRight, Down | KP_Down => Key::ArrowDown, Prior | KP_Prior => Key::PageUp, Next | KP_Next => Key::PageDown, End | KP_End => Key::End, Select => Key::Select, // Treat Print/PrintScreen as PrintScreen https://crbug.com/683097. Print | _3270_PrintScreen => Key::PrintScreen, Execute => Key::Execute, Insert | KP_Insert => Key::Insert, Undo => Key::Undo, Redo => Key::Redo, Menu => Key::ContextMenu, Find => Key::Find, Cancel => Key::Cancel, Help => Key::Help, Break | _3270_Attn => Key::Attn, Mode_switch => Key::ModeChange, Num_Lock => Key::NumLock, F1 | KP_F1 => Key::F1, F2 | KP_F2 => Key::F2, F3 | KP_F3 => Key::F3, F4 | KP_F4 => Key::F4, F5 => Key::F5, F6 => Key::F6, F7 => Key::F7, F8 => Key::F8, F9 => Key::F9, F10 => Key::F10, F11 => Key::F11, F12 => Key::F12, Tools | F13 => Key::F13, F14 | Launch5 => Key::F14, F15 | Launch6 => Key::F15, F16 | Launch7 => Key::F16, F17 | Launch8 => Key::F17, F18 | Launch9 => Key::F18, F19 => Key::F19, F20 => Key::F20, F21 => Key::F21, F22 => Key::F22, F23 => Key::F23, F24 => Key::F24, // not available in keyboard-types // Calculator => Key::LaunchCalculator, // MyComputer | Explorer => Key::LaunchMyComputer, // ISO_Level3_Latch => Key::AltGraphLatch, // ISO_Level5_Shift => Key::ShiftLevel5, Shift_L | Shift_R => Key::Shift, Control_L | Control_R => Key::Control, Caps_Lock => Key::CapsLock, Meta_L | Meta_R => Key::Meta, Alt_L | Alt_R => Key::Alt, Super_L | Super_R => Key::Meta, Hyper_L | Hyper_R => Key::Hyper, Delete => Key::Delete, Next_VMode => Key::VideoModeNext, MonBrightnessUp => Key::BrightnessUp, MonBrightnessDown => Key::BrightnessDown, Standby | Sleep | Suspend => Key::Standby, AudioLowerVolume => Key::AudioVolumeDown, AudioMute => Key::AudioVolumeMute, AudioRaiseVolume => Key::AudioVolumeUp, AudioPlay => Key::MediaPlayPause, AudioStop => Key::MediaStop, AudioPrev => Key::MediaTrackPrevious, AudioNext => Key::MediaTrackNext, HomePage => Key::BrowserHome, Mail => Key::LaunchMail, Search => Key::BrowserSearch, AudioRecord => Key::MediaRecord, Calendar => Key::LaunchCalendar, Back => Key::BrowserBack, Forward => Key::BrowserForward, Stop => Key::BrowserStop, Refresh | Reload => Key::BrowserRefresh, PowerOff => Key::PowerOff, WakeUp => Key::WakeUp, Eject => Key::Eject, ScreenSaver => Key::LaunchScreenSaver, WWW => Key::LaunchWebBrowser, Favorites => Key::BrowserFavorites, AudioPause => Key::MediaPause, AudioMedia | Music => Key::LaunchMusicPlayer, AudioRewind => Key::MediaRewind, CD | Video => Key::LaunchMediaPlayer, Close => Key::Close, Copy => Key::Copy, Cut => Key::Cut, Display => Key::DisplaySwap, Excel => Key::LaunchSpreadsheet, LogOff => Key::LogOff, New => Key::New, Open => Key::Open, Paste => Key::Paste, Reply => Key::MailReply, Save => Key::Save, Send => Key::MailSend, Spell => Key::SpellCheck, SplitScreen => Key::SplitScreenToggle, Word | OfficeHome => Key::LaunchWordProcessor, ZoomIn => Key::ZoomIn, ZoomOut => Key::ZoomOut, WebCam => Key::LaunchWebCam, MailForward => Key::MailForward, AudioForward => Key::MediaFastForward, AudioRandomPlay => Key::RandomToggle, Subtitle => Key::Subtitle, Hibernate => Key::Hibernate, _3270_EraseEOF => Key::EraseEof, _3270_Play => Key::Play, _3270_ExSelect => Key::ExSel, _3270_CursorSelect => Key::CrSel, ISO_Level3_Shift => Key::AltGraph, ISO_Next_Group => Key::GroupNext, ISO_Prev_Group => Key::GroupPrevious, ISO_First_Group => Key::GroupFirst, ISO_Last_Group => Key::GroupLast, dead_grave | dead_acute | dead_circumflex | dead_tilde | dead_macron | dead_breve | dead_abovedot | dead_diaeresis | dead_abovering | dead_doubleacute | dead_caron | dead_cedilla | dead_ogonek | dead_iota | dead_voiced_sound | dead_semivoiced_sound | dead_belowdot | dead_hook | dead_horn | dead_stroke | dead_abovecomma | dead_abovereversedcomma | dead_doublegrave | dead_belowring | dead_belowmacron | dead_belowcircumflex | dead_belowtilde | dead_belowbreve | dead_belowdiaeresis | dead_invertedbreve | dead_belowcomma | dead_currency | dead_greek => Key::Dead, _ => return None, }) } #[allow(clippy::just_underscores_and_digits, non_upper_case_globals)] pub fn raw_key_to_location(raw: RawKey) -> Location { match raw { Control_L | Shift_L | Alt_L | Super_L | Meta_L => Location::Left, Control_R | Shift_R | Alt_R | Super_R | Meta_R => Location::Right, KP_0 | KP_1 | KP_2 | KP_3 | KP_4 | KP_5 | KP_6 | KP_7 | KP_8 | KP_9 | KP_Add | KP_Begin | KP_Decimal | KP_Delete | KP_Divide | KP_Down | KP_End | KP_Enter | KP_Equal | KP_F1 | KP_F2 | KP_F3 | KP_F4 | KP_Home | KP_Insert | KP_Left | KP_Multiply | KP_Page_Down | KP_Page_Up | KP_Right | KP_Separator | KP_Space | KP_Subtract | KP_Tab | KP_Up => { Location::Numpad } _ => Location::Standard, } } #[allow(non_upper_case_globals)] pub fn key_to_raw_key(src: &Key) -> Option<RawKey> { Some(match src { Key::Escape => Escape, Key::Backspace => BackSpace, Key::Tab => Tab, Key::Enter => Return, // Give "left" variants Key::Control => Control_L, Key::Alt => Alt_L, Key::Shift => Shift_L, Key::Meta => Super_L, Key::CapsLock => Caps_Lock, Key::F1 => F1, Key::F2 => F2, Key::F3 => F3, Key::F4 => F4, Key::F5 => F5, Key::F6 => F6, Key::F7 => F7, Key::F8 => F8, Key::F9 => F9, Key::F10 => F10, Key::F11 => F11, Key::F12 => F12, Key::F13 => F13, Key::F14 => F14, Key::F15 => F15, Key::F16 => F16, Key::F17 => F17, Key::F18 => F18, Key::F19 => F19, Key::F20 => F20, Key::F21 => F21, Key::F22 => F22, Key::F23 => F23, Key::F24 => F24, Key::PrintScreen => Print, Key::ScrollLock => Scroll_Lock, // Pause/Break not audio. Key::Pause => Pause, Key::Insert => Insert, Key::Delete => Delete, Key::Home => Home, Key::End => End, Key::PageUp => Page_Up, Key::PageDown => Page_Down, Key::NumLock => Num_Lock, Key::ArrowUp => Up, Key::ArrowDown => Down, Key::ArrowLeft => Left, Key::ArrowRight => Right, Key::ContextMenu => Menu, Key::WakeUp => WakeUp, Key::LaunchApplication1 => Launch0, Key::LaunchApplication2 => Launch1, Key::AltGraph => ISO_Level3_Shift, // TODO: probably more _ => return None, }) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/dialog.rs
druid-shell/src/backend/gtk/dialog.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! File open/save dialogs, GTK implementation. use std::ffi::OsString; use anyhow::anyhow; use gtk::{FileChooserAction, FileFilter, ResponseType, Window}; use gtk::prelude::{FileChooserExt, NativeDialogExt}; use crate::dialog::{FileDialogOptions, FileDialogType, FileSpec}; use crate::Error; fn file_filter(fs: &FileSpec) -> FileFilter { let ret = FileFilter::new(); ret.set_name(Some(fs.name)); for ext in fs.extensions { ret.add_pattern(&format!("*.{ext}")); } ret } pub(crate) fn get_file_dialog_path( window: &Window, ty: FileDialogType, options: FileDialogOptions, ) -> Result<Vec<OsString>, Error> { // TODO: support message localization let (title, action) = match (ty, options.select_directories) { (FileDialogType::Open, false) => ("Open File", FileChooserAction::Open), (FileDialogType::Open, true) => ("Open Folder", FileChooserAction::SelectFolder), (FileDialogType::Save, _) => ("Save File", FileChooserAction::Save), }; let title = options.title.as_deref().unwrap_or(title); let mut dialog = gtk::FileChooserNative::builder() .transient_for(window) .title(title); if let Some(button_text) = &options.button_text { dialog = dialog.accept_label(button_text); } let dialog = dialog.build(); dialog.set_action(action); dialog.set_show_hidden(options.show_hidden); if action != FileChooserAction::Save { dialog.set_select_multiple(options.multi_selection); } // Don't set the filters when showing the folder selection dialog, // because then folder traversing won't work. if action != FileChooserAction::SelectFolder { let mut found_default_filter = false; if let Some(file_types) = &options.allowed_types { for f in file_types { let filter = file_filter(f); // We need to clone filter, because we may need it again for the default filter. // It has to be the same FileFilter instance and can't be a new file_filter() call. dialog.add_filter(filter.clone()); if let Some(default) = &options.default_type { if default == f { dialog.set_filter(&filter); found_default_filter = true; } } } } if let Some(dt) = &options.default_type { if !found_default_filter { tracing::warn!("The default type {:?} is not present in allowed types.", dt); } } } if let Some(default_name) = &options.default_name { dialog.set_current_name(default_name); } let result = dialog.run(); let result = match result { ResponseType::Accept => match dialog.filenames() { filenames if filenames.is_empty() => Err(anyhow!("No path received for filename")), // If we receive more than one file, but `multi_selection` is false, return an error. filenames if filenames.len() > 1 && !options.multi_selection => { Err(anyhow!("More than one path received for single selection")) } // If we receive more than one file with a save action, return an error. filenames if filenames.len() > 1 && action == FileChooserAction::Save => { Err(anyhow!("More than one path received for save action")) } filenames => Ok(filenames.into_iter().map(|p| p.into_os_string()).collect()), }, ResponseType::Cancel => Err(anyhow!("Dialog was deleted")), _ => { tracing::warn!("Unhandled dialog result: {:?}", result); Err(anyhow!("Unhandled dialog result")) } }; // TODO properly handle errors into the Error type dialog.destroy(); Ok(result?) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/clipboard.rs
druid-shell/src/backend/gtk/clipboard.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interactions with the system pasteboard on GTK+. use gtk::gdk::Atom; use gtk::{TargetEntry, TargetFlags}; use crate::clipboard::{ClipboardFormat, FormatId}; const CLIPBOARD_TARGETS: [&str; 5] = [ "UTF8_STRING", "TEXT", "STRING", "text/plain;charset=utf-8", "text/plain", ]; /// The system clipboard. #[derive(Clone)] pub struct Clipboard { pub(crate) selection: Atom, } impl std::fmt::Debug for Clipboard { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let name = match self.selection { gtk::gdk::SELECTION_PRIMARY => "Primary", gtk::gdk::SELECTION_CLIPBOARD => "Clipboard", _ => "(other)", }; f.debug_tuple("Clipboard").field(&name).finish() } } impl Clipboard { /// Put a string onto the system clipboard. pub fn put_string(&mut self, string: impl AsRef<str>) { let string = string.as_ref().to_string(); let display = gtk::gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::for_display(&display, &self.selection); let targets: Vec<TargetEntry> = CLIPBOARD_TARGETS .iter() .enumerate() .map(|(i, target)| TargetEntry::new(target, TargetFlags::all(), i as u32)) .collect(); clipboard.set_with_data(&targets, move |_, selection, _| { const STRIDE_BITS: i32 = 8; selection.set(&selection.target(), STRIDE_BITS, string.as_bytes()); }); } /// Put multi-format data on the system clipboard. pub fn put_formats(&mut self, formats: &[ClipboardFormat]) { let entries = make_entries(formats); let display = gtk::gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::for_display(&display, &self.selection); // this is gross: we need to reclone all the data in formats in order // to move it into the closure. :/ let formats = formats.to_owned(); let success = clipboard.set_with_data(&entries, move |_, sel, idx| { tracing::info!("got paste callback {}", idx); let idx = idx as usize; if idx < formats.len() { let item = &formats[idx]; if let (ClipboardFormat::TEXT, Ok(data)) = (item.identifier, std::str::from_utf8(&item.data)) { sel.set_text(data); } else { let atom = Atom::intern(item.identifier); let stride = 8; sel.set(&atom, stride, item.data.as_slice()); } } }); if !success { tracing::warn!("failed to set clipboard data."); } } /// Get a string from the system clipboard, if one is available. pub fn get_string(&self) -> Option<String> { let display = gtk::gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::for_display(&display, &self.selection); for target in &CLIPBOARD_TARGETS { let atom = Atom::intern(target); if let Some(selection) = clipboard.wait_for_contents(&atom) { return String::from_utf8(selection.data()).ok(); } } None } /// Given a list of supported clipboard types, returns the supported type which has /// highest priority on the system clipboard, or `None` if no types are supported. pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> { let display = gtk::gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::for_display(&display, &self.selection); let targets = clipboard.wait_for_targets()?; let format_atoms = formats .iter() .map(|fmt| Atom::intern(fmt)) .collect::<Vec<_>>(); for atom in targets.iter() { if let Some(idx) = format_atoms.iter().position(|fmt| fmt == atom) { return Some(formats[idx]); } } None } /// Return data in a given format, if available. /// /// It is recommended that the `fmt` argument be a format returned by /// [`Clipboard::preferred_format`] pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> { let display = gtk::gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::for_display(&display, &self.selection); let atom = Atom::intern(format); clipboard.wait_for_contents(&atom).map(|data| data.data()) } pub fn available_type_names(&self) -> Vec<String> { let display = gtk::gdk::Display::default().unwrap(); let clipboard = gtk::Clipboard::for_display(&display, &self.selection); let targets = clipboard.wait_for_targets().unwrap_or_default(); targets .iter() .map(|atom| format!("{} ({})", atom.name(), atom.value())) .collect() } } fn make_entries(formats: &[ClipboardFormat]) -> Vec<TargetEntry> { formats .iter() .enumerate() .map(|(i, fmt)| TargetEntry::new(fmt.identifier, TargetFlags::all(), i as u32)) .collect() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/menu.rs
druid-shell/src/backend/gtk/menu.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK implementation of menus. use gtk::gdk::ModifierType; use gtk::{ AccelGroup, CheckMenuItem, Menu as GtkMenu, MenuBar as GtkMenuBar, MenuItem as GtkMenuItem, }; use gtk_rs::SeparatorMenuItem; use gtk::prelude::{GtkMenuExt, GtkMenuItemExt, MenuShellExt, WidgetExt}; use super::keycodes; use super::window::WindowHandle; use crate::common_util::strip_access_key; use crate::hotkey::{HotKey, RawMods}; use crate::keyboard::{KbKey, Modifiers}; #[derive(Default, Debug)] pub struct Menu { items: Vec<MenuItem>, } #[derive(Debug)] enum MenuItem { Entry { name: String, id: u32, key: Option<HotKey>, selected: Option<bool>, enabled: bool, }, SubMenu(String, Menu), Separator, } impl Menu { pub fn new() -> Menu { Menu { items: Vec::new() } } pub fn new_for_popup() -> Menu { Menu { items: Vec::new() } } pub fn add_dropdown(&mut self, menu: Menu, text: &str, _enabled: bool) { // TODO: implement enabled dropdown self.items .push(MenuItem::SubMenu(strip_access_key(text), menu)); } pub fn add_item( &mut self, id: u32, text: &str, key: Option<&HotKey>, selected: Option<bool>, enabled: bool, ) { self.items.push(MenuItem::Entry { name: strip_access_key(text), id, key: key.cloned(), selected, enabled, }); } pub fn add_separator(&mut self) { self.items.push(MenuItem::Separator) } fn append_items_to_menu<M: gtk::prelude::IsA<gtk::MenuShell>>( self, menu: &mut M, handle: &WindowHandle, accel_group: &AccelGroup, ) { for item in self.items { match item { MenuItem::Entry { name, id, key, selected, enabled, } => { if let Some(state) = selected { let item = CheckMenuItem::with_label(&name); if state { item.activate(); } add_menu_entry(menu, handle, accel_group, &item, id, key, enabled); } else { let entry = GtkMenuItem::with_label(&name); add_menu_entry(menu, handle, accel_group, &entry, id, key, enabled); } } MenuItem::SubMenu(name, submenu) => { let item = GtkMenuItem::with_label(&name); item.set_submenu(Some(&submenu.into_gtk_menu(handle, accel_group))); menu.append(&item); } MenuItem::Separator => menu.append(&SeparatorMenuItem::new()), } } } pub(crate) fn into_gtk_menubar( self, handle: &WindowHandle, accel_group: &AccelGroup, ) -> GtkMenuBar { let mut menu = GtkMenuBar::new(); self.append_items_to_menu(&mut menu, handle, accel_group); menu } pub fn into_gtk_menu(self, handle: &WindowHandle, accel_group: &AccelGroup) -> GtkMenu { let mut menu = GtkMenu::new(); menu.set_accel_group(Some(accel_group)); self.append_items_to_menu(&mut menu, handle, accel_group); menu } } fn add_menu_entry< M: gtk::prelude::IsA<gtk::MenuShell>, I: gtk::prelude::IsA<gtk::MenuItem> + gtk::prelude::IsA<gtk::Widget>, >( menu: &mut M, handle: &WindowHandle, accel_group: &AccelGroup, item: &I, id: u32, key: Option<HotKey>, enabled: bool, ) { item.set_sensitive(enabled); if let Some(k) = key { register_accelerator(item, accel_group, k); } let handle = handle.clone(); item.connect_activate(move |_| { if let Some(state) = handle.state.upgrade() { state.handler.borrow_mut().command(id); } }); menu.append(item); } fn register_accelerator<M: GtkMenuItemExt + WidgetExt>( item: &M, accel_group: &AccelGroup, menu_key: HotKey, ) { let gdk_keyval = match &menu_key.key { KbKey::Character(text) => text.chars().next().unwrap() as u32, k => { if let Some(gdk_key) = keycodes::key_to_raw_key(k) { *gdk_key } else { tracing::warn!("Cannot map key {:?}", k); return; } } }; item.add_accelerator( "activate", accel_group, gdk_keyval, modifiers_to_gdk_modifier_type(menu_key.mods), gtk::AccelFlags::VISIBLE, ); } fn modifiers_to_gdk_modifier_type(raw_modifiers: RawMods) -> ModifierType { let mut result = ModifierType::empty(); let modifiers: Modifiers = raw_modifiers.into(); result.set(ModifierType::MOD1_MASK, modifiers.alt()); result.set(ModifierType::CONTROL_MASK, modifiers.ctrl()); result.set(ModifierType::SHIFT_MASK, modifiers.shift()); result.set(ModifierType::META_MASK, modifiers.meta()); result }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/error.rs
druid-shell/src/backend/gtk/error.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK backend errors. use std::fmt; use gtk::glib::{BoolError, Error as GLibError}; /// GTK backend errors. #[derive(Debug, Clone)] pub enum Error { /// Generic GTK error. Error(GLibError), /// GTK error that has no information provided by GTK, /// but may have extra information provided by gtk-rs. BoolError(BoolError), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { Error::Error(err) => write!(f, "GTK Error: {err}"), Error::BoolError(err) => write!(f, "GTK BoolError: {err}"), } } } impl std::error::Error for Error {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/application.rs
druid-shell/src/backend/gtk/application.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK implementation of features at the application scope. use gtk::gio::prelude::ApplicationExtManual; use gtk::gio::{ApplicationFlags, Cancellable}; use gtk::Application as GtkApplication; use gtk::prelude::{ApplicationExt, GtkApplicationExt}; use crate::application::AppHandler; use super::clipboard::Clipboard; use super::error::Error; #[derive(Clone)] pub(crate) struct Application { gtk_app: GtkApplication, } impl Application { pub fn new() -> Result<Application, Error> { // TODO: we should give control over the application ID to the user let gtk_app = GtkApplication::new( Some("com.github.linebender.druid"), // TODO we set this to avoid connecting to an existing running instance // of "com.github.linebender.druid" after which we would never receive // the "Activate application" below. See pull request druid#384 // Which shows another way once we have in place a mechanism for // communication with remote instances. ApplicationFlags::NON_UNIQUE, ); gtk_app.connect_activate(|_app| { tracing::info!("gtk: Activated application"); }); if let Err(err) = gtk_app.register(None as Option<&Cancellable>) { return Err(Error::Error(err)); } Ok(Application { gtk_app }) } #[inline] pub fn gtk_app(&self) -> &GtkApplication { &self.gtk_app } pub fn run(self, _handler: Option<Box<dyn AppHandler>>) { self.gtk_app.run(); } pub fn quit(&self) { match self.gtk_app.active_window() { None => { // no application is running, main is not running } Some(_) => { // we still have an active window, close the run loop self.gtk_app.quit(); } } } pub fn clipboard(&self) -> Clipboard { Clipboard { selection: gtk::gdk::SELECTION_CLIPBOARD, } } pub fn get_locale() -> String { let mut locale: String = gtk::glib::language_names()[0].as_str().into(); // This is done because the locale parsing library we use expects an unicode locale, but these vars have an ISO locale if let Some(idx) = locale.chars().position(|c| c == '.' || c == '@') { locale.truncate(idx); } locale } } impl crate::platform::linux::ApplicationExt for crate::Application { fn primary_clipboard(&self) -> crate::Clipboard { crate::Clipboard(Clipboard { selection: gtk::gdk::SELECTION_PRIMARY, }) } } pub fn init_harness() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/util.rs
druid-shell/src/backend/gtk/util.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Utilities, GTK specific. pub(crate) fn assert_main_thread() { assert!(gtk::is_initialized_main_thread()); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/mod.rs
druid-shell/src/backend/gtk/mod.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK-based backend support pub mod application; pub mod clipboard; pub mod dialog; pub mod error; pub mod keycodes; pub mod menu; pub mod screen; pub mod util; pub mod window;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/window.rs
druid-shell/src/backend/gtk/window.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK window creation and management. use std::cell::{Cell, RefCell}; use std::convert::TryInto; use std::ffi::c_void; use std::os::raw::{c_int, c_uint}; use std::panic::Location; use std::ptr; use std::slice; use std::sync::{Arc, Mutex, Weak}; use std::time::Instant; use gtk::gdk::ffi::GdkKeymapKey; use gtk::gdk_pixbuf::Colorspace::Rgb; use gtk::gdk_pixbuf::Pixbuf; use gtk::glib::translate::FromGlib; use gtk::glib::{ControlFlow, Propagation}; use gtk::prelude::*; use gtk::{AccelGroup, ApplicationWindow, DrawingArea}; use anyhow::anyhow; use cairo::Surface; use gtk::gdk::{ EventKey, EventMask, EventType, ModifierType, ScrollDirection, Window, WindowTypeHint, }; use instant::Duration; use tracing::{error, warn}; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, XcbWindowHandle}; use crate::kurbo::{Insets, Point, Rect, Size, Vec2}; use crate::piet::{Piet, PietText, RenderContext}; use crate::common_util::{ClickCounter, IdleCallback}; use crate::dialog::{FileDialogOptions, FileDialogType, FileInfo}; use crate::error::Error as ShellError; use crate::keyboard::{KbKey, KeyEvent, KeyState, Modifiers}; use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent}; use crate::piet::ImageFormat; use crate::region::Region; use crate::scale::{Scalable, Scale, ScaledArea}; use crate::text::{simulate_input, Event}; use crate::window::{ self, FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel, }; use super::application::Application; use super::dialog; use super::keycodes; use super::menu::Menu; use super::util; /// The backend target DPI. /// /// GTK considers 96 the default value which represents a 1.0 scale factor. const SCALE_TARGET_DPI: f64 = 96.0; /// Taken from <https://gtk-rs.org/docs-src/tutorial/closures> /// It is used to reduce the boilerplate of setting up gtk callbacks /// Example: /// ```ignore /// button.connect_clicked(clone!(handle => move |_| { ... })) /// ``` /// is equivalent to: /// ```ignore /// { /// let handle = handle.clone(); /// button.connect_clicked(move |_| { ... }) /// } /// ``` macro_rules! clone { (@param _) => ( _ ); (@param $x:ident) => ( $x ); ($($n:ident),+ => move || $body:expr) => ( { $( let $n = $n.clone(); )+ move || $body } ); ($($n:ident),+ => move |$($p:tt),+| $body:expr) => ( { $( let $n = $n.clone(); )+ move |$(clone!(@param $p),)+| $body } ); } #[derive(Clone, Default, Debug)] pub struct WindowHandle { pub(crate) state: Weak<WindowState>, // Ensure that we don't implement Send, because it isn't actually safe to send the WindowState. marker: std::marker::PhantomData<*const ()>, } impl PartialEq for WindowHandle { fn eq(&self, other: &Self) -> bool { match (self.state.upgrade(), other.state.upgrade()) { (None, None) => true, (Some(s), Some(o)) => std::sync::Arc::ptr_eq(&s, &o), (_, _) => false, } } } impl Eq for WindowHandle {} #[cfg(feature = "raw-win-handle")] unsafe impl HasRawWindowHandle for WindowHandle { fn raw_window_handle(&self) -> RawWindowHandle { error!("HasRawWindowHandle trait not implemented for gtk."); // GTK is not a platform, and there's no empty generic handle. Pick XCB randomly as fallback. RawWindowHandle::Xcb(XcbWindowHandle::empty()) } } /// Operations that we defer in order to avoid re-entrancy. See the documentation in the windows /// backend for more details. enum DeferredOp { SaveAs(FileDialogOptions, FileDialogToken), Open(FileDialogOptions, FileDialogToken), ContextMenu(Menu, WindowHandle), } /// Builder abstraction for creating new windows pub(crate) struct WindowBuilder { app: Application, handler: Option<Box<dyn WinHandler>>, title: String, menu: Option<Menu>, position: Option<Point>, level: Option<WindowLevel>, state: Option<window::WindowState>, size: Size, min_size: Option<Size>, resizable: bool, show_titlebar: bool, transparent: bool, always_on_top: bool, } #[derive(Clone)] pub struct IdleHandle { idle_queue: Arc<Mutex<Vec<IdleKind>>>, state: Weak<WindowState>, } /// This represents different Idle Callback Mechanism enum IdleKind { Callback(Box<dyn IdleCallback>), Token(IdleToken), } // We use RefCells for interior mutability, but we try to structure things so that double-borrows // are impossible. See the documentation on crate::backend::x11::window::Window for more details, // since the idea there is basically the same. pub(crate) struct WindowState { window: ApplicationWindow, scale: Cell<Scale>, area: Cell<ScaledArea>, is_transparent: Cell<bool>, handle_titlebar: Cell<bool>, /// Used to determine whether to honor close requests from the system: we inhibit them unless /// this is true, and this gets set to true when our client requests a close. closing: Cell<bool>, drawing_area: DrawingArea, // A cairo surface for us to render to; we copy this to the drawing_area whenever necessary. // This extra buffer is necessitated by DrawingArea's painting model: when our paint callback // is called, we are given a cairo context that's already clipped to the invalid region. This // doesn't match up with our painting model, because we need to call `prepare_paint` before we // know what the invalid region is. // // The way we work around this is by always invalidating the entire DrawingArea whenever we // need repainting; this ensures that GTK gives us an unclipped cairo context. Meanwhile, we // keep track of the actual invalid region. We use that region to render onto `surface`, which // we then copy onto `drawing_area`. surface: RefCell<Option<Surface>>, // The size of `surface` in pixels. This could be bigger than `drawing_area`. surface_size: Cell<(i32, i32)>, // The invalid region, in display points. invalid: RefCell<Region>, pub(crate) handler: RefCell<Box<dyn WinHandler>>, idle_queue: Arc<Mutex<Vec<IdleKind>>>, current_keycode: Cell<Option<u16>>, click_counter: ClickCounter, active_text_input: Cell<Option<TextFieldToken>>, deferred_queue: RefCell<Vec<DeferredOp>>, request_animation: Cell<bool>, in_draw: Cell<bool>, parent: Option<crate::WindowHandle>, } impl std::fmt::Debug for WindowState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { f.write_str("WindowState{")?; self.window.fmt(f)?; f.write_str("}")?; Ok(()) } } #[derive(Clone, PartialEq, Eq)] pub struct CustomCursor(gtk::gdk::Cursor); impl WindowBuilder { pub fn new(app: Application) -> WindowBuilder { WindowBuilder { app, handler: None, title: String::new(), menu: None, size: Size::new(500.0, 400.0), position: None, level: None, state: None, min_size: None, resizable: true, show_titlebar: true, transparent: false, always_on_top: false, } } pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.handler = Some(handler); } pub fn set_size(&mut self, size: Size) { self.size = size; } pub fn set_min_size(&mut self, size: Size) { self.min_size = Some(size); } pub fn resizable(&mut self, resizable: bool) { self.resizable = resizable; } pub fn show_titlebar(&mut self, show_titlebar: bool) { self.show_titlebar = show_titlebar; } pub fn set_always_on_top(&mut self, always_on_top: bool) { self.always_on_top = always_on_top; } pub fn set_transparent(&mut self, transparent: bool) { self.transparent = transparent; } pub fn set_position(&mut self, position: Point) { self.position = Some(position); } pub fn set_level(&mut self, level: WindowLevel) { self.level = Some(level); } pub fn set_window_state(&mut self, state: window::WindowState) { self.state = Some(state); } pub fn set_title(&mut self, title: impl Into<String>) { self.title = title.into(); } pub fn set_menu(&mut self, menu: Menu) { self.menu = Some(menu); } pub fn build(self) -> Result<WindowHandle, ShellError> { let handler = self .handler .expect("Tried to build a window without setting the handler"); let window = ApplicationWindow::new(self.app.gtk_app()); window.set_title(&self.title); window.set_resizable(self.resizable); window.set_decorated(self.show_titlebar); let mut transparent = false; if self.transparent { if let Some(screen) = gtk::prelude::GtkWindowExt::screen(&window) { let visual = screen.rgba_visual(); transparent = visual.is_some(); window.set_visual(visual.as_ref()); } } window.set_app_paintable(transparent); // Get the scale factor based on the GTK reported DPI let scale_factor = window.display().default_screen().resolution() / SCALE_TARGET_DPI; let scale = Scale::new(scale_factor, scale_factor); let area = ScaledArea::from_dp(self.size, scale); let size_px = area.size_px(); window.set_default_size(size_px.width as i32, size_px.height as i32); let accel_group = AccelGroup::new(); window.add_accel_group(&accel_group); let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0); window.add(&vbox); let drawing_area = gtk::DrawingArea::new(); // Set the parent widget and handle level specific code let mut parent: Option<crate::WindowHandle> = None; if let Some(level) = &self.level { let hint = match level { WindowLevel::AppWindow => WindowTypeHint::Normal, WindowLevel::Tooltip(_) => WindowTypeHint::Tooltip, WindowLevel::DropDown(_) => WindowTypeHint::DropdownMenu, WindowLevel::Modal(_) => WindowTypeHint::Dialog, }; window.set_type_hint(hint); match &level { WindowLevel::Tooltip(p) => { parent = Some(p.clone()); } WindowLevel::DropDown(p) => { parent = Some(p.clone()); } WindowLevel::Modal(p) => { parent = Some(p.clone()); window.set_urgency_hint(true); window.set_modal(true); } _ => (), }; if let Some(parent) = &parent { if let Some(parent_state) = parent.0.state.upgrade() { window.set_transient_for(Some(&parent_state.window)); } } } let state = WindowState { window, scale: Cell::new(scale), area: Cell::new(area), is_transparent: Cell::new(transparent), handle_titlebar: Cell::new(false), closing: Cell::new(false), drawing_area, surface: RefCell::new(None), surface_size: Cell::new((0, 0)), invalid: RefCell::new(Region::EMPTY), handler: RefCell::new(handler), idle_queue: Arc::new(Mutex::new(vec![])), current_keycode: Cell::new(None), click_counter: ClickCounter::default(), active_text_input: Cell::new(None), deferred_queue: RefCell::new(Vec::new()), request_animation: Cell::new(false), in_draw: Cell::new(false), parent, }; let win_state = Arc::new(state); self.app .gtk_app() .connect_shutdown(clone!(win_state => move |_| { // this ties a clone of Arc<WindowState> to the ApplicationWindow to keep it alive // when the ApplicationWindow is destroyed, the last Arc is dropped // and any Weak<WindowState> will be None on upgrade() let _ = &win_state; })); let mut handle = WindowHandle { state: Arc::downgrade(&win_state), marker: std::marker::PhantomData, }; if let Some(pos) = self.position { handle.set_position(pos); } if let Some(state) = self.state { handle.set_window_state(state) } if let Some(menu) = self.menu { let menu = menu.into_gtk_menubar(&handle, &accel_group); vbox.pack_start(&menu, false, false, 0); } win_state.drawing_area.set_events( EventMask::EXPOSURE_MASK | EventMask::POINTER_MOTION_MASK | EventMask::LEAVE_NOTIFY_MASK | EventMask::BUTTON_PRESS_MASK | EventMask::BUTTON_RELEASE_MASK | EventMask::KEY_PRESS_MASK | EventMask::ENTER_NOTIFY_MASK | EventMask::KEY_RELEASE_MASK | EventMask::SCROLL_MASK | EventMask::SMOOTH_SCROLL_MASK | EventMask::FOCUS_CHANGE_MASK, ); win_state.drawing_area.set_can_focus(true); win_state.drawing_area.grab_focus(); win_state .drawing_area .connect_enter_notify_event(|widget, _| { widget.grab_focus(); Propagation::Stop }); // Set the minimum size if let Some(min_size_dp) = self.min_size { let min_area = ScaledArea::from_dp(min_size_dp, scale); let min_size_px = min_area.size_px(); win_state .drawing_area .set_size_request(min_size_px.width as i32, min_size_px.height as i32); } win_state .drawing_area .connect_realize(clone!(handle => move |drawing_area| { if let Some(clock) = drawing_area.frame_clock() { clock.connect_before_paint(clone!(handle => move |_clock|{ if let Some(state) = handle.state.upgrade() { state.in_draw.set(true); } })); clock.connect_after_paint(clone!(handle => move |_clock|{ if let Some(state) = handle.state.upgrade() { state.in_draw.set(false); if state.request_animation.get() { state.request_animation.set(false); state.drawing_area.queue_draw(); } } })); } })); win_state.drawing_area.connect_draw(clone!(handle => move |widget, context| { if let Some(state) = handle.state.upgrade() { let mut scale = state.scale.get(); let mut scale_changed = false; // Check if the GTK reported DPI has changed, // so that we can change our scale factor without restarting the application. if let Some(scale_factor) = state.window.window() .map(|w| w.display().default_screen().resolution() / SCALE_TARGET_DPI) { let reported_scale = Scale::new(scale_factor, scale_factor); if scale != reported_scale { scale = reported_scale; state.scale.set(scale); scale_changed = true; state.with_handler(|h| h.scale(scale)); } } // Create a new cairo surface if necessary (either because there is no surface, or // because the size or scale changed). let extents = widget.allocation(); let size_px = Size::new(extents.width() as f64, extents.height() as f64); let no_surface = state.surface.try_borrow().map(|x| x.is_none()).ok() == Some(true); if no_surface || scale_changed || state.area.get().size_px() != size_px { let area = ScaledArea::from_px(size_px, scale); let size_dp = area.size_dp(); state.area.set(area); if let Err(e) = state.resize_surface(extents.width(), extents.height()) { error!("Failed to resize surface: {}", e); } state.with_handler(|h| h.size(size_dp)); state.invalidate_rect(size_dp.to_rect()); } state.with_handler(|h| h.prepare_paint()); let invalid = match state.invalid.try_borrow_mut() { Ok(mut invalid) => std::mem::replace(&mut *invalid, Region::EMPTY), Err(_) => { error!("invalid region borrowed while drawing"); Region::EMPTY } }; if let Ok(Some(surface)) = state.surface.try_borrow().as_ref().map(|s| s.as_ref()) { // Note that we're borrowing the surface while calling the handler. This is ok, // because we don't return control to the system or re-borrow the surface from // any code that the client can call. state.with_handler_and_dont_check_the_other_borrows(|handler| { let surface_context = cairo::Context::new(surface).unwrap(); // Clip to the invalid region, in order that our surface doesn't get // messed up if there's any painting outside them. for rect in invalid.rects() { let rect = rect.to_px(scale); surface_context.rectangle(rect.x0, rect.y0, rect.width(), rect.height()); } surface_context.clip(); surface_context.scale(scale.x(), scale.y()); let mut piet_context = Piet::new(&surface_context); handler.paint(&mut piet_context, &invalid); if let Err(e) = piet_context.finish() { error!("piet error on render: {:?}", e); } // Copy the entire surface to the drawing area (not just the invalid // region, because there might be parts of the drawing area that were // invalidated by external forces). // TODO: how are we supposed to handle these errors? What can we do besides panic? Probably nothing right? let alloc = widget.allocation(); context.set_source_surface(surface, 0.0, 0.0).unwrap(); context.rectangle(0.0, 0.0, alloc.width() as f64, alloc.height() as f64); context.fill().unwrap(); }); } else { warn!("Drawing was skipped because there was no surface"); } } Propagation::Proceed })); win_state.drawing_area.connect_screen_changed( clone!(handle => move |widget, _prev_screen| { if let Some(state) = handle.state.upgrade() { if let Some(screen) = widget.screen(){ let visual = screen.rgba_visual(); state.is_transparent.set(visual.is_some()); widget.set_visual(visual.as_ref()); } } }), ); win_state.drawing_area.connect_button_press_event(clone!(handle => move |_widget, event| { if let Some(state) = handle.state.upgrade() { state.with_handler(|handler| { if let Some(button) = get_mouse_button(event.button()) { let scale = state.scale.get(); let button_state = event.state(); let gtk_count = get_mouse_click_count(event.event_type()); let pos: Point = event.position().into(); let count = if gtk_count == 1 { let settings = state.drawing_area.settings().unwrap(); let thresh_dist = settings.gtk_double_click_distance(); state.click_counter.set_distance(thresh_dist.into()); if let Ok(ms) = settings.gtk_double_click_time().try_into() { state.click_counter.set_interval_ms(ms); } state.click_counter.count_for_click(pos) } else { 0 }; if gtk_count == 0 || gtk_count == 1 { handler.mouse_down( &MouseEvent { pos: pos.to_dp(scale), buttons: get_mouse_buttons_from_modifiers(button_state).with(button), mods: get_modifiers(button_state), count, focus: false, button, wheel_delta: Vec2::ZERO }, ); } if button.is_left() && state.handle_titlebar.replace(false) { let (root_x, root_y) = event.root(); state.window.begin_move_drag(event.button() as i32, root_x as i32, root_y as i32, event.time()); } } }); } Propagation::Stop })); win_state.drawing_area.connect_button_release_event(clone!(handle => move |_widget, event| { if let Some(state) = handle.state.upgrade() { state.with_handler(|handler| { if let Some(button) = get_mouse_button(event.button()) { let scale = state.scale.get(); let button_state = event.state(); handler.mouse_up( &MouseEvent { pos: Point::from(event.position()).to_dp(scale), buttons: get_mouse_buttons_from_modifiers(button_state).without(button), mods: get_modifiers(button_state), count: 0, focus: false, button, wheel_delta: Vec2::ZERO }, ); if button.is_left() { state.handle_titlebar.set(false); } } }); } Propagation::Stop })); win_state.drawing_area.connect_motion_notify_event( clone!(handle => move |_widget, motion| { if let Some(state) = handle.state.upgrade() { let scale = state.scale.get(); let motion_state = motion.state(); let mouse_event = MouseEvent { pos: Point::from(motion.position()).to_dp(scale), buttons: get_mouse_buttons_from_modifiers(motion_state), mods: get_modifiers(motion_state), count: 0, focus: false, button: MouseButton::None, wheel_delta: Vec2::ZERO }; state.with_handler(|h| h.mouse_move(&mouse_event)); } Propagation::Stop }), ); win_state.drawing_area.connect_leave_notify_event( clone!(handle => move |_widget, _crossing| { if let Some(state) = handle.state.upgrade() { state.with_handler(|h| h.mouse_leave()); } Propagation::Stop }), ); win_state .drawing_area .connect_scroll_event(clone!(handle => move |_widget, scroll| { if let Some(state) = handle.state.upgrade() { let scale = state.scale.get(); let mods = get_modifiers(scroll.state()); // The magic "120"s are from Microsoft's documentation for WM_MOUSEWHEEL. // They claim that one "tick" on a scroll wheel should be 120 units. let shift = mods.shift(); let wheel_delta = match scroll.direction() { ScrollDirection::Up if shift => Some(Vec2::new(-120.0, 0.0)), ScrollDirection::Up => Some(Vec2::new(0.0, -120.0)), ScrollDirection::Down if shift => Some(Vec2::new(120.0, 0.0)), ScrollDirection::Down => Some(Vec2::new(0.0, 120.0)), ScrollDirection::Left => Some(Vec2::new(-120.0, 0.0)), ScrollDirection::Right => Some(Vec2::new(120.0, 0.0)), ScrollDirection::Smooth => { //TODO: Look at how gtk's scroll containers implements it let (mut delta_x, mut delta_y) = scroll.delta(); delta_x *= 120.; delta_y *= 120.; if shift { delta_x += delta_y; delta_y = 0.; } Some(Vec2::new(delta_x, delta_y)) } e => { warn!( "Warning: the Druid widget got some whacky scroll direction {:?}", e ); None } }; if let Some(wheel_delta) = wheel_delta { let mouse_event = MouseEvent { pos: Point::from(scroll.position()).to_dp(scale), buttons: get_mouse_buttons_from_modifiers(scroll.state()), mods, count: 0, focus: false, button: MouseButton::None, wheel_delta }; state.with_handler(|h| h.wheel(&mouse_event)); } } Propagation::Stop })); win_state .drawing_area .connect_key_press_event(clone!(handle => move |_widget, key| { if let Some(state) = handle.state.upgrade() { let hw_keycode = key.hardware_keycode(); let repeat = state.current_keycode.get() == Some(hw_keycode); state.current_keycode.set(Some(hw_keycode)); state.with_handler(|h| simulate_input(h, state.active_text_input.get(), make_key_event(key, repeat, KeyState::Down)) ); } Propagation::Stop })); win_state .drawing_area .connect_key_release_event(clone!(handle => move |_widget, key| { if let Some(state) = handle.state.upgrade() { if state.current_keycode.get() == Some(key.hardware_keycode()) { state.current_keycode.set(None); } state.with_handler(|h| h.key_up(make_key_event(key, false, KeyState::Up)) ); } Propagation::Stop })); win_state .drawing_area .connect_focus_in_event(clone!(handle => move |_widget, _event| { if let Some(state) = handle.state.upgrade() { state.with_handler(|h| h.got_focus()); } Propagation::Stop })); win_state .drawing_area .connect_focus_out_event(clone!(handle => move |_widget, _event| { if let Some(state) = handle.state.upgrade() { state.with_handler(|h| h.lost_focus()); } Propagation::Stop })); win_state .window .connect_delete_event(clone!(handle => move |_widget, _ev| { if let Some(state) = handle.state.upgrade() { state.with_handler(|h| h.request_close()); match state.closing.get() { true => Propagation::Proceed, false => Propagation::Stop, } } else { Propagation::Proceed } })); win_state .drawing_area .connect_destroy(clone!(handle => move |_widget| { if let Some(state) = handle.state.upgrade() { state.with_handler(|h| h.destroy()); } })); vbox.pack_end(&win_state.drawing_area, true, true, 0); win_state.drawing_area.realize(); win_state .drawing_area .window() .expect("realize didn't create window") .set_event_compression(false); if let Some(level) = self.level { let override_redirect = match level { WindowLevel::AppWindow => false, WindowLevel::Tooltip(_) | WindowLevel::DropDown(_) | WindowLevel::Modal(_) => true, }; if let Some(window) = win_state.window.window() { window.set_override_redirect(override_redirect); } } let size = self.size; win_state.with_handler(|h| { h.connect(&handle.clone().into()); h.scale(scale); h.size(size); }); Ok(handle) } } impl WindowState { #[track_caller] fn with_handler<T, F: FnOnce(&mut dyn WinHandler) -> T>(&self, f: F) -> Option<T> { if self.invalid.try_borrow_mut().is_err() || self.surface.try_borrow_mut().is_err() { error!("other RefCells were borrowed when calling into the handler"); return None; } let ret = self.with_handler_and_dont_check_the_other_borrows(f); self.run_deferred(); ret } #[track_caller] fn with_handler_and_dont_check_the_other_borrows<T, F: FnOnce(&mut dyn WinHandler) -> T>( &self, f: F, ) -> Option<T> { match self.handler.try_borrow_mut() { Ok(mut h) => Some(f(&mut **h)), Err(_) => { error!("failed to borrow WinHandler at {}", Location::caller()); None } } } fn resize_surface(&self, width: i32, height: i32) -> Result<(), anyhow::Error> { fn next_size(x: i32) -> i32 { // We round up to the nearest multiple of `accuracy`, which is between x/2 and x/4. // Don't bother rounding to anything smaller than 32 = 2^(7-1). let accuracy = 1 << ((32 - x.leading_zeros()).max(7) - 2); let mask = accuracy - 1; (x + mask) & !mask } let mut surface = self.surface.borrow_mut(); let mut cur_size = self.surface_size.get(); let (width, height) = (next_size(width), next_size(height)); if surface.is_none() || cur_size != (width, height) { cur_size = (width, height); self.surface_size.set(cur_size); if let Some(s) = surface.as_ref() { s.finish(); } *surface = None;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/gtk/screen.rs
druid-shell/src/backend/gtk/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! GTK Monitors and Screen information. use crate::kurbo::{Point, Rect, Size}; use crate::screen::Monitor; use gtk::gdk::{Display, DisplayManager, Rectangle}; use gtk::prelude::MonitorExt as _; fn translate_gdk_rectangle(r: Rectangle) -> Rect { Rect::from_origin_size( Point::new(r.x() as f64, r.y() as f64), Size::new(r.width() as f64, r.height() as f64), ) } fn translate_gdk_monitor(mon: gtk::gdk::Monitor) -> Monitor { let area = translate_gdk_rectangle(mon.geometry()); Monitor::new( mon.is_primary(), area, translate_gdk_rectangle(mon.workarea()), ) } pub(crate) fn get_monitors() -> Vec<Monitor> { if !gtk::is_initialized() { if let Err(err) = gtk::init() { tracing::error!("{}", err.message); return Vec::new(); } } DisplayManager::get() .list_displays() .iter() .flat_map(|display: &Display| { (0..display.n_monitors()) .filter_map(move |i| display.monitor(i).map(translate_gdk_monitor)) }) .collect() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/dialog.rs
druid-shell/src/backend/mac/dialog.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! File open/save dialogs, macOS implementation. #![allow(non_upper_case_globals, clippy::upper_case_acronyms)] use std::ffi::OsString; use cocoa::appkit::NSView; use cocoa::base::{id, nil, NO, YES}; use cocoa::foundation::{NSArray, NSAutoreleasePool, NSInteger, NSPoint, NSRect, NSSize, NSURL}; use objc::{class, msg_send, sel, sel_impl}; use super::util::{from_nsstring, make_nsstring}; use crate::dialog::{FileDialogOptions, FileDialogType}; use crate::{FileInfo, FileSpec}; pub(crate) type NSModalResponse = NSInteger; const NSModalResponseOK: NSInteger = 1; const NSModalResponseCancel: NSInteger = 0; pub(crate) unsafe fn get_file_info( panel: id, options: FileDialogOptions, result: NSModalResponse, ) -> Option<FileInfo> { match result { NSModalResponseOK => { let url: id = msg_send![panel, URL]; let path: id = msg_send![url, path]; let (path, format) = rewritten_path(panel, path, options); let path: OsString = from_nsstring(path).into(); Some(FileInfo { path: path.into(), format, }) } NSModalResponseCancel => None, _ => unreachable!(), } } #[allow(clippy::cognitive_complexity)] pub(crate) unsafe fn build_panel(ty: FileDialogType, mut options: FileDialogOptions) -> id { let panel: id = match ty { FileDialogType::Open => msg_send![class!(NSOpenPanel), openPanel], FileDialogType::Save => msg_send![class!(NSSavePanel), savePanel], }; // Enable the user to choose whether file extensions are hidden in the dialog. // This defaults to off, but is recommended to be turned on by Apple. // https://developer.apple.com/design/human-interface-guidelines/macos/user-interaction/file-handling/ let () = msg_send![panel, setCanSelectHiddenExtension: YES]; // Set open dialog specific options // NSOpenPanel inherits from NSSavePanel and thus has more options. let mut set_type_filter = true; if let FileDialogType::Open = ty { if options.select_directories { let () = msg_send![panel, setCanChooseDirectories: YES]; // Disable the selection of files in directory selection mode, // because other backends like Windows have no support for it, // and expecting it to work will lead to buggy cross-platform behavior. let () = msg_send![panel, setCanChooseFiles: NO]; // File filters are used by macOS to determine which paths are packages. // If we are going to treat packages as directories, then file filters // need to be disabled. Otherwise macOS will allow picking of regular files // that match the filters as if they were directories too. set_type_filter = !options.packages_as_directories; } if options.multi_selection { let () = msg_send![panel, setAllowsMultipleSelection: YES]; } } // Set universal options if options.packages_as_directories { let () = msg_send![panel, setTreatsFilePackagesAsDirectories: YES]; } if options.show_hidden { let () = msg_send![panel, setShowsHiddenFiles: YES]; } if let Some(default_name) = &options.default_name { let () = msg_send![panel, setNameFieldStringValue: make_nsstring(default_name)]; } if let Some(name_label) = &options.name_label { let () = msg_send![panel, setNameFieldLabel: make_nsstring(name_label)]; } if let Some(title) = &options.title { let () = msg_send![panel, setTitle: make_nsstring(title)]; } if let Some(text) = &options.button_text { let () = msg_send![panel, setPrompt: make_nsstring(text)]; } if let Some(path) = &options.starting_directory { if let Some(path) = path.to_str() { let url = NSURL::alloc(nil) .initFileURLWithPath_isDirectory_(make_nsstring(path), YES) .autorelease(); let () = msg_send![panel, setDirectoryURL: url]; } } // If we have non-empty allowed types and a file save dialog, // we add a accessory view to set the file format match (&options.allowed_types, ty) { (Some(allowed_types), FileDialogType::Save) if !allowed_types.is_empty() => { let accessory_view = allowed_types_accessory_view(allowed_types); let _: () = msg_send![panel, setAccessoryView: accessory_view]; } _ => (), } if set_type_filter { // If a default type was specified, then we must reorder the allowed types, // because there's no way to specify the default type other than having it be first. if let Some(dt) = &options.default_type { let mut present = false; if let Some(allowed_types) = options.allowed_types.as_mut() { if let Some(idx) = allowed_types.iter().position(|t| t == dt) { present = true; allowed_types.swap(idx, 0); } } if !present { tracing::warn!("The default type {:?} is not present in allowed types.", dt); } } // A vector of NSStrings. this must outlive `nsarray_allowed_types`. let allowed_types = options.allowed_types.as_ref().map(|specs| { specs .iter() .flat_map(|spec| spec.extensions.iter().map(|s| make_nsstring(s))) .collect::<Vec<_>>() }); let nsarray_allowed_types = allowed_types .as_ref() .map(|types| NSArray::arrayWithObjects(nil, types.as_slice())); if let Some(nsarray) = nsarray_allowed_types { let () = msg_send![panel, setAllowedFileTypes: nsarray]; } } panel } // AppKit has a built-in file format accessory view. However, this is only // displayed for `NSDocument` based apps. We have to construct our own `NSView` // hierarchy to implement something similar. unsafe fn allowed_types_accessory_view(allowed_types: &[crate::FileSpec]) -> id { // Build the View Structure required to have file format popup. // This requires a container view, a label, a popup button, // and some layout code to make sure it behaves correctly for // fixed size and resizable views let total_frame = NSRect::new( NSPoint { x: 0.0, y: 0.0 }, NSSize { width: 320.0, height: 30.0, }, ); let padding = 10.0; // Prepare the label let (label, label_size) = file_format_label(); // Place the label centered (similar to the popup button) label.setFrameOrigin(NSPoint { x: padding, y: label_size.height / 2.0, }); // Prepare the popup button let popup_frame = NSRect::new( NSPoint { x: padding + label_size.width + padding, y: 0.0, }, NSSize { width: total_frame.size.width - (padding * 3.0) - label_size.width, height: total_frame.size.height, }, ); let popup_button = file_format_popup_button(allowed_types, popup_frame); // Prepare the container let container_view: id = msg_send![class!(NSView), alloc]; let container_view: id = container_view.initWithFrame_(total_frame); container_view.addSubview_(label); container_view.addSubview_(popup_button); container_view.autorelease() } const FileFormatPopoverTag: NSInteger = 10; unsafe fn file_format_popup_button(allowed_types: &[crate::FileSpec], popup_frame: NSRect) -> id { let popup_button: id = msg_send![class!(NSPopUpButton), alloc]; let _: () = msg_send![popup_button, initWithFrame:popup_frame pullsDown:false]; for allowed_type in allowed_types { let title = make_nsstring(allowed_type.name); msg_send![popup_button, addItemWithTitle: title] } let _: () = msg_send![popup_button, setTag: FileFormatPopoverTag]; popup_button.autorelease() } unsafe fn file_format_label() -> (id, NSSize) { let label: id = msg_send![class!(NSTextField), new]; let _: () = msg_send![label, setBezeled:false]; let _: () = msg_send![label, setDrawsBackground:false]; // FIXME: As we have to roll our own view hierarchy, we're not getting a translated // title here. So we ought to find a way to translate this. let title = make_nsstring("File Format:"); let _: () = msg_send![label, setStringValue: title]; let _: () = msg_send![label, sizeToFit]; (label.autorelease(), label.frame().size) } /// Take a panel, a chosen path, and the file dialog options /// and rewrite the path to utilize the chosen file format. unsafe fn rewritten_path( panel: id, path: id, options: FileDialogOptions, ) -> (id, Option<FileSpec>) { let allowed_types = match options.allowed_types { Some(t) if !t.is_empty() => t, _ => return (path, None), }; let accessory: id = msg_send![panel, accessoryView]; if accessory == nil { return (path, None); } let popup_button: id = msg_send![accessory, viewWithTag: FileFormatPopoverTag]; if popup_button == nil { return (path, None); } let index: NSInteger = msg_send![popup_button, indexOfSelectedItem]; let file_spec = allowed_types[index as usize]; let extension = file_spec.extensions[0]; // Remove any extension the user might have entered and replace it with the // selected extension. // We're using `NSString` methods instead of `String` simply because // they are made for this purpose and simplify the implementation. let path: id = msg_send![path, stringByDeletingPathExtension]; let path: id = msg_send![ path, stringByAppendingPathExtension: make_nsstring(extension) ]; (path, Some(file_spec)) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/clipboard.rs
druid-shell/src/backend/mac/clipboard.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interactions with the system pasteboard on macOS. use cocoa::appkit::NSPasteboardTypeString; use cocoa::base::{id, nil, BOOL, YES}; use cocoa::foundation::{NSArray, NSInteger, NSUInteger}; use objc::{class, msg_send, sel, sel_impl}; use super::util; use crate::clipboard::{ClipboardFormat, FormatId}; #[derive(Debug, Clone, Default)] pub struct Clipboard; impl Clipboard { /// Put a string onto the system clipboard. pub fn put_string(&mut self, s: impl AsRef<str>) { let s = s.as_ref(); put_string_impl(s); fn put_string_impl(s: &str) { unsafe { let nsstring = util::make_nsstring(s); let pasteboard: id = msg_send![class!(NSPasteboard), generalPasteboard]; let _: NSInteger = msg_send![pasteboard, clearContents]; let result: BOOL = msg_send![pasteboard, setString: nsstring forType: NSPasteboardTypeString]; if result != YES { tracing::warn!("failed to set clipboard"); } } } } /// Put multi-format data on the system clipboard. pub fn put_formats(&mut self, formats: &[ClipboardFormat]) { unsafe { let pasteboard: id = msg_send![class!(NSPasteboard), generalPasteboard]; let _: NSInteger = msg_send![pasteboard, clearContents]; let idents = formats .iter() .map(|f| util::make_nsstring(f.identifier)) .collect::<Vec<_>>(); let array = NSArray::arrayWithObjects(nil, &idents); let _: NSInteger = msg_send![pasteboard, declareTypes: array owner: nil]; for (i, format) in formats.iter().enumerate() { let data = util::make_nsdata(&format.data); let data_type = idents[i]; let result: BOOL = msg_send![pasteboard, setData: data forType: data_type]; if result != YES { tracing::warn!( "failed to set clipboard contents for type '{}'", format.identifier ); } } } } /// Get a string from the system clipboard, if one is available. pub fn get_string(&self) -> Option<String> { unsafe { let pasteboard: id = msg_send![class!(NSPasteboard), generalPasteboard]; let contents: id = msg_send![pasteboard, stringForType: NSPasteboardTypeString]; if contents.is_null() { None } else { Some(util::from_nsstring(contents)) } } } /// Given a list of supported clipboard types, returns the supported type which has /// highest priority on the system clipboard, or `None` if no types are supported. pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> { unsafe { let pasteboard: id = msg_send![class!(NSPasteboard), generalPasteboard]; let nsstrings = formats .iter() .map(|s| util::make_nsstring(s)) .collect::<Vec<_>>(); let array = NSArray::arrayWithObjects(nil, &nsstrings); let available: id = msg_send![pasteboard, availableTypeFromArray: array]; if available.is_null() { None } else { let idx: NSUInteger = msg_send![array, indexOfObject: available]; let idx = idx as usize; if idx > formats.len() { tracing::error!("clipboard object not found"); None } else { Some(formats[idx]) } } } } /// Return data in a given format, if available. /// /// It is recommended that the `fmt` argument be a format returned by /// [`Clipboard::preferred_format`] pub fn get_format(&self, fmt: FormatId) -> Option<Vec<u8>> { unsafe { let pb_type = util::make_nsstring(fmt); let pasteboard: id = msg_send![class!(NSPasteboard), generalPasteboard]; let data: id = msg_send![pasteboard, dataForType: pb_type]; if !data.is_null() { let data = util::from_nsdata(data); Some(data) } else { None } } } pub fn available_type_names(&self) -> Vec<String> { unsafe { let pasteboard: id = msg_send![class!(NSPasteboard), generalPasteboard]; let types: id = msg_send![pasteboard, types]; let types_len = types.count() as usize; (0..types_len) .map(|i| util::from_nsstring(types.objectAtIndex(i as NSUInteger))) .collect() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/text_input.rs
druid-shell/src/backend/mac/text_input.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 // massive thanks to github.com/yvt and their project tcw3 (https://github.com/yvt/Stella2), which is some // of the most solid/well documented input method code for mac written in Rust that we've found. tcw3 was // instrumental in this file's implementation. // apple's documentation on text editing is also very helpful: // https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/TextEditing/TextEditing.html#//apple_ref/doc/uid/TP40009459-CH3-SW3 #![allow(clippy::upper_case_acronyms, non_snake_case)] use std::ffi::c_void; use std::ops::Range; use std::os::raw::c_uchar; use super::window::with_edit_lock_from_window; use crate::kurbo::Point; use crate::text::{ Action, Affinity, Direction, InputHandler, Movement, Selection, VerticalMovement, WritingDirection, }; use cocoa::base::{id, nil, BOOL}; use cocoa::foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSUInteger}; use cocoa::{appkit::NSWindow, foundation::NSNotFound}; use objc::runtime::{Object, Sel}; use objc::{class, msg_send, sel, sel_impl}; // thanks to winit for the custom NSRange code: // https://github.com/rust-windowing/winit/pull/518/files#diff-61be96e960785f102cb20ad8464eafeb6edd4245ea40224b3c3206c72cd5bf56R12-R34 // this is necessary until objc implements objc::Encode for their NSRange; ideally this code could get upstreamed // and we could delete it. #[repr(C)] #[derive(Debug)] pub struct NSRange { pub location: NSUInteger, pub length: NSUInteger, } impl NSRange { pub const NONE: NSRange = NSRange::new(NSNotFound as NSUInteger, 0); #[inline] pub const fn new(location: NSUInteger, length: NSUInteger) -> NSRange { NSRange { location, length } } } unsafe impl objc::Encode for NSRange { fn encode() -> objc::Encoding { let encoding = format!( "{{NSRange={}{}}}", NSUInteger::encode().as_str(), NSUInteger::encode().as_str(), ); unsafe { objc::Encoding::from_str(&encoding) } } } // BOOL is i8 on x86, but bool on aarch64 #[cfg_attr(target_arch = "aarch64", allow(clippy::useless_conversion))] pub extern "C" fn has_marked_text(this: &mut Object, _: Sel) -> BOOL { with_edit_lock_from_window(this, false, |edit_lock| { edit_lock.composition_range().is_some() }) .unwrap_or(false) .into() } pub extern "C" fn marked_range(this: &mut Object, _: Sel) -> NSRange { with_edit_lock_from_window(this, false, |mut edit_lock| { edit_lock .composition_range() .map(|range| encode_nsrange(&mut edit_lock, range)) .unwrap_or(NSRange::NONE) }) .unwrap_or(NSRange::NONE) } pub extern "C" fn selected_range(this: &mut Object, _: Sel) -> NSRange { with_edit_lock_from_window(this, false, |mut edit_lock| { let range = edit_lock.selection().range(); encode_nsrange(&mut edit_lock, range) }) .unwrap_or(NSRange::NONE) } pub extern "C" fn set_marked_text( this: &mut Object, _: Sel, text: id, selected_range: NSRange, replacement_range: NSRange, ) { with_edit_lock_from_window(this, true, |mut edit_lock| { let mut composition_range = edit_lock.composition_range().unwrap_or_else(|| { // no existing composition range? default to replacement range, interpreted in absolute coordinates // undocumented by apple, see // https://github.com/yvt/Stella2/blob/076fb6ee2294fcd1c56ed04dd2f4644bf456e947/tcw3/pal/src/macos/window.rs#L1144-L1146 decode_nsrange(&*edit_lock, &replacement_range, 0).unwrap_or_else(|| { // no replacement range either? apparently we default to the selection in this case edit_lock.selection().range() }) }); let replace_range_offset = edit_lock .composition_range() .map(|range| range.start) .unwrap_or(0); let replace_range = decode_nsrange(&*edit_lock, &replacement_range, replace_range_offset) .unwrap_or_else(|| { // default replacement range is already-exsiting composition range // undocumented by apple, see // https://github.com/yvt/Stella2/blob/076fb6ee2294fcd1c56ed04dd2f4644bf456e947/tcw3/pal/src/macos/window.rs#L1124-L1125 composition_range.clone() }); let text_string = parse_attributed_string(&text); edit_lock.replace_range(replace_range.clone(), text_string); // Update the composition range composition_range.end -= replace_range.len(); composition_range.end += text_string.len(); if composition_range.is_empty() { edit_lock.set_composition_range(None); } else { edit_lock.set_composition_range(Some(composition_range)); }; // Update the selection if let Some(selection_range) = decode_nsrange(&*edit_lock, &selected_range, replace_range.start) { // preserve ordering of anchor and active let existing_selection = edit_lock.selection(); let new_selection = if existing_selection.anchor < existing_selection.active { Selection::new(selection_range.start, selection_range.end) } else { Selection::new(selection_range.end, selection_range.start) }; edit_lock.set_selection(new_selection); } }); } pub extern "C" fn unmark_text(this: &mut Object, _: Sel) { with_edit_lock_from_window(this, false, |mut edit_lock| { edit_lock.set_composition_range(None) }); } pub extern "C" fn valid_attributes_for_marked_text(_this: &mut Object, _: Sel) -> id { // we don't support any attributes unsafe { NSArray::array(nil) } } pub extern "C" fn attributed_substring_for_proposed_range( this: &mut Object, _: Sel, proposed_range: NSRange, actual_range: *mut c_void, ) -> id { with_edit_lock_from_window(this, false, |mut edit_lock| { let range = match decode_nsrange(&*edit_lock, &proposed_range, 0) { Some(v) => v, None => return nil, }; if !actual_range.is_null() { let ptr = actual_range as *mut NSRange; let range_utf16 = encode_nsrange(&mut edit_lock, range.clone()); unsafe { *ptr = range_utf16; } } let text = edit_lock.slice(range); unsafe { let ns_string = NSString::alloc(nil).init_str(&text); let attr_string: id = msg_send![class!(NSAttributedString), alloc]; msg_send![attr_string, initWithString: ns_string] } }) .unwrap_or(nil) } pub extern "C" fn insert_text(this: &mut Object, _: Sel, text: id, replacement_range: NSRange) { with_edit_lock_from_window(this, true, |mut edit_lock| { let text_string = parse_attributed_string(&text); // yvt notes: // [The null range case] is undocumented, but it seems that it means // the whole marked text or selected text should be finalized // and replaced with the given string. // https://github.com/yvt/Stella2/blob/076fb6ee2294fcd1c56ed04dd2f4644bf456e947/tcw3/pal/src/macos/window.rs#L1041-L1043 let converted_range = decode_nsrange(&*edit_lock, &replacement_range, 0) .or_else(|| edit_lock.composition_range()) .unwrap_or_else(|| edit_lock.selection().range()); edit_lock.replace_range(converted_range.clone(), text_string); edit_lock.set_composition_range(None); // move the caret next to the inserted text let caret_index = converted_range.start + text_string.len(); edit_lock.set_selection(Selection::caret(caret_index)); }); } pub extern "C" fn character_index_for_point( this: &mut Object, _: Sel, point: NSPoint, ) -> NSUInteger { with_edit_lock_from_window(this, true, |edit_lock| { let hit_test = edit_lock.hit_test_point(Point::new(point.x, point.y)); hit_test.idx as NSUInteger }) .unwrap_or(0) } pub extern "C" fn first_rect_for_character_range( this: &mut Object, _: Sel, character_range: NSRange, actual_range: *mut c_void, ) -> NSRect { let rect = with_edit_lock_from_window(this, true, |mut edit_lock| { let mut range = decode_nsrange(&*edit_lock, &character_range, 0).unwrap_or(0..0); { let line_range = edit_lock.line_range(range.start, Affinity::Downstream); range.end = usize::min(range.end, line_range.end); } let rect = match edit_lock.slice_bounding_box(range.clone()) { Some(v) => v, None => return NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(0.0, 0.0)), }; if !actual_range.is_null() { let ptr = actual_range as *mut NSRange; let range_utf16 = encode_nsrange(&mut edit_lock, range); unsafe { *ptr = range_utf16; } } NSRect::new( NSPoint::new(rect.x0, rect.y0), NSSize::new(rect.width(), rect.height()), ) }) .unwrap_or_else(|| NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))); unsafe { let window_space_rect: NSRect = msg_send![this as *const _, convertRect: rect toView: nil]; let window: id = msg_send![this as *const _, window]; window.convertRectToScreen_(window_space_rect) } } pub extern "C" fn do_command_by_selector(this: &mut Object, _: Sel, cmd: Sel) { with_edit_lock_from_window(this, true, |lock| do_command_by_selector_impl(lock, cmd)); } fn do_command_by_selector_impl(mut edit_lock: Box<dyn InputHandler>, cmd: Sel) { match cmd.name() { // see https://developer.apple.com/documentation/appkit/nsstandardkeybindingresponding?language=objc // and https://support.apple.com/en-us/HT201236 // and https://support.apple.com/lv-lv/guide/mac-help/mh21243/mac "centerSelectionInVisibleArea:" => edit_lock.handle_action(Action::ScrollToSelection), "deleteBackward:" => { edit_lock.handle_action(Action::Delete(Movement::Grapheme(Direction::Upstream))) } "deleteBackwardByDecomposingPreviousCharacter:" => { edit_lock.handle_action(Action::DecomposingBackspace) } "deleteForward:" => { edit_lock.handle_action(Action::Delete(Movement::Grapheme(Direction::Downstream))) } "deleteToBeginningOfLine:" => { edit_lock.handle_action(Action::Delete(Movement::Line(Direction::Upstream))) } "deleteToBeginningOfParagraph:" => { // TODO(lord): this seems to also kill the text into a buffer that can get pasted with yank edit_lock.handle_action(Action::Delete(Movement::ParagraphStart)) } "deleteToEndOfLine:" => { edit_lock.handle_action(Action::Delete(Movement::Line(Direction::Downstream))) } "deleteToEndOfParagraph:" => { // TODO(lord): this seems to also kill the text into a buffer that can get pasted with yank edit_lock.handle_action(Action::Delete(Movement::ParagraphEnd)) } "deleteWordBackward:" => { edit_lock.handle_action(Action::Delete(Movement::Word(Direction::Upstream))) } "deleteWordForward:" => { edit_lock.handle_action(Action::Delete(Movement::Word(Direction::Downstream))) } "insertBacktab:" => edit_lock.handle_action(Action::InsertBacktab), "insertLineBreak:" => edit_lock.handle_action(Action::InsertNewLine { ignore_hotkey: false, newline_type: '\u{2028}', }), "insertNewline:" => edit_lock.handle_action(Action::InsertNewLine { ignore_hotkey: false, newline_type: '\n', }), "insertNewlineIgnoringFieldEditor:" => edit_lock.handle_action(Action::InsertNewLine { ignore_hotkey: true, newline_type: '\n', }), "insertParagraphSeparator:" => edit_lock.handle_action(Action::InsertNewLine { ignore_hotkey: false, newline_type: '\u{2029}', }), "insertTab:" => edit_lock.handle_action(Action::InsertTab { ignore_hotkey: false, }), "insertTabIgnoringFieldEditor:" => edit_lock.handle_action(Action::InsertTab { ignore_hotkey: true, }), "makeBaseWritingDirectionLeftToRight:" => edit_lock.handle_action( Action::SetParagraphWritingDirection(WritingDirection::LeftToRight), ), "makeBaseWritingDirectionNatural:" => edit_lock.handle_action( Action::SetParagraphWritingDirection(WritingDirection::Natural), ), "makeBaseWritingDirectionRightToLeft:" => edit_lock.handle_action( Action::SetParagraphWritingDirection(WritingDirection::RightToLeft), ), "makeTextWritingDirectionLeftToRight:" => edit_lock.handle_action( Action::SetSelectionWritingDirection(WritingDirection::LeftToRight), ), "makeTextWritingDirectionNatural:" => edit_lock.handle_action( Action::SetSelectionWritingDirection(WritingDirection::Natural), ), "makeTextWritingDirectionRightToLeft:" => edit_lock.handle_action( Action::SetSelectionWritingDirection(WritingDirection::RightToLeft), ), "moveBackward:" => { edit_lock.handle_action(Action::Move(Movement::Grapheme(Direction::Upstream))) } "moveBackwardAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Grapheme(Direction::Upstream), )), "moveDown:" => { edit_lock.handle_action(Action::Move(Movement::Vertical(VerticalMovement::LineDown))) } "moveDownAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Vertical(VerticalMovement::LineDown), )), "moveForward:" => { edit_lock.handle_action(Action::Move(Movement::Grapheme(Direction::Downstream))) } "moveForwardAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Grapheme(Direction::Downstream), )), "moveLeft:" => edit_lock.handle_action(Action::Move(Movement::Grapheme(Direction::Left))), "moveLeftAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme(Direction::Left))) } "moveParagraphBackwardAndModifySelection:" => { let selection = edit_lock.selection(); let is_active_after_anchor = selection.active > selection.anchor; edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme( Direction::Upstream, ))); edit_lock.handle_action(Action::MoveSelecting(Movement::ParagraphStart)); if is_active_after_anchor && selection.active <= selection.anchor { // textedit testing showed that this operation never fully inverts a selection; if this action // would cause a selection's active and anchor to swap order, it makes a caret instead. applying // the operation a second time (on the selection that is now a caret) is required to invert. edit_lock.set_selection(Selection::caret(selection.anchor)); } } "moveParagraphForwardAndModifySelection:" => { let selection = edit_lock.selection(); let is_anchor_after_active = selection.active < selection.anchor; edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme( Direction::Downstream, ))); edit_lock.handle_action(Action::MoveSelecting(Movement::ParagraphEnd)); if is_anchor_after_active && selection.active >= selection.anchor { // textedit testing showed that this operation never fully inverts a selection; if this action // would cause a selection's active and anchor to swap order, it makes a caret instead. applying // the operation a second time (on the selection that is now a caret) is required to invert. edit_lock.set_selection(Selection::caret(selection.anchor)); } } "moveRight:" => edit_lock.handle_action(Action::Move(Movement::Grapheme(Direction::Right))), "moveRightAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme(Direction::Right))) } "moveToBeginningOfDocument:" => edit_lock.handle_action(Action::Move(Movement::Vertical( VerticalMovement::DocumentStart, ))), "moveToBeginningOfDocumentAndModifySelection:" => edit_lock.handle_action( Action::MoveSelecting(Movement::Vertical(VerticalMovement::DocumentStart)), ), "moveToBeginningOfLine:" => { edit_lock.handle_action(Action::Move(Movement::Line(Direction::Upstream))) } "moveToBeginningOfLineAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Line(Direction::Upstream))) } "moveToBeginningOfParagraph:" => { // initially, it may seem like this and moveToEndOfParagraph shouldn't be idempotent. after all, // option-up and option-down aren't idempotent, and those seem to call this method. however, on // further inspection, you can find that option-up first calls `moveBackward` before calling this. // if you send the raw command to TextEdit by editing your `DefaultKeyBinding.dict`, you can find // that this operation is in fact idempotent. edit_lock.handle_action(Action::Move(Movement::ParagraphStart)) } "moveToBeginningOfParagraphAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::ParagraphStart)) } "moveToEndOfDocument:" => edit_lock.handle_action(Action::Move(Movement::Vertical( VerticalMovement::DocumentEnd, ))), "moveToEndOfDocumentAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Vertical(VerticalMovement::DocumentEnd), )), "moveToEndOfLine:" => { edit_lock.handle_action(Action::Move(Movement::Line(Direction::Downstream))) } "moveToEndOfLineAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Line(Direction::Downstream))) } "moveToEndOfParagraph:" => edit_lock.handle_action(Action::Move(Movement::ParagraphEnd)), "moveToEndOfParagraphAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::ParagraphEnd)) } "moveToLeftEndOfLine:" => { edit_lock.handle_action(Action::Move(Movement::Line(Direction::Left))) } "moveToLeftEndOfLineAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Line(Direction::Left))) } "moveToRightEndOfLine:" => { edit_lock.handle_action(Action::Move(Movement::Line(Direction::Right))) } "moveToRightEndOfLineAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Line(Direction::Right))) } "moveUp:" => { edit_lock.handle_action(Action::Move(Movement::Vertical(VerticalMovement::LineUp))) } "moveUpAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Vertical(VerticalMovement::LineUp), )), "moveWordBackward:" => { edit_lock.handle_action(Action::Move(Movement::Word(Direction::Upstream))) } "moveWordBackwardAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Word(Direction::Upstream))) } "moveWordForward:" => { edit_lock.handle_action(Action::Move(Movement::Word(Direction::Downstream))) } "moveWordForwardAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Word(Direction::Downstream))) } "moveWordLeft:" => edit_lock.handle_action(Action::Move(Movement::Word(Direction::Left))), "moveWordLeftAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Word(Direction::Left))) } "moveWordRight:" => edit_lock.handle_action(Action::Move(Movement::Word(Direction::Right))), "moveWordRightAndModifySelection:" => { edit_lock.handle_action(Action::MoveSelecting(Movement::Word(Direction::Right))) } "pageDown:" => { edit_lock.handle_action(Action::Move(Movement::Vertical(VerticalMovement::PageDown))) } "pageDownAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Vertical(VerticalMovement::PageDown), )), "pageUp:" => { edit_lock.handle_action(Action::Move(Movement::Vertical(VerticalMovement::PageUp))) } "pageUpAndModifySelection:" => edit_lock.handle_action(Action::MoveSelecting( Movement::Vertical(VerticalMovement::PageUp), )), "scrollLineDown:" => edit_lock.handle_action(Action::Scroll(VerticalMovement::LineDown)), "scrollLineUp:" => edit_lock.handle_action(Action::Scroll(VerticalMovement::LineUp)), "scrollPageDown:" => edit_lock.handle_action(Action::Scroll(VerticalMovement::PageDown)), "scrollPageUp:" => edit_lock.handle_action(Action::Scroll(VerticalMovement::PageUp)), "scrollToBeginningOfDocument:" => { edit_lock.handle_action(Action::Scroll(VerticalMovement::DocumentStart)) } "scrollToEndOfDocument:" => { edit_lock.handle_action(Action::Scroll(VerticalMovement::DocumentEnd)) } "selectAll:" => edit_lock.handle_action(Action::SelectAll), "selectLine:" => edit_lock.handle_action(Action::SelectLine), "selectParagraph:" => edit_lock.handle_action(Action::SelectParagraph), "selectWord:" => edit_lock.handle_action(Action::SelectWord), "transpose:" => { // transpose is a tricky-to-implement-correctly mac-specific operation, and so we implement it using // edit_lock commands directly instead of allowing applications to implement it directly through an // action handler. it seems extremely unlikely anybody would want to override its behavior, anyway. // Swaps the graphemes before and after the caret, and then moves the caret downstream one grapheme. If the caret is at the // end of a hard-wrapped line or document, act as though the caret was one grapheme upstream instead. If the caret is at the // beginning of the document, this is a no-op. This is a no-op on non-caret selections (when `anchor != active`). { let selection = edit_lock.selection(); if !selection.is_caret() || selection.anchor == 0 { return; } } // move caret to the end of the transpose region { let old_selection = edit_lock.selection(); edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme( Direction::Downstream, ))); let new_selection = edit_lock.selection().range(); let next_grapheme = edit_lock.slice(new_selection.clone()); let next_char = next_grapheme.chars().next(); if next_char == Some('\n') || next_char == Some('\r') || next_char == Some('\u{2029}') || next_char == Some('\u{2028}') || next_char.is_none() { // next char is a newline or end of doc; so end of transpose range will actually be the starting selection.anchor edit_lock.set_selection(old_selection); } else { // normally, end of transpose range will be next grapheme edit_lock.set_selection(Selection::caret(new_selection.end)); } } // now find the previous two graphemes edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme( Direction::Upstream, ))); let middle_idx = edit_lock.selection().active; edit_lock.handle_action(Action::MoveSelecting(Movement::Grapheme( Direction::Upstream, ))); let selection = edit_lock.selection(); let first_grapheme = edit_lock.slice(selection.min()..middle_idx).into_owned(); let second_grapheme = edit_lock.slice(middle_idx..selection.max()); let new_string = format!("{second_grapheme}{first_grapheme}"); // replace_range should automatically set selection to end of inserted range edit_lock.replace_range(selection.range(), &new_string); } "capitalizeWord:" => { // this command expands the selection to words, and then applies titlecase to that selection // not actually sure what keyboard shortcut corresponds to this or the other case changing commands, // but textedit seems to have this behavior when this action is simulated by editing DefaultKeyBinding.dict. edit_lock.handle_action(Action::SelectWord); edit_lock.handle_action(Action::TitlecaseSelection) } "lowercaseWord:" => { // this command expands the selection to words, and then applies uppercase to that selection edit_lock.handle_action(Action::SelectWord); edit_lock.handle_action(Action::LowercaseSelection); } "uppercaseWord:" => { // this command expands the selection to words, and then applies uppercase to that selection edit_lock.handle_action(Action::SelectWord); edit_lock.handle_action(Action::UppercaseSelection); } "insertDoubleQuoteIgnoringSubstitution:" => { edit_lock.handle_action(Action::InsertDoubleQuoteIgnoringSmartQuotes) } "insertSingleQuoteIgnoringSubstitution:" => { edit_lock.handle_action(Action::InsertSingleQuoteIgnoringSmartQuotes) } "cancelOperation:" => edit_lock.handle_action(Action::Cancel), // "deleteToMark:" => {} // TODO(lord): selectToMark, then delete selection. also puts selection in yank buffer // "selectToMark:" => {} // TODO(lord): extends the selection to include the mark // "setMark:" => {} // TODO(lord): remembers index in document (but what about grapheme clusters??) // "swapWithMark:" => {} // TODO(lord): swaps current and stored mark indices // "yank:" => {} // TODO(lord): triggered with control-y, inserts in the text previously killed deleteTo*OfParagraph "transposeWords:" => {} // textedit doesn't support, so neither will we "changeCaseOfLetter:" => {} // textedit doesn't support, so neither will we "indent:" => {} // textedit doesn't support, so neither will we "insertContainerBreak:" => {} // textedit and pages don't seem to support, so neither will we "quickLookPreviewItems:" => {} // don't seem to apply to text editing?? hopefully // TODO(lord): reply to cmyr comment "complete:" => { // these are normally intercepted by the IME; if it gets to us, log eprintln!("got an unexpected 'complete' text input command from macOS"); } "noop:" => {} e => { eprintln!("unknown text editing command from macOS: {e}"); } }; } /// Parses the UTF-16 `NSRange` into a UTF-8 `Range<usize>`. /// `start_offset` is the UTF-8 offset into the document that `range` values are relative to. Set it to `0` if `range` /// is absolute instead of relative. /// Returns `None` if `range` was invalid; macOS often uses this to indicate some special null value. fn decode_nsrange( edit_lock: &dyn InputHandler, range: &NSRange, start_offset: usize, ) -> Option<Range<usize>> { if range.location as usize >= i32::MAX as usize { return None; } let start_offset_utf16 = edit_lock.utf8_to_utf16(0..start_offset); let location_utf16 = range.location as usize + start_offset_utf16; let length_utf16 = range.length as usize; let start_utf8 = edit_lock.utf16_to_utf8(0..location_utf16); let end_utf8 = start_utf8 + edit_lock.utf16_to_utf8(location_utf16..location_utf16 + length_utf16); Some(start_utf8..end_utf8) } // Encodes the UTF-8 `Range<usize>` into a UTF-16 `NSRange`. fn encode_nsrange(edit_lock: &mut Box<dyn InputHandler>, mut range: Range<usize>) -> NSRange { while !edit_lock.is_char_boundary(range.start) { range.start -= 1; } while !edit_lock.is_char_boundary(range.end) { range.end -= 1; } let start = edit_lock.utf8_to_utf16(0..range.start); let len = edit_lock.utf8_to_utf16(range); NSRange::new(start as NSUInteger, len as NSUInteger) } fn parse_attributed_string(text: &id) -> &str { unsafe { let nsstring = if msg_send![*text, isKindOfClass: class!(NSAttributedString)] { msg_send![*text, string] } else { // already a NSString *text }; let slice = std::slice::from_raw_parts(nsstring.UTF8String() as *const c_uchar, nsstring.len()); std::str::from_utf8_unchecked(slice) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/menu.rs
druid-shell/src/backend/mac/menu.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS implementation of menus. use cocoa::appkit::{NSEventModifierFlags, NSMenu, NSMenuItem}; use cocoa::base::{id, nil, NO}; use cocoa::foundation::{NSAutoreleasePool, NSString}; use objc::{msg_send, sel, sel_impl}; use super::util::make_nsstring; use crate::common_util::strip_access_key; use crate::hotkey::HotKey; use crate::keyboard::{KbKey, Modifiers}; pub struct Menu { pub menu: id, } fn make_menu_item( id: u32, text: &str, key: Option<&HotKey>, selected: Option<bool>, enabled: bool, ) -> id { let key_equivalent = key.map(HotKey::key_equivalent).unwrap_or(""); let stripped_text = strip_access_key(text); unsafe { let item = NSMenuItem::alloc(nil) .initWithTitle_action_keyEquivalent_( make_nsstring(&stripped_text), sel!(handleMenuItem:), make_nsstring(key_equivalent), ) .autorelease(); let () = msg_send![item, setTag: id as isize]; if let Some(mask) = key.map(HotKey::key_modifier_mask) { let () = msg_send![item, setKeyEquivalentModifierMask: mask]; } if !enabled { let () = msg_send![item, setEnabled: NO]; } if let Some(true) = selected { let () = msg_send![item, setState: 1_isize]; } item } } impl Menu { pub fn new() -> Menu { unsafe { let title = NSString::alloc(nil).init_str("").autorelease(); let menu = NSMenu::alloc(nil).initWithTitle_(title).autorelease(); let () = msg_send![menu, setAutoenablesItems: NO]; Menu { menu } } } pub fn new_for_popup() -> Menu { // mac doesn't distinguish between application and context menu types. Menu::new() } pub fn add_dropdown(&mut self, menu: Menu, text: &str, enabled: bool) { unsafe { let menu_item = NSMenuItem::alloc(nil).autorelease(); let title = make_nsstring(&strip_access_key(text)); let () = msg_send![menu.menu, setTitle: title]; let () = msg_send![menu_item, setTitle: title]; if !enabled { let () = msg_send![menu_item, setEnabled: NO]; } menu_item.setSubmenu_(menu.menu); self.menu.addItem_(menu_item); } } pub fn add_item( &mut self, id: u32, text: &str, key: Option<&HotKey>, selected: Option<bool>, enabled: bool, ) { let menu_item = make_menu_item(id, text, key, selected, enabled); unsafe { self.menu.addItem_(menu_item); } } pub fn add_separator(&mut self) { unsafe { let sep = id::separatorItem(self.menu); self.menu.addItem_(sep); } } } impl HotKey { /// Return the string value of this hotkey, for use with Cocoa `NSResponder` /// objects. /// /// Returns the empty string if no key equivalent is known. fn key_equivalent(&self) -> &str { match &self.key { KbKey::Character(t) => t, // from NSText.h KbKey::Enter => "\u{0003}", KbKey::Backspace => "\u{0008}", KbKey::Delete => "\u{007f}", // from NSEvent.h KbKey::Insert => "\u{F727}", KbKey::Home => "\u{F729}", KbKey::End => "\u{F72B}", KbKey::PageUp => "\u{F72C}", KbKey::PageDown => "\u{F72D}", KbKey::PrintScreen => "\u{F72E}", KbKey::ScrollLock => "\u{F72F}", KbKey::ArrowUp => "\u{F700}", KbKey::ArrowDown => "\u{F701}", KbKey::ArrowLeft => "\u{F702}", KbKey::ArrowRight => "\u{F703}", KbKey::F1 => "\u{F704}", KbKey::F2 => "\u{F705}", KbKey::F3 => "\u{F706}", KbKey::F4 => "\u{F707}", KbKey::F5 => "\u{F708}", KbKey::F6 => "\u{F709}", KbKey::F7 => "\u{F70A}", KbKey::F8 => "\u{F70B}", KbKey::F9 => "\u{F70C}", KbKey::F10 => "\u{F70D}", KbKey::F11 => "\u{F70E}", KbKey::F12 => "\u{F70F}", KbKey::F13 => "\u{F710}", KbKey::F14 => "\u{F711}", KbKey::F15 => "\u{F712}", KbKey::F16 => "\u{F713}", KbKey::F17 => "\u{F714}", KbKey::F18 => "\u{F715}", KbKey::F19 => "\u{F716}", KbKey::F20 => "\u{F717}", _ => { eprintln!("no key equivalent for {self:?}"); "" } } } fn key_modifier_mask(&self) -> NSEventModifierFlags { let mods: Modifiers = self.mods.into(); let mut flags = NSEventModifierFlags::empty(); if mods.shift() { flags.insert(NSEventModifierFlags::NSShiftKeyMask); } if mods.meta() { flags.insert(NSEventModifierFlags::NSCommandKeyMask); } if mods.alt() { flags.insert(NSEventModifierFlags::NSAlternateKeyMask); } if mods.ctrl() { flags.insert(NSEventModifierFlags::NSControlKeyMask); } flags } } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn strip_access() { assert_eq!(strip_access_key("&Exit").as_str(), "Exit"); assert_eq!(strip_access_key("&&Exit").as_str(), "&Exit"); assert_eq!(strip_access_key("E&&xit").as_str(), "E&xit"); assert_eq!(strip_access_key("E&xit").as_str(), "Exit"); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/error.rs
druid-shell/src/backend/mac/error.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS backend errors. //TODO: add a backend error for macOS, based on NSError #[derive(Debug, Clone)] pub struct Error; impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "NSError") } } impl std::error::Error for Error {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/application.rs
druid-shell/src/backend/mac/application.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS implementation of features at the application scope. #![allow(non_upper_case_globals)] use std::cell::RefCell; use std::ffi::c_void; use std::rc::Rc; use std::sync::Once; use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular}; use cocoa::base::{id, nil, NO, YES}; use cocoa::foundation::{NSArray, NSAutoreleasePool}; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel}; use objc::{class, msg_send, sel, sel_impl}; use once_cell::sync::Lazy; use crate::application::AppHandler; use super::clipboard::Clipboard; use super::error::Error; use super::util; static APP_HANDLER_IVAR: &str = "druidAppHandler"; #[derive(Clone)] pub(crate) struct Application { ns_app: id, state: Rc<RefCell<State>>, } struct State { quitting: bool, } impl Application { pub fn new() -> Result<Application, Error> { // macOS demands that we run not just on one thread, // but specifically the first thread of the app. util::assert_main_thread(); unsafe { let _pool = NSAutoreleasePool::new(nil); let ns_app = NSApp(); let state = Rc::new(RefCell::new(State { quitting: false })); Ok(Application { ns_app, state }) } } pub fn run(self, handler: Option<Box<dyn AppHandler>>) { unsafe { // Initialize the application delegate let delegate: id = msg_send![APP_DELEGATE.0, alloc]; let () = msg_send![delegate, init]; let state = DelegateState { handler }; let state_ptr = Box::into_raw(Box::new(state)); (*delegate).set_ivar(APP_HANDLER_IVAR, state_ptr as *mut c_void); let () = msg_send![self.ns_app, setDelegate: delegate]; // Run the main app loop self.ns_app.run(); // Clean up the delegate let () = msg_send![self.ns_app, setDelegate: nil]; drop(Box::from_raw(state_ptr)); } } pub fn quit(&self) { if let Ok(mut state) = self.state.try_borrow_mut() { if !state.quitting { state.quitting = true; unsafe { // We want to queue up the destruction of all our windows. // Failure to do so will lead to resource leaks. let windows: id = msg_send![self.ns_app, windows]; for i in 0..windows.count() { let window: id = windows.objectAtIndex(i); let () = msg_send![window, performSelectorOnMainThread: sel!(close) withObject: nil waitUntilDone: NO]; } // Stop sets a stop request flag in the OS. // The run loop is stopped after dealing with events. let () = msg_send![self.ns_app, stop: nil]; } } } else { tracing::warn!("Application state already borrowed"); } } pub fn clipboard(&self) -> Clipboard { Clipboard } pub fn get_locale() -> String { unsafe { let nslocale_class = class!(NSLocale); let locale: id = msg_send![nslocale_class, currentLocale]; let ident: id = msg_send![locale, localeIdentifier]; let mut locale = util::from_nsstring(ident); // This is done because the locale parsing library we use expects an unicode locale, but these vars have an ISO locale if let Some(idx) = locale.chars().position(|c| c == '@') { locale.truncate(idx); } locale } } } impl crate::platform::mac::ApplicationExt for crate::Application { fn hide(&self) { unsafe { let () = msg_send![self.backend_app.ns_app, hide: nil]; } } fn hide_others(&self) { unsafe { let workspace = class!(NSWorkspace); let shared: id = msg_send![workspace, sharedWorkspace]; let () = msg_send![shared, hideOtherApplications]; } } fn set_menu(&self, menu: crate::Menu) { unsafe { NSApp().setMainMenu_(menu.0.menu); } } } struct DelegateState { handler: Option<Box<dyn AppHandler>>, } impl DelegateState { fn command(&mut self, command: u32) { if let Some(inner) = self.handler.as_mut() { inner.command(command) } } } struct AppDelegate(*const Class); unsafe impl Sync for AppDelegate {} unsafe impl Send for AppDelegate {} static APP_DELEGATE: Lazy<AppDelegate> = Lazy::new(|| unsafe { let mut decl = ClassDecl::new("DruidAppDelegate", class!(NSObject)) .expect("App Delegate definition failed"); decl.add_ivar::<*mut c_void>(APP_HANDLER_IVAR); decl.add_method( sel!(applicationDidFinishLaunching:), application_did_finish_launching as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(handleMenuItem:), handle_menu_item as extern "C" fn(&mut Object, Sel, id), ); AppDelegate(decl.register()) }); extern "C" fn application_did_finish_launching(_this: &mut Object, _: Sel, _notification: id) { unsafe { let ns_app = NSApp(); // We need to delay setting the activation policy and activating the app // until we have the main menu all set up. Otherwise the menu won't be interactable. ns_app.setActivationPolicy_(NSApplicationActivationPolicyRegular); let () = msg_send![ns_app, activateIgnoringOtherApps: YES]; } } /// This handles menu items in the case that all windows are closed. extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) { unsafe { let tag: isize = msg_send![item, tag]; let inner: *mut c_void = *this.get_ivar(APP_HANDLER_IVAR); let inner = &mut *(inner as *mut DelegateState); (*inner).command(tag as u32); } } pub fn init_harness() { static INIT: Once = Once::new(); INIT.call_once(|| unsafe { let _app: id = msg_send![class!(NSApplication), sharedApplication]; }); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/util.rs
druid-shell/src/backend/mac/util.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Utilities, macOS specific. use std::ffi::c_void; use cocoa::base::{id, nil, BOOL, YES}; use cocoa::foundation::{NSAutoreleasePool, NSString, NSUInteger}; use objc::{class, msg_send, sel, sel_impl}; /// Panic if not on the main thread. /// /// Many Cocoa operations are only valid on the main thread, and (I think) /// undefined behavior is possible if invoked from other threads. If so, /// failing on non main thread is necessary for safety. pub(crate) fn assert_main_thread() { unsafe { let is_main_thread: BOOL = msg_send!(class!(NSThread), isMainThread); assert_eq!(is_main_thread, YES); } } /// Create a new NSString from a &str. pub(crate) fn make_nsstring(s: &str) -> id { unsafe { NSString::alloc(nil).init_str(s).autorelease() } } pub(crate) fn from_nsstring(s: id) -> String { unsafe { let slice = std::slice::from_raw_parts(s.UTF8String() as *const _, s.len()); let result = std::str::from_utf8_unchecked(slice); result.into() } } pub(crate) fn make_nsdata(bytes: &[u8]) -> id { let dlen = bytes.len() as NSUInteger; unsafe { msg_send![class!(NSData), dataWithBytes: bytes.as_ptr() as *const c_void length: dlen] } } pub(crate) fn from_nsdata(data: id) -> Vec<u8> { unsafe { let len: NSUInteger = msg_send![data, length]; let bytes: *const c_void = msg_send![data, bytes]; let mut out: Vec<u8> = Vec::with_capacity(len as usize); std::ptr::copy_nonoverlapping(bytes as *const u8, out.as_mut_ptr(), len as usize); out.set_len(len as usize); out } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/mod.rs
druid-shell/src/backend/mac/mod.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS `druid-shell` backend. #![allow(clippy::let_unit_value)] pub mod appkit; pub mod application; pub mod clipboard; pub mod dialog; pub mod error; mod keyboard; pub mod menu; pub mod screen; pub mod text_input; pub mod util; pub mod window;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/window.rs
druid-shell/src/backend/mac/window.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS implementation of window creation. #![allow(non_snake_case)] use std::ffi::c_void; use std::mem; use std::sync::{Arc, Mutex, Weak}; use std::time::Instant; use block::ConcreteBlock; use cocoa::appkit::{ CGFloat, NSApp, NSApplication, NSAutoresizingMaskOptions, NSBackingStoreBuffered, NSColor, NSEvent, NSView, NSViewHeightSizable, NSViewWidthSizable, NSWindow, NSWindowStyleMask, }; use cocoa::base::{id, nil, BOOL, NO, YES}; use cocoa::foundation::{ NSArray, NSAutoreleasePool, NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger, }; use core_graphics::context::CGContextRef; use foreign_types::ForeignTypeRef; use objc::declare::ClassDecl; use objc::rc::WeakPtr; use objc::runtime::{Class, Object, Protocol, Sel}; use objc::{class, msg_send, sel, sel_impl}; use once_cell::sync::Lazy; use tracing::{debug, error, info}; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{AppKitWindowHandle, HasRawWindowHandle, RawWindowHandle}; use crate::kurbo::{Insets, Point, Rect, Size, Vec2}; use crate::piet::{Piet, PietText, RenderContext}; use self::levels::{NSFloatingWindowLevel, NSNormalWindowLevel}; use super::appkit::{ NSRunLoopCommonModes, NSTrackingArea, NSTrackingAreaOptions, NSView as NSViewExt, }; use super::application::Application; use super::dialog; use super::keyboard::{make_modifiers, KeyboardState}; use super::menu::Menu; use super::text_input::NSRange; use super::util::{assert_main_thread, make_nsstring}; use crate::common_util::IdleCallback; use crate::dialog::{FileDialogOptions, FileDialogType}; use crate::keyboard_types::KeyState; use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent}; use crate::region::Region; use crate::scale::Scale; use crate::text::{Event, InputHandler}; use crate::window::{ FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel, WindowState, }; use crate::Error; #[allow(non_upper_case_globals)] const NSWindowDidBecomeKeyNotification: &str = "NSWindowDidBecomeKeyNotification"; #[allow(dead_code)] #[allow(non_upper_case_globals)] mod levels { use crate::window::WindowLevel; // These are the levels that AppKit seems to have. pub const NSModalPanelLevel: i32 = 24; pub const NSNormalWindowLevel: i32 = 0; pub const NSFloatingWindowLevel: i32 = 3; pub const NSTornOffMenuWindowLevel: i32 = NSFloatingWindowLevel; pub const NSSubmenuWindowLevel: i32 = NSFloatingWindowLevel; pub const NSModalPanelWindowLevel: i32 = 8; pub const NSStatusWindowLevel: i32 = 25; pub const NSPopUpMenuWindowLevel: i32 = 101; pub const NSScreenSaverWindowLevel: i32 = 1000; pub fn as_raw_window_level(window_level: WindowLevel) -> i32 { use WindowLevel::*; match window_level { AppWindow => NSNormalWindowLevel, Tooltip(_) => NSFloatingWindowLevel, DropDown(_) => NSFloatingWindowLevel, Modal(_) => NSModalPanelWindowLevel, } } } #[derive(Clone)] pub(crate) struct WindowHandle { /// This is an NSView, as our concept of "window" is more the top-level container holding /// a view. Also, this is better for hosted applications such as VST. nsview: WeakPtr, idle_queue: Weak<Mutex<Vec<IdleKind>>>, } impl PartialEq for WindowHandle { fn eq(&self, other: &Self) -> bool { match (self.idle_queue.upgrade(), other.idle_queue.upgrade()) { (None, None) => true, (Some(s), Some(o)) => std::sync::Arc::ptr_eq(&s, &o), (_, _) => false, } } } impl Eq for WindowHandle {} impl std::fmt::Debug for WindowHandle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { f.write_str("WindowHandle{\n")?; f.write_str("}")?; Ok(()) } } impl Default for WindowHandle { fn default() -> Self { WindowHandle { nsview: unsafe { WeakPtr::new(nil) }, idle_queue: Default::default(), } } } /// Builder abstraction for creating new windows. pub(crate) struct WindowBuilder { handler: Option<Box<dyn WinHandler>>, title: String, menu: Option<Menu>, size: Size, min_size: Option<Size>, position: Option<Point>, level: Option<WindowLevel>, window_state: Option<WindowState>, resizable: bool, show_titlebar: bool, transparent: bool, always_on_top: bool, } #[derive(Clone)] pub(crate) struct IdleHandle { nsview: WeakPtr, idle_queue: Weak<Mutex<Vec<IdleKind>>>, } #[derive(Debug)] enum DeferredOp { SetSize(Size), SetPosition(Point), } /// This represents different Idle Callback Mechanism enum IdleKind { Callback(Box<dyn IdleCallback>), Token(IdleToken), DeferredOp(DeferredOp), } /// This is the state associated with our custom NSView. struct ViewState { nsview: WeakPtr, handler: Box<dyn WinHandler>, idle_queue: Arc<Mutex<Vec<IdleKind>>>, /// Tracks window focusing left clicks focus_click: bool, // Tracks whether we have already received the mouseExited event mouse_left: bool, keyboard_state: KeyboardState, text: PietText, active_text_input: Option<TextFieldToken>, parent: Option<crate::WindowHandle>, } #[derive(Clone, PartialEq, Eq)] // TODO: support custom cursors pub struct CustomCursor; impl WindowBuilder { pub fn new(_app: Application) -> WindowBuilder { WindowBuilder { handler: None, title: String::new(), menu: None, size: Size::new(500., 400.), min_size: None, position: None, level: None, window_state: None, resizable: true, show_titlebar: true, transparent: false, always_on_top: false, } } pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.handler = Some(handler); } pub fn set_size(&mut self, size: Size) { self.size = size; } pub fn set_min_size(&mut self, size: Size) { self.min_size = Some(size); } pub fn resizable(&mut self, resizable: bool) { self.resizable = resizable; } pub fn show_titlebar(&mut self, show_titlebar: bool) { self.show_titlebar = show_titlebar; } pub fn set_transparent(&mut self, transparent: bool) { self.transparent = transparent; } pub fn set_level(&mut self, level: WindowLevel) { self.level = Some(level); } pub fn set_always_on_top(&mut self, always_on_top: bool) { self.always_on_top = always_on_top; } pub fn set_position(&mut self, position: Point) { self.position = Some(position) } pub fn set_window_state(&mut self, state: WindowState) { self.window_state = Some(state); } pub fn set_title(&mut self, title: impl Into<String>) { self.title = title.into(); } pub fn set_menu(&mut self, menu: Menu) { self.menu = Some(menu); } pub fn build(self) -> Result<WindowHandle, Error> { assert_main_thread(); unsafe { let mut style_mask = NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSMiniaturizableWindowMask; if self.show_titlebar { style_mask |= NSWindowStyleMask::NSTitledWindowMask; } if self.resizable { style_mask |= NSWindowStyleMask::NSResizableWindowMask; } let screen_height = crate::Screen::get_display_rect().height(); let position = self.position.unwrap_or_else(|| Point::new(20., 20.)); let origin = NSPoint::new(position.x, screen_height - position.y - self.size.height); // Flip back let rect = NSRect::new(origin, NSSize::new(self.size.width, self.size.height)); let window: id = msg_send![WINDOW_CLASS.0, alloc]; let window = window.initWithContentRect_styleMask_backing_defer_( rect, style_mask, NSBackingStoreBuffered, NO, ); if let Some(min_size) = self.min_size { let size = NSSize::new(min_size.width, min_size.height); window.setContentMinSize_(size); } if self.transparent { window.setOpaque_(NO); window.setBackgroundColor_(NSColor::clearColor(nil)); } window.setTitle_(make_nsstring(&self.title)); let (view, idle_queue) = make_view(self.handler.expect("view")); let content_view = window.contentView(); let frame = NSView::frame(content_view); view.initWithFrame_(frame); // The rect of the tracking area doesn't matter, because // we use the InVisibleRect option where the OS syncs the size automatically. let rect = NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)); let opts = NSTrackingAreaOptions::MouseEnteredAndExited | NSTrackingAreaOptions::MouseMoved | NSTrackingAreaOptions::ActiveAlways | NSTrackingAreaOptions::InVisibleRect; let tracking_area = NSTrackingArea::alloc(nil) .initWithRect_options_owner_userInfo(rect, opts, view, nil) .autorelease(); view.addTrackingArea(tracking_area); let () = msg_send![window, setDelegate: view]; if let Some(menu) = self.menu { NSApp().setMainMenu_(menu.menu); } content_view.addSubview_(view); let view_state: *mut c_void = *(*view).get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let mut handle = WindowHandle { nsview: view_state.nsview.clone(), idle_queue, }; if let Some(window_state) = self.window_state { handle.set_window_state(window_state); } if let Some(level) = self.level { match &level { WindowLevel::Tooltip(parent) => view_state.parent = Some(parent.clone()), WindowLevel::DropDown(parent) => view_state.parent = Some(parent.clone()), WindowLevel::Modal(parent) => view_state.parent = Some(parent.clone()), _ => {} } handle.set_level(level); } if self.always_on_top { handle.set_always_on_top(self.always_on_top); } // set_window_state above could have invalidated the frame size let frame = NSView::frame(content_view); view_state.handler.connect(&handle.clone().into()); view_state.handler.scale(Scale::default()); view_state .handler .size(Size::new(frame.size.width, frame.size.height)); Ok(handle) } } } // Wrap pointer because statics requires Sync. struct ViewClass(*const Class); unsafe impl Sync for ViewClass {} unsafe impl Send for ViewClass {} static VIEW_CLASS: Lazy<ViewClass> = Lazy::new(|| unsafe { let mut decl = ClassDecl::new("DruidView", class!(NSView)).expect("View class defined"); decl.add_ivar::<*mut c_void>("viewState"); decl.add_method( sel!(isFlipped), isFlipped as extern "C" fn(&Object, Sel) -> BOOL, ); extern "C" fn isFlipped(_this: &Object, _sel: Sel) -> BOOL { YES } decl.add_method( sel!(acceptsFirstResponder), acceptsFirstResponder as extern "C" fn(&Object, Sel) -> BOOL, ); extern "C" fn acceptsFirstResponder(_this: &Object, _sel: Sel) -> BOOL { YES } // acceptsFirstMouse is called when a left mouse click would focus the window decl.add_method( sel!(acceptsFirstMouse:), acceptsFirstMouse as extern "C" fn(&Object, Sel, id) -> BOOL, ); extern "C" fn acceptsFirstMouse(this: &Object, _sel: Sel, _nsevent: id) -> BOOL { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); view_state.focus_click = true; } YES } decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); extern "C" fn dealloc(this: &Object, _sel: Sel) { info!("view is dealloc'ed"); unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); drop(Box::from_raw(view_state as *mut ViewState)); } } decl.add_method( sel!(windowDidBecomeKey:), window_did_become_key as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(windowDidResignKey:), window_did_resign_key as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(setFrameSize:), set_frame_size as extern "C" fn(&mut Object, Sel, NSSize), ); decl.add_method( sel!(mouseDown:), mouse_down_left as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(rightMouseDown:), mouse_down_right as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(otherMouseDown:), mouse_down_other as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(mouseUp:), mouse_up_left as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(rightMouseUp:), mouse_up_right as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(otherMouseUp:), mouse_up_other as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(mouseMoved:), mouse_move as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(mouseDragged:), mouse_move as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(otherMouseDragged:), mouse_move as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(mouseEntered:), mouse_enter as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(mouseExited:), mouse_leave as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(scrollWheel:), scroll_wheel as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(magnifyWithEvent:), pinch_event as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(keyDown:), key_down as extern "C" fn(&mut Object, Sel, id), ); decl.add_method(sel!(keyUp:), key_up as extern "C" fn(&mut Object, Sel, id)); decl.add_method( sel!(flagsChanged:), mods_changed as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(drawRect:), draw_rect as extern "C" fn(&mut Object, Sel, NSRect), ); decl.add_method(sel!(runIdle), run_idle as extern "C" fn(&mut Object, Sel)); decl.add_method( sel!(viewWillDraw), view_will_draw as extern "C" fn(&mut Object, Sel), ); decl.add_method(sel!(redraw), redraw as extern "C" fn(&mut Object, Sel)); decl.add_method( sel!(handleTimer:), handle_timer as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(handleMenuItem:), handle_menu_item as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(showContextMenu:), show_context_menu as extern "C" fn(&mut Object, Sel, id), ); decl.add_method( sel!(windowShouldClose:), window_should_close as extern "C" fn(&mut Object, Sel, id) -> BOOL, ); decl.add_method( sel!(windowWillClose:), window_will_close as extern "C" fn(&mut Object, Sel, id), ); // methods for NSTextInputClient decl.add_method( sel!(hasMarkedText), super::text_input::has_marked_text as extern "C" fn(&mut Object, Sel) -> BOOL, ); decl.add_method( sel!(markedRange), super::text_input::marked_range as extern "C" fn(&mut Object, Sel) -> NSRange, ); decl.add_method( sel!(selectedRange), super::text_input::selected_range as extern "C" fn(&mut Object, Sel) -> NSRange, ); decl.add_method( sel!(setMarkedText:selectedRange:replacementRange:), super::text_input::set_marked_text as extern "C" fn(&mut Object, Sel, id, NSRange, NSRange), ); decl.add_method( sel!(unmarkText), super::text_input::unmark_text as extern "C" fn(&mut Object, Sel), ); decl.add_method( sel!(validAttributesForMarkedText), super::text_input::valid_attributes_for_marked_text as extern "C" fn(&mut Object, Sel) -> id, ); decl.add_method( sel!(attributedSubstringForProposedRange:actualRange:), super::text_input::attributed_substring_for_proposed_range as extern "C" fn(&mut Object, Sel, NSRange, *mut c_void) -> id, ); decl.add_method( sel!(insertText:replacementRange:), super::text_input::insert_text as extern "C" fn(&mut Object, Sel, id, NSRange), ); decl.add_method( sel!(characterIndexForPoint:), super::text_input::character_index_for_point as extern "C" fn(&mut Object, Sel, NSPoint) -> NSUInteger, ); decl.add_method( sel!(firstRectForCharacterRange:actualRange:), super::text_input::first_rect_for_character_range as extern "C" fn(&mut Object, Sel, NSRange, *mut c_void) -> NSRect, ); decl.add_method( sel!(doCommandBySelector:), super::text_input::do_command_by_selector as extern "C" fn(&mut Object, Sel, Sel), ); let protocol = Protocol::get("NSTextInputClient").unwrap(); decl.add_protocol(protocol); ViewClass(decl.register()) }); /// Acquires a lock to an `InputHandler`, passes it to a closure, and releases the lock. pub(super) fn with_edit_lock_from_window<R>( this: &mut Object, mutable: bool, f: impl FnOnce(Box<dyn InputHandler>) -> R, ) -> Option<R> { let view_state = unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); &mut (*view_state) }; let input_token = view_state.active_text_input?; let handler = view_state.handler.acquire_input_lock(input_token, mutable); let r = f(handler); view_state.handler.release_input_lock(input_token); Some(r) } fn make_view(handler: Box<dyn WinHandler>) -> (id, Weak<Mutex<Vec<IdleKind>>>) { let idle_queue = Arc::new(Mutex::new(Vec::new())); let queue_handle = Arc::downgrade(&idle_queue); unsafe { let view: id = msg_send![VIEW_CLASS.0, new]; let nsview = WeakPtr::new(view); let keyboard_state = KeyboardState::new(); let state = ViewState { nsview, handler, idle_queue, focus_click: false, mouse_left: true, keyboard_state, text: PietText::new_with_unique_state(), active_text_input: None, parent: None, }; let state_ptr = Box::into_raw(Box::new(state)); (*view).set_ivar("viewState", state_ptr as *mut c_void); let options: NSAutoresizingMaskOptions = NSViewWidthSizable | NSViewHeightSizable; view.setAutoresizingMask_(options); (view.autorelease(), queue_handle) } } struct WindowClass(*const Class); unsafe impl Sync for WindowClass {} unsafe impl Send for WindowClass {} static WINDOW_CLASS: Lazy<WindowClass> = Lazy::new(|| unsafe { let mut decl = ClassDecl::new("DruidWindow", class!(NSWindow)).expect("Window class defined"); decl.add_method( sel!(canBecomeKeyWindow), canBecomeKeyWindow as extern "C" fn(&Object, Sel) -> BOOL, ); extern "C" fn canBecomeKeyWindow(_this: &Object, _sel: Sel) -> BOOL { YES } WindowClass(decl.register()) }); extern "C" fn set_frame_size(this: &mut Object, _: Sel, size: NSSize) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); view_state.handler.size(Size::new(size.width, size.height)); let superclass = msg_send![this, superclass]; let () = msg_send![super(this, superclass), setFrameSize: size]; } } fn mouse_event( nsevent: id, view: id, count: u8, focus: bool, button: MouseButton, wheel_delta: Vec2, ) -> MouseEvent { unsafe { let point = nsevent.locationInWindow(); let view_point = view.convertPoint_fromView_(point, nil); let pos = Point::new(view_point.x, view_point.y); let buttons = get_mouse_buttons(NSEvent::pressedMouseButtons(nsevent)); let modifiers = make_modifiers(nsevent.modifierFlags()); MouseEvent { pos, buttons, mods: modifiers, count, focus, button, wheel_delta, } } } fn get_mouse_button(button: NSInteger) -> Option<MouseButton> { match button { 0 => Some(MouseButton::Left), 1 => Some(MouseButton::Right), 2 => Some(MouseButton::Middle), 3 => Some(MouseButton::X1), 4 => Some(MouseButton::X2), _ => None, } } fn get_mouse_buttons(mask: NSUInteger) -> MouseButtons { let mut buttons = MouseButtons::new(); if mask & 1 != 0 { buttons.insert(MouseButton::Left); } if mask & 1 << 1 != 0 { buttons.insert(MouseButton::Right); } if mask & 1 << 2 != 0 { buttons.insert(MouseButton::Middle); } if mask & 1 << 3 != 0 { buttons.insert(MouseButton::X1); } if mask & 1 << 4 != 0 { buttons.insert(MouseButton::X2); } buttons } extern "C" fn mouse_down_left(this: &mut Object, _: Sel, nsevent: id) { mouse_down(this, nsevent, MouseButton::Left); } extern "C" fn mouse_down_right(this: &mut Object, _: Sel, nsevent: id) { mouse_down(this, nsevent, MouseButton::Right); } extern "C" fn mouse_down_other(this: &mut Object, _: Sel, nsevent: id) { unsafe { if let Some(button) = get_mouse_button(nsevent.buttonNumber()) { mouse_down(this, nsevent, button); } } } fn mouse_down(this: &mut Object, nsevent: id, button: MouseButton) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let count = nsevent.clickCount() as u8; let focus = view_state.focus_click && button == MouseButton::Left; let event = mouse_event(nsevent, this as id, count, focus, button, Vec2::ZERO); view_state.handler.mouse_down(&event); } } extern "C" fn mouse_up_left(this: &mut Object, _: Sel, nsevent: id) { mouse_up(this, nsevent, MouseButton::Left); } extern "C" fn mouse_up_right(this: &mut Object, _: Sel, nsevent: id) { mouse_up(this, nsevent, MouseButton::Right); } extern "C" fn mouse_up_other(this: &mut Object, _: Sel, nsevent: id) { unsafe { if let Some(button) = get_mouse_button(nsevent.buttonNumber()) { mouse_up(this, nsevent, button); } } } fn mouse_up(this: &mut Object, nsevent: id, button: MouseButton) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let focus = if view_state.focus_click && button == MouseButton::Left { view_state.focus_click = false; true } else { false }; let event = mouse_event(nsevent, this as id, 0, focus, button, Vec2::ZERO); view_state.handler.mouse_up(&event); // If we have already received a mouseExited event then that means // we're still receiving mouse events because some buttons are being held down. // When the last held button is released and we haven't received a mouseEntered event, // then we will no longer receive mouse events until the next mouseEntered event // and need to inform the handler of the mouse leaving. if view_state.mouse_left && event.buttons.is_empty() { view_state.handler.mouse_leave(); } } } extern "C" fn mouse_move(this: &mut Object, _: Sel, nsevent: id) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let event = mouse_event(nsevent, this as id, 0, false, MouseButton::None, Vec2::ZERO); view_state.handler.mouse_move(&event); } } extern "C" fn mouse_enter(this: &mut Object, _sel: Sel, nsevent: id) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); view_state.mouse_left = false; let event = mouse_event(nsevent, this, 0, false, MouseButton::None, Vec2::ZERO); view_state.handler.mouse_move(&event); } } extern "C" fn mouse_leave(this: &mut Object, _: Sel, _nsevent: id) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); view_state.mouse_left = true; view_state.handler.mouse_leave(); } } extern "C" fn scroll_wheel(this: &mut Object, _: Sel, nsevent: id) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let (dx, dy) = { let dx = -nsevent.scrollingDeltaX(); let dy = -nsevent.scrollingDeltaY(); if nsevent.hasPreciseScrollingDeltas() == cocoa::base::YES { (dx, dy) } else { (dx * 32.0, dy * 32.0) } }; let event = mouse_event( nsevent, this as id, 0, false, MouseButton::None, Vec2::new(dx, dy), ); view_state.handler.wheel(&event); } } extern "C" fn pinch_event(this: &mut Object, _: Sel, nsevent: id) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let delta: CGFloat = msg_send![nsevent, magnification]; view_state.handler.zoom(delta); } } extern "C" fn key_down(this: &mut Object, _: Sel, nsevent: id) { let view_state = unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); &mut *(view_state as *mut ViewState) }; if let Some(event) = view_state.keyboard_state.process_native_event(nsevent) { if !view_state.handler.key_down(event) { // key down not handled; forward to text input system unsafe { let events = NSArray::arrayWithObjects(nil, &[nsevent]); let _: () = msg_send![*view_state.nsview.load(), interpretKeyEvents: events]; } } } } extern "C" fn key_up(this: &mut Object, _: Sel, nsevent: id) { let view_state = unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); &mut *(view_state as *mut ViewState) }; if let Some(event) = view_state.keyboard_state.process_native_event(nsevent) { view_state.handler.key_up(event); } } extern "C" fn mods_changed(this: &mut Object, _: Sel, nsevent: id) { let view_state = unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); &mut *(view_state as *mut ViewState) }; if let Some(event) = view_state.keyboard_state.process_native_event(nsevent) { if event.state == KeyState::Down { view_state.handler.key_down(event); } else { view_state.handler.key_up(event); } } } extern "C" fn view_will_draw(this: &mut Object, _: Sel) { unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); view_state.handler.prepare_paint(); } } extern "C" fn draw_rect(this: &mut Object, _: Sel, dirtyRect: NSRect) { unsafe { let context: id = msg_send![class![NSGraphicsContext], currentContext]; //FIXME: when core_graphics is at 0.20, we should be able to use //core_graphics::sys::CGContextRef as our pointer type. let cgcontext_ptr: *mut <CGContextRef as ForeignTypeRef>::CType = msg_send![context, CGContext]; let cgcontext_ref = CGContextRef::from_ptr_mut(cgcontext_ptr); // FIXME: use the actual invalid region instead of just this bounding box. // https://developer.apple.com/documentation/appkit/nsview/1483772-getrectsbeingdrawn?language=objc let rect = Rect::from_origin_size( (dirtyRect.origin.x, dirtyRect.origin.y), (dirtyRect.size.width, dirtyRect.size.height), ); let invalid = Region::from(rect); let view_state: *mut c_void = *this.get_ivar("viewState"); let view_state = &mut *(view_state as *mut ViewState); let mut piet_ctx = Piet::new_y_down(cgcontext_ref, Some(view_state.text.clone())); view_state.handler.paint(&mut piet_ctx, &invalid); if let Err(e) = piet_ctx.finish() { error!("{}", e) } let superclass = msg_send![this, superclass]; let () = msg_send![super(this, superclass), drawRect: dirtyRect]; } } fn run_deferred(this: &mut Object, view_state: &mut ViewState, op: DeferredOp) { match op { DeferredOp::SetSize(size) => set_size_deferred(this, view_state, size), DeferredOp::SetPosition(pos) => set_position_deferred(this, view_state, pos), } } fn set_size_deferred(this: &mut Object, _view_state: &mut ViewState, size: Size) { unsafe { let window: id = msg_send![this, window]; let current_frame: NSRect = msg_send![window, frame]; let mut new_frame = current_frame; // maintain Druid origin (as mac origin is bottom left) new_frame.origin.y -= size.height - current_frame.size.height; new_frame.size.width = size.width; new_frame.size.height = size.height; let () = msg_send![window, setFrame: new_frame display: YES]; } } fn set_position_deferred(this: &mut Object, _view_state: &mut ViewState, position: Point) { unsafe { let window: id = msg_send![this, window]; let frame: NSRect = msg_send![window, frame]; let mut new_frame = frame; new_frame.origin.x = position.x; // TODO Everywhere we use the height for flipping around y it should be the max y in orig mac coords. // Need to set up a 3 screen config to test in this arrangement. // 3 // 1 // 2 let screen_height = crate::Screen::get_display_rect().height(); new_frame.origin.y = screen_height - position.y - frame.size.height; // Flip back let () = msg_send![window, setFrame: new_frame display: YES]; debug!("set_position_deferred {:?}", position); } } extern "C" fn run_idle(this: &mut Object, _: Sel) { let view_state = unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); &mut *(view_state as *mut ViewState) }; let queue: Vec<_> = mem::take(&mut view_state.idle_queue.lock().expect("queue")); for item in queue { match item { IdleKind::Callback(it) => it.call(&mut *view_state.handler), IdleKind::Token(it) => { view_state.handler.as_mut().idle(it); } IdleKind::DeferredOp(op) => run_deferred(this, view_state, op), } } } extern "C" fn redraw(this: &mut Object, _: Sel) { unsafe { let () = msg_send![this as *const _, setNeedsDisplay: YES]; } } extern "C" fn handle_timer(this: &mut Object, _: Sel, timer: id) { let view_state = unsafe { let view_state: *mut c_void = *this.get_ivar("viewState"); &mut *(view_state as *mut ViewState) }; let token = unsafe { let user_info: id = msg_send![timer, userInfo]; msg_send![user_info, unsignedIntValue] }; view_state.handler.timer(TimerToken::from_raw(token)); } extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) { unsafe {
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/keyboard.rs
druid-shell/src/backend/mac/keyboard.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Conversion of backend keyboard event into cross-platform event. use cocoa::appkit::{NSEvent, NSEventModifierFlags, NSEventType}; use cocoa::base::id; use objc::{msg_send, sel, sel_impl}; use crate::keyboard::{Code, KbKey, KeyEvent, KeyState, Modifiers}; use super::super::shared; use super::util::from_nsstring; /// State for processing of keyboard events. /// /// This needs to be stateful for proper processing of dead keys. The current /// implementation is somewhat primitive and is not based on IME; in the future /// when IME is implemented, it will need to be redone somewhat, letting the IME /// be the authoritative source of truth for Unicode string values of keys. /// /// Most of the logic in this module is adapted from Mozilla, and in particular /// InputHandler.mm. pub(crate) struct KeyboardState { last_mods: NSEventModifierFlags, } /// Convert a macOS platform key code (keyCode field of NSEvent). /// /// The primary source for this mapping is: /// <https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values> /// /// It should also match up with CODE_MAP_MAC bindings in /// NativeKeyToDOMCodeName.h. fn key_code_to_code(key_code: u16) -> Code { match key_code { 0x00 => Code::KeyA, 0x01 => Code::KeyS, 0x02 => Code::KeyD, 0x03 => Code::KeyF, 0x04 => Code::KeyH, 0x05 => Code::KeyG, 0x06 => Code::KeyZ, 0x07 => Code::KeyX, 0x08 => Code::KeyC, 0x09 => Code::KeyV, 0x0a => Code::IntlBackslash, 0x0b => Code::KeyB, 0x0c => Code::KeyQ, 0x0d => Code::KeyW, 0x0e => Code::KeyE, 0x0f => Code::KeyR, 0x10 => Code::KeyY, 0x11 => Code::KeyT, 0x12 => Code::Digit1, 0x13 => Code::Digit2, 0x14 => Code::Digit3, 0x15 => Code::Digit4, 0x16 => Code::Digit6, 0x17 => Code::Digit5, 0x18 => Code::Equal, 0x19 => Code::Digit9, 0x1a => Code::Digit7, 0x1b => Code::Minus, 0x1c => Code::Digit8, 0x1d => Code::Digit0, 0x1e => Code::BracketRight, 0x1f => Code::KeyO, 0x20 => Code::KeyU, 0x21 => Code::BracketLeft, 0x22 => Code::KeyI, 0x23 => Code::KeyP, 0x24 => Code::Enter, 0x25 => Code::KeyL, 0x26 => Code::KeyJ, 0x27 => Code::Quote, 0x28 => Code::KeyK, 0x29 => Code::Semicolon, 0x2a => Code::Backslash, 0x2b => Code::Comma, 0x2c => Code::Slash, 0x2d => Code::KeyN, 0x2e => Code::KeyM, 0x2f => Code::Period, 0x30 => Code::Tab, 0x31 => Code::Space, 0x32 => Code::Backquote, 0x33 => Code::Backspace, 0x34 => Code::NumpadEnter, 0x35 => Code::Escape, 0x36 => Code::MetaRight, 0x37 => Code::MetaLeft, 0x38 => Code::ShiftLeft, 0x39 => Code::CapsLock, 0x3a => Code::AltLeft, 0x3b => Code::ControlLeft, 0x3c => Code::ShiftRight, 0x3d => Code::AltRight, 0x3e => Code::ControlRight, 0x3f => Code::Fn, 0x40 => Code::F17, 0x41 => Code::NumpadDecimal, 0x43 => Code::NumpadMultiply, 0x45 => Code::NumpadAdd, 0x47 => Code::NumLock, 0x48 => Code::AudioVolumeUp, 0x49 => Code::AudioVolumeDown, 0x4a => Code::AudioVolumeMute, 0x4b => Code::NumpadDivide, 0x4c => Code::NumpadEnter, 0x4e => Code::NumpadSubtract, 0x4f => Code::F18, 0x50 => Code::F19, 0x51 => Code::NumpadEqual, 0x52 => Code::Numpad0, 0x53 => Code::Numpad1, 0x54 => Code::Numpad2, 0x55 => Code::Numpad3, 0x56 => Code::Numpad4, 0x57 => Code::Numpad5, 0x58 => Code::Numpad6, 0x59 => Code::Numpad7, 0x5a => Code::F20, 0x5b => Code::Numpad8, 0x5c => Code::Numpad9, 0x5d => Code::IntlYen, 0x5e => Code::IntlRo, 0x5f => Code::NumpadComma, 0x60 => Code::F5, 0x61 => Code::F6, 0x62 => Code::F7, 0x63 => Code::F3, 0x64 => Code::F8, 0x65 => Code::F9, 0x66 => Code::Lang2, 0x67 => Code::F11, 0x68 => Code::Lang1, 0x69 => Code::F13, 0x6a => Code::F16, 0x6b => Code::F14, 0x6d => Code::F10, 0x6e => Code::ContextMenu, 0x6f => Code::F12, 0x71 => Code::F15, // Apple hasn't been producing any keyboards with `Help` anymore since // 2007. So this can be considered Insert instead. 0x72 => Code::Insert, 0x73 => Code::Home, 0x74 => Code::PageUp, 0x75 => Code::Delete, 0x76 => Code::F4, 0x77 => Code::End, 0x78 => Code::F2, 0x79 => Code::PageDown, 0x7a => Code::F1, 0x7b => Code::ArrowLeft, 0x7c => Code::ArrowRight, 0x7d => Code::ArrowDown, 0x7e => Code::ArrowUp, _ => Code::Unidentified, } } /// Convert code to key. /// /// On macOS, for non-printable keys, the keyCode we get from the event serves is /// really more of a key than a physical scan code. /// /// When this function returns None, the code can be considered printable. /// /// The logic for this function is derived from KEY_MAP_COCOA bindings in /// NativeKeyToDOMKeyName.h. fn code_to_key(code: Code) -> Option<KbKey> { Some(match code { Code::Escape => KbKey::Escape, Code::ShiftLeft | Code::ShiftRight => KbKey::Shift, Code::AltLeft | Code::AltRight => KbKey::Alt, Code::MetaLeft | Code::MetaRight => KbKey::Meta, Code::ControlLeft | Code::ControlRight => KbKey::Control, Code::CapsLock => KbKey::CapsLock, // kVK_ANSI_KeypadClear Code::NumLock => KbKey::Clear, Code::Fn => KbKey::Fn, Code::F1 => KbKey::F1, Code::F2 => KbKey::F2, Code::F3 => KbKey::F3, Code::F4 => KbKey::F4, Code::F5 => KbKey::F5, Code::F6 => KbKey::F6, Code::F7 => KbKey::F7, Code::F8 => KbKey::F8, Code::F9 => KbKey::F9, Code::F10 => KbKey::F10, Code::F11 => KbKey::F11, Code::F12 => KbKey::F12, Code::F13 => KbKey::F13, Code::F14 => KbKey::F14, Code::F15 => KbKey::F15, Code::F16 => KbKey::F16, Code::F17 => KbKey::F17, Code::F18 => KbKey::F18, Code::F19 => KbKey::F19, Code::F20 => KbKey::F20, Code::F21 => KbKey::F21, Code::F22 => KbKey::F22, Code::F23 => KbKey::F23, Code::F24 => KbKey::F24, Code::Pause => KbKey::Pause, Code::ScrollLock => KbKey::ScrollLock, Code::PrintScreen => KbKey::PrintScreen, Code::Insert => KbKey::Insert, Code::Delete => KbKey::Delete, Code::Tab => KbKey::Tab, Code::Backspace => KbKey::Backspace, Code::ContextMenu => KbKey::ContextMenu, // kVK_JIS_Kana Code::Lang1 => KbKey::KanjiMode, // kVK_JIS_Eisu Code::Lang2 => KbKey::Eisu, Code::Home => KbKey::Home, Code::End => KbKey::End, Code::PageUp => KbKey::PageUp, Code::PageDown => KbKey::PageDown, Code::ArrowLeft => KbKey::ArrowLeft, Code::ArrowRight => KbKey::ArrowRight, Code::ArrowUp => KbKey::ArrowUp, Code::ArrowDown => KbKey::ArrowDown, Code::Enter => KbKey::Enter, Code::NumpadEnter => KbKey::Enter, Code::Help => KbKey::Help, _ => return None, }) } fn is_valid_key(s: &str) -> bool { match s.chars().next() { None => false, Some(c) => c >= ' ' && c != '\x7f' && !('\u{e000}'..'\u{f900}').contains(&c), } } fn is_modifier_code(code: Code) -> bool { matches!( code, Code::ShiftLeft | Code::ShiftRight | Code::AltLeft | Code::AltRight | Code::ControlLeft | Code::ControlRight | Code::MetaLeft | Code::MetaRight | Code::CapsLock | Code::Help ) } impl KeyboardState { pub(crate) fn new() -> KeyboardState { let last_mods = NSEventModifierFlags::empty(); KeyboardState { last_mods } } pub(crate) fn process_native_event(&mut self, event: id) -> Option<KeyEvent> { unsafe { let event_type = event.eventType(); let key_code = event.keyCode(); let code = key_code_to_code(key_code); let location = shared::code_to_location(code); let raw_mods = event.modifierFlags(); let mods = make_modifiers(raw_mods); let state = match event_type { NSEventType::NSKeyDown => KeyState::Down, NSEventType::NSKeyUp => KeyState::Up, NSEventType::NSFlagsChanged => { // We use `bits` here because we want to distinguish the // device dependent bits (when both left and right keys // may be pressed, for example). let any_down = raw_mods.bits() & !self.last_mods.bits(); self.last_mods = raw_mods; if is_modifier_code(code) { if any_down == 0 { KeyState::Up } else { KeyState::Down } } else { // HandleFlagsChanged has some logic for this; it might // happen when an app is deactivated by Command-Tab. In // that case, the best thing to do is synthesize the event // from the modifiers. But a challenge there is that we // might get multiple events. return None; } } _ => unreachable!(), }; let is_composing = false; let repeat: bool = event_type == NSEventType::NSKeyDown && msg_send![event, isARepeat]; let key = if let Some(key) = code_to_key(code) { key } else { let characters = from_nsstring(event.characters()); if is_valid_key(&characters) { KbKey::Character(characters) } else { let chars_ignoring = from_nsstring(event.charactersIgnoringModifiers()); if is_valid_key(&chars_ignoring) { KbKey::Character(chars_ignoring) } else { // There may be more heroic things we can do here. KbKey::Unidentified } } }; let event = KeyEvent { state, key, code, location, mods, repeat, is_composing, }; Some(event) } } } const MODIFIER_MAP: &[(NSEventModifierFlags, Modifiers)] = &[ (NSEventModifierFlags::NSShiftKeyMask, Modifiers::SHIFT), (NSEventModifierFlags::NSAlternateKeyMask, Modifiers::ALT), (NSEventModifierFlags::NSControlKeyMask, Modifiers::CONTROL), (NSEventModifierFlags::NSCommandKeyMask, Modifiers::META), ( NSEventModifierFlags::NSAlphaShiftKeyMask, Modifiers::CAPS_LOCK, ), ]; pub(crate) fn make_modifiers(raw: NSEventModifierFlags) -> Modifiers { let mut modifiers = Modifiers::empty(); for &(flags, mods) in MODIFIER_MAP { if raw.contains(flags) { modifiers |= mods; } } modifiers }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/appkit.rs
druid-shell/src/backend/mac/appkit.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS AppKit bindings. #![allow(clippy::upper_case_acronyms, non_snake_case, non_upper_case_globals)] use bitflags::bitflags; use cocoa::base::id; use cocoa::foundation::NSRect; use objc::{class, msg_send, sel, sel_impl}; #[link(name = "AppKit", kind = "framework")] extern "C" { pub static NSRunLoopCommonModes: id; } bitflags! { pub struct NSTrackingAreaOptions: i32 { const MouseEnteredAndExited = 1; const MouseMoved = 1 << 1; const CursorUpdate = 1 << 2; // What's 1 << 3? const ActiveWhenFirstResponder = 1 << 4; const ActiveInKeyWindow = 1 << 5; const ActiveInActiveApp = 1 << 6; const ActiveAlways = 1 << 7; const AssumeInside = 1 << 8; const InVisibleRect = 1 << 9; const EnabledDuringMouseDrag = 1 << 10; } } pub trait NSTrackingArea: Sized { unsafe fn alloc(_: Self) -> id { msg_send![class!(NSTrackingArea), alloc] } unsafe fn initWithRect_options_owner_userInfo( self, rect: NSRect, options: NSTrackingAreaOptions, owner: id, userInfo: id, ) -> id; } impl NSTrackingArea for id { unsafe fn initWithRect_options_owner_userInfo( self, rect: NSRect, options: NSTrackingAreaOptions, owner: id, userInfo: id, ) -> id { msg_send![self, initWithRect:rect options:options owner:owner userInfo:userInfo] } } pub trait NSView: Sized { unsafe fn addTrackingArea(self, trackingArea: id) -> id; } impl NSView for id { unsafe fn addTrackingArea(self, trackingArea: id) -> id { msg_send![self, addTrackingArea: trackingArea] } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/mac/screen.rs
druid-shell/src/backend/mac/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS Monitors and Screen information. use crate::kurbo::Rect; use crate::screen::Monitor; use cocoa::appkit::NSScreen; use cocoa::base::id; use cocoa::foundation::NSArray; use objc::{class, msg_send, sel, sel_impl}; pub(crate) fn get_monitors() -> Vec<Monitor> { unsafe { let screens: id = msg_send![class![NSScreen], screens]; let mut monitors = Vec::<(Rect, Rect)>::new(); let mut total_rect = Rect::ZERO; for idx in 0..screens.count() { let screen = screens.objectAtIndex(idx); let frame = NSScreen::frame(screen); let frame_r = Rect::from_origin_size( (frame.origin.x, frame.origin.y), (frame.size.width, frame.size.height), ); let vis_frame = NSScreen::visibleFrame(screen); let vis_frame_r = Rect::from_origin_size( (vis_frame.origin.x, vis_frame.origin.y), (vis_frame.size.width, vis_frame.size.height), ); monitors.push((frame_r, vis_frame_r)); total_rect = total_rect.union(frame_r) } // TODO save this total_rect.y1 for screen coord transformations in get_position/set_position // and invalidate on monitor changes transform_coords(monitors, total_rect.y1) } } fn transform_coords(monitors_build: Vec<(Rect, Rect)>, max_y: f64) -> Vec<Monitor> { //Flip y and move to opposite horizontal edges (On mac, Y goes up and origin is bottom left corner) let fix_rect = |frame: &Rect| { Rect::new( frame.x0, (max_y - frame.y0) - frame.height(), frame.x1, (max_y - frame.y1) + frame.height(), ) }; monitors_build .iter() .enumerate() .map(|(idx, (frame, vis_frame))| { Monitor::new(idx == 0, fix_rect(frame), fix_rect(vis_frame)) }) .collect() } #[cfg(test)] mod test { use crate::backend::mac::screen::transform_coords; use crate::kurbo::Rect; use crate::Monitor; use test_log::test; fn pair(rect: Rect) -> (Rect, Rect) { (rect, rect) } fn monitor(primary: bool, rect: Rect) -> Monitor { Monitor::new(primary, rect, rect) } #[test] fn test_transform_coords_1() { let mons = transform_coords(vec![pair(Rect::new(0., 0., 100., 100.))], 100.); assert_eq!(vec![monitor(true, Rect::new(0., 0., 100., 100.))], mons) } #[test] fn test_transform_coords_2_right() { let mons = transform_coords( vec![ pair(Rect::new(0., 0., 100., 100.)), pair(Rect::new(100., 0., 200., 100.)), ], 100., ); assert_eq!( vec![ monitor(true, Rect::new(0., 0., 100., 100.),), monitor(false, Rect::new(100., 0., 200., 100.)) ], mons ) } #[test] fn test_transform_coords_2_up() { let mons = transform_coords( vec![ pair(Rect::new(0., 0., 100., 100.)), pair(Rect::new(0., 100., 0., 200.)), ], 100., ); assert_eq!( vec![ monitor(true, Rect::new(0., 0., 100., 100.),), monitor(false, Rect::new(0., -100., 0., 0.0)) ], mons ) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/pointers.rs
druid-shell/src/backend/wayland/pointers.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::collections::VecDeque; use wayland_client::protocol::wl_pointer; use wayland_client::protocol::wl_surface::{self, WlSurface}; use wayland_client::{self as wl}; use wayland_cursor::CursorImageBuffer; use wayland_cursor::CursorTheme; use crate::keyboard::Modifiers; use crate::kurbo::{Point, Vec2}; use crate::mouse; use super::application::Data; // Button constants (linux specific) const BTN_LEFT: u32 = 0x110; const BTN_RIGHT: u32 = 0x111; const BTN_MIDDLE: u32 = 0x112; // used to keep track of click event counts. #[derive(Debug, Clone)] struct ClickDebouncer { timestamp: std::time::Instant, count: u8, previous: mouse::MouseButton, } impl Default for ClickDebouncer { fn default() -> Self { Self { timestamp: std::time::Instant::now(), count: 1, previous: mouse::MouseButton::None, } } } impl ClickDebouncer { // this threshold was arbitrarily chosen based on experimention. // there is likely a better default based on research to use. // during experimentation this allowed one to get to around 4 clicks. // but likely heavily dependent on the machine. const THRESHOLD: std::time::Duration = std::time::Duration::from_millis(500); fn reset(ts: std::time::Instant, btn: mouse::MouseButton) -> Self { Self { timestamp: ts, count: 1, previous: btn, } } fn debounce(&mut self, current: MouseEvtKind) -> MouseEvtKind { let ts = std::time::Instant::now(); // reset counting and button. if self.timestamp + ClickDebouncer::THRESHOLD < ts { *self = ClickDebouncer::default(); } match current { MouseEvtKind::Up(mut evt) if self.previous == evt.button => { evt.count = self.count; MouseEvtKind::Up(evt) } MouseEvtKind::Down(mut evt) if self.previous == evt.button => { self.count += 1; evt.count = self.count; MouseEvtKind::Down(evt) } MouseEvtKind::Down(evt) if self.previous != evt.button => { *self = ClickDebouncer::reset(ts, evt.button); MouseEvtKind::Down(evt) } MouseEvtKind::Leave => { *self = ClickDebouncer::reset(ts, mouse::MouseButton::None); current } _ => current, } } } /// Collect up mouse events then emit them together on a pointer frame. pub(crate) struct Pointer { /// The image surface which contains the cursor image. pub(crate) cursor_surface: wl::Main<WlSurface>, /// Events that have occurred since the last frame. pub(crate) queued_events: std::cell::RefCell<VecDeque<PointerEvent>>, /// Currently pressed buttons buttons: std::cell::RefCell<mouse::MouseButtons>, /// Current position pos: std::cell::Cell<Point>, wl_pointer: std::cell::RefCell<Option<wl_pointer::WlPointer>>, // used to keep track of the current clicking clickevent: std::cell::RefCell<ClickDebouncer>, /// cursor theme data. theme: std::cell::RefCell<CursorTheme>, /// Cache the current cursor, so we can see if it changed current_cursor: std::cell::RefCell<mouse::Cursor>, } /// Raw wayland pointer events. #[derive(Debug)] pub(crate) enum PointerEvent { /// Mouse moved/entered Motion { pointer: wl_pointer::WlPointer, point: Point, }, /// Mouse button pressed/released Button { button: u32, state: wl_pointer::ButtonState, }, /// Axis movement Axis { axis: wl_pointer::Axis, value: f64 }, /// Mouse left Leave, } /// An enum that we will convert into the different callbacks. #[derive(Debug)] pub(crate) enum MouseEvtKind { Move(mouse::MouseEvent), Up(mouse::MouseEvent), Down(mouse::MouseEvent), Leave, Wheel(mouse::MouseEvent), } #[allow(unused)] impl Pointer { /// Create a new pointer pub fn new(theme: CursorTheme, cursor: wl::Main<WlSurface>) -> Self { // ignore all events cursor.quick_assign(|a1, event, a2| { tracing::trace!("pointer surface event {:?} {:?} {:?}", a1, event, a2); }); Pointer { theme: std::cell::RefCell::new(theme), buttons: std::cell::RefCell::new(mouse::MouseButtons::new()), pos: std::cell::Cell::new(Point::ZERO), // will get set before we emit any events queued_events: std::cell::RefCell::new(VecDeque::with_capacity(3)), // should be enough most of the time cursor_surface: cursor, wl_pointer: std::cell::RefCell::new(None), current_cursor: std::cell::RefCell::new(mouse::Cursor::Arrow), clickevent: std::cell::RefCell::new(ClickDebouncer::default()), } } pub fn attach(&self, current: wl_pointer::WlPointer) { tracing::trace!("attaching pointer reference {:?}", current); self.wl_pointer.replace(Some(current)); } #[inline] pub fn push(&self, event: PointerEvent) { self.queued_events.borrow_mut().push_back(event); } #[inline] pub fn pop(&self) -> Option<PointerEvent> { self.queued_events.borrow_mut().pop_front() } #[inline] pub fn cursor(&self) -> &WlSurface { &self.cursor_surface } pub fn replace(&self, cursor: &mouse::Cursor) { let current = self.current_cursor.borrow().clone(); let cursor = cursor.clone(); // Setting a new cursor involves communicating with the server, so don't do it if we // don't have to. if current == cursor { return; } let b = self.wl_pointer.borrow_mut(); let wl_pointer = match &*b { None => return, Some(p) => p, }; tracing::trace!("replacing cursor {:?} -> {:?}", current, cursor); let buffer = match self.get_cursor_buffer(&cursor) { None => return, Some(b) => b, }; let (hot_x, hot_y) = buffer.hotspot(); self.current_cursor.replace(cursor); wl_pointer.set_cursor(0, Some(&self.cursor_surface), hot_x as i32, hot_y as i32); self.cursor_surface.attach(Some(&*buffer), 0, 0); if self.cursor_surface.as_ref().version() >= wl_surface::REQ_DAMAGE_BUFFER_SINCE { self.cursor_surface.damage_buffer(0, 0, i32::MAX, i32::MAX); } else { self.cursor_surface.damage(0, 0, i32::MAX, i32::MAX); } self.cursor_surface.commit(); } fn get_cursor_buffer(&self, cursor: &mouse::Cursor) -> Option<CursorImageBuffer> { #[allow(deprecated)] match cursor { mouse::Cursor::Arrow => self.unpack_image_buffer("left_ptr"), mouse::Cursor::IBeam => self.unpack_image_buffer("xterm"), mouse::Cursor::Crosshair => self.unpack_image_buffer("cross"), mouse::Cursor::OpenHand => self.unpack_image_buffer("openhand"), mouse::Cursor::NotAllowed => self.unpack_image_buffer("X_cursor"), mouse::Cursor::ResizeLeftRight => self.unpack_image_buffer("row-resize"), mouse::Cursor::ResizeUpDown => self.unpack_image_buffer("col-resize"), mouse::Cursor::Pointer => self.unpack_image_buffer("pointer"), mouse::Cursor::Custom(_) => { tracing::warn!("custom cursors not implemented"); self.unpack_image_buffer("left_ptr") } } } // Just use the first image, people using animated cursors have already made bad life // choices and shouldn't expect it to work. fn unpack_image_buffer(&self, name: &str) -> Option<CursorImageBuffer> { self.theme .borrow_mut() .get_cursor(name) .map(|c| c[c.frame_and_duration(0).frame_index].clone()) } pub(super) fn consume( appdata: std::sync::Arc<Data>, source: wl_pointer::WlPointer, event: wl_pointer::Event, ) { match event { wl_pointer::Event::Enter { surface, surface_x, surface_y, .. } => { appdata.pointer.push(PointerEvent::Motion { point: Point::new(surface_x, surface_y), pointer: source, }); } wl_pointer::Event::Leave { surface, .. } => { appdata.pointer.push(PointerEvent::Leave); } wl_pointer::Event::Motion { surface_x, surface_y, .. } => { appdata.pointer.push(PointerEvent::Motion { point: Point::new(surface_x, surface_y), pointer: source, }); } wl_pointer::Event::Button { button, state, .. } => { appdata.pointer.push(PointerEvent::Button { button, state }); } wl_pointer::Event::Axis { axis, value, .. } => { appdata.pointer.push(PointerEvent::Axis { axis, value }); } wl_pointer::Event::Frame => { let winhandle = match appdata.acquire_current_window().and_then(|w| w.data()) { Some(w) => w, None => { tracing::warn!("dropping mouse events, no window available"); appdata.pointer.queued_events.borrow_mut().clear(); return; } }; let mut winhandle = winhandle.handler.borrow_mut(); // (re-entrancy) call user code while let Some(event) = appdata.pointer.dequeue() { match event { MouseEvtKind::Move(evt) => winhandle.mouse_move(&evt), MouseEvtKind::Up(evt) => winhandle.mouse_up(&evt), MouseEvtKind::Down(evt) => winhandle.mouse_down(&evt), MouseEvtKind::Wheel(evt) => winhandle.wheel(&evt), MouseEvtKind::Leave => winhandle.mouse_leave(), } } } evt => { log::warn!("Unhandled pointer event: {:?}", evt); } } } fn dequeue(&self) -> Option<MouseEvtKind> { use wl_pointer::{Axis, ButtonState}; // sometimes we need to ignore an event and move on loop { let event = self.queued_events.borrow_mut().pop_front()?; tracing::trace!("mouse event {:?}", event); match event { PointerEvent::Motion { pointer, point } => { self.pos.replace(point); return Some(MouseEvtKind::Move(mouse::MouseEvent { pos: point, buttons: *self.buttons.borrow(), mods: Modifiers::empty(), count: 0, focus: false, button: mouse::MouseButton::None, wheel_delta: Vec2::ZERO, })); } PointerEvent::Button { button, state } => { let button = match linux_to_mouse_button(button) { // Skip unsupported buttons. None => { tracing::debug!("unsupported button click {:?}", button); continue; } Some(b) => b, }; let evt = match state { ButtonState::Pressed => { self.buttons.borrow_mut().insert(button); self.clickevent.borrow_mut().debounce(MouseEvtKind::Down( mouse::MouseEvent { pos: self.pos.get(), buttons: *self.buttons.borrow(), mods: Modifiers::empty(), count: 1, focus: false, button, wheel_delta: Vec2::ZERO, }, )) } ButtonState::Released => { self.buttons.borrow_mut().remove(button); self.clickevent.borrow_mut().debounce(MouseEvtKind::Up( mouse::MouseEvent { pos: self.pos.get(), buttons: *self.buttons.borrow(), mods: Modifiers::empty(), count: 0, focus: false, button, wheel_delta: Vec2::ZERO, }, )) } _ => { log::error!("mouse button changed, but not pressed or released"); continue; } }; return Some(evt); } PointerEvent::Axis { axis, value } => { let wheel_delta = match axis { Axis::VerticalScroll => Vec2::new(0., value), Axis::HorizontalScroll => Vec2::new(value, 0.), _ => { log::error!("axis direction not vertical or horizontal"); continue; } }; return Some(MouseEvtKind::Wheel(mouse::MouseEvent { pos: self.pos.get(), buttons: *self.buttons.borrow(), mods: Modifiers::empty(), count: 0, focus: false, button: mouse::MouseButton::None, wheel_delta, })); } PointerEvent::Leave => { // The parent will remove us. return Some(MouseEvtKind::Leave); } } } } } impl Drop for Pointer { fn drop(&mut self) { self.cursor_surface.destroy(); } } #[inline] fn linux_to_mouse_button(button: u32) -> Option<mouse::MouseButton> { match button { BTN_LEFT => Some(mouse::MouseButton::Left), BTN_RIGHT => Some(mouse::MouseButton::Right), BTN_MIDDLE => Some(mouse::MouseButton::Middle), _ => None, } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/clipboard.rs
druid-shell/src/backend/wayland/clipboard.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interactions with the system pasteboard on wayland compositors. use super::application; use super::error as waylanderr; use crate::clipboard::{ClipboardFormat, FormatId}; use std::io::Read; use wayland_client as wl; use wayland_client::protocol::wl_data_device; use wayland_client::protocol::wl_data_device_manager; use wayland_client::protocol::wl_data_offer; use wayland_client::protocol::wl_data_source; #[derive(Clone)] struct Offer { wobj: wl::Main<wl_data_offer::WlDataOffer>, mimetype: String, } impl Offer { fn new(d: wl::Main<wl_data_offer::WlDataOffer>, mimetype: impl Into<String>) -> Self { Self { wobj: d, mimetype: mimetype.into(), } } } #[derive(Default)] struct Data { pending: std::cell::RefCell<Vec<Offer>>, current: std::cell::RefCell<Vec<Offer>>, } impl Data { fn receive(&self, mimetype: &str) -> Option<Offer> { for offer in self.current.borrow().iter() { if !offer.mimetype.starts_with(mimetype) { continue; } return Some(offer.clone()); } None } } impl std::fmt::Debug for Data { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Data") .field("pending", &self.pending.borrow().len()) .field("current", &self.current.borrow().len()) .finish() } } impl From<Vec<Offer>> for Data { fn from(current: Vec<Offer>) -> Self { Self { current: std::cell::RefCell::new(current), pending: Default::default(), } } } struct Inner { display: wl::Display, wobj: wl::Main<wl_data_device_manager::WlDataDeviceManager>, wdsobj: wl::Main<wl_data_source::WlDataSource>, devices: std::rc::Rc<std::cell::RefCell<Data>>, } impl std::fmt::Debug for Inner { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("") .field("wobj", &self.wobj) .field("wdsobj", &self.wdsobj) .finish() } } #[derive(Debug, Clone)] pub struct Manager { inner: std::rc::Rc<Inner>, } impl Manager { pub(super) fn new( display: &wl::Display, gm: &wl::GlobalManager, ) -> Result<Self, waylanderr::Error> { let m = gm .instantiate_exact::<wl_data_device_manager::WlDataDeviceManager>(3) .map_err(|e| waylanderr::Error::global("wl_data_device_manager", 1, e))?; m.quick_assign(|i, event, _ignored| { tracing::info!("clipboard {:?} event {:?}", i, event); }); let ds = m.create_data_source(); ds.quick_assign(|i, event, _ignored| { tracing::info!("clipboard {:?} event {:?}", i, event); }); Ok(Self { inner: std::rc::Rc::new(Inner { wobj: m, wdsobj: ds, display: display.clone(), devices: Default::default(), }), }) } pub fn attach<'a>(&'a self, seat: &'a mut application::Seat) { let device = self.inner.wobj.get_data_device(&seat.wl_seat); device.quick_assign({ let m = self.inner.clone(); move |i, event, _ignored| match event { wl_data_device::Event::DataOffer { id } => { let offer = id; offer.quick_assign({ let m = m.clone(); move |i, event, _ignored| match event { wl_data_offer::Event::Offer { mime_type } => { let data = m.devices.borrow_mut(); let offer = Offer::new(i, mime_type); data.pending.borrow_mut().push(offer); } _ => tracing::warn!("clipboard unhandled {:?} event {:?}", i, event), } }); } wl_data_device::Event::Selection { id } => { if id.is_some() { let data = m.devices.borrow(); tracing::debug!( "current data offers {:?} {:?}", data.current.borrow().len(), data.pending.borrow().len() ); let upd = Data::from(data.pending.take()); drop(data); tracing::debug!( "updated data offers {:?} {:?}", upd.current.borrow().len(), upd.pending.borrow().len() ); m.devices.replace(upd); } else { let upd = Data::from(Vec::new()); m.devices.replace(upd); } } _ => tracing::warn!("clipboard unhandled {:?} event {:?}", i, event), } }); } fn initiate(&self, o: Offer) -> Option<Vec<u8>> { tracing::debug!("retrieving {:?} {:?}", o.wobj, o.mimetype); let (fdread, fdwrite) = match nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC) { Ok(pipe) => pipe, Err(cause) => { tracing::error!("clipboard failed to request data {:?}", cause); return None; } }; o.wobj.receive(o.mimetype.to_string(), fdwrite); if let Err(cause) = self.inner.display.flush() { tracing::error!("clipboard failed to request data {:?}", cause); return None; } if let Err(cause) = nix::unistd::close(fdwrite) { tracing::error!("clipboard failed to request data {:?}", cause); return None; } let mut data = Vec::new(); let mut io: std::fs::File = unsafe { std::os::unix::io::FromRawFd::from_raw_fd(fdread) }; let transferred = match io.read_to_end(&mut data) { Err(cause) => { tracing::error!("clipboard unable to retrieve pasted content {:?}", cause); return None; } Ok(transferred) => transferred, }; tracing::debug!("transferred {:?} bytes", transferred); match transferred { 0 => None, _ => Some(data), } } pub(super) fn receive(&self, mimetype: impl Into<String>) -> Option<Vec<u8>> { let mimetype: String = mimetype.into(); if let Some(offer) = self.inner.devices.borrow().receive(&mimetype) { return self.initiate(offer); } None } } /// The system clipboard. #[derive(Debug, Clone)] pub struct Clipboard { inner: Manager, } impl From<&Manager> for Clipboard { fn from(m: &Manager) -> Self { Self { inner: m.clone() } } } impl Clipboard { const UTF8: &'static str = "text/plain;charset=utf-8"; const TEXT: &'static str = "text/plain"; const UTF8_STRING: &'static str = "UTF8_STRING"; /// Put a string onto the system clipboard. pub fn put_string(&mut self, s: impl AsRef<str>) { let _s = s.as_ref().to_string(); self.inner.inner.wdsobj.offer(Clipboard::UTF8.to_string()); } /// Put multi-format data on the system clipboard. pub fn put_formats(&mut self, _formats: &[ClipboardFormat]) { tracing::warn!("clipboard copy not implemented"); } /// Get a string from the system clipboard, if one is available. pub fn get_string(&self) -> Option<String> { [Clipboard::UTF8, Clipboard::TEXT, Clipboard::UTF8_STRING] .iter() .find_map( |mimetype| match std::str::from_utf8(&self.inner.receive(*mimetype)?) { Ok(s) => Some(s.to_string()), Err(cause) => { tracing::error!("clipboard unable to retrieve utf8 content {:?}", cause); None } }, ) } /// Given a list of supported clipboard types, returns the supported type which has /// highest priority on the system clipboard, or `None` if no types are supported. pub fn preferred_format(&self, _formats: &[FormatId]) -> Option<FormatId> { tracing::warn!("clipboard preferred_format not implemented"); None } /// Return data in a given format, if available. /// /// It is recommended that the `fmt` argument be a format returned by /// [`Clipboard::preferred_format`] pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> { self.inner.receive(format) } pub fn available_type_names(&self) -> Vec<String> { tracing::warn!("clipboard available_type_names not implemented"); Vec::new() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/menu.rs
druid-shell/src/backend/wayland/menu.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #![allow(unused)] use super::window::WindowHandle; use crate::common_util::strip_access_key; use crate::hotkey::{HotKey, RawMods}; use crate::keyboard::{KbKey, Modifiers}; #[derive(Default, Debug)] pub struct Menu; #[derive(Debug)] struct MenuItem; impl Menu { pub fn new() -> Menu { Menu } pub fn new_for_popup() -> Menu { Menu } pub fn add_dropdown(&mut self, menu: Menu, text: &str, _enabled: bool) { tracing::warn!("unimplemented"); } pub fn add_item( &mut self, _id: u32, _text: &str, _key: Option<&HotKey>, _selected: Option<bool>, _enabled: bool, ) { tracing::warn!("unimplemented"); } pub fn add_separator(&mut self) { tracing::warn!("unimplemented"); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/error.rs
druid-shell/src/backend/wayland/error.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! wayland platform errors. use std::{error::Error as StdError, fmt, sync::Arc}; use wayland_client as wl; #[derive(Debug, Clone)] pub enum Error { /// Error connecting to wayland server. Connect(Arc<wl::ConnectError>), /// A wayland global either doesn't exist, or doesn't support the version we need. Global { name: String, version: u32, inner: Arc<wl::GlobalError>, }, /// An unexpected error occurred. It's not handled by `druid-shell`/wayland, so you should /// terminate the app. Fatal(Arc<dyn StdError + 'static>), String(ErrorString), InvalidParent(u32), /// general error. Err(Arc<dyn StdError + 'static>), } impl Error { #[allow(clippy::self_named_constructors)] pub fn error(e: impl StdError + 'static) -> Self { Self::Err(Arc::new(e)) } pub fn fatal(e: impl StdError + 'static) -> Self { Self::Fatal(Arc::new(e)) } pub fn global(name: impl Into<String>, version: u32, inner: wl::GlobalError) -> Self { Error::Global { name: name.into(), version, inner: Arc::new(inner), } } pub fn string(s: impl Into<String>) -> Self { Error::String(ErrorString::from(s)) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { Self::Connect(e) => write!(f, "could not connect to the wayland server: {e:?}"), Self::Global { name, version, .. } => write!( f, "a required wayland global ({name}@{version}) was unavailable" ), Self::Fatal(e) => write!(f, "an unhandled error occurred: {e:?}"), Self::Err(e) => write!(f, "an unhandled error occurred: {e:?}"), Self::String(e) => e.fmt(f), Self::InvalidParent(id) => write!(f, "invalid parent window for popup: {id:?}"), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { Self::Connect(e) => Some(&**e), Self::Global { inner, .. } => Some(&**inner), Self::Fatal(e) => Some(&**e), Self::Err(e) => Some(&**e), Self::String(e) => Some(e), Self::InvalidParent(_) => None, } } } impl From<wl::ConnectError> for Error { fn from(err: wl::ConnectError) -> Self { Self::Connect(Arc::new(err)) } } #[derive(Debug, Clone)] pub struct ErrorString { details: String, } impl ErrorString { pub fn from(s: impl Into<String>) -> Self { Self { details: s.into() } } } impl std::fmt::Display for ErrorString { fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result { write!(f, "{}", self.details) } } impl std::error::Error for ErrorString { fn description(&self) -> &str { &self.details } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/application.rs
druid-shell/src/backend/wayland/application.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #![allow(clippy::single_match)] use super::{ clipboard, display, error::Error, events::WaylandSource, keyboard, outputs, pointers, surfaces, window::WindowHandle, }; use crate::{backend, mouse, AppHandler, TimerToken}; use calloop; use std::{ cell::{Cell, RefCell}, collections::{BTreeMap, BinaryHeap}, rc::Rc, time::{Duration, Instant}, }; use crate::backend::shared::linux; use wayland_client::protocol::wl_keyboard::WlKeyboard; use wayland_client::protocol::wl_registry; use wayland_client::{ self as wl, protocol::{ wl_compositor::WlCompositor, wl_pointer::WlPointer, wl_region::WlRegion, wl_seat::{self, WlSeat}, wl_shm::{self, WlShm}, wl_surface::WlSurface, }, }; use wayland_cursor::CursorTheme; use wayland_protocols::wlr::unstable::layer_shell::v1::client::zwlr_layer_shell_v1::ZwlrLayerShellV1; use wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner; use wayland_protocols::xdg_shell::client::xdg_surface; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct Timer(backend::shared::Timer<u64>); impl Timer { pub(crate) fn new(id: u64, deadline: Instant) -> Self { Self(backend::shared::Timer::new(deadline, id)) } pub(crate) fn id(self) -> u64 { self.0.data } pub(crate) fn deadline(&self) -> Instant { self.0.deadline() } pub fn token(&self) -> TimerToken { self.0.token() } } impl std::cmp::Ord for Timer { /// Ordering is so that earliest deadline sorts first // "Earliest deadline first" that a std::collections::BinaryHeap will have the earliest timer // at its head, which is just what is needed for timer management. fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.deadline().cmp(&other.0.deadline()).reverse() } } impl std::cmp::PartialOrd for Timer { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } #[derive(Clone)] pub struct Application { pub(super) data: std::sync::Arc<Data>, } #[allow(dead_code)] pub(crate) struct Data { pub(super) wayland: std::rc::Rc<display::Environment>, pub(super) zwlr_layershell_v1: Option<wl::Main<ZwlrLayerShellV1>>, pub(super) wl_compositor: wl::Main<WlCompositor>, pub(super) wl_shm: wl::Main<WlShm>, /// A map of wayland object IDs to outputs. /// /// Wayland will update this if the output change. Keep a record of the `Instant` you last /// observed a change, and use `Output::changed` to see if there are any newer changes. /// /// It's a BTreeMap so the ordering is consistent when enumerating outputs (not sure if this is /// necessary, but it negligible cost). pub(super) outputs: Rc<RefCell<BTreeMap<u32, outputs::Meta>>>, pub(super) seats: Rc<RefCell<BTreeMap<u32, Rc<RefCell<Seat>>>>>, /// Handles to any surfaces that have been created. pub(super) handles: RefCell<im::OrdMap<u64, WindowHandle>>, /// Available pixel formats pub(super) formats: RefCell<Vec<wl_shm::Format>>, /// Close flag pub(super) shutdown: Cell<bool>, /// The currently active surface, if any (by wayland object ID) pub(super) active_surface_id: RefCell<std::collections::VecDeque<u64>>, // Stuff for timers /// A calloop event source for timers. We always set it to fire at the next set timer, if any. pub(super) timer_handle: calloop::timer::TimerHandle<TimerToken>, /// We stuff this here until the event loop, then `take` it and use it. timer_source: RefCell<Option<calloop::timer::Timer<TimerToken>>>, /// Currently pending timers /// /// The extra data is the surface this timer is for. pub(super) timers: RefCell<BinaryHeap<Timer>>, pub(super) roundtrip_requested: RefCell<bool>, /// track if the display was flushed during the event loop. /// prevents double flushing unnecessarily. pub(super) display_flushed: RefCell<bool>, /// reference to the pointer events manager. pub(super) pointer: pointers::Pointer, /// reference to the keyboard events manager. keyboard: keyboard::Manager, clipboard: clipboard::Manager, // wakeup events when outputs are added/removed. outputsqueue: RefCell<Option<calloop::channel::Channel<outputs::Event>>>, } impl Application { pub fn new() -> Result<Self, Error> { tracing::info!("wayland application initiated"); // Global objects that can come and go (so we must handle them dynamically). // // They have to be behind a shared pointer because wayland may need to add or remove them // for the life of the application. Use weak rcs inside the callbacks to avoid leaking // memory. let dispatcher = display::Dispatcher::default(); let outputqueue = outputs::auto(&dispatcher)?; let seats: Rc<RefCell<BTreeMap<u32, Rc<RefCell<Seat>>>>> = Rc::new(RefCell::new(BTreeMap::new())); // This object will create a container for the global wayland objects, and request that // it is populated by the server. Doesn't take ownership of the registry, we are // responsible for keeping it alive. let weak_seats = Rc::downgrade(&seats); display::GlobalEventDispatch::subscribe( &dispatcher, move |event: &'_ wl::GlobalEvent, registry: &'_ wl::Attached<wl_registry::WlRegistry>, _ctx: &'_ wl::DispatchData| { match event { wl::GlobalEvent::New { id, interface, version, } => { let id = *id; let version = *version; if interface.as_str() != "wl_seat" { return; } tracing::debug!("seat detected {:?} {:?} {:?}", interface, id, version); // 7 is the max version supported by wayland-rs 0.29.5 let version = version.min(7); let new_seat = registry.bind::<WlSeat>(version, id); let prev_seat = weak_seats .upgrade() .unwrap() .borrow_mut() .insert(id, Rc::new(RefCell::new(Seat::new(new_seat)))); assert!( prev_seat.is_none(), "internal: wayland should always use new IDs" ); // TODO: This code handles only app startup, but seats can come and go on the fly, // so we have to handle that in the future // Defer setting up the pointer/keyboard event handling until we've // finished constructing the `Application`. That way we can pass it as a // parameter. } wl::GlobalEvent::Removed { .. } => { // nothing to do. } }; }, ); let env = display::new(dispatcher)?; display::print(&env.registry); let zwlr_layershell_v1 = env .registry .instantiate_exact::<ZwlrLayerShellV1>(1) .map_or_else( |e| { tracing::info!("unable to instantiate layershell {:?}", e); None }, Some, ); let wl_compositor = env .registry .instantiate_range::<WlCompositor>(1, 5) .map_err(|e| Error::global("wl_compositor", 1, e))?; let wl_shm = env .registry .instantiate_exact::<WlShm>(1) .map_err(|e| Error::global("wl_shm", 1, e))?; let timer_source = calloop::timer::Timer::new().unwrap(); let timer_handle = timer_source.handle(); // TODO the cursor theme size needs more refinement, it should probably be the size needed to // draw sharp cursors on the largest scaled monitor. let pointer = pointers::Pointer::new( CursorTheme::load(64, &wl_shm), wl_compositor.create_surface(), ); // We need to have keyboard events set up for our seats before the next roundtrip. let appdata = std::sync::Arc::new(Data { zwlr_layershell_v1, wl_compositor, wl_shm: wl_shm.clone(), outputs: Rc::new(RefCell::new(BTreeMap::new())), seats, handles: RefCell::new(im::OrdMap::new()), formats: RefCell::new(vec![]), shutdown: Cell::new(false), active_surface_id: RefCell::new(std::collections::VecDeque::with_capacity(20)), timer_handle, timer_source: RefCell::new(Some(timer_source)), timers: RefCell::new(BinaryHeap::new()), display_flushed: RefCell::new(false), pointer, keyboard: keyboard::Manager::default(), clipboard: clipboard::Manager::new(&env.display, &env.registry)?, roundtrip_requested: RefCell::new(false), outputsqueue: RefCell::new(Some(outputqueue)), wayland: std::rc::Rc::new(env), }); // Collect the supported image formats. wl_shm.quick_assign(with_cloned!(appdata; move |d1, event, d3| { tracing::debug!("shared memory events {:?} {:?} {:?}", d1, event, d3); match event { wl_shm::Event::Format { format } => appdata.formats.borrow_mut().push(format), _ => (), // ignore other messages } })); // Setup seat event listeners with our application for (id, seat) in appdata.seats.borrow().iter() { let id = *id; // move into closure. let wl_seat = seat.borrow().wl_seat.clone(); wl_seat.quick_assign(with_cloned!(seat, appdata; move |d1, event, d3| { tracing::debug!("seat events {:?} {:?} {:?}", d1, event, d3); let mut seat = seat.borrow_mut(); appdata.clipboard.attach(&mut seat); match event { wl_seat::Event::Capabilities { capabilities } => { seat.capabilities = capabilities; if capabilities.contains(wl_seat::Capability::Keyboard) && seat.keyboard.is_none() { seat.keyboard = Some(appdata.keyboard.attach(id, seat.wl_seat.clone())); } if capabilities.contains(wl_seat::Capability::Pointer) && seat.pointer.is_none() { let pointer = seat.wl_seat.get_pointer(); appdata.pointer.attach(pointer.detach()); pointer.quick_assign({ let app = appdata.clone(); move |pointer, event, _| { pointers::Pointer::consume(app.clone(), pointer.detach(), event); } }); seat.pointer = Some(pointer); } // TODO: We should react to capability removal, // "if a seat regains the pointer capability // and a client has a previously obtained wl_pointer object // of version 4 or less, that object may start sending pointer events again. // This behavior is considered a misinterpretation of the intended behavior // and must not be relied upon by the client", // versions 5 up guarantee that events will not be sent for sure } wl_seat::Event::Name { name } => { seat.name = name; } _ => tracing::info!("seat quick assign unknown event {:?}", event), // ignore future events } })); } // Let wayland finish setup before we allow the client to start creating windows etc. appdata.sync()?; Ok(Application { data: appdata }) } pub fn run(mut self, _handler: Option<Box<dyn AppHandler>>) { tracing::info!("wayland event loop initiated"); // NOTE if we want to call this function more than once, we will need to put the timer // source back. let timer_source = self.data.timer_source.borrow_mut().take().unwrap(); // flush pending events (otherwise anything we submitted since sync will never be sent) self.data.wayland.display.flush().unwrap(); // Use calloop so we can epoll both wayland events and others (e.g. timers) let mut eventloop = calloop::EventLoop::try_new().unwrap(); let handle = eventloop.handle(); let wayland_dispatcher = WaylandSource::new(self.data.clone()).into_dispatcher(); self.data.keyboard.events(&handle); handle.register_dispatcher(wayland_dispatcher).unwrap(); handle .insert_source(self.data.outputsqueue.take().unwrap(), { move |evt, _ignored, appdata| match evt { calloop::channel::Event::Closed => {} calloop::channel::Event::Msg(output) => match output { outputs::Event::Located(output) => { tracing::debug!("output added {:?} {:?}", output.gid, output.id()); appdata .outputs .borrow_mut() .insert(output.id(), output.clone()); for (_, win) in appdata.handles_iter() { surfaces::Outputs::inserted(&win, &output); } } outputs::Event::Removed(output) => { tracing::debug!("output removed {:?} {:?}", output.gid, output.id()); appdata.outputs.borrow_mut().remove(&output.id()); for (_, win) in appdata.handles_iter() { surfaces::Outputs::removed(&win, &output); } } }, } }) .unwrap(); handle .insert_source(timer_source, move |token, _metadata, appdata| { tracing::trace!("timer source {:?}", token); appdata.handle_timer_event(token); }) .unwrap(); let signal = eventloop.get_signal(); let handle = handle.clone(); let res = eventloop.run(Duration::from_millis(20), &mut self.data, move |appdata| { if appdata.shutdown.get() { tracing::debug!("shutting down, requested"); signal.stop(); return; } if appdata.handles.borrow().is_empty() { tracing::debug!("shutting down, no window remaining"); signal.stop(); return; } Data::idle_repaint(handle.clone()); }); match res { Ok(_) => tracing::info!("wayland event loop completed"), Err(cause) => tracing::error!("wayland event loop failed {:?}", cause), } } pub fn quit(&self) { self.data.shutdown.set(true); } pub fn clipboard(&self) -> clipboard::Clipboard { clipboard::Clipboard::from(&self.data.clipboard) } pub fn get_locale() -> String { linux::env::locale() } } impl surfaces::Compositor for Data { fn output(&self, id: u32) -> Option<outputs::Meta> { self.outputs.borrow().get(&id).cloned() } fn create_surface(&self) -> wl::Main<WlSurface> { self.wl_compositor.create_surface() } fn create_region(&self) -> wl::Main<WlRegion> { self.wl_compositor.create_region() } fn shared_mem(&self) -> wl::Main<WlShm> { self.wl_shm.clone() } fn get_xdg_positioner(&self) -> wl::Main<XdgPositioner> { self.wayland.xdg_base.create_positioner() } fn get_xdg_surface(&self, s: &wl::Main<WlSurface>) -> wl::Main<xdg_surface::XdgSurface> { self.wayland.xdg_base.get_xdg_surface(s) } fn zwlr_layershell_v1(&self) -> Option<wl::Main<ZwlrLayerShellV1>> { self.zwlr_layershell_v1.clone() } } impl Data { pub(crate) fn set_cursor(&self, cursor: &mouse::Cursor) { self.pointer.replace(cursor); } /// Send all pending messages and process all received messages. /// /// Don't use this once the event loop has started. pub(crate) fn sync(&self) -> Result<(), Error> { self.wayland .queue .borrow_mut() .sync_roundtrip(&mut (), |evt, _, _| { panic!("unexpected wayland event: {evt:?}") }) .map_err(Error::fatal)?; Ok(()) } fn current_window_id(&self) -> u64 { static DEFAULT: u64 = 0_u64; *self.active_surface_id.borrow().front().unwrap_or(&DEFAULT) } pub(super) fn acquire_current_window(&self) -> Option<WindowHandle> { self.handles .borrow() .get(&self.current_window_id()) .cloned() } fn handle_timer_event(&self, _token: TimerToken) { // Don't borrow the timers in case the callbacks want to add more. let mut expired_timers = Vec::with_capacity(1); let mut timers = self.timers.borrow_mut(); let now = Instant::now(); while matches!(timers.peek(), Some(timer) if timer.deadline() < now) { // timer has passed expired_timers.push(timers.pop().unwrap()); } drop(timers); for expired in expired_timers { let win = match self.handles.borrow().get(&expired.id()).cloned() { Some(s) => s, None => { // NOTE this might be expected tracing::warn!( "received event for surface that doesn't exist any more {:?} {:?}", expired, expired.id() ); continue; } }; // re-entrancy if let Some(data) = win.data() { data.handler.borrow_mut().timer(expired.token()) } } for (_, win) in self.handles_iter() { if let Some(data) = win.data() { data.run_deferred_tasks() } } // Get the deadline soonest and queue it. if let Some(timer) = self.timers.borrow().peek() { self.timer_handle .add_timeout(timer.deadline() - now, timer.token()); } // Now flush so the events actually get sent (we don't do this automatically because we // aren't in a wayland callback. self.wayland.display.flush().unwrap(); } /// Shallow clones surfaces so we can modify it during iteration. pub(super) fn handles_iter(&self) -> impl Iterator<Item = (u64, WindowHandle)> { self.handles.borrow().clone().into_iter() } fn idle_repaint(loophandle: calloop::LoopHandle<'_, std::sync::Arc<Data>>) { loophandle.insert_idle({ move |appdata| { tracing::trace!("idle processing initiated"); for (_id, winhandle) in appdata.handles_iter() { winhandle.request_anim_frame(); winhandle.run_idle(); // if we already flushed this cycle don't flush again. if *appdata.display_flushed.borrow() { tracing::trace!("idle repaint flushing display initiated"); if let Err(cause) = appdata.wayland.queue.borrow().display().flush() { tracing::warn!("unable to flush display: {:?}", cause); } } } tracing::trace!("idle processing completed"); } }); } } impl From<Application> for surfaces::CompositorHandle { fn from(app: Application) -> surfaces::CompositorHandle { surfaces::CompositorHandle::from(app.data) } } impl From<std::sync::Arc<Data>> for surfaces::CompositorHandle { fn from(data: std::sync::Arc<Data>) -> surfaces::CompositorHandle { surfaces::CompositorHandle::direct( std::sync::Arc::downgrade(&data) as std::sync::Weak<dyn surfaces::Compositor> ) } } #[derive(Debug, Clone)] pub struct Seat { pub(super) wl_seat: wl::Main<WlSeat>, name: String, capabilities: wl_seat::Capability, keyboard: Option<wl::Main<WlKeyboard>>, pointer: Option<wl::Main<WlPointer>>, } impl Seat { fn new(wl_seat: wl::Main<WlSeat>) -> Self { Self { wl_seat, name: "".into(), capabilities: wl_seat::Capability::empty(), keyboard: None, pointer: None, } } } pub fn init_harness() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/display.rs
druid-shell/src/backend/wayland/display.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #![allow(clippy::single_match)] use super::error; use std::collections::BTreeMap; use wayland_client as wlc; use wayland_client::protocol::wl_registry; use wayland_protocols::xdg_shell::client::xdg_wm_base; type GlobalEventConsumer = dyn Fn(&wlc::GlobalEvent, &wlc::Attached<wl_registry::WlRegistry>, &wlc::DispatchData) + 'static; #[derive(Clone)] pub struct GlobalEventSubscription { id: u64, sub: std::sync::Arc<GlobalEventConsumer>, } impl GlobalEventSubscription { fn with_id(mut self, id: u64) -> Self { self.id = id; self } } impl GlobalEventSubscription { fn consume( &self, event: &wlc::GlobalEvent, registry: &wlc::Attached<wl_registry::WlRegistry>, ctx: &wlc::DispatchData, ) { (self.sub)(event, registry, ctx) } } impl<X> From<X> for GlobalEventSubscription where X: Fn(&wlc::GlobalEvent, &wlc::Attached<wl_registry::WlRegistry>, &wlc::DispatchData) + 'static, { fn from(closure: X) -> Self { Self { id: 0, sub: std::sync::Arc::new(closure), } } } pub trait GlobalEventDispatch { fn subscribe(&self, sub: impl Into<GlobalEventSubscription>) -> GlobalEventSubscription; #[expect(dead_code)] // Until it's not dead fn release(&self, s: &GlobalEventSubscription); } pub(super) struct Dispatcher { incr: crate::Counter, subscriptions: std::cell::RefCell<BTreeMap<u64, GlobalEventSubscription>>, } impl Default for Dispatcher { fn default() -> Self { Self { incr: crate::Counter::new(), subscriptions: std::cell::RefCell::new(BTreeMap::new()), } } } impl Dispatcher { fn consume( &self, event: &wlc::GlobalEvent, registry: &wlc::Attached<wl_registry::WlRegistry>, ctx: &wlc::DispatchData, ) { for (_, sub) in self.subscriptions.borrow().iter() { sub.consume(event, registry, ctx); } } } impl GlobalEventDispatch for Dispatcher { fn subscribe(&self, sub: impl Into<GlobalEventSubscription>) -> GlobalEventSubscription { let sub = sub.into().with_id(self.incr.next()); self.subscriptions.borrow_mut().insert(sub.id, sub.clone()); sub } fn release(&self, s: &GlobalEventSubscription) { self.subscriptions.borrow_mut().remove(&s.id); } } pub(super) struct Environment { pub(super) display: wlc::Display, pub(super) registry: wlc::GlobalManager, pub(super) xdg_base: wlc::Main<xdg_wm_base::XdgWmBase>, pub(super) queue: std::rc::Rc<std::cell::RefCell<wlc::EventQueue>>, dispatcher: std::sync::Arc<Dispatcher>, } impl GlobalEventDispatch for Environment { fn subscribe(&self, sub: impl Into<GlobalEventSubscription>) -> GlobalEventSubscription { self.dispatcher.subscribe(sub) } fn release(&self, s: &GlobalEventSubscription) { self.dispatcher.release(s) } } impl GlobalEventDispatch for std::sync::Arc<Environment> { fn subscribe(&self, sub: impl Into<GlobalEventSubscription>) -> GlobalEventSubscription { self.dispatcher.subscribe(sub) } fn release(&self, s: &GlobalEventSubscription) { self.dispatcher.release(s) } } pub(super) fn new(dispatcher: Dispatcher) -> Result<Environment, error::Error> { let dispatcher = std::sync::Arc::new(dispatcher); let d = wlc::Display::connect_to_env()?; let mut queue = d.create_event_queue(); let handle = d.attach(queue.token()); let registry = wlc::GlobalManager::new_with_cb(&handle, { let dispatcher = dispatcher.clone(); move |event, registry, ctx| { dispatcher.consume(&event, &registry, &ctx); } }); // do a round trip to make sure we have all the globals queue .sync_roundtrip(&mut (), |_, _, _| unreachable!()) .map_err(error::Error::fatal)?; // 3 is the max version supported by wayland-rs 0.29.5 let xdg_base = registry .instantiate_range::<xdg_wm_base::XdgWmBase>(1, 3) .map_err(|e| error::Error::global("xdg_wm_base", 1, e))?; // We do this to make sure wayland knows we're still responsive. // // NOTE: This means that clients mustn't hold up the event loop, or else wayland might kill // your app's connection. Move *everything* to another thread, including e.g. file i/o, // computation, network, ... This is good practice for all back-ends: it will improve // responsiveness. xdg_base.quick_assign(|xdg_base, event, ctx| { tracing::debug!( "global xdg_base events {:?} {:?} {:?}", xdg_base, event, ctx ); match event { xdg_wm_base::Event::Ping { serial } => xdg_base.pong(serial), _ => (), } }); let env = Environment { queue: std::rc::Rc::new(std::cell::RefCell::new(queue)), display: d, registry, xdg_base, dispatcher, }; Ok(env) } #[allow(unused)] pub(super) fn print(reg: &wlc::GlobalManager) { let mut globals_list = reg.list(); globals_list.sort_by(|(_, name1, version1), (_, name2, version2)| { name1.cmp(name2).then(version1.cmp(version2)) }); for (id, name, version) in globals_list.into_iter() { tracing::debug!("{:?}@{:?} - {:?}", name, version, id); } } pub(super) fn count(reg: &wlc::GlobalManager, i: &str) -> usize { reg.list().iter().filter(|(_, name, _)| name == i).count() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/mod.rs
druid-shell/src/backend/wayland/mod.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! wayland platform support // TODO: Remove this and fix the non-Send/Sync Arc issues #![allow(clippy::arc_with_non_send_sync)] pub mod application; pub mod clipboard; mod display; pub mod error; mod events; pub mod keyboard; pub mod menu; mod outputs; pub mod pointers; pub mod screen; pub mod surfaces; pub mod window; /// Little enum to make it clearer what some return values mean. #[derive(Copy, Clone)] enum Changed { Changed, Unchanged, } impl Changed { fn is_changed(self) -> bool { matches!(self, Changed::Changed) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/window.rs
druid-shell/src/backend/wayland/window.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #![allow(clippy::single_match)] use tracing; use wayland_protocols::xdg_shell::client::xdg_popup; use wayland_protocols::xdg_shell::client::xdg_positioner; use wayland_protocols::xdg_shell::client::xdg_surface; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, WaylandWindowHandle}; use super::application::{self, Timer}; use super::{error::Error, menu::Menu, outputs, surfaces}; use crate::Region; use crate::{ dialog::FileDialogOptions, error::Error as ShellError, kurbo::{Insets, Point, Rect, Size}, mouse::{Cursor, CursorDesc}, piet::PietText, scale::Scale, text::Event, window::{self, FileDialogToken, TimerToken, WinHandler, WindowLevel}, TextFieldToken, }; pub use surfaces::idle::Handle as IdleHandle; // holds references to the various components for a window implementation. struct Inner { pub(super) id: u64, pub(super) decor: Box<dyn surfaces::Decor>, pub(super) surface: Box<dyn surfaces::Handle>, pub(super) outputs: Box<dyn surfaces::Outputs>, pub(super) popup: Box<dyn surfaces::Popup>, pub(super) appdata: std::sync::Weak<application::Data>, } #[derive(Clone)] pub struct WindowHandle { inner: std::sync::Arc<Inner>, } impl surfaces::Outputs for WindowHandle { fn removed(&self, o: &outputs::Meta) { self.inner.outputs.removed(o) } fn inserted(&self, o: &outputs::Meta) { self.inner.outputs.inserted(o) } } impl surfaces::Popup for WindowHandle { fn surface( &self, popup: &wayland_client::Main<xdg_surface::XdgSurface>, pos: &wayland_client::Main<xdg_positioner::XdgPositioner>, ) -> Result<wayland_client::Main<xdg_popup::XdgPopup>, Error> { self.inner.popup.surface(popup, pos) } } impl WindowHandle { pub(super) fn new( outputs: impl Into<Box<dyn surfaces::Outputs>>, decor: impl Into<Box<dyn surfaces::Decor>>, surface: impl Into<Box<dyn surfaces::Handle>>, popup: impl Into<Box<dyn surfaces::Popup>>, appdata: impl Into<std::sync::Weak<application::Data>>, ) -> Self { Self { inner: std::sync::Arc::new(Inner { id: surfaces::GLOBAL_ID.next(), outputs: outputs.into(), decor: decor.into(), surface: surface.into(), popup: popup.into(), appdata: appdata.into(), }), } } pub fn id(&self) -> u64 { self.inner.id } pub fn show(&self) { tracing::debug!("show initiated"); } pub fn resizable(&self, _resizable: bool) { tracing::warn!("resizable is unimplemented on wayland"); } pub fn show_titlebar(&self, _show_titlebar: bool) { tracing::warn!("show_titlebar is unimplemented on wayland"); } pub fn set_position(&self, _position: Point) { tracing::warn!("set_position is unimplemented on wayland"); } pub fn set_always_on_top(&self, _always_on_top: bool) { // Not supported by wayland tracing::warn!("set_always_on_top is unimplemented on wayland"); } pub fn set_mouse_pass_through(&self, _mouse_pass_thorugh: bool) { tracing::warn!("set_mouse_pass_through unimplemented"); } pub fn set_input_region(&self, region: Option<Region>) { self.inner.surface.set_input_region(region); } pub fn get_position(&self) -> Point { tracing::warn!("get_position is unimplemented on wayland"); Point::ZERO } pub fn content_insets(&self) -> Insets { Insets::from(0.) } pub fn set_size(&self, size: Size) { self.inner.surface.set_size(size); } pub fn get_size(&self) -> Size { self.inner.surface.get_size() } pub fn is_foreground_window(&self) -> bool { true } pub fn set_window_state(&mut self, _current_state: window::WindowState) { tracing::warn!("set_window_state is unimplemented on wayland"); } pub fn get_window_state(&self) -> window::WindowState { tracing::warn!("get_window_state is unimplemented on wayland"); window::WindowState::Maximized } pub fn handle_titlebar(&self, _val: bool) { tracing::warn!("handle_titlebar is unimplemented on wayland"); } /// Close the window. pub fn close(&self) { if let Some(appdata) = self.inner.appdata.upgrade() { tracing::trace!( "closing window initiated {:?}", appdata.active_surface_id.borrow() ); appdata.handles.borrow_mut().remove(&self.id()); appdata.active_surface_id.borrow_mut().pop_front(); self.inner.surface.release(); tracing::trace!( "closing window completed {:?}", appdata.active_surface_id.borrow() ); } } /// Hide the window. pub fn hide(&self) { tracing::warn!("hide is unimplemented on wayland"); } /// Bring this window to the front of the window stack and give it focus. pub fn bring_to_front_and_focus(&self) { tracing::warn!("bring_to_front_and_focus is unimplemented on wayland"); } /// Request a new paint, but without invalidating anything. pub fn request_anim_frame(&self) { self.inner.surface.request_anim_frame(); } /// Request invalidation of the entire window contents. pub fn invalidate(&self) { self.inner.surface.invalidate(); } /// Request invalidation of one rectangle, which is given in display points relative to the /// drawing area. pub fn invalidate_rect(&self, rect: Rect) { self.inner.surface.invalidate_rect(rect); } pub fn text(&self) -> PietText { PietText::new() } pub fn add_text_field(&self) -> TextFieldToken { TextFieldToken::next() } pub fn remove_text_field(&self, token: TextFieldToken) { self.inner.surface.remove_text_field(token); } pub fn set_focused_text_field(&self, active_field: Option<TextFieldToken>) { self.inner.surface.set_focused_text_field(active_field); } pub fn update_text_field(&self, _token: TextFieldToken, _update: Event) { // noop until we get a real text input implementation } pub fn request_timer(&self, deadline: std::time::Instant) -> TimerToken { let appdata = match self.inner.appdata.upgrade() { Some(d) => d, None => { tracing::warn!("requested timer on a window that was destroyed"); return Timer::new(self.id(), deadline).token(); } }; let now = instant::Instant::now(); let mut timers = appdata.timers.borrow_mut(); let sooner = timers .peek() .map(|timer| deadline < timer.deadline()) .unwrap_or(true); let timer = Timer::new(self.id(), deadline); timers.push(timer); // It is possible that the deadline has passed since it was set. let timeout = if deadline < now { std::time::Duration::ZERO } else { deadline - now }; if sooner { appdata.timer_handle.cancel_all_timeouts(); appdata.timer_handle.add_timeout(timeout, timer.token()); } timer.token() } pub fn set_cursor(&mut self, cursor: &Cursor) { if let Some(appdata) = self.inner.appdata.upgrade() { appdata.set_cursor(cursor); } } pub fn make_cursor(&self, _desc: &CursorDesc) -> Option<Cursor> { tracing::warn!("unimplemented make_cursor initiated"); None } pub fn open_file(&mut self, _options: FileDialogOptions) -> Option<FileDialogToken> { tracing::warn!("unimplemented open_file"); None } pub fn save_as(&mut self, _options: FileDialogOptions) -> Option<FileDialogToken> { tracing::warn!("unimplemented save_as"); None } /// Get a handle that can be used to schedule an idle task. pub fn get_idle_handle(&self) -> Option<IdleHandle> { Some(self.inner.surface.get_idle_handle()) } /// Get the `Scale` of the window. pub fn get_scale(&self) -> Result<Scale, ShellError> { Ok(self.inner.surface.get_scale()) } pub fn set_menu(&self, _menu: Menu) { tracing::warn!("set_menu not implement for wayland"); } pub fn show_context_menu(&self, _menu: Menu, _pos: Point) { tracing::warn!("show_context_menu not implement for wayland"); } pub fn set_title(&self, title: impl Into<String>) { self.inner.decor.set_title(title); } pub(super) fn run_idle(&self) { self.inner.surface.run_idle(); } pub(super) fn data(&self) -> Option<std::sync::Arc<surfaces::surface::Data>> { self.inner.surface.data() } } impl std::cmp::PartialEq for WindowHandle { fn eq(&self, rhs: &Self) -> bool { self.id() == rhs.id() } } impl Eq for WindowHandle {} impl std::default::Default for WindowHandle { fn default() -> WindowHandle { WindowHandle { inner: std::sync::Arc::new(Inner { id: surfaces::GLOBAL_ID.next(), outputs: Box::<surfaces::surface::Dead>::default(), decor: Box::<surfaces::surface::Dead>::default(), surface: Box::<surfaces::surface::Dead>::default(), popup: Box::<surfaces::surface::Dead>::default(), appdata: std::sync::Weak::new(), }), } } } #[cfg(feature = "raw-win-handle")] unsafe impl HasRawWindowHandle for WindowHandle { fn raw_window_handle(&self) -> RawWindowHandle { tracing::error!("HasRawWindowHandle trait not implemented for wasm."); RawWindowHandle::Wayland(WaylandWindowHandle::empty()) } } #[derive(Clone, PartialEq, Eq)] pub struct CustomCursor; /// Builder abstraction for creating new windows pub(crate) struct WindowBuilder { appdata: std::sync::Weak<application::Data>, handler: Option<Box<dyn WinHandler>>, title: String, menu: Option<Menu>, position: Option<Point>, level: WindowLevel, state: Option<window::WindowState>, // pre-scaled size: Size, min_size: Option<Size>, resizable: bool, show_titlebar: bool, } impl WindowBuilder { pub fn new(app: application::Application) -> WindowBuilder { WindowBuilder { appdata: std::sync::Arc::downgrade(&app.data), handler: None, title: String::new(), menu: None, size: Size::new(0.0, 0.0), position: None, level: WindowLevel::AppWindow, state: None, min_size: None, resizable: true, show_titlebar: true, } } pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.handler = Some(handler); } pub fn set_size(&mut self, size: Size) { self.size = size; } pub fn set_min_size(&mut self, size: Size) { self.min_size = Some(size); } pub fn resizable(&mut self, resizable: bool) { self.resizable = resizable; } pub fn show_titlebar(&mut self, show_titlebar: bool) { self.show_titlebar = show_titlebar; } pub fn set_always_on_top(&mut self, _always_on_top: bool) { // This needs to be handled manually by the user with the desktop environment. tracing::warn!( "set_always_on_top unimplemented for wayland, since wayland is more restrictive." ); } pub fn set_transparent(&mut self, _transparent: bool) { tracing::warn!( "set_transparent unimplemented for wayland, it allows transparency by default" ); } pub fn set_position(&mut self, position: Point) { self.position = Some(position); } pub fn set_level(&mut self, level: WindowLevel) { self.level = level; } pub fn set_window_state(&mut self, state: window::WindowState) { self.state = Some(state); } pub fn set_title(&mut self, title: impl Into<String>) { self.title = title.into(); } pub fn set_menu(&mut self, menu: Menu) { self.menu = Some(menu); } pub fn build(self) -> Result<WindowHandle, ShellError> { if self.menu.is_some() { tracing::warn!("menus unimplemented for wayland"); } let level = self.level.clone(); if let WindowLevel::Modal(parent) = level { return self.create_popup(parent); } if let WindowLevel::DropDown(parent) = level { return self.create_popup(parent); } let appdata = match self.appdata.upgrade() { Some(d) => d, None => return Err(ShellError::ApplicationDropped), }; let handler = self.handler.expect("must set a window handler"); let surface = surfaces::toplevel::Surface::new(appdata.clone(), handler, self.size, self.min_size); (&surface as &dyn surfaces::Decor).set_title(self.title); let handle = WindowHandle::new( surface.clone(), surface.clone(), surface.clone(), surface.clone(), self.appdata.clone(), ); if appdata .handles .borrow_mut() .insert(handle.id(), handle.clone()) .is_some() { return Err(ShellError::Platform(Error::string( "wayland should use a unique id", ))); } appdata .active_surface_id .borrow_mut() .push_front(handle.id()); surface.with_handler({ let handle = handle.clone(); move |winhandle| winhandle.connect(&handle.into()) }); Ok(handle) } fn create_popup(self, parent: window::WindowHandle) -> Result<WindowHandle, ShellError> { let dim = self.min_size.unwrap_or(Size::ZERO); let dim = Size::new(dim.width.max(1.), dim.height.max(1.)); let dim = Size::new( self.size.width.max(dim.width), self.size.height.max(dim.height), ); let config = surfaces::popup::Config::default() .with_size(dim) .with_offset(Into::into( self.position.unwrap_or_else(|| Into::into((0., 0.))), )); tracing::debug!("popup {:?}", config); popup::create(&parent.0, &config, self.appdata, self.handler) } } #[allow(unused)] pub mod layershell { use crate::error::Error as ShellError; use crate::window::WinHandler; use super::WindowHandle; use crate::backend::wayland::application::{Application, Data}; use crate::backend::wayland::error::Error; use crate::backend::wayland::surfaces; /// Builder abstraction for creating new windows pub(crate) struct Builder { appdata: std::sync::Weak<Data>, winhandle: Option<Box<dyn WinHandler>>, pub(crate) config: surfaces::layershell::Config, } impl Builder { pub fn new(app: Application) -> Builder { Builder { appdata: std::sync::Arc::downgrade(&app.data), config: surfaces::layershell::Config::default(), winhandle: None, } } pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.winhandle = Some(handler); } pub fn build(self) -> Result<WindowHandle, ShellError> { let appdata = match self.appdata.upgrade() { Some(d) => d, None => return Err(ShellError::ApplicationDropped), }; let winhandle = match self.winhandle { Some(winhandle) => winhandle, None => { return Err(ShellError::Platform(Error::string( "window handler required", ))) } }; let surface = surfaces::layershell::Surface::new(appdata.clone(), winhandle, self.config.clone()); let handle = WindowHandle::new( surface.clone(), surfaces::surface::Dead, surface.clone(), surface.clone(), self.appdata.clone(), ); if appdata .handles .borrow_mut() .insert(handle.id(), handle.clone()) .is_some() { panic!("wayland should use unique object IDs"); } appdata .active_surface_id .borrow_mut() .push_front(handle.id()); surface.with_handler({ let handle = handle.clone(); move |winhandle| winhandle.connect(&handle.into()) }); Ok(handle) } } } #[allow(unused)] pub mod popup { use crate::error::Error as ShellError; use crate::window::WinHandler; use super::WindowBuilder; use super::WindowHandle; use crate::backend::wayland::application::{Application, Data}; use crate::backend::wayland::error::Error; use crate::backend::wayland::surfaces; pub(super) fn create( parent: &WindowHandle, config: &surfaces::popup::Config, wappdata: std::sync::Weak<Data>, winhandle: Option<Box<dyn WinHandler>>, ) -> Result<WindowHandle, ShellError> { let appdata = match wappdata.upgrade() { Some(d) => d, None => return Err(ShellError::ApplicationDropped), }; let winhandle = match winhandle { Some(winhandle) => winhandle, None => { return Err(ShellError::Platform(Error::string( "window handler required", ))) } }; // compute the initial window size. let updated = config.clone(); let surface = match surfaces::popup::Surface::new(appdata.clone(), winhandle, updated, parent) { Err(cause) => return Err(ShellError::Platform(cause)), Ok(s) => s, }; let handle = WindowHandle::new( surface.clone(), surfaces::surface::Dead, surface.clone(), surface.clone(), wappdata, ); if appdata .handles .borrow_mut() .insert(handle.id(), handle.clone()) .is_some() { panic!("wayland should use unique object IDs"); } appdata .active_surface_id .borrow_mut() .push_front(handle.id()); surface.with_handler({ let handle = handle.clone(); move |winhandle| winhandle.connect(&handle.into()) }); Ok(handle) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/events.rs
druid-shell/src/backend/wayland/events.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Multiplexing events. //! //! Calloop is a wrapper around `epoll` essentially allowing us to *select* multiple file //! descriptors. We use it here to select events from a timer and from wayland. //! //! Based on `client-toolkit/src/event_loop.rs` in `smithay-client-toolkit` (MIT Licensed). use calloop::{ generic::{Fd, Generic}, Dispatcher, EventSource, Interest, Mode, }; use std::{cell::RefCell, io, rc::Rc}; use wayland_client::EventQueue; use super::{application, window}; /// A wrapper around the wayland event queue that calloop knows how to select. pub(crate) struct WaylandSource { appdata: std::sync::Arc<application::Data>, queue: Rc<RefCell<EventQueue>>, fd: Generic<Fd>, } impl WaylandSource { /// Wrap an `EventQueue` as a `WaylandSource`. pub fn new(appdata: std::sync::Arc<application::Data>) -> WaylandSource { let queue = appdata.wayland.queue.clone(); let fd = queue.borrow().display().get_connection_fd(); WaylandSource { appdata, queue, fd: Generic::from_fd(fd, Interest::READ, Mode::Level), } } /// Get a dispatcher that we can insert into our event loop. pub fn into_dispatcher( self, ) -> Dispatcher< Self, impl FnMut( window::WindowHandle, &mut Rc<RefCell<EventQueue>>, &mut std::sync::Arc<application::Data>, ) -> io::Result<u32>, > { Dispatcher::new(self, |_winhandle, queue, appdata| { queue .borrow_mut() .dispatch_pending(appdata, |event, object, _| { tracing::error!( "[druid-shell] Encountered an orphan event: {}@{} : {}", event.interface, object.as_ref().id(), event.name ); tracing::error!("all events should be handled: please raise an issue"); }) }) } } impl EventSource for WaylandSource { type Event = window::WindowHandle; type Metadata = Rc<RefCell<EventQueue>>; type Ret = io::Result<u32>; fn process_events<F>( &mut self, ready: calloop::Readiness, token: calloop::Token, mut callback: F, ) -> std::io::Result<()> where F: FnMut(window::WindowHandle, &mut Rc<RefCell<EventQueue>>) -> Self::Ret, { tracing::trace!("processing events invoked {:?} {:?}", ready, token); self.appdata.display_flushed.replace(false); let winhandle = match self.appdata.acquire_current_window() { Some(winhandle) => winhandle, None => { tracing::error!("unable to acquire current window"); return Ok(()); } }; // in case of readiness of the wayland socket we do the following in a loop, until nothing // more can be read: loop { // 1. read events from the socket if any are available if let Some(guard) = self.queue.borrow().prepare_read() { // might be None if some other thread read events before us, concurrently if let Err(e) = guard.read_events() { if e.kind() != io::ErrorKind::WouldBlock { return Err(e); } } } tracing::trace!("processing events initiated"); // 2. dispatch any pending event in the queue // propagate orphan events to the user let ret = callback(winhandle.clone(), &mut self.queue); tracing::trace!("processing events completed {:?}", ret); match ret { Ok(0) => { // no events were dispatched even after reading the socket, // nothing more to do, stop here break; } Ok(_) => {} Err(e) => { // in case of error, forward it and fast-exit return Err(e); } } } tracing::trace!("dispatching completed, flushing"); // 3. Once dispatching is finished, flush the responses to the compositor if let Err(e) = self.queue.borrow().display().flush() { if e.kind() != io::ErrorKind::WouldBlock { // in case of error, forward it and fast-exit return Err(e); } // WouldBlock error means the compositor could not process all our messages // quickly. Either it is slowed down or we are a spammer. // Should not really happen, if it does we do nothing and will flush again later. tracing::warn!("unable to flush display: {:?}", e); } else { self.appdata.display_flushed.replace(true); } tracing::trace!("event queue completed"); Ok(()) } fn register(&mut self, poll: &mut calloop::Poll, token: calloop::Token) -> std::io::Result<()> { self.fd.register(poll, token) } fn reregister( &mut self, poll: &mut calloop::Poll, token: calloop::Token, ) -> std::io::Result<()> { self.fd.reregister(poll, token) } fn unregister(&mut self, poll: &mut calloop::Poll) -> std::io::Result<()> { self.fd.unregister(poll) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/keyboard.rs
druid-shell/src/backend/wayland/keyboard.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::convert::TryInto; use wayland_client as wlc; use wayland_client::protocol::wl_keyboard; use wayland_client::protocol::wl_seat; use crate::keyboard_types::KeyState; use crate::text; use crate::KeyEvent; use crate::Modifiers; use super::application::Data; use super::surfaces::buffers; use crate::backend::shared::xkb; #[allow(unused)] #[derive(Clone)] struct CachedKeyPress { seat: u32, serial: u32, timestamp: u32, key: u32, repeat: bool, state: wayland_client::protocol::wl_keyboard::KeyState, queue: calloop::channel::Sender<KeyEvent>, } impl CachedKeyPress { fn repeat(&self) -> Self { let mut c = self.clone(); c.repeat = true; c } } #[derive(Debug, Clone)] struct Repeat { rate: std::time::Duration, delay: std::time::Duration, } impl Default for Repeat { fn default() -> Self { Self { rate: std::time::Duration::from_millis(40), delay: std::time::Duration::from_millis(600), } } } struct Keyboard { /// Whether we've currently got keyboard focus. focused: bool, repeat: Repeat, last_key_press: Option<CachedKeyPress>, xkb_context: xkb::Context, xkb_keymap: std::cell::RefCell<Option<xkb::Keymap>>, xkb_state: std::cell::RefCell<Option<xkb::State>>, xkb_mods: std::cell::Cell<Modifiers>, } impl Default for Keyboard { fn default() -> Self { Self { focused: false, repeat: Repeat::default(), last_key_press: None, xkb_context: xkb::Context::new(), xkb_keymap: std::cell::RefCell::new(None), xkb_state: std::cell::RefCell::new(None), xkb_mods: std::cell::Cell::new(Modifiers::empty()), } } } impl Keyboard { fn focused(&mut self, updated: bool) { self.focused = updated; } fn repeat(&mut self, u: Repeat) { self.repeat = u; } fn replace_last_key_press(&mut self, u: Option<CachedKeyPress>) { self.last_key_press = u; } fn release_last_key_press(&self, current: &CachedKeyPress) -> Option<CachedKeyPress> { match &self.last_key_press { None => None, // nothing to do. Some(last) => { if last.serial >= current.serial { return Some(last.clone()); } if last.key != current.key { return Some(last.clone()); } None } } } fn keystroke<'a>(&'a mut self, keystroke: &'a CachedKeyPress) { let keystate = match keystroke.state { wl_keyboard::KeyState::Released => { self.replace_last_key_press(self.release_last_key_press(keystroke)); KeyState::Up } wl_keyboard::KeyState::Pressed => { self.replace_last_key_press(Some(keystroke.repeat())); KeyState::Down } _ => panic!("unrecognised key event"), }; let mut event = self.xkb_state.borrow_mut().as_mut().unwrap().key_event( keystroke.key, keystate, keystroke.repeat, ); event.mods = self.xkb_mods.get(); if let Err(cause) = keystroke.queue.send(event) { tracing::error!("failed to send Druid key event: {:?}", cause); } } fn consume( &mut self, seat: u32, event: wl_keyboard::Event, keyqueue: calloop::channel::Sender<KeyEvent>, ) { tracing::trace!("consume {:?} -> {:?}", seat, event); match event { wl_keyboard::Event::Keymap { format, fd, size } => { if !matches!(format, wl_keyboard::KeymapFormat::XkbV1) { panic!("only xkb keymap supported for now"); } // TODO to test memory ownership we copy the memory. That way we can deallocate it // and see if we get a segfault. let keymap_data = unsafe { buffers::Mmap::from_raw_private( fd, size.try_into().unwrap(), 0, size.try_into().unwrap(), ) .unwrap() .as_ref() .to_vec() }; // keymap data is '\0' terminated. let keymap = self.xkb_context.keymap_from_slice(&keymap_data); let keymapstate = keymap.state(); self.xkb_keymap.replace(Some(keymap)); self.xkb_state.replace(Some(keymapstate)); } wl_keyboard::Event::Enter { .. } => { self.focused(true); } wl_keyboard::Event::Leave { .. } => { self.focused(false); } wl_keyboard::Event::Key { serial, time, state, key, } => { tracing::trace!( "key stroke registered {:?} {:?} {:?} {:?}", time, serial, key, state ); self.keystroke(&CachedKeyPress { repeat: false, seat, serial, timestamp: time, key: key + 8, // TODO: understand the magic 8. state, queue: keyqueue, }) } wl_keyboard::Event::Modifiers { .. } => { self.xkb_mods.replace(event_to_mods(event)); } wl_keyboard::Event::RepeatInfo { rate, delay } => { tracing::trace!("keyboard repeat info received {:?} {:?}", rate, delay); self.repeat(Repeat { rate: std::time::Duration::from_millis((1000 / rate) as u64), delay: std::time::Duration::from_millis(delay as u64), }); } evt => { tracing::warn!("unimplemented keyboard event: {:?}", evt); } } } } pub(super) struct State { apptx: calloop::channel::Sender<KeyEvent>, apprx: std::cell::RefCell<Option<calloop::channel::Channel<KeyEvent>>>, tx: calloop::channel::Sender<(u32, wl_keyboard::Event, calloop::channel::Sender<KeyEvent>)>, } impl Default for State { fn default() -> Self { let (apptx, apprx) = calloop::channel::channel::<KeyEvent>(); let (tx, rx) = calloop::channel::channel::<( u32, wl_keyboard::Event, calloop::channel::Sender<KeyEvent>, )>(); let state = Self { apptx, apprx: std::cell::RefCell::new(Some(apprx)), tx, }; std::thread::spawn(move || { let mut eventloop: calloop::EventLoop<(calloop::LoopSignal, Keyboard)> = calloop::EventLoop::try_new() .expect("failed to initialize the keyboard event loop!"); let signal = eventloop.get_signal(); let handle = eventloop.handle(); let repeat = calloop::timer::Timer::<CachedKeyPress>::new().unwrap(); handle .insert_source(rx, { let repeater = repeat.handle(); move |event, _ignored, state| { let event = match event { calloop::channel::Event::Closed => { tracing::info!("keyboard event loop closed shutting down"); state.0.stop(); return; } calloop::channel::Event::Msg(keyevent) => keyevent, }; state.1.consume(event.0, event.1, event.2); match &state.1.last_key_press { None => repeater.cancel_all_timeouts(), Some(cached) => { repeater.cancel_all_timeouts(); repeater.add_timeout(state.1.repeat.delay, cached.clone()); } }; } }) .unwrap(); // generate repeat keypresses. handle .insert_source(repeat, |event, timer, state| { timer.add_timeout(state.1.repeat.rate, event.clone()); state.1.keystroke(&event); }) .unwrap(); tracing::debug!("keyboard event loop initiated"); eventloop .run( std::time::Duration::from_secs(60), &mut (signal, Keyboard::default()), |_ignored| { tracing::trace!("keyboard event loop idle"); }, ) .expect("keyboard event processing failed"); tracing::debug!("keyboard event loop completed"); }); state } } struct ModMap(u32, Modifiers); impl ModMap { fn merge(self, m: Modifiers, mods: u32, locked: u32) -> Modifiers { if self.0 & mods == 0 && self.0 & locked == 0 { return m; } m | self.1 } } const MOD_SHIFT: ModMap = ModMap(1, Modifiers::SHIFT); const MOD_CAP_LOCK: ModMap = ModMap(2, Modifiers::CAPS_LOCK); const MOD_CTRL: ModMap = ModMap(4, Modifiers::CONTROL); const MOD_ALT: ModMap = ModMap(8, Modifiers::ALT); const MOD_NUM_LOCK: ModMap = ModMap(16, Modifiers::NUM_LOCK); const MOD_META: ModMap = ModMap(64, Modifiers::META); pub fn event_to_mods(event: wl_keyboard::Event) -> Modifiers { match event { wl_keyboard::Event::Modifiers { mods_depressed, mods_locked, .. } => { let mods = Modifiers::empty(); let mods = MOD_SHIFT.merge(mods, mods_depressed, mods_locked); let mods = MOD_CAP_LOCK.merge(mods, mods_depressed, mods_locked); let mods = MOD_CTRL.merge(mods, mods_depressed, mods_locked); let mods = MOD_ALT.merge(mods, mods_depressed, mods_locked); let mods = MOD_NUM_LOCK.merge(mods, mods_depressed, mods_locked); MOD_META.merge(mods, mods_depressed, mods_locked) } _ => Modifiers::empty(), } } pub struct Manager { inner: std::sync::Arc<State>, } impl Default for Manager { fn default() -> Self { Self { inner: std::sync::Arc::new(State::default()), } } } impl Manager { pub(super) fn attach( &self, id: u32, seat: wlc::Main<wl_seat::WlSeat>, ) -> wlc::Main<wl_keyboard::WlKeyboard> { let keyboard = seat.get_keyboard(); keyboard.quick_assign({ let tx = self.inner.tx.clone(); let queue = self.inner.apptx.clone(); move |_, event, _| { if let Err(cause) = tx.send((id, event, queue.clone())) { tracing::error!("failed to transmit keyboard event {:?}", cause); }; } }); keyboard } // TODO turn struct into a calloop event source. pub(super) fn events(&self, handle: &calloop::LoopHandle<std::sync::Arc<Data>>) { let rx = self.inner.apprx.borrow_mut().take().unwrap(); handle .insert_source(rx, { move |evt, _ignored, appdata| { let evt = match evt { calloop::channel::Event::Msg(e) => e, calloop::channel::Event::Closed => { tracing::info!("keyboard events receiver closed"); return; } }; if let Some(winhandle) = appdata.acquire_current_window() { if let Some(windata) = winhandle.data() { windata.with_handler({ let windata = windata.clone(); move |handler| match evt.state { KeyState::Up => { handler.key_up(evt.clone()); tracing::trace!( "key press event up {:?} {:?}", evt, windata.active_text_input.get() ); } KeyState::Down => { let handled = text::simulate_input( handler, windata.active_text_input.get(), evt.clone(), ); tracing::trace!( "key press event down {:?} {:?} {:?}", handled, evt, windata.active_text_input.get() ); } } }); } } } }) .unwrap(); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/screen.rs
druid-shell/src/backend/wayland/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! wayland Monitors and Screen information. use crate::kurbo::Rect; use crate::screen::Monitor; use super::error; use super::outputs; fn _get_monitors() -> Result<Vec<Monitor>, error::Error> { let metas = outputs::current()?; let monitors: Vec<Monitor> = metas .iter() .map(|m| { let rect = Rect::from_origin_size( (m.position.x as f64, m.position.y as f64), (m.logical.width as f64, m.logical.height as f64), ); Monitor::new(false, rect, rect) }) .collect(); Ok(monitors) } pub(crate) fn get_monitors() -> Vec<Monitor> { match _get_monitors() { Ok(m) => m, Err(cause) => { tracing::error!( "unable to detect monitors, failed to connect to wayland server {:?}", cause ); Vec::new() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/outputs/mod.rs
druid-shell/src/backend/wayland/outputs/mod.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use wayland_client as wlc; use wayland_client::protocol::wl_output; use super::display; use super::error; pub mod output; #[derive(Debug, Clone)] #[allow(unused)] pub enum Event { Located(Meta), Removed(Meta), } pub fn auto( env: &impl display::GlobalEventDispatch, ) -> Result<calloop::channel::Channel<Event>, error::Error> { tracing::debug!("detecting xdg outputs"); match output::detect(env) { Ok(rx) => return Ok(rx), Err(cause) => tracing::info!("unable to detect xdg outputs {:?}", cause), } Err(error::Error::string("unable to detect display outputs")) } pub(super) fn current() -> Result<Vec<Meta>, error::Error> { let dispatcher = display::Dispatcher::default(); let rx = auto(&dispatcher)?; let env = display::new(dispatcher)?; let mut cache = std::collections::BTreeMap::new(); let mut eventloop: calloop::EventLoop<( calloop::LoopSignal, &mut std::collections::BTreeMap<String, Meta>, )> = calloop::EventLoop::try_new().expect("failed to initialize the displays event loop!"); let signal = eventloop.get_signal(); let handle = eventloop.handle(); handle .insert_source(rx, { move |event, _ignored, (signal, cache)| { let event = match event { calloop::channel::Event::Msg(event) => event, calloop::channel::Event::Closed => return signal.stop(), }; match event { Event::Located(meta) => { cache.insert(meta.name.clone(), meta); } Event::Removed(meta) => { cache.remove(&meta.name); } } } }) .map_err(error::Error::error)?; // do a round trip to flush commands. let mut queue = env.queue.try_borrow_mut().map_err(error::Error::error)?; queue .sync_roundtrip(&mut (), |_, _, _| unreachable!()) .map_err(error::Error::error)?; let expected = display::count(&env.registry, "wl_output"); let result: std::sync::Arc<std::cell::RefCell<Vec<Meta>>> = std::sync::Arc::new(std::cell::RefCell::new(Vec::new())); eventloop .run( std::time::Duration::from_secs(1), &mut (signal, &mut cache), { let result = result.clone(); move |(signal, cache)| { if expected <= cache.len() { result.replace(cache.values().cloned().collect()); signal.stop(); } let res = queue .sync_roundtrip(&mut (), |_, _, _| unreachable!()) .map_err(error::Error::error); if let Err(cause) = res { tracing::error!("wayland sync failed {:?}", cause); signal.stop(); } } }, ) .map_err(error::Error::error)?; Ok(result.take()) } #[allow(dead_code)] pub trait Wayland { fn consume<'a>( &'a mut self, obj: &'a wlc::Main<wl_output::WlOutput>, event: &'a wl_output::Event, ); } #[derive(Clone, Debug, Default)] pub struct Dimensions { pub width: i32, pub height: i32, } impl From<(i32, i32)> for Dimensions { fn from(v: (i32, i32)) -> Self { Self { width: v.0, height: v.1, } } } #[derive(Clone, Debug, Default)] pub struct Position { pub x: i32, pub y: i32, } impl From<(i32, i32)> for Position { fn from(v: (i32, i32)) -> Self { Self { x: v.0, y: v.1 } } } #[derive(Debug, Default, Clone)] #[allow(dead_code)] pub struct Mode { pub logical: Dimensions, pub refresh: i32, pub preferred: bool, } #[derive(Clone, Debug)] pub struct Meta { pub output: Option<wl_output::WlOutput>, pub gid: u32, pub name: String, pub description: String, pub logical: Dimensions, pub refresh: i32, pub physical: Dimensions, pub subpixel: wl_output::Subpixel, pub transform: wl_output::Transform, pub make: String, pub model: String, pub scale: f64, pub enabled: bool, pub position: Position, } impl Default for Meta { fn default() -> Self { Self { output: None, gid: Default::default(), name: Default::default(), description: Default::default(), logical: Default::default(), refresh: Default::default(), physical: Default::default(), position: Default::default(), subpixel: wl_output::Subpixel::Unknown, transform: wl_output::Transform::Normal, make: Default::default(), model: Default::default(), scale: Default::default(), enabled: Default::default(), } } } impl Meta { pub fn normalize(mut self) -> Self { match self.transform { wl_output::Transform::Flipped270 | wl_output::Transform::_270 => { self.logical = Dimensions::from((self.logical.height, self.logical.width)); self.physical = Dimensions::from((self.physical.height, self.physical.width)); } _ => {} } self } pub fn id(&self) -> u32 { self.gid } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/outputs/output.rs
druid-shell/src/backend/wayland/outputs/output.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use super::super::display; use super::super::error; use super::super::outputs; use wayland_client as wlc; use wayland_client::protocol::wl_output; use wayland_client::protocol::wl_registry; use wayland_protocols::unstable::xdg_output::v1::client::zxdg_output_manager_v1; use wayland_protocols::unstable::xdg_output::v1::client::zxdg_output_v1; pub fn detect( env: &impl display::GlobalEventDispatch, ) -> Result<calloop::channel::Channel<outputs::Event>, error::Error> { let (outputstx, outputsrx) = calloop::channel::channel::<outputs::Event>(); let xdg_output_manager_id: std::cell::RefCell<Option<u32>> = std::cell::RefCell::new(None); display::GlobalEventDispatch::subscribe(env, { move |event: &'_ wlc::GlobalEvent, registry: &'_ wlc::Attached<wl_registry::WlRegistry>, _ctx: &'_ wlc::DispatchData| { match event { wlc::GlobalEvent::New { id, interface, version, } => { let id = *id; let version = *version; if interface.as_str() == "zxdg_output_manager_v1" && version == 3 { xdg_output_manager_id.replace(Some(id)); return; } // We rely on wl_output::done() event so version 2 is our minimum, // it is also 9 years old so we can assume that any non-abandonware compositor uses it. if !(interface.as_str() == "wl_output" && version >= 2) { return; } let version = version.min(3); let output = registry.bind::<wl_output::WlOutput>(version, id); let xdgm = (*xdg_output_manager_id.borrow()).map(|xdgm_id| { registry.bind::<zxdg_output_manager_v1::ZxdgOutputManagerV1>(3, xdgm_id) }); let mut meta = Meta::default(); let mut xdgmeta = XdgMeta::new(); output.quick_assign({ let outputstx = outputstx.clone(); move |output, event, _ctx| { let mut m = match meta.consume(&output, &event) { Some(m) => m, None => return, }; if !xdgmeta.set_xdg_handled() { if let Some(xdgm) = &xdgm { let xdg_output = xdgm.get_xdg_output(&output); xdg_output.quick_assign({ let mut xdgmeta = xdgmeta.clone(); move |xdg_output, event, _ctx| { xdgmeta.consume(&xdg_output, &event); } }); return; } } xdgmeta.modify(&mut m); m.output = Some(output.detach()); if let Err(cause) = outputstx.send(outputs::Event::Located(m)) { tracing::warn!("unable to transmit output {:?}", cause); } } }); } wlc::GlobalEvent::Removed { interface, .. } => { if interface.as_str() != "wl_output" { return; } tracing::debug!("output removed event {:?} {:?}", registry, interface); } }; } }); Ok(outputsrx) } #[derive(Debug, Default)] struct XdgState { name: String, description: String, position: outputs::Position, logical: outputs::Dimensions, } #[derive(Clone, Debug)] struct XdgMeta { handled: bool, state: std::sync::Arc<std::cell::RefCell<XdgState>>, } impl XdgMeta { fn new() -> Self { Self { handled: false, state: std::sync::Arc::new(std::cell::RefCell::new(XdgState::default())), } } fn set_xdg_handled(&mut self) -> bool { let tmp = self.handled; self.handled = true; tmp } fn consume( &mut self, output: &wlc::Main<zxdg_output_v1::ZxdgOutputV1>, evt: &zxdg_output_v1::Event, ) { match evt { zxdg_output_v1::Event::Name { name } => { self.state.borrow_mut().name = name.clone(); } zxdg_output_v1::Event::Description { description } => { self.state.borrow_mut().description = description.clone(); } zxdg_output_v1::Event::LogicalPosition { x, y } => { self.state.borrow_mut().position = outputs::Position::from((*x, *y)); } zxdg_output_v1::Event::LogicalSize { width, height } => { self.state.borrow_mut().logical = outputs::Dimensions::from((*width, *height)); } _ => tracing::warn!("unused xdg_output_v1 event {:?} {:?}", output, evt), }; } fn modify(&self, meta: &mut outputs::Meta) { if !self.handled { return; } let state = self.state.borrow(); meta.name = state.name.clone(); meta.description = state.description.clone(); meta.position = state.position.clone(); meta.logical = state.logical.clone(); } } #[derive(Default)] struct Meta { meta: outputs::Meta, } impl Meta { /// Incorporate update data from the server for this output. fn consume( &mut self, output: &wlc::Main<wl_output::WlOutput>, evt: &wl_output::Event, ) -> Option<outputs::Meta> { match evt { wl_output::Event::Geometry { x, y, physical_width, physical_height, subpixel, make, model, transform, } => { self.meta.position = outputs::Position::from((*x, *y)); self.meta.physical = outputs::Dimensions::from((*physical_width, *physical_height)); self.meta.subpixel = *subpixel; self.meta.make = make.clone(); self.meta.model = model.clone(); self.meta.transform = *transform; None } wl_output::Event::Mode { flags, width, height, refresh, } => { if flags.contains(wl_output::Mode::Current) { self.meta.logical = outputs::Dimensions::from((*width, *height)); self.meta.refresh = *refresh; } None } wl_output::Event::Done => { self.meta.gid = wlc::Proxy::from(output.detach()).id(); self.meta.enabled = true; Some(self.meta.clone()) } wl_output::Event::Scale { factor } => { self.meta.scale = (*factor).into(); None } _ => { tracing::warn!("unknown output event {:?}", evt); // ignore possible future events None } } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/buffers.rs
druid-shell/src/backend/wayland/surfaces/buffers.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::kurbo::{Rect, Size}; use nix::{ errno::Errno, fcntl::OFlag, sys::{ mman::{mmap, munmap, shm_open, MapFlags, ProtFlags}, stat::Mode, }, unistd::{close, ftruncate}, }; use std::{ cell::{Cell, RefCell}, convert::{TryFrom, TryInto}, fmt, ops::{Deref, DerefMut}, os::{raw::c_void, unix::prelude::RawFd}, ptr::{self, NonNull}, rc::{Rc, Weak as WeakRc}, slice, }; use wayland_client::{ self as wl, protocol::{ wl_buffer::{self, WlBuffer}, wl_shm::{self, WlShm}, wl_shm_pool::WlShmPool, wl_surface::WlSurface, }, }; use super::surface; /// Number of bytes for a pixel (argb = 4) pub(super) const PIXEL_WIDTH: i32 = 4; /// Number of frames we need (2 for double buffering) pub(super) const NUM_FRAMES: i32 = 2; /// A collection of buffers that can change size. /// /// This object knows nothing about scaling or events. It just provides buffers to draw into. pub struct Buffers<const N: usize> { /// Release buffers which are just waiting to be freed. released: Cell<Vec<Buffer>>, /// The actual buffer objects. buffers: Cell<Option<[Buffer; N]>>, /// Which buffer is the next to present. Iterates through to `N-1` then wraps. Draw to this /// buffer pending: Cell<usize>, /// The physical size of the buffers. /// /// This will be different from the buffers' actual size if `recreate_buffers` is true. // NOTE: This really should support fractional scaling, use unstable protocol. size: Cell<RawSize>, /// Do we need to rebuild the framebuffers (size changed). recreate_buffers: Cell<bool>, /// This flag allows us to check that we only hand out a mutable ref to the buffer data once. /// Otherwise providing mutable access to the data would be unsafe. pending_buffer_borrowed: Cell<bool>, /// Shared memory to allocate buffers in shm: RefCell<Shm>, } impl<const N: usize> Buffers<N> { /// Create a new `Buffers` object. /// pub fn new(wl_shm: wl::Main<WlShm>, size: RawSize) -> Rc<Self> { assert!(N >= 2, "must be at least 2 buffers"); Rc::new(Self { released: Cell::new(Vec::new()), buffers: Cell::new(None), pending: Cell::new(0), size: Cell::new(size), recreate_buffers: Cell::new(true), pending_buffer_borrowed: Cell::new(false), shm: RefCell::new(Shm::new(wl_shm).expect("error allocating shared memory")), }) } /// Get the physical size of the buffer. pub fn size(&self) -> RawSize { self.size.get() } /// Request that the size of the buffer is changed. pub fn set_size(&self, updated: RawSize) { assert!(!updated.is_empty(), "window size must not be empty"); let old = self.size.replace(updated); self.recreate_buffers.set(old != updated); } /// Request painting the next frame. /// /// This calls into user code. To avoid re-entrancy, ensure that we are not already in user /// code (defer this call if necessary). /// /// We will call into `WindowData` to paint the frame, and present it. If no buffers are /// available we will set a flag, so that when one becomes available we immediately paint and /// present. This includes if we need to resize. pub fn request_paint(self: &Rc<Self>, window: &surface::Data) { tracing::trace!( "request_paint {:?} {:?}", self.size.get(), window.get_size() ); // if our size is empty there is nothing to do. if self.size.get().is_empty() { return; } if self.pending_buffer_borrowed.get() { panic!("called request_paint during painting"); } // recreate if necessary self.buffers_recreate(); // paint if we have a buffer available. if self.pending_buffer_released() { self.paint_unchecked(window); } // attempt to release any unused buffers. self.buffers_drop_unused(); } /// Paint the next frame, without checking if the buffer is free. fn paint_unchecked(self: &Rc<Self>, window: &surface::Data) { tracing::trace!("buffer.paint_unchecked"); let mut buf_data = self.pending_buffer_data().unwrap(); debug_assert!( self.pending_buffer_released(), "buffer in use/not initialized" ); window.paint( self.size.get(), &mut buf_data, self.recreate_buffers.replace(false), ); } // attempt to release unused buffers. fn buffers_drop_unused(&self) { let mut pool = self.released.take(); pool.retain(|b| { if b.in_use.get() { return true; } b.destroy(); false }); self.released.replace(pool); } fn buffers_invalidate(&self) { if let Some(buffers) = self.buffers.replace(None) { let mut tmp = self.released.take(); tmp.append(&mut buffers.to_vec()); self.released.replace(tmp); } } /// Destroy the current buffers, resize the shared memory pool if necessary, and create new /// buffers. fn buffers_recreate(&self) { if !self.recreate_buffers.get() { return; } debug_assert!(!self.pending_buffer_borrowed.get()); // move current buffers into the release queue to be cleaned up later. self.buffers_invalidate(); let new_buffer_size = self.size.get().buffer_size(N.try_into().unwrap()); // This is probably OOM if it fails, but we unwrap to report the underlying error. self.shm.borrow_mut().extend(new_buffer_size).unwrap(); let pool = self.shm.borrow_mut().create_pool(); self.buffers.set({ let mut buffers = vec![]; let size = self.size.get(); for i in 0..N { buffers.push(Buffer::create(&pool, i, size.width, size.height)); } Some(buffers.try_into().unwrap()) }); pool.destroy(); // Don't unset `recreate_buffers` here. We immediately call paint_unchecked, and need to // know if buffers were recreated (to invalidate the whole window). } fn with_buffers<T>(&self, f: impl FnOnce(&Option<[Buffer; N]>) -> T) -> T { let buffers = self.buffers.replace(None); let out = f(&buffers); self.buffers.set(buffers); out } /// Get a ref to the next buffer to draw to. fn with_pending_buffer<T>(&self, f: impl FnOnce(Option<&Buffer>) -> T) -> T { self.with_buffers(|buffers| f(buffers.as_ref().map(|buffers| &buffers[self.pending.get()]))) } /// For checking whether the next buffer is free. fn pending_buffer_released(&self) -> bool { self.with_pending_buffer(|buf| buf.map(|buf| !buf.in_use.get()).unwrap_or(false)) } /// Get the raw buffer data of the next buffer to draw to. /// /// Will return `None` if buffer already borrowed. fn pending_buffer_data(self: &Rc<Self>) -> Option<impl DerefMut<Target = [u8]>> { if self.pending_buffer_borrowed.get() { None } else { self.pending_buffer_borrowed.set(true); let frame_len = self.frame_len(); // Safety: we make sure the data is only loaned out once. unsafe { Some(BufferData { buffers: Rc::downgrade(self), mmap: self .shm .borrow() .mmap(frame_len * self.pending.get(), frame_len), }) } } } /// Signal to wayland that the pending buffer is ready to be presented, and switch the next /// buffer to be the pending one. pub(crate) fn attach(&self, window: &surface::Data) { self.with_pending_buffer(|buf| buf.unwrap().attach(&window.wl_surface.borrow())); self.pending.set((self.pending.get() + 1) % N); } fn frame_len(&self) -> usize { let size = self.size.get(); (PIXEL_WIDTH * size.width * size.height) .try_into() .expect("integer overflow") } } /// A wrapper round `WlBuffer` that tracks whether the buffer is released. /// /// No allocations on `clone`. #[derive(Debug, Clone)] pub struct Buffer { inner: wl::Main<WlBuffer>, in_use: Rc<Cell<bool>>, } impl Buffer { /// Create a new buffer using the given backing storage. It is the responsibility of the caller /// to ensure buffers don't overlap, and the backing storage has enough space. // Window handle is needed for the callback. pub fn create(pool: &wl::Main<WlShmPool>, idx: usize, width: i32, height: i32) -> Self { let offset = i32::try_from(idx).unwrap() * width * height * PIXEL_WIDTH; let stride = width * PIXEL_WIDTH; let inner = pool.create_buffer(offset, width, height, stride, wl_shm::Format::Argb8888); let in_use = Rc::new(Cell::new(false)); inner.quick_assign(with_cloned!(in_use; move |b, event, _dispatchdata| { tracing::trace!("buffer event: {:?} {:?}", b, event); match event { wl_buffer::Event::Release => { in_use.set(false); } _ => tracing::warn!("unhandled wayland buffer event: {:?} {:?}", b, event), } })); Buffer { inner, in_use } } pub fn attach(&self, wl_surface: &wl::Main<WlSurface>) { if self.in_use.get() { panic!("attaching an already in-use surface"); } self.in_use.set(true); wl_surface.attach(Some(&self.inner), 0, 0); } pub fn destroy(&self) { if self.in_use.get() { panic!("Destroying a buffer while it is in use"); } self.inner.destroy(); } } pub struct BufferData<const N: usize> { buffers: WeakRc<Buffers<N>>, mmap: Mmap, } impl<const N: usize> Deref for BufferData<N> { type Target = [u8]; fn deref(&self) -> &[u8] { self.mmap.deref() } } impl<const N: usize> DerefMut for BufferData<N> { fn deref_mut(&mut self) -> &mut [u8] { self.mmap.deref_mut() } } impl<const N: usize> Drop for BufferData<N> { fn drop(&mut self) { if let Some(buffers) = self.buffers.upgrade() { buffers.pending_buffer_borrowed.set(false); } } } /// RAII wrapper for shm_open (file descriptors for mmap'd shared memory) /// /// Designed to work like a vec: to manage extending when necessary. pub struct Shm { inner: RawFd, size: usize, // a handle on the wayland structure. wl_shm: wl::Main<WlShm>, } #[allow(unused)] impl Shm { /// Create a new shared memory object. Will be empty until resized. pub fn new(wl_shm: wl::Main<WlShm>) -> Result<Self, nix::Error> { // TODO is this a good way to choose a filename? What should our retry strategy be? let name = format!("/druid-wl-{}", rand::random::<i32>()); // Open the file we will use for shared memory. let fd = shm_open( name.as_str(), OFlag::O_RDWR | OFlag::O_EXCL | OFlag::O_CREAT, Mode::S_IRUSR | Mode::S_IWUSR, )?; // The memory is 0-sized until we resize it with `ftruncate`. let shm = Shm { inner: fd, size: 0, wl_shm, }; Ok(shm) } /// Resizes the shared memory pool. /// /// This is almost certainly unsafe if the server is using the memory TODO use locking /// (provided by wayland I think). pub fn resize(&mut self, new_size: i32) -> Result<(), nix::Error> { let new_size: usize = new_size.try_into().unwrap(); if self.size == new_size { return Ok(()); } // allocate the space (retry on interrupt) loop { match ftruncate(self.inner, new_size.try_into().unwrap()) { Ok(()) => { self.size = new_size; return Ok(()); } Err(Errno::EINTR) => { // continue (try again) } Err(e) => { return Err(e); } } } } /// Like `resize`, but doesn't shrink. pub fn extend(&mut self, new_size: i32) -> Result<(), nix::Error> { if self.size < new_size.try_into().unwrap() { self.resize(new_size) } else { Ok(()) } } pub fn size(&self) -> usize { self.size } /// Create a `WlShmPool` backed by our memory that will be mmap'd by the server. pub fn create_pool(&self) -> wl::Main<WlShmPool> { self.wl_shm .create_pool(self.inner, self.size.try_into().unwrap()) } /// A method to make all the data `1` (white). Useful for debugging. /// /// Safe only when no frames are in use. #[allow(unused)] pub fn fill_white(&mut self) { unsafe { let mut buf = self.mmap(0, self.size); for byte in buf.as_mut() { *byte = 0xff; } } } /// Get access to the shared memory for the given frame. /// /// # Safety /// /// It's not checked if any other process has access to the memory. Data races may occur if /// they do. pub unsafe fn mmap(&self, offset: usize, len: usize) -> Mmap { Mmap::from_raw(self.inner, self.size, offset, len).unwrap() } /// Closing with error checking pub fn close(self) -> Result<(), nix::Error> { close(self.inner) } } impl Drop for Shm { fn drop(&mut self) { // cannot handle errors in drop. let _ = close(self.inner); } } pub struct Mmap { ptr: NonNull<c_void>, size: usize, offset: usize, len: usize, } impl Mmap { /// `fd` and `size` are the whole memory you want to map. `offset` and `len` are there to /// provide extra protection (only giving you access to that part). /// /// # Safety /// /// Concurrent use of the memory we map to isn't checked. #[inline] pub unsafe fn from_raw( fd: RawFd, size: usize, offset: usize, len: usize, ) -> Result<Self, nix::Error> { Self::from_raw_inner(fd, size, offset, len, false) } #[inline] pub unsafe fn from_raw_private( fd: RawFd, size: usize, offset: usize, len: usize, ) -> Result<Self, nix::Error> { Self::from_raw_inner(fd, size, offset, len, true) } unsafe fn from_raw_inner( fd: RawFd, size: usize, offset: usize, len: usize, private: bool, ) -> Result<Self, nix::Error> { assert!(offset + len <= size, "{offset} + {len} <= {size}"); let map_flags = if private { MapFlags::MAP_PRIVATE } else { MapFlags::MAP_SHARED }; let ptr = mmap( ptr::null_mut(), size, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, map_flags, fd, 0, )?; Ok(Mmap { ptr: NonNull::new(ptr).unwrap(), size, offset, len, }) } } impl Deref for Mmap { type Target = [u8]; fn deref(&self) -> &[u8] { unsafe { let start = self.ptr.as_ptr().offset(self.offset.try_into().unwrap()); slice::from_raw_parts(start as *const u8, self.len) } } } impl DerefMut for Mmap { fn deref_mut(&mut self) -> &mut [u8] { unsafe { let start = self.ptr.as_ptr().offset(self.offset.try_into().unwrap()); slice::from_raw_parts_mut(start as *mut u8, self.len) } } } impl Drop for Mmap { fn drop(&mut self) { unsafe { if let Err(e) = munmap(self.ptr.as_ptr(), self.size) { log::warn!("Error unmapping memory: {}", e); } } } } #[derive(Copy, Clone, PartialEq, Eq)] pub struct RawSize { pub width: i32, pub height: i32, } impl RawSize { pub const ZERO: Self = Self { width: 0, height: 0, }; /// How many bytes do we need to store a frame of this size (in pixels) pub fn frame_size(self) -> i32 { // Check for overflow assert!(self.width.checked_mul(self.height).unwrap() < i32::MAX / PIXEL_WIDTH); self.width * self.height * PIXEL_WIDTH } /// Helper function to get the total buffer size we will need for all the frames. pub fn buffer_size(self, frames: i32) -> i32 { // Check for overflow assert!(self.width.checked_mul(self.height).unwrap() < i32::MAX / (PIXEL_WIDTH * frames)); self.width * self.height * PIXEL_WIDTH * frames } pub fn scale(self, scale: i32) -> Self { // NOTE no overflow checking atm. RawSize { width: self.width * scale, height: self.height * scale, } } pub fn to_rect(self) -> RawRect { RawRect { x0: 0, y0: 0, x1: self.width, y1: self.height, } } pub fn area(self) -> i32 { self.width * self.height } pub fn is_empty(self) -> bool { self.area() == 0 } } impl From<Size> for RawSize { fn from(s: Size) -> Self { let width = s.width as i32; let height = s.height as i32; // Sanity check assert!(width >= 0 && height >= 0); RawSize { width, height } } } impl From<RawSize> for Size { fn from(s: RawSize) -> Self { Size::new(s.width as f64, s.height as f64) } } impl fmt::Debug for RawSize { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}×{}", self.width, self.height) } } #[derive(Debug)] pub struct RawRect { pub x0: i32, pub y0: i32, pub x1: i32, pub y1: i32, } impl RawRect { pub fn scale(self, scale: i32) -> Self { // NOTE no overflow checking atm. RawRect { x0: self.x0 * scale, y0: self.y0 * scale, x1: self.x1 * scale, y1: self.y1 * scale, } } } impl From<Rect> for RawRect { fn from(r: Rect) -> Self { let max = i32::MAX as f64; let r = r.expand(); assert!(r.x0.abs() < max && r.y0.abs() < max && r.x1.abs() < max && r.y1.abs() < max); RawRect { x0: r.x0 as i32, y0: r.y0 as i32, x1: r.x1 as i32, y1: r.y1 as i32, } } } impl From<RawRect> for Rect { fn from(r: RawRect) -> Self { Rect { x0: r.x0 as f64, y0: r.y0 as f64, x1: r.x1 as f64, y1: r.y1 as f64, } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/idle.rs
druid-shell/src/backend/wayland/surfaces/idle.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::common_util::IdleCallback; use crate::window; /// This represents different Idle Callback Mechanism pub(super) enum Kind { Callback(Box<dyn IdleCallback>), Token(window::IdleToken), } impl std::fmt::Debug for Kind { fn fmt(&self, format: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { match self { Kind::Callback(_) => format.debug_struct("Idle(Callback)").finish(), Kind::Token(token) => format .debug_struct("Idle(Token)") .field("token", &token) .finish(), } } } #[derive(Clone)] pub struct Handle { pub(super) queue: std::sync::Arc<std::sync::Mutex<Vec<Kind>>>, } impl Handle { /// Add an idle handler, which is called (once) when the message loop /// is empty. The idle handler will be run from the main UI thread, and /// won't be scheduled if the associated view has been dropped. /// /// Note: the name "idle" suggests that it will be scheduled with a lower /// priority than other UI events, but that's not necessarily the case. pub fn add_idle_callback<F>(&self, callback: F) where F: FnOnce(&mut dyn window::WinHandler) + Send + 'static, { tracing::trace!("add_idle_callback initiated"); let mut queue = self.queue.lock().unwrap(); queue.push(Kind::Callback(Box::new(callback))); } pub fn add_idle_token(&self, token: window::IdleToken) { tracing::trace!("add_idle_token initiated {:?}", token); let mut queue = self.queue.lock().unwrap(); queue.push(Kind::Token(token)); } } pub(crate) fn run(state: &Handle, winhandle: &mut dyn window::WinHandler) { let queue: Vec<_> = std::mem::take(&mut state.queue.lock().unwrap()); for item in queue { match item { Kind::Callback(it) => it.call(winhandle), Kind::Token(it) => winhandle.idle(it), } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/toplevel.rs
druid-shell/src/backend/wayland/surfaces/toplevel.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use wayland_client as wlc; use wayland_protocols::xdg_shell::client::xdg_surface; use wayland_protocols::xdg_shell::client::xdg_toplevel; use crate::kurbo; use crate::window; use super::error; use super::surface; use super::Compositor; use super::CompositorHandle; use super::Decor; use super::Handle; use super::Outputs; use super::Popup; struct Inner { wl_surface: surface::Surface, pub(super) xdg_surface: wlc::Main<xdg_surface::XdgSurface>, pub(super) xdg_toplevel: wlc::Main<xdg_toplevel::XdgToplevel>, } impl From<Inner> for std::sync::Arc<surface::Data> { fn from(s: Inner) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.wl_surface) } } #[derive(Clone)] pub struct Surface { inner: std::sync::Arc<Inner>, } impl Surface { pub fn new( c: impl Into<CompositorHandle>, handler: Box<dyn window::WinHandler>, size: kurbo::Size, min_size: Option<kurbo::Size>, ) -> Self { let min_size = min_size.unwrap_or_else(|| kurbo::Size::from((1.0, 1.0))); let compositor = CompositorHandle::new(c); let wl_surface = surface::Surface::new(compositor.clone(), handler, kurbo::Size::ZERO); let xdg_surface = compositor.get_xdg_surface(&wl_surface.inner.wl_surface.borrow()); let xdg_toplevel = xdg_surface.get_toplevel(); // register to receive xdg_surface events. xdg_surface.quick_assign({ let wl_surface = wl_surface.clone(); move |xdg_surface, event, _| { tracing::debug!("xdg_surface event configure {:?}", event); match event { xdg_surface::Event::Configure { serial } => { xdg_surface.ack_configure(serial); wl_surface.resize(wl_surface.get_size()); wl_surface.request_paint(); } _ => tracing::warn!("unhandled xdg_surface event {:?}", event), } } }); xdg_toplevel.quick_assign({ let wl_surface = wl_surface.clone(); move |_xdg_toplevel, event, a3| match event { xdg_toplevel::Event::Configure { width, height, states, } => { tracing::debug!( "configure event {:?} {:?} {:?} {:?}", width, height, states, a3 ); // If the width or height arguments are zero, it means the client should decide its own window dimension. // This may happen when the compositor needs to configure the state of the surface // but doesn't have any information about any previous or expected dimension. let (width, height) = if width == 0 || height == 0 { (size.width, size.height) } else { (width as f64, height as f64) }; let dim = kurbo::Size::new(width.max(min_size.width), height.max(min_size.height)); wl_surface.update_dimensions(dim); } xdg_toplevel::Event::Close => { tracing::info!("xdg close event {:?}", event); wl_surface.inner.handler.borrow_mut().request_close(); } _ => tracing::info!("unimplemented event {:?}", event), } }); let inner = Inner { wl_surface, xdg_toplevel, xdg_surface, }; inner .xdg_toplevel .set_min_size(min_size.width as i32, min_size.height as i32); inner.xdg_toplevel.set_maximized(); let handle = Self { inner: std::sync::Arc::new(inner), }; handle.commit(); handle } pub(crate) fn with_handler<T, F: FnOnce(&mut dyn window::WinHandler) -> T>( &self, f: F, ) -> Option<T> { std::sync::Arc::<surface::Data>::from(self).with_handler(f) } pub(crate) fn commit(&self) { self.inner.wl_surface.commit(); } } impl Popup for Surface { fn surface<'a>( &self, popup: &'a wlc::Main<xdg_surface::XdgSurface>, pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>, ) -> Result<wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup>, error::Error> { Ok(popup.get_popup(Some(&self.inner.xdg_surface), pos)) } } impl Decor for Surface { fn inner_set_title(&self, title: String) { self.inner.xdg_toplevel.set_title(title); } } impl From<&Surface> for std::sync::Arc<surface::Data> { fn from(s: &Surface) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.clone()) } } impl From<Surface> for std::sync::Arc<surface::Data> { fn from(s: Surface) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.clone()) } } impl From<Surface> for Box<dyn Handle> { fn from(s: Surface) -> Box<dyn Handle> { Box::new(s.inner.wl_surface.clone()) as Box<dyn Handle> } } impl From<Surface> for Box<dyn Decor> { fn from(s: Surface) -> Box<dyn Decor> { Box::new(s) as Box<dyn Decor> } } impl From<Surface> for Box<dyn Outputs> { fn from(s: Surface) -> Box<dyn Outputs> { Box::new(s.inner.wl_surface.clone()) as Box<dyn Outputs> } } impl From<Surface> for Box<dyn Popup> { fn from(s: Surface) -> Self { Box::new(s) as Box<dyn Popup> } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/surface.rs
druid-shell/src/backend/wayland/surfaces/surface.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::cell::{Cell, RefCell}; use std::rc::Rc; use wayland_client as wlc; use wayland_client::protocol::wl_surface; use wayland_protocols::xdg_shell::client::xdg_popup; use wayland_protocols::xdg_shell::client::xdg_positioner; use wayland_protocols::xdg_shell::client::xdg_surface; use wlc::protocol::wl_region::WlRegion; use crate::kurbo; use crate::window; use crate::{piet::Piet, region::Region, scale::Scale, TextFieldToken}; use super::super::Changed; use super::super::outputs; use super::buffers; use super::error; use super::idle; use super::Popup; use super::{Compositor, CompositorHandle, Decor, Handle, Outputs}; pub enum DeferredTask { Paint, AnimationClear, } #[derive(Clone)] pub struct Surface { pub(super) inner: std::sync::Arc<Data>, } impl From<std::sync::Arc<Data>> for Surface { fn from(d: std::sync::Arc<Data>) -> Self { Self { inner: d } } } impl Surface { pub fn new( c: impl Into<CompositorHandle>, handler: Box<dyn window::WinHandler>, initial_size: kurbo::Size, ) -> Self { let compositor = CompositorHandle::new(c); let wl_surface = match compositor.create_surface() { None => panic!("unable to create surface"), Some(v) => v, }; let current = std::sync::Arc::new(Data { compositor: compositor.clone(), wl_surface: RefCell::new(wl_surface), outputs: RefCell::new(std::collections::HashSet::new()), buffers: buffers::Buffers::new(compositor.shared_mem(), initial_size.into()), logical_size: Cell::new(initial_size), scale: Cell::new(1), anim_frame_requested: Cell::new(false), handler: RefCell::new(handler), idle_queue: std::sync::Arc::new(std::sync::Mutex::new(vec![])), active_text_input: Cell::new(None), damaged_region: RefCell::new(Region::EMPTY), deferred_tasks: RefCell::new(std::collections::VecDeque::new()), }); // register to receive wl_surface events. Surface::initsurface(&current); Self { inner: current } } pub(super) fn output(&self) -> Option<outputs::Meta> { self.inner.output() } pub(super) fn request_paint(&self) { self.inner.buffers.request_paint(&self.inner); } pub(super) fn update_dimensions(&self, dim: impl Into<kurbo::Size>) -> kurbo::Size { self.inner.update_dimensions(dim) } pub(super) fn resize(&self, dim: kurbo::Size) -> kurbo::Size { self.inner.resize(dim) } pub(super) fn commit(&self) { self.inner.wl_surface.borrow().commit() } pub(super) fn replace(current: &std::sync::Arc<Data>) -> Surface { current .wl_surface .replace(match current.compositor.create_surface() { None => panic!("unable to create surface"), Some(v) => v, }); Surface::initsurface(current); Self { inner: current.clone(), } } fn initsurface(current: &std::sync::Arc<Data>) { current.wl_surface.borrow().quick_assign({ let current = current.clone(); move |a, event, b| { tracing::debug!("wl_surface event {:?} {:?} {:?}", a, event, b); Surface::consume_surface_event(&current, &a, &event, &b); } }); } pub(super) fn consume_surface_event( current: &std::sync::Arc<Data>, surface: &wlc::Main<wlc::protocol::wl_surface::WlSurface>, event: &wlc::protocol::wl_surface::Event, data: &wlc::DispatchData, ) { tracing::debug!("wl_surface event {:?} {:?} {:?}", surface, event, data); match event { wl_surface::Event::Enter { output } => { let proxy = wlc::Proxy::from(output.clone()); current.outputs.borrow_mut().insert(proxy.id()); } wl_surface::Event::Leave { output } => { let proxy = wlc::Proxy::from(output.clone()); current.outputs.borrow_mut().remove(&proxy.id()); } _ => tracing::warn!("unhandled wayland surface event {:?}", event), } if current.wl_surface.borrow().as_ref().version() >= wl_surface::REQ_SET_BUFFER_SCALE_SINCE { let new_scale = current.recompute_scale(); if current.set_scale(new_scale).is_changed() { current.wl_surface.borrow().set_buffer_scale(new_scale); // We also need to change the physical size to match the new scale current .buffers .set_size(buffers::RawSize::from(current.logical_size.get()).scale(new_scale)); // always repaint, because the scale changed. current.schedule_deferred_task(DeferredTask::Paint); } } } } impl Outputs for Surface { fn removed(&self, o: &outputs::Meta) { self.inner.outputs.borrow_mut().remove(&o.id()); } fn inserted(&self, _: &outputs::Meta) { // nothing to do here. } } impl Handle for Surface { fn get_size(&self) -> kurbo::Size { self.inner.get_size() } fn set_size(&self, dim: kurbo::Size) { self.inner.resize(dim); } fn request_anim_frame(&self) { self.inner.request_anim_frame() } fn remove_text_field(&self, token: TextFieldToken) { self.inner.remove_text_field(token) } fn set_focused_text_field(&self, active_field: Option<TextFieldToken>) { self.inner.set_focused_text_field(active_field) } fn set_input_region(&self, region: Option<Region>) { self.inner.set_interactable_region(region); } fn get_idle_handle(&self) -> idle::Handle { self.inner.get_idle_handle() } fn get_scale(&self) -> Scale { self.inner.get_scale() } fn invalidate(&self) { self.inner.invalidate() } fn invalidate_rect(&self, rect: kurbo::Rect) { self.inner.invalidate_rect(rect) } fn run_idle(&self) { self.inner.run_idle(); } fn release(&self) { self.inner.release() } fn data(&self) -> Option<std::sync::Arc<Data>> { Some(Into::into(self)) } } impl From<Surface> for std::sync::Arc<Data> { fn from(s: Surface) -> std::sync::Arc<Data> { s.inner } } impl From<&Surface> for std::sync::Arc<Data> { fn from(s: &Surface) -> std::sync::Arc<Data> { s.inner.clone() } } pub struct Data { pub(super) compositor: CompositorHandle, pub(super) wl_surface: RefCell<wlc::Main<wl_surface::WlSurface>>, /// The outputs that our surface is present on (we should get the first enter event early). pub(super) outputs: RefCell<std::collections::HashSet<u32>>, /// Buffers in our shared memory. // Buffers sometimes need to move references to themselves into closures, so must be behind a // reference counter. pub(super) buffers: Rc<buffers::Buffers<{ buffers::NUM_FRAMES as usize }>>, /// The logical size of the next frame. pub(crate) logical_size: Cell<kurbo::Size>, /// The scale we are rendering to (defaults to 1) pub(crate) scale: Cell<i32>, /// Contains the callbacks from user code. pub(crate) handler: RefCell<Box<dyn window::WinHandler>>, pub(crate) active_text_input: Cell<Option<TextFieldToken>>, /// Whether we have requested an animation frame. This stops us requesting more than 1. anim_frame_requested: Cell<bool>, /// Rects of the image that are damaged and need repainting in the logical coordinate space. /// /// This lives outside `data` because they can be borrowed concurrently without re-entrancy. damaged_region: RefCell<Region>, /// Tasks that were requested in user code. /// /// These call back into user code, and so should only be run after all user code has returned, /// to avoid possible re-entrancy. deferred_tasks: RefCell<std::collections::VecDeque<DeferredTask>>, idle_queue: std::sync::Arc<std::sync::Mutex<Vec<idle::Kind>>>, } impl Data { pub(crate) fn output(&self) -> Option<outputs::Meta> { match self.outputs.borrow().iter().find(|_| true) { None => None, Some(id) => self.compositor.output(*id), } } #[track_caller] pub(crate) fn with_handler<T, F: FnOnce(&mut dyn window::WinHandler) -> T>( &self, f: F, ) -> Option<T> { let ret = self.with_handler_and_dont_check_the_other_borrows(f); self.run_deferred_tasks(); ret } #[track_caller] fn with_handler_and_dont_check_the_other_borrows< T, F: FnOnce(&mut dyn window::WinHandler) -> T, >( &self, f: F, ) -> Option<T> { match self.handler.try_borrow_mut() { Ok(mut h) => Some(f(&mut **h)), Err(_) => { tracing::error!( "failed to borrow WinHandler at {}", std::panic::Location::caller() ); None } } } pub(super) fn update_dimensions(&self, dim: impl Into<kurbo::Size>) -> kurbo::Size { let dim = dim.into(); if self.logical_size.get() != self.resize(dim) { match self.handler.try_borrow_mut() { Ok(mut handler) => handler.size(dim), Err(cause) => tracing::warn!("unhable to borrow handler {:?}", cause), }; } dim } // client initiated resizing. pub(super) fn resize(&self, dim: kurbo::Size) -> kurbo::Size { // The size here is the logical size let scale = self.scale.get(); let raw_logical_size = buffers::RawSize { width: dim.width as i32, height: dim.height as i32, }; let previous_logical_size = self.logical_size.replace(dim); if previous_logical_size != dim { self.buffers.set_size(raw_logical_size.scale(scale)); } dim } pub(super) fn set_interactable_region(&self, region: Option<Region>) { match region { Some(region) => { let wl_region = self.compositor.create_region(); let detached_region: WlRegion = wl_region.detach(); for rect in region.rects() { detached_region.add( rect.x0 as i32, rect.y0 as i32, rect.width().ceil() as i32, rect.height().ceil() as i32, ); } self.wl_surface .borrow() .set_input_region(Some(&detached_region)); detached_region.destroy(); } None => { // This, for some reason, causes a shift in the cursor. self.wl_surface.borrow().set_input_region(None); } } } /// Assert that the physical size = logical size * scale #[allow(unused)] fn assert_size(&self) { assert_eq!( self.buffers.size(), buffers::RawSize::from(self.logical_size.get()).scale(self.scale.get()), "phy {:?} == logic {:?} * {}", self.buffers.size(), self.logical_size.get(), self.scale.get() ); } /// Recompute the scale to use (the maximum of all the scales for the different outputs this /// surface is drawn to). fn recompute_scale(&self) -> i32 { tracing::debug!("recompute initiated"); self.compositor.recompute_scale(&self.outputs.borrow()) } /// Sets the scale /// /// Up to the caller to make sure `physical_size`, `logical_size` and `scale` are consistent. fn set_scale(&self, new_scale: i32) -> Changed { tracing::debug!("set_scale initiated"); if self.scale.get() != new_scale { self.scale.set(new_scale); // (re-entrancy) Report change to client self.handler .borrow_mut() .scale(Scale::new(new_scale as f64, new_scale as f64)); Changed::Changed } else { Changed::Unchanged } } /// Paint the next frame. /// /// The buffers object is responsible for calling this function after we called /// `request_paint`. /// /// - `buf` is what we draw the frame into /// - `size` is the physical size in pixels we are drawing. /// - `force` means draw the whole frame, even if it wasn't all invalidated. pub(super) fn paint(&self, physical_size: buffers::RawSize, buf: &mut [u8], force: bool) { tracing::trace!( "paint initiated {:?} - {:?} {:?}", self.get_size(), physical_size, force ); // We don't care about obscure pre version 4 compositors // and just damage the whole surface instead of // translating from buffer coordinates to surface coordinates let damage_buffer_supported = self.wl_surface.borrow().as_ref().version() >= wl_surface::REQ_DAMAGE_BUFFER_SINCE; if force || !damage_buffer_supported { self.invalidate(); self.wl_surface.borrow().damage(0, 0, i32::MAX, i32::MAX); } else { let damaged_region = self.damaged_region.borrow_mut(); for rect in damaged_region.rects() { // Convert it to physical coordinate space. let rect = buffers::RawRect::from(*rect).scale(self.scale.get()); self.wl_surface.borrow().damage_buffer( rect.x0, rect.y0, rect.x1 - rect.x0, rect.y1 - rect.y0, ); } if damaged_region.is_empty() { // Nothing to draw, so we can finish here! return; } } // create cairo context (safety: we must drop the buffer before we commit the frame) // TODO: Cairo is native-endian while wayland is little-endian, which is a pain. Currently // will give incorrect results on big-endian architectures. // TODO cairo might use a different stride than the width of the format. Since we always // use argb32 which is 32-bit aligned we should be ok, but strictly speaking cairo might // choose a wider stride and read past the end of our buffer (UB). Fixing this would // require a fair bit of effort. unsafe { // We're going to lie about the lifetime of our buffer here. This is (I think) ok, // because the Rust wrapper for cairo is overly pessimistic: the buffer only has to // last as long as the `ImageSurface` (which we know this buffer will). let buf: &'static mut [u8] = &mut *(buf as *mut _); let cairo_surface = match cairo::ImageSurface::create_for_data( buf, cairo::Format::ARgb32, physical_size.width, physical_size.height, physical_size.width * buffers::PIXEL_WIDTH, ) { Ok(s) => s, Err(cause) => { tracing::error!("unable to create cairo surface: {:?}", cause); return; } }; let ctx = match cairo::Context::new(&cairo_surface) { Ok(ctx) => ctx, Err(cause) => { tracing::error!("unable to create cairo context: {:?}", cause); return; } }; // Apply scaling let scale = self.scale.get() as f64; ctx.scale(scale, scale); let mut piet = Piet::new(&ctx); // Actually paint the new frame let region = self.damaged_region.borrow(); // The handler must not be already borrowed. This may mean deferring this call. self.handler.borrow_mut().paint(&mut piet, &region); } // reset damage ready for next frame. self.damaged_region.borrow_mut().clear(); self.buffers.attach(self); self.wl_surface.borrow().commit(); } /// Request invalidation of the entire window contents. fn invalidate(&self) { tracing::trace!("invalidate initiated"); // This is one of 2 methods the user can use to schedule a repaint, the other is // `invalidate_rect`. let window_rect = self.logical_size.get().to_rect(); self.damaged_region.borrow_mut().add_rect(window_rect); self.schedule_deferred_task(DeferredTask::Paint); } /// Request invalidation of one rectangle, which is given in display points relative to the /// drawing area. fn invalidate_rect(&self, rect: kurbo::Rect) { tracing::trace!("invalidate_rect initiated {:?}", rect); // Quick check to see if we can skip the rect entirely (if it is outside the visible // screen). if rect .intersect(self.logical_size.get().to_rect()) .is_zero_area() { return; } /* this would be useful for debugging over-keen invalidation by clients. println!( "{:?} {:?}", rect, self.with_data(|data| data.logical_size.to_rect()) ); */ self.damaged_region.borrow_mut().add_rect(rect); self.schedule_deferred_task(DeferredTask::Paint); } pub fn schedule_deferred_task(&self, task: DeferredTask) { tracing::trace!("scedule_deferred_task initiated"); self.deferred_tasks.borrow_mut().push_back(task); } pub fn run_deferred_tasks(&self) { tracing::trace!("run_deferred_tasks initiated"); while let Some(task) = self.next_deferred_task() { self.run_deferred_task(task); } } fn next_deferred_task(&self) -> Option<DeferredTask> { self.deferred_tasks.borrow_mut().pop_front() } fn run_deferred_task(&self, task: DeferredTask) { match task { DeferredTask::Paint => { self.buffers.request_paint(self); } DeferredTask::AnimationClear => { self.anim_frame_requested.set(false); } } } pub(super) fn get_size(&self) -> kurbo::Size { // size in pixels, so we must apply scale. let logical_size = self.logical_size.get(); let scale = self.scale.get() as f64; kurbo::Size::new(logical_size.width * scale, logical_size.height * scale) } pub(super) fn request_anim_frame(&self) { if self.anim_frame_requested.replace(true) { return; } let idle = self.get_idle_handle(); idle.add_idle_callback(move |winhandle| { winhandle.prepare_paint(); }); self.schedule_deferred_task(DeferredTask::AnimationClear); } pub(super) fn remove_text_field(&self, token: TextFieldToken) { if self.active_text_input.get() == Some(token) { self.active_text_input.set(None); } } pub(super) fn set_focused_text_field(&self, active_field: Option<TextFieldToken>) { self.active_text_input.set(active_field); } pub(super) fn get_idle_handle(&self) -> idle::Handle { idle::Handle { queue: self.idle_queue.clone(), } } pub(super) fn get_scale(&self) -> Scale { let scale = self.scale.get() as f64; Scale::new(scale, scale) } pub(super) fn run_idle(&self) { self.with_handler(|winhandle| { idle::run(&self.get_idle_handle(), winhandle); }); } pub(super) fn release(&self) { self.wl_surface.borrow().destroy(); } } #[derive(Default)] pub struct Dead; impl From<Dead> for Box<dyn Decor> { fn from(d: Dead) -> Box<dyn Decor> { Box::new(d) as Box<dyn Decor> } } impl From<Dead> for Box<dyn Outputs> { fn from(d: Dead) -> Box<dyn Outputs> { Box::new(d) as Box<dyn Outputs> } } impl Decor for Dead { fn inner_set_title(&self, title: String) { tracing::warn!("set_title not implemented for this surface: {:?}", title); } } impl Outputs for Dead { fn removed(&self, _: &outputs::Meta) {} fn inserted(&self, _: &outputs::Meta) {} } impl Popup for Dead { fn surface<'a>( &self, _: &'a wlc::Main<xdg_surface::XdgSurface>, _: &'a wlc::Main<xdg_positioner::XdgPositioner>, ) -> Result<wlc::Main<xdg_popup::XdgPopup>, error::Error> { tracing::warn!("popup invoked on a dead surface"); Err(error::Error::InvalidParent(0)) } } impl Handle for Dead { fn get_size(&self) -> kurbo::Size { kurbo::Size::ZERO } fn set_size(&self, dim: kurbo::Size) { tracing::warn!("set_size invoked on a dead surface {:?}", dim); } fn request_anim_frame(&self) { tracing::warn!("request_anim_frame invoked on a dead surface") } fn remove_text_field(&self, _token: TextFieldToken) { tracing::warn!("remove_text_field invoked on a dead surface") } fn set_focused_text_field(&self, _active_field: Option<TextFieldToken>) { tracing::warn!("set_focused_text_field invoked on a dead surface") } fn set_input_region(&self, _region: Option<Region>) { tracing::warn!("set_input_region invoked on a dead surface") } fn get_idle_handle(&self) -> idle::Handle { panic!("get_idle_handle invoked on a dead surface") } fn get_scale(&self) -> Scale { Scale::new(1., 1.) } fn invalidate(&self) { tracing::warn!("invalidate invoked on a dead surface") } fn invalidate_rect(&self, _rect: kurbo::Rect) { tracing::warn!("invalidate_rect invoked on a dead surface") } fn run_idle(&self) { tracing::warn!("run_idle invoked on a dead surface") } fn release(&self) { tracing::warn!("release invoked on a dead surface"); } fn data(&self) -> Option<std::sync::Arc<Data>> { tracing::warn!("data invoked on a dead surface"); None } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/layershell.rs
druid-shell/src/backend/wayland/surfaces/layershell.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use wayland_client as wlc; use wayland_protocols::wlr::unstable::layer_shell::v1::client as layershell; use wayland_protocols::xdg_shell::client::xdg_surface; use crate::kurbo; use crate::window; use super::super::error; use super::super::outputs; use super::surface; use super::Compositor; use super::CompositorHandle; use super::Handle; use super::Outputs; use super::Popup; #[derive(Default)] struct Output { preferred: Option<String>, current: Option<outputs::Meta>, } struct Inner { config: Config, wl_surface: std::cell::RefCell<surface::Surface>, ls_surface: std::cell::RefCell<wlc::Main<layershell::zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>>, requires_initialization: std::cell::RefCell<bool>, available: std::cell::RefCell<bool>, output: std::cell::RefCell<Output>, } impl Inner { fn popup<'a>( &self, surface: &'a wlc::Main<xdg_surface::XdgSurface>, pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>, ) -> wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup> { let popup = surface.get_popup(None, pos); self.ls_surface.borrow().get_popup(&popup); popup } } impl Popup for Inner { fn surface<'a>( &self, surface: &'a wlc::Main<xdg_surface::XdgSurface>, pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>, ) -> Result<wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup>, error::Error> { Ok(self.popup(surface, pos)) } } impl Drop for Inner { fn drop(&mut self) { self.ls_surface.borrow().destroy(); } } impl From<Inner> for std::sync::Arc<surface::Data> { fn from(s: Inner) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.wl_surface.borrow().clone()) } } #[derive(Clone, Debug)] pub struct Margin { top: i32, right: i32, bottom: i32, left: i32, } impl Default for Margin { fn default() -> Self { Margin::from((0, 0, 0, 0)) } } impl Margin { pub fn new(m: impl Into<Margin>) -> Self { m.into() } pub fn uniform(m: i32) -> Self { Margin::from((m, m, m, m)) } } impl From<(i32, i32, i32, i32)> for Margin { fn from(margins: (i32, i32, i32, i32)) -> Self { Self { top: margins.0, left: margins.1, bottom: margins.2, right: margins.3, } } } impl From<i32> for Margin { fn from(m: i32) -> Self { Margin::from((m, m, m, m)) } } impl From<(i32, i32)> for Margin { fn from(m: (i32, i32)) -> Self { Margin::from((m.0, m.1, m.0, m.1)) } } #[derive(Clone)] pub struct Config { pub initial_size: kurbo::Size, pub layer: layershell::zwlr_layer_shell_v1::Layer, pub keyboard_interactivity: layershell::zwlr_layer_surface_v1::KeyboardInteractivity, pub anchor: layershell::zwlr_layer_surface_v1::Anchor, pub exclusive_zone: i32, pub margin: Margin, pub namespace: &'static str, pub app_id: &'static str, } impl Config { pub fn keyboard_interactivity( mut self, mode: layershell::zwlr_layer_surface_v1::KeyboardInteractivity, ) -> Self { self.keyboard_interactivity = mode; self } pub fn layer(mut self, layer: layershell::zwlr_layer_shell_v1::Layer) -> Self { self.layer = layer; self } pub fn anchor(mut self, anchor: layershell::zwlr_layer_surface_v1::Anchor) -> Self { self.anchor = anchor; self } pub fn margin(mut self, m: impl Into<Margin>) -> Self { self.margin = m.into(); self } fn apply(&self, surface: &Surface) { let ls = surface.inner.ls_surface.borrow(); ls.set_exclusive_zone(self.exclusive_zone); ls.set_anchor(self.anchor); ls.set_keyboard_interactivity(self.keyboard_interactivity); ls.set_margin( self.margin.top, self.margin.right, self.margin.bottom, self.margin.left, ); ls.set_size( self.initial_size.width as u32, self.initial_size.height as u32, ); } } impl Default for Config { fn default() -> Self { Self { layer: layershell::zwlr_layer_shell_v1::Layer::Overlay, initial_size: kurbo::Size::ZERO, keyboard_interactivity: layershell::zwlr_layer_surface_v1::KeyboardInteractivity::None, anchor: layershell::zwlr_layer_surface_v1::Anchor::all(), exclusive_zone: 0, margin: Margin::default(), namespace: "druid", app_id: "", } } } #[derive(Clone)] pub struct Surface { inner: std::sync::Arc<Inner>, } impl Surface { pub fn new( c: impl Into<CompositorHandle>, handler: Box<dyn window::WinHandler>, config: Config, ) -> Self { let compositor = CompositorHandle::new(c); let wl_surface = surface::Surface::new(compositor.clone(), handler, kurbo::Size::ZERO); let ls_surface = compositor.zwlr_layershell_v1().unwrap().get_layer_surface( &wl_surface.inner.wl_surface.borrow(), None, config.layer, config.namespace.to_string(), ); let handle = Self { inner: std::sync::Arc::new(Inner { config, wl_surface: std::cell::RefCell::new(wl_surface), ls_surface: std::cell::RefCell::new(ls_surface), requires_initialization: std::cell::RefCell::new(true), available: std::cell::RefCell::new(false), output: std::cell::RefCell::new(Default::default()), }), }; Surface::initialize(&handle); handle } pub(crate) fn with_handler<T, F: FnOnce(&mut dyn window::WinHandler) -> T>( &self, f: F, ) -> Option<T> { std::sync::Arc::<surface::Data>::from(self).with_handler(f) } fn initialize(handle: &Surface) { handle.inner.requires_initialization.replace(false); tracing::debug!("attempting to initialize layershell"); handle.inner.ls_surface.borrow().quick_assign({ let handle = handle.clone(); move |a1, event, a2| { tracing::debug!("consuming event {:?} {:?} {:?}", a1, event, a2); Surface::consume_layershell_event(&handle, &a1, &event, &a2); } }); handle.inner.config.apply(handle); handle.inner.wl_surface.borrow().commit(); } fn consume_layershell_event( handle: &Surface, a1: &wlc::Main<layershell::zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>, event: &layershell::zwlr_layer_surface_v1::Event, data: &wlc::DispatchData, ) { match *event { layershell::zwlr_layer_surface_v1::Event::Configure { serial, width, height, } => { let mut dim = handle.inner.config.initial_size; // compositor is deferring to the client for determining the size // when values are zero. if width != 0 && height != 0 { dim = kurbo::Size::new(width as f64, height as f64); } let ls = handle.inner.ls_surface.borrow(); ls.ack_configure(serial); ls.set_size(dim.width as u32, dim.height as u32); handle.inner.wl_surface.borrow().update_dimensions(dim); handle.inner.wl_surface.borrow().request_paint(); handle.inner.available.replace(true); } layershell::zwlr_layer_surface_v1::Event::Closed => { if let Some(o) = handle.inner.wl_surface.borrow().output() { handle .inner .output .borrow_mut() .preferred .get_or_insert(o.name.clone()); handle.inner.output.borrow_mut().current.get_or_insert(o); } handle.inner.ls_surface.borrow().destroy(); handle.inner.available.replace(false); handle.inner.requires_initialization.replace(true); } _ => tracing::warn!("unimplemented event {:?} {:?} {:?}", a1, event, data), } } } impl Outputs for Surface { fn removed(&self, o: &outputs::Meta) { self.inner.wl_surface.borrow().removed(o); self.inner.output.borrow_mut().current.take(); } fn inserted(&self, o: &outputs::Meta) { let old = String::from( self.inner .output .borrow() .preferred .as_ref() .map_or("", |name| name), ); let reinitialize = *self.inner.requires_initialization.borrow(); let reinitialize = old == o.name || reinitialize; if !reinitialize { tracing::debug!( "skipping reinitialization output for layershell {:?} {:?} == {:?} || {:?} -> {:?}", o.id(), o.name, old, *self.inner.requires_initialization.borrow(), reinitialize, ); return; } tracing::debug!( "reinitializing output for layershell {:?} {:?} == {:?} || {:?} -> {:?}", o.id(), o.name, old, *self.inner.requires_initialization.borrow(), reinitialize, ); let sdata = self.inner.wl_surface.borrow().inner.clone(); self.inner .wl_surface .replace(surface::Surface::replace(&sdata)); let sdata = self.inner.wl_surface.borrow().inner.clone(); let replacedlayershell = self.inner.ls_surface.replace( sdata .compositor .zwlr_layershell_v1() .unwrap() .get_layer_surface( &self.inner.wl_surface.borrow().inner.wl_surface.borrow(), o.output.as_ref(), self.inner.config.layer, self.inner.config.namespace.to_string(), ), ); Surface::initialize(self); replacedlayershell.destroy(); } } impl Popup for Surface { fn surface<'a>( &self, popup: &'a wlc::Main<xdg_surface::XdgSurface>, pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>, ) -> Result<wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup>, error::Error> { Ok(self.inner.popup(popup, pos)) } } impl Handle for Surface { fn get_size(&self) -> kurbo::Size { return self.inner.wl_surface.borrow().get_size(); } fn set_size(&self, dim: kurbo::Size) { return self.inner.wl_surface.borrow().set_size(dim); } fn request_anim_frame(&self) { if *self.inner.available.borrow() { self.inner.wl_surface.borrow().request_anim_frame() } } fn invalidate(&self) { return self.inner.wl_surface.borrow().invalidate(); } fn invalidate_rect(&self, rect: kurbo::Rect) { return self.inner.wl_surface.borrow().invalidate_rect(rect); } fn remove_text_field(&self, token: crate::TextFieldToken) { return self.inner.wl_surface.borrow().remove_text_field(token); } fn set_focused_text_field(&self, active_field: Option<crate::TextFieldToken>) { return self .inner .wl_surface .borrow() .set_focused_text_field(active_field); } fn set_input_region(&self, region: Option<crate::Region>) { self.inner.wl_surface.borrow().set_input_region(region); } fn get_idle_handle(&self) -> super::idle::Handle { return self.inner.wl_surface.borrow().get_idle_handle(); } fn get_scale(&self) -> crate::Scale { return self.inner.wl_surface.borrow().get_scale(); } fn run_idle(&self) { if *self.inner.available.borrow() { self.inner.wl_surface.borrow().run_idle(); } } fn release(&self) { self.inner.wl_surface.borrow().release() } fn data(&self) -> Option<std::sync::Arc<surface::Data>> { self.inner.wl_surface.borrow().data() } } impl From<&Surface> for std::sync::Arc<surface::Data> { fn from(s: &Surface) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.borrow().clone()) } } impl From<Surface> for std::sync::Arc<surface::Data> { fn from(s: Surface) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.borrow().clone()) } } impl From<Surface> for Box<dyn Handle> { fn from(s: Surface) -> Box<dyn Handle> { Box::new(s) as Box<dyn Handle> } } impl From<Surface> for Box<dyn Outputs> { fn from(s: Surface) -> Box<dyn Outputs> { Box::new(s) as Box<dyn Outputs> } } impl From<Surface> for Box<dyn Popup> { fn from(s: Surface) -> Self { Box::new(s) as Box<dyn Popup> } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/mod.rs
druid-shell/src/backend/wayland/surfaces/mod.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use wayland_client::protocol::wl_shm::WlShm; use wayland_client::{self as wlc, protocol::wl_region::WlRegion, protocol::wl_surface::WlSurface}; use wayland_protocols::wlr::unstable::layer_shell::v1::client::zwlr_layer_shell_v1::ZwlrLayerShellV1; use wayland_protocols::xdg_shell::client::xdg_popup; use wayland_protocols::xdg_shell::client::xdg_positioner; use wayland_protocols::xdg_shell::client::xdg_surface; use crate::Scale; use crate::TextFieldToken; use crate::{kurbo, Region}; use super::error; use super::outputs; pub mod buffers; pub mod idle; pub mod layershell; pub mod popup; pub mod surface; pub mod toplevel; pub static GLOBAL_ID: crate::Counter = crate::Counter::new(); pub trait Compositor { fn output(&self, id: u32) -> Option<outputs::Meta>; fn create_surface(&self) -> wlc::Main<WlSurface>; fn create_region(&self) -> wlc::Main<WlRegion>; fn shared_mem(&self) -> wlc::Main<WlShm>; fn get_xdg_surface(&self, surface: &wlc::Main<WlSurface>) -> wlc::Main<xdg_surface::XdgSurface>; fn get_xdg_positioner(&self) -> wlc::Main<xdg_positioner::XdgPositioner>; fn zwlr_layershell_v1(&self) -> Option<wlc::Main<ZwlrLayerShellV1>>; } pub trait Decor { fn inner_set_title(&self, title: String); } impl dyn Decor { pub fn set_title(&self, title: impl Into<String>) { self.inner_set_title(title.into()) } } pub trait Popup { fn surface<'a>( &self, popup: &'a wlc::Main<xdg_surface::XdgSurface>, pos: &'a wlc::Main<xdg_positioner::XdgPositioner>, ) -> Result<wlc::Main<xdg_popup::XdgPopup>, error::Error>; } pub(super) trait Outputs { fn removed(&self, o: &outputs::Meta); fn inserted(&self, o: &outputs::Meta); } // handle on given surface. pub trait Handle { fn get_size(&self) -> kurbo::Size; fn set_size(&self, dim: kurbo::Size); fn request_anim_frame(&self); fn invalidate(&self); fn invalidate_rect(&self, rect: kurbo::Rect); fn remove_text_field(&self, token: TextFieldToken); fn set_focused_text_field(&self, active_field: Option<TextFieldToken>); fn set_input_region(&self, region: Option<Region>); fn get_idle_handle(&self) -> idle::Handle; fn get_scale(&self) -> Scale; fn run_idle(&self); fn release(&self); fn data(&self) -> Option<std::sync::Arc<surface::Data>>; } #[derive(Clone)] pub struct CompositorHandle { inner: std::sync::Weak<dyn Compositor>, } impl CompositorHandle { pub fn new(c: impl Into<CompositorHandle>) -> Self { c.into() } pub fn direct(c: std::sync::Weak<dyn Compositor>) -> Self { Self { inner: c } } fn create_surface(&self) -> Option<wlc::Main<WlSurface>> { self.inner.upgrade().map(|c| c.create_surface()) } /// Recompute the scale to use (the maximum of all the provided outputs). fn recompute_scale(&self, outputs: &std::collections::HashSet<u32>) -> i32 { let compositor = match self.inner.upgrade() { Some(c) => c, None => panic!("should never recompute scale of window that has been dropped"), }; tracing::debug!("computing scale using {:?} outputs", outputs.len()); let scale = outputs.iter().fold(0, |scale, id| { tracing::debug!("recomputing scale using output {:?}", id); match compositor.output(*id) { None => { tracing::warn!( "we still have a reference to an output that's gone away. The output had id {}", id, ); scale }, Some(output) => scale.max(output.scale as i32), } }); match scale { 0 => { tracing::warn!("wayland never reported which output we are drawing to"); 1 } scale => scale, } } } impl Compositor for CompositorHandle { fn output(&self, id: u32) -> Option<outputs::Meta> { match self.inner.upgrade() { None => None, Some(c) => c.output(id), } } fn create_surface(&self) -> wlc::Main<WlSurface> { match self.inner.upgrade() { None => panic!("unable to acquire underlying compositor to create a surface"), Some(c) => c.create_surface(), } } fn create_region(&self) -> wlc::Main<WlRegion> { match self.inner.upgrade() { None => panic!("unable to acquire underlying compositor to create a region"), Some(c) => c.create_region(), } } fn shared_mem(&self) -> wlc::Main<WlShm> { match self.inner.upgrade() { None => panic!("unable to acquire underlying compositor to acquire shared memory"), Some(c) => c.shared_mem(), } } fn get_xdg_positioner(&self) -> wlc::Main<xdg_positioner::XdgPositioner> { match self.inner.upgrade() { None => panic!("unable to acquire underlying compositor to create an xdg positioner"), Some(c) => c.get_xdg_positioner(), } } fn get_xdg_surface(&self, s: &wlc::Main<WlSurface>) -> wlc::Main<xdg_surface::XdgSurface> { match self.inner.upgrade() { None => panic!("unable to acquire underlying compositor to create an xdg surface"), Some(c) => c.get_xdg_surface(s), } } fn zwlr_layershell_v1(&self) -> Option<wlc::Main<ZwlrLayerShellV1>> { match self.inner.upgrade() { None => { tracing::warn!( "unable to acquire underyling compositor to acquire the layershell manager" ); None } Some(c) => c.zwlr_layershell_v1(), } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/wayland/surfaces/popup.rs
druid-shell/src/backend/wayland/surfaces/popup.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use wayland_client as wlc; use wayland_protocols::xdg_shell::client::xdg_popup; use wayland_protocols::xdg_shell::client::xdg_positioner; use wayland_protocols::xdg_shell::client::xdg_surface; use crate::kurbo; use crate::window; use super::error; use super::surface; use super::Compositor; use super::CompositorHandle; use super::Handle; use super::Outputs; use super::Popup; #[allow(unused)] struct Inner { wl_surface: surface::Surface, wl_xdg_surface: wlc::Main<xdg_surface::XdgSurface>, wl_xdg_popup: wlc::Main<xdg_popup::XdgPopup>, wl_xdg_pos: wlc::Main<xdg_positioner::XdgPositioner>, } impl From<Inner> for std::sync::Arc<surface::Data> { fn from(s: Inner) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.wl_surface) } } #[derive(Clone, Debug)] pub struct Config { pub size: kurbo::Size, pub offset: kurbo::Point, pub anchor_rect: (kurbo::Point, kurbo::Size), pub anchor: xdg_positioner::Anchor, pub gravity: xdg_positioner::Gravity, pub constraint_adjustment: xdg_positioner::ConstraintAdjustment, } impl Config { fn apply(self, c: &CompositorHandle) -> wlc::Main<xdg_positioner::XdgPositioner> { tracing::debug!("configuring popup {:?}", self); let pos = c.get_xdg_positioner(); pos.set_size(self.size.width as i32, self.size.height as i32); pos.set_offset(self.offset.x as i32, self.offset.y as i32); pos.set_anchor_rect( self.anchor_rect.0.x as i32, self.anchor_rect.0.y as i32, self.anchor_rect.1.width as i32, self.anchor_rect.1.height as i32, ); pos.set_anchor(self.anchor); pos.set_gravity(self.gravity); pos.set_constraint_adjustment(self.constraint_adjustment.bits()); // requires version 3... // pos.set_reactive(); pos } pub fn with_size(mut self, dim: kurbo::Size) -> Self { self.size = dim; self } pub fn with_offset(mut self, p: kurbo::Point) -> Self { self.offset = p; self } } impl Default for Config { fn default() -> Self { Self { size: kurbo::Size::new(1., 1.), anchor: xdg_positioner::Anchor::Bottom, offset: kurbo::Point::ZERO, anchor_rect: (kurbo::Point::ZERO, kurbo::Size::from((1., 1.))), gravity: xdg_positioner::Gravity::BottomLeft, constraint_adjustment: xdg_positioner::ConstraintAdjustment::all(), } } } #[derive(Clone)] pub struct Surface { inner: std::sync::Arc<Inner>, } impl Surface { pub fn new( c: impl Into<CompositorHandle>, handler: Box<dyn window::WinHandler>, config: Config, parent: &dyn Popup, ) -> Result<Self, error::Error> { let compositor = CompositorHandle::new(c); let wl_surface = surface::Surface::new(compositor.clone(), handler, kurbo::Size::ZERO); let wl_xdg_surface = compositor.get_xdg_surface(&wl_surface.inner.wl_surface.borrow()); // register to receive xdg_surface events. wl_xdg_surface.quick_assign({ let wl_surface = wl_surface.clone(); move |xdg_surface, event, _| match event { xdg_surface::Event::Configure { serial } => { xdg_surface.ack_configure(serial); let dim = wl_surface.inner.logical_size.get(); wl_surface.inner.handler.borrow_mut().size(dim); wl_surface.request_paint(); } _ => tracing::warn!("unhandled xdg_surface event {:?}", event), } }); let wl_xdg_pos = config.apply(&compositor); wl_xdg_pos.quick_assign(|obj, event, _| { tracing::debug!("{:?} {:?}", obj, event); }); let wl_xdg_popup = parent.surface(&wl_xdg_surface, &wl_xdg_pos)?; wl_xdg_popup.quick_assign({ let wl_surface = wl_surface.clone(); move |_xdg_popup, event, _| { match event { xdg_popup::Event::Configure { x, y, width, height, } => { tracing::debug!( "popup configuration ({:?},{:?}) {:?}x{:?}", x, y, width, height ); wl_surface.update_dimensions((width as f64, height as f64)); } xdg_popup::Event::PopupDone => { tracing::debug!("popup done {:?}", event); match wl_surface.data() { None => tracing::warn!("missing surface data, cannot close popup"), Some(data) => { data.with_handler(|winhandle| { winhandle.request_close(); }); } }; } _ => tracing::warn!("unhandled xdg_popup event configure {:?}", event), }; } }); let handle = Self { inner: std::sync::Arc::new(Inner { wl_surface, wl_xdg_surface, wl_xdg_popup, wl_xdg_pos, }), }; handle.commit(); Ok(handle) } pub(super) fn commit(&self) { let wl_surface = &self.inner.wl_surface; wl_surface.commit(); } pub(crate) fn with_handler<T, F: FnOnce(&mut dyn window::WinHandler) -> T>( &self, f: F, ) -> Option<T> { std::sync::Arc::<surface::Data>::from(self).with_handler(f) } } impl Handle for Surface { fn get_size(&self) -> kurbo::Size { self.inner.wl_surface.get_size() } fn set_size(&self, dim: kurbo::Size) { self.inner.wl_surface.set_size(dim); } fn request_anim_frame(&self) { self.inner.wl_surface.request_anim_frame() } fn invalidate(&self) { self.inner.wl_surface.invalidate() } fn invalidate_rect(&self, rect: kurbo::Rect) { self.inner.wl_surface.invalidate_rect(rect) } fn remove_text_field(&self, token: crate::TextFieldToken) { self.inner.wl_surface.remove_text_field(token) } fn set_focused_text_field(&self, active_field: Option<crate::TextFieldToken>) { self.inner.wl_surface.set_focused_text_field(active_field) } fn set_input_region(&self, region: Option<crate::Region>) { self.inner.wl_surface.set_input_region(region) } fn get_idle_handle(&self) -> super::idle::Handle { self.inner.wl_surface.get_idle_handle() } fn get_scale(&self) -> crate::Scale { self.inner.wl_surface.get_scale() } fn run_idle(&self) { self.inner.wl_surface.run_idle(); } fn release(&self) { self.inner.wl_surface.release() } fn data(&self) -> Option<std::sync::Arc<surface::Data>> { self.inner.wl_surface.data() } } impl From<&Surface> for std::sync::Arc<surface::Data> { fn from(s: &Surface) -> std::sync::Arc<surface::Data> { std::sync::Arc::<surface::Data>::from(s.inner.wl_surface.clone()) } } impl Popup for Surface { fn surface<'a>( &self, popup: &'a wlc::Main<xdg_surface::XdgSurface>, pos: &'a wlc::Main<wayland_protocols::xdg_shell::client::xdg_positioner::XdgPositioner>, ) -> Result<wlc::Main<wayland_protocols::xdg_shell::client::xdg_popup::XdgPopup>, error::Error> { Ok(popup.get_popup(Some(&self.inner.wl_xdg_surface), pos)) } } impl From<Surface> for Box<dyn Outputs> { fn from(s: Surface) -> Box<dyn Outputs> { Box::new(s.inner.wl_surface.clone()) as Box<dyn Outputs> } } impl From<Surface> for Box<dyn Handle> { fn from(s: Surface) -> Box<dyn Handle> { Box::new(s) as Box<dyn Handle> } } impl From<Surface> for Box<dyn Popup> { fn from(s: Surface) -> Self { Box::new(s) as Box<dyn Popup> } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/keycodes.rs
druid-shell/src/backend/windows/keycodes.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Windows keycode conversion. use win_vks::*; use winapi::um::winuser::*; use crate::keycodes::KeyCode; pub type RawKeyCode = i32; mod win_vks { //NOTE: Most keys on Windows have VK_ values defined in use winapi::um::winuser, // but ASCII digits and letters are the exception. Fill those in here // (following https://github.com/Eljay/directx) so all keys have constants, // even though these are not official names for virtual-key codes. pub const VK_0: i32 = 0x30; pub const VK_1: i32 = 0x31; pub const VK_2: i32 = 0x32; pub const VK_3: i32 = 0x33; pub const VK_4: i32 = 0x34; pub const VK_5: i32 = 0x35; pub const VK_6: i32 = 0x36; pub const VK_7: i32 = 0x37; pub const VK_8: i32 = 0x38; pub const VK_9: i32 = 0x39; pub const VK_A: i32 = 0x41; pub const VK_B: i32 = 0x42; pub const VK_C: i32 = 0x43; pub const VK_D: i32 = 0x44; pub const VK_E: i32 = 0x45; pub const VK_F: i32 = 0x46; pub const VK_G: i32 = 0x47; pub const VK_H: i32 = 0x48; pub const VK_I: i32 = 0x49; pub const VK_J: i32 = 0x4A; pub const VK_K: i32 = 0x4B; pub const VK_L: i32 = 0x4C; pub const VK_M: i32 = 0x4D; pub const VK_N: i32 = 0x4E; pub const VK_O: i32 = 0x4F; pub const VK_P: i32 = 0x50; pub const VK_Q: i32 = 0x51; pub const VK_R: i32 = 0x52; pub const VK_S: i32 = 0x53; pub const VK_T: i32 = 0x54; pub const VK_U: i32 = 0x55; pub const VK_V: i32 = 0x56; pub const VK_W: i32 = 0x57; pub const VK_X: i32 = 0x58; pub const VK_Y: i32 = 0x59; pub const VK_Z: i32 = 0x5A; } macro_rules! map_keys { ($( $id:ident => $code:path),*) => { impl KeyCode { pub(crate) fn to_i32(&self) -> Option<i32> { // Some keycode are same value as others #[allow(unreachable_patterns)] match self { $( $code => Some($id) ),*, _ => None, } } } impl From<i32> for KeyCode { fn from(src: i32) -> KeyCode { match src { $( $id => $code ),*, other => KeyCode::Unknown(other), } } } } } map_keys! { VK_LSHIFT => KeyCode::LeftShift, VK_SHIFT => KeyCode::LeftShift, VK_RSHIFT => KeyCode::RightShift, VK_LCONTROL => KeyCode::LeftControl, VK_CONTROL => KeyCode::LeftControl, VK_RCONTROL => KeyCode::RightControl, VK_LMENU => KeyCode::LeftAlt, VK_MENU => KeyCode::LeftAlt, VK_RMENU => KeyCode::RightAlt, VK_OEM_PLUS => KeyCode::Equals, VK_OEM_COMMA => KeyCode::Comma, VK_OEM_MINUS => KeyCode::Minus, VK_OEM_PERIOD => KeyCode::Period, VK_OEM_1 => KeyCode::Semicolon, VK_OEM_2 => KeyCode::Slash, VK_OEM_3 => KeyCode::Backtick, VK_OEM_4 => KeyCode::LeftBracket, VK_OEM_5 => KeyCode::Backslash, VK_OEM_6 => KeyCode::RightBracket, VK_OEM_7 => KeyCode::Quote, VK_BACK => KeyCode::Backspace, VK_TAB => KeyCode::Tab, VK_RETURN => KeyCode::Return, VK_PAUSE => KeyCode::Pause, VK_ESCAPE => KeyCode::Escape, VK_SPACE => KeyCode::Space, VK_PRIOR => KeyCode::PageUp, VK_NEXT => KeyCode::PageDown, VK_END => KeyCode::End, VK_HOME => KeyCode::Home, VK_LEFT => KeyCode::ArrowLeft, VK_UP => KeyCode::ArrowUp, VK_RIGHT => KeyCode::ArrowRight, VK_DOWN => KeyCode::ArrowDown, VK_SNAPSHOT => KeyCode::PrintScreen, VK_INSERT => KeyCode::Insert, VK_DELETE => KeyCode::Delete, VK_CAPITAL => KeyCode::CapsLock, VK_NUMLOCK => KeyCode::NumLock, VK_SCROLL => KeyCode::ScrollLock, VK_0 => KeyCode::Key0, VK_1 => KeyCode::Key1, VK_2 => KeyCode::Key2, VK_3 => KeyCode::Key3, VK_4 => KeyCode::Key4, VK_5 => KeyCode::Key5, VK_6 => KeyCode::Key6, VK_7 => KeyCode::Key7, VK_8 => KeyCode::Key8, VK_9 => KeyCode::Key9, VK_A => KeyCode::KeyA, VK_B => KeyCode::KeyB, VK_C => KeyCode::KeyC, VK_D => KeyCode::KeyD, VK_E => KeyCode::KeyE, VK_F => KeyCode::KeyF, VK_G => KeyCode::KeyG, VK_H => KeyCode::KeyH, VK_I => KeyCode::KeyI, VK_J => KeyCode::KeyJ, VK_K => KeyCode::KeyK, VK_L => KeyCode::KeyL, VK_M => KeyCode::KeyM, VK_N => KeyCode::KeyN, VK_O => KeyCode::KeyO, VK_P => KeyCode::KeyP, VK_Q => KeyCode::KeyQ, VK_R => KeyCode::KeyR, VK_S => KeyCode::KeyS, VK_T => KeyCode::KeyT, VK_U => KeyCode::KeyU, VK_V => KeyCode::KeyV, VK_W => KeyCode::KeyW, VK_X => KeyCode::KeyX, VK_Y => KeyCode::KeyY, VK_Z => KeyCode::KeyZ, VK_NUMPAD0 => KeyCode::Numpad0, VK_NUMPAD1 => KeyCode::Numpad1, VK_NUMPAD2 => KeyCode::Numpad2, VK_NUMPAD3 => KeyCode::Numpad3, VK_NUMPAD4 => KeyCode::Numpad4, VK_NUMPAD5 => KeyCode::Numpad5, VK_NUMPAD6 => KeyCode::Numpad6, VK_NUMPAD7 => KeyCode::Numpad7, VK_NUMPAD8 => KeyCode::Numpad8, VK_NUMPAD9 => KeyCode::Numpad9, VK_MULTIPLY => KeyCode::NumpadMultiply, VK_ADD => KeyCode::NumpadAdd, VK_SUBTRACT => KeyCode::NumpadSubtract, VK_DECIMAL => KeyCode::NumpadDecimal, VK_DIVIDE => KeyCode::NumpadDivide, VK_F1 => KeyCode::F1, VK_F2 => KeyCode::F2, VK_F3 => KeyCode::F3, VK_F4 => KeyCode::F4, VK_F5 => KeyCode::F5, VK_F6 => KeyCode::F6, VK_F7 => KeyCode::F7, VK_F8 => KeyCode::F8, VK_F9 => KeyCode::F9, VK_F10 => KeyCode::F10, VK_F11 => KeyCode::F11, VK_F12 => KeyCode::F12 VK_F13 => KeyCode::F13, VK_F14 => KeyCode::F14, VK_F15 => KeyCode::F15, VK_F16 => KeyCode::F16, VK_F17 => KeyCode::F17, VK_F18 => KeyCode::F18, VK_F19 => KeyCode::F19, VK_F20 => KeyCode::F20, VK_F21 => KeyCode::F21, VK_F22 => KeyCode::F22, VK_F23 => KeyCode::F23, VK_F24 => KeyCode::F24, } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn win_vk() { assert_eq!(KeyCode::from(0x4F_i32), KeyCode::KeyO); // VK_ZOOM assert_eq!(KeyCode::from(0xFB_i32), KeyCode::Unknown(251)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/paint.rs
druid-shell/src/backend/windows/paint.rs
// Copyright 2017 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Bureaucracy to create render targets for painting. //! //! Note that these are currently implemented using hwnd render targets //! because they are are (relatively) easy, but for high performance we want //! dxgi render targets so we can use present options for minimal //! invalidation and low-latency frame timing. use std::ptr::null_mut; use winapi::ctypes::c_void; use winapi::shared::dxgi::*; use winapi::shared::dxgi1_2::*; use winapi::shared::dxgiformat::*; use winapi::shared::winerror::*; use winapi::um::d2d1::*; use winapi::um::dcommon::*; use winapi::Interface; use piet_common::d2d::D2DFactory; use crate::backend::windows::DxgiSurfaceRenderTarget; use crate::scale::Scale; use super::error::Error; use super::util::as_result; use super::window::SCALE_TARGET_DPI; /// Create a render target from a DXGI swapchain. /// /// TODO: probably want to create a DeviceContext, it's more flexible. pub(crate) unsafe fn create_render_target_dxgi( d2d_factory: &D2DFactory, swap_chain: *mut IDXGISwapChain1, scale: Scale, transparent: bool, ) -> Result<DxgiSurfaceRenderTarget, Error> { let mut buffer: *mut IDXGISurface = null_mut(); as_result((*swap_chain).GetBuffer( 0, &IDXGISurface::uuidof(), &mut buffer as *mut _ as *mut *mut c_void, ))?; let props = D2D1_RENDER_TARGET_PROPERTIES { _type: D2D1_RENDER_TARGET_TYPE_DEFAULT, pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: if transparent { D2D1_ALPHA_MODE_PREMULTIPLIED } else { D2D1_ALPHA_MODE_IGNORE }, }, dpiX: (scale.x() * SCALE_TARGET_DPI) as f32, dpiY: (scale.y() * SCALE_TARGET_DPI) as f32, usage: D2D1_RENDER_TARGET_USAGE_NONE, minLevel: D2D1_FEATURE_LEVEL_DEFAULT, }; let mut render_target: *mut ID2D1RenderTarget = null_mut(); let res = (*d2d_factory.get_raw()).CreateDxgiSurfaceRenderTarget(buffer, &props, &mut render_target); (*buffer).Release(); if SUCCEEDED(res) { // TODO: maybe use builder Ok(DxgiSurfaceRenderTarget::from_raw(render_target)) } else { Err(res.into()) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/dialog.rs
druid-shell/src/backend/windows/dialog.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! File open/save dialogs, Windows implementation. //! //! For more information about how windows handles file dialogs, see //! documentation for [_FILEOPENDIALOGOPTIONS] and [SetFileTypes]. //! //! [_FILEOPENDIALOGOPTIONS]: https://docs.microsoft.com/en-us/windows/desktop/api/shobjidl_core/ne-shobjidl_core-_fileopendialogoptions //! [SetFileTypes]: https://docs.microsoft.com/en-ca/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfiletypes #![allow(non_upper_case_globals)] use std::convert::TryInto; use std::ffi::OsString; use std::ptr::null_mut; use winapi::ctypes::c_void; use winapi::shared::minwindef::*; use winapi::shared::ntdef::LPWSTR; use winapi::shared::windef::*; use winapi::shared::wtypesbase::*; use winapi::um::combaseapi::*; use winapi::um::shobjidl::*; use winapi::um::shobjidl_core::*; use winapi::um::shtypes::COMDLG_FILTERSPEC; use winapi::{Interface, DEFINE_GUID}; use wio::com::ComPtr; use super::error::Error; use super::util::{as_result, FromWide, ToWide}; use crate::dialog::{FileDialogOptions, FileDialogType, FileSpec}; // TODO: remove these when they get added to winapi DEFINE_GUID! {CLSID_FileOpenDialog, 0xDC1C_5A9C, 0xE88A, 0x4DDE, 0xA5, 0xA1, 0x60, 0xF8, 0x2A, 0x20, 0xAE, 0xF7} DEFINE_GUID! {CLSID_FileSaveDialog, 0xC0B4_E2F3, 0xBA21, 0x4773, 0x8D, 0xBA, 0x33, 0x5E, 0xC9, 0x46, 0xEB, 0x8B} /// For each item in `spec`, returns a pair of utf16 strings representing the name /// and the filter spec. /// /// As an example: given the name `"Markdown Document"`, and the extensions /// `&["md", "mdown", "markdown"]`, this will return /// `("Markdown Document (*.md; *.mdown; *.markdown)", "*.md;*.mdown;*.markdown")`. /// /// The first of these is displayed to the user, and the second is used to match the path. unsafe fn make_wstrs(spec: &FileSpec) -> (Vec<u16>, Vec<u16>) { let exts = spec .extensions .iter() .map(|s| normalize_extension(s)) .collect::<Vec<_>>(); let name = format!("{} ({})", spec.name, exts.as_slice().join("; ")).to_wide(); let extensions = exts.as_slice().join(";").to_wide(); (name, extensions) } /// add preceding *., trimming preceding *. that might've been included by the user. fn normalize_extension(ext: &str) -> String { format!("*.{}", ext.trim_start_matches('*').trim_start_matches('.')) } pub(crate) unsafe fn get_file_dialog_path( hwnd_owner: HWND, ty: FileDialogType, options: FileDialogOptions, ) -> Result<OsString, Error> { let mut pfd: *mut IFileDialog = null_mut(); let (class, id) = match ty { FileDialogType::Open => (&CLSID_FileOpenDialog, IFileOpenDialog::uuidof()), FileDialogType::Save => (&CLSID_FileSaveDialog, IFileSaveDialog::uuidof()), }; as_result(CoCreateInstance( class, null_mut(), CLSCTX_INPROC_SERVER, &id, &mut pfd as *mut *mut IFileDialog as *mut LPVOID, ))?; let file_dialog = ComPtr::from_raw(pfd); // set options let mut flags: DWORD = 0; if options.show_hidden { flags |= FOS_FORCESHOWHIDDEN; } if options.select_directories { flags |= FOS_PICKFOLDERS; } if options.multi_selection { flags |= FOS_ALLOWMULTISELECT; } // - allowed filetypes // this is a vec of vec<u16>, e.g wide strings. this memory needs to be live // until `Show` returns. let spec = options.allowed_types.as_ref().map(|allowed_types| { allowed_types .iter() .map(|t| make_wstrs(t)) .collect::<Vec<_>>() }); // this is a vector of structs whose members point into the vector above. // this has to outlive that vector. let raw_spec = spec.as_ref().map(|buf_pairs| { buf_pairs .iter() .map(|(name, ext)| COMDLG_FILTERSPEC { pszName: name.as_ptr(), pszSpec: ext.as_ptr(), }) .collect::<Vec<_>>() }); // Having Some in raw_spec means that we can safely unwrap options.allowed_types. // Be careful when moving the unwraps out of this block or changing how raw_spec is made. if let Some(spec) = &raw_spec { // We also want to make sure that options.allowed_types wasn't Some(zero-length vector) if !spec.is_empty() { as_result(file_dialog.SetFileTypes(spec.len() as u32, spec.as_ptr()))?; let index = match (&options.default_type, &options.allowed_types) { (Some(typ), Some(typs)) => typs.iter().position(|t| t == typ).unwrap_or(0), _ => 0, }; let default_allowed_type = options.allowed_types.as_ref().unwrap().get(index).unwrap(); let default_extension = default_allowed_type.extensions.first().unwrap_or(&""); as_result(file_dialog.SetFileTypeIndex((index + 1).try_into().unwrap()))?; as_result(file_dialog.SetDefaultExtension(default_extension.to_wide().as_ptr()))?; } } as_result(file_dialog.SetOptions(flags))?; // set a starting directory if let Some(path) = options.starting_directory { let mut item: *mut IShellItem = null_mut(); if let Err(err) = as_result(SHCreateItemFromParsingName( path.as_os_str().to_wide().as_ptr(), null_mut(), &IShellItem::uuidof(), &mut item as *mut *mut IShellItem as *mut *mut c_void, )) { tracing::warn!("Failed to convert path: {}", err.to_string()); } else { as_result(file_dialog.SetDefaultFolder(item))?; } } // show the dialog as_result(file_dialog.Show(hwnd_owner))?; let mut result_ptr: *mut IShellItem = null_mut(); as_result(file_dialog.GetResult(&mut result_ptr))?; let shell_item = ComPtr::from_raw(result_ptr); let mut display_name: LPWSTR = null_mut(); as_result(shell_item.GetDisplayName(SIGDN_FILESYSPATH, &mut display_name))?; let filename = display_name.to_os_string(); CoTaskMemFree(display_name as LPVOID); Ok(filename) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/clipboard.rs
druid-shell/src/backend/windows/clipboard.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interactions with the system pasteboard on Windows. use std::ffi::CString; use std::mem; use std::ptr; use winapi::shared::minwindef::{FALSE, UINT}; use winapi::shared::ntdef::{CHAR, HANDLE, LPWSTR, WCHAR}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::errhandlingapi::GetLastError; use winapi::um::winbase::{GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock, GMEM_MOVEABLE}; use winapi::um::winuser::{ CloseClipboard, EmptyClipboard, EnumClipboardFormats, GetClipboardData, GetClipboardFormatNameA, IsClipboardFormatAvailable, OpenClipboard, RegisterClipboardFormatA, SetClipboardData, CF_UNICODETEXT, }; use super::util::{FromWide, ToWide}; use crate::clipboard::{ClipboardFormat, FormatId}; #[derive(Debug, Clone, Default)] pub struct Clipboard; impl Clipboard { /// Put a string onto the system clipboard. pub fn put_string(&mut self, s: impl AsRef<str>) { let s = s.as_ref(); let format: ClipboardFormat = s.into(); self.put_formats(&[format]) } /// Put multi-format data on the system clipboard. pub fn put_formats(&mut self, formats: &[ClipboardFormat]) { with_clipboard(|| unsafe { EmptyClipboard(); for format in formats { let handle = make_handle(format); let format_id = match get_format_id(format.identifier) { Some(id) => id, None => { tracing::warn!( "failed to register clipboard format {}", &format.identifier ); continue; } }; let result = SetClipboardData(format_id, handle); if result.is_null() { tracing::warn!( "failed to set clipboard for fmt {}, error: {}", &format.identifier, GetLastError() ); } } }); } /// Get a string from the system clipboard, if one is available. pub fn get_string(&self) -> Option<String> { with_clipboard(|| unsafe { let handle = GetClipboardData(CF_UNICODETEXT); if handle.is_null() { None } else { let unic_str = GlobalLock(handle) as LPWSTR; let result = unic_str.to_string(); GlobalUnlock(handle); result } }) .flatten() } /// Given a list of supported clipboard types, returns the supported type which has /// highest priority on the system clipboard, or `None` if no types are supported. pub fn preferred_format(&self, formats: &[FormatId]) -> Option<FormatId> { with_clipboard(|| { let format_ids = formats .iter() .map(|id| get_format_id(id)) .collect::<Vec<_>>(); let first_match = iter_clipboard_types().find(|available| format_ids.contains(&Some(*available))); let format_idx = first_match.and_then(|id| format_ids.iter().position(|i| i == &Some(id))); format_idx.map(|idx| formats[idx]) }) .flatten() } /// Return data in a given format, if available. /// /// It is recommended that the `fmt` argument be a format returned by /// [`Clipboard::preferred_format`] pub fn get_format(&self, format: FormatId) -> Option<Vec<u8>> { if format == ClipboardFormat::TEXT { return self.get_string().map(String::into_bytes); } with_clipboard(|| { let format_id = match get_format_id(format) { Some(id) => id, None => { tracing::warn!("failed to register clipboard format {}", format); return None; } }; unsafe { if IsClipboardFormatAvailable(format_id) != 0 { let handle = GetClipboardData(format_id); let size = GlobalSize(handle); let locked = GlobalLock(handle) as *const u8; let mut dest = Vec::<u8>::with_capacity(size); ptr::copy_nonoverlapping(locked, dest.as_mut_ptr(), size); dest.set_len(size); GlobalUnlock(handle); Some(dest) } else { None } } }) .flatten() } pub fn available_type_names(&self) -> Vec<String> { with_clipboard(|| { iter_clipboard_types() .map(|id| format!("{}: {}", get_format_name(id), id)) .collect() }) .unwrap_or_default() } } fn with_clipboard<V>(f: impl FnOnce() -> V) -> Option<V> { unsafe { if OpenClipboard(ptr::null_mut()) == FALSE { return None; } let result = f(); CloseClipboard(); Some(result) } } unsafe fn make_handle(format: &ClipboardFormat) -> HANDLE { if format.identifier == ClipboardFormat::TEXT { let s = std::str::from_utf8_unchecked(&format.data); let wstr = s.to_wide(); let handle = GlobalAlloc(GMEM_MOVEABLE, wstr.len() * mem::size_of::<WCHAR>()); let locked = GlobalLock(handle) as LPWSTR; ptr::copy_nonoverlapping(wstr.as_ptr(), locked, wstr.len()); GlobalUnlock(handle); handle } else { let handle = GlobalAlloc(GMEM_MOVEABLE, format.data.len() * mem::size_of::<CHAR>()); let locked = GlobalLock(handle) as *mut u8; ptr::copy_nonoverlapping(format.data.as_ptr(), locked, format.data.len()); GlobalUnlock(handle); handle } } fn get_format_id(format: FormatId) -> Option<UINT> { if let Some((id, _)) = STANDARD_FORMATS.iter().find(|(_, s)| s == &format) { return Some(*id); } match format { ClipboardFormat::TEXT => Some(CF_UNICODETEXT), other => register_identifier(other), } } fn register_identifier(ident: &str) -> Option<UINT> { let cstr = match CString::new(ident) { Ok(s) => s, Err(_) => { // granted this should happen _never_, but unwrap feels bad tracing::warn!("Null byte in clipboard identifier '{}'", ident); return None; } }; unsafe { let pb_format = RegisterClipboardFormatA(cstr.as_ptr()); if pb_format == 0 { let err = GetLastError(); tracing::warn!( "failed to register clipboard format '{}'; error {}.", ident, err ); return None; } Some(pb_format) } } fn iter_clipboard_types() -> impl Iterator<Item = UINT> { struct ClipboardTypeIter { last: UINT, done: bool, } impl Iterator for ClipboardTypeIter { type Item = UINT; fn next(&mut self) -> Option<Self::Item> { if self.done { return None; } unsafe { let nxt = EnumClipboardFormats(self.last); match nxt { 0 => { self.done = true; match GetLastError() { ERROR_SUCCESS => (), other => { tracing::error!( "iterating clipboard formats failed, error={}", other ) } } None } nxt => { self.last = nxt; Some(nxt) } } } } } ClipboardTypeIter { last: 0, done: false, } } fn get_format_name(format: UINT) -> String { if let Some(name) = get_standard_format_name(format) { return name.to_owned(); } const BUF_SIZE: usize = 64; unsafe { let mut buffer: [CHAR; BUF_SIZE] = [0; BUF_SIZE]; let result = GetClipboardFormatNameA(format, buffer.as_mut_ptr(), BUF_SIZE as i32); if result > 0 { let len = result as usize; let lpstr = std::slice::from_raw_parts(buffer.as_ptr() as *const u8, len); String::from_utf8_lossy(lpstr).into_owned() } else { let err = GetLastError(); if err == 87 { String::from("Unknown Format") } else { tracing::warn!( "error getting clipboard format name for format {}, errno {}", format, err ); String::new() } } } } // https://docs.microsoft.com/en-ca/windows/win32/dataxchg/standard-clipboard-formats static STANDARD_FORMATS: &[(UINT, &str)] = &[ (1, "CF_TEXT"), (2, "CF_BITMAP"), (3, "CF_METAFILEPICT"), (4, "CF_SYLK"), (5, "CF_DIF"), (6, "CF_TIFF"), (7, "CF_OEMTEXT"), (8, "CF_DIB"), (9, "CF_PALETTE"), (10, "CF_PENDATA"), (11, "CF_RIFF"), (12, "CF_WAVE"), (13, "CF_UNICODETEXT"), (14, "CF_ENHMETAFILE"), (15, "CF_HDROP"), (16, "CF_LOCALE"), (17, "CF_DIBV5"), (0x0080, "CF_OWNERDISPLAY"), (0x0081, "CF_DSPTEXT"), (0x0082, "CF_DSPBITMAP"), (0x0083, "CF_DSPMETAFILEPICT"), (0x008E, "CF_DSPENHMETAFILE"), (0x0200, "CF_PRIVATEFIRST"), (0x02FF, "CF_PRIVATELAST"), (0x0300, "CF_GDIOBJFIRST"), (0x03FF, "CF_GDIOBJLAST"), ]; fn get_standard_format_name(format: UINT) -> Option<&'static str> { STANDARD_FORMATS .iter() .find(|(id, _)| *id == format) .map(|(_, s)| *s) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/menu.rs
druid-shell/src/backend/windows/menu.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Safe wrapper for menus. use std::collections::HashMap; use std::fmt::Write as _; use std::mem; use std::ptr::null; use winapi::shared::basetsd::*; use winapi::shared::windef::*; use winapi::um::winuser::*; use super::util::ToWide; use crate::hotkey::HotKey; use crate::keyboard::{KbKey, Modifiers}; /// A menu object, which can be either a top-level menubar or a /// submenu. pub struct Menu { hmenu: HMENU, accels: HashMap<u32, ACCEL>, } impl Drop for Menu { fn drop(&mut self) { unsafe { DestroyMenu(self.hmenu); } } } impl Menu { /// Create a new menu for a window. pub fn new() -> Menu { unsafe { let hmenu = CreateMenu(); Menu { hmenu, accels: HashMap::default(), } } } /// Create a new popup (context / right-click) menu. pub fn new_for_popup() -> Menu { unsafe { let hmenu = CreatePopupMenu(); Menu { hmenu, accels: HashMap::default(), } } } pub fn into_hmenu(self) -> HMENU { let hmenu = self.hmenu; mem::forget(self); hmenu } /// Add a dropdown menu. This takes the menu by ownership, but we'll /// probably want to change that so we can manipulate it later. /// /// The `text` field has all the fun behavior of winapi CreateMenu. pub fn add_dropdown(&mut self, mut menu: Menu, text: &str, enabled: bool) { let child_accels = std::mem::take(&mut menu.accels); self.accels.extend(child_accels); unsafe { let mut flags = MF_POPUP; if !enabled { flags |= MF_GRAYED; } AppendMenuW( self.hmenu, flags, menu.into_hmenu() as UINT_PTR, text.to_wide().as_ptr(), ); } } /// Add an item to the menu. pub fn add_item( &mut self, id: u32, text: &str, key: Option<&HotKey>, selected: Option<bool>, enabled: bool, ) { let mut anno_text = text.to_string(); if let Some(key) = key { anno_text.push('\t'); format_hotkey(key, &mut anno_text); } unsafe { let mut flags = MF_STRING; if !enabled { flags |= MF_GRAYED; } if let Some(true) = selected { flags |= MF_CHECKED; } AppendMenuW( self.hmenu, flags, id as UINT_PTR, anno_text.to_wide().as_ptr(), ); } if let Some(key) = key { if let Some(accel) = convert_hotkey(id, key) { self.accels.insert(id, accel); } } } /// Add a separator to the menu. pub fn add_separator(&mut self) { unsafe { AppendMenuW(self.hmenu, MF_SEPARATOR, 0, null()); } } /// Get the accels table pub fn accels(&self) -> Option<Vec<ACCEL>> { if self.accels.is_empty() { return None; } Some(self.accels.values().cloned().collect()) } } /// Convert a hotkey to an accelerator. /// /// Note that this conversion is dependent on the keyboard map. /// Therefore, when the keyboard map changes (WM_INPUTLANGCHANGE), /// we should be rebuilding the accelerator map. fn convert_hotkey(id: u32, key: &HotKey) -> Option<ACCEL> { let mut virt_key = FVIRTKEY; let key_mods: Modifiers = key.mods.into(); if key_mods.ctrl() { virt_key |= FCONTROL; } if key_mods.alt() { virt_key |= FALT; } if key_mods.shift() { virt_key |= FSHIFT; } let raw_key = if let Some(vk_code) = super::keyboard::key_to_vk(&key.key) { let mod_code = vk_code >> 8; if mod_code & 0x1 != 0 { virt_key |= FSHIFT; } if mod_code & 0x02 != 0 { virt_key |= FCONTROL; } if mod_code & 0x04 != 0 { virt_key |= FALT; } vk_code & 0x00ff } else { tracing::error!("Failed to convert key {:?} into virtual key code", key.key); return None; }; Some(ACCEL { fVirt: virt_key, key: raw_key as u16, cmd: id as u16, }) } /// Format the hotkey in a Windows-native way. fn format_hotkey(key: &HotKey, s: &mut String) { let key_mods: Modifiers = key.mods.into(); if key_mods.ctrl() { s.push_str("Ctrl+"); } if key_mods.shift() { s.push_str("Shift+"); } if key_mods.alt() { s.push_str("Alt+"); } if key_mods.meta() { s.push_str("Windows+"); } match &key.key { KbKey::Character(c) => match c.as_str() { "+" => s.push_str("Plus"), "-" => s.push_str("Minus"), " " => s.push_str("Space"), _ => s.extend(c.chars().flat_map(|c| c.to_uppercase())), }, KbKey::Escape => s.push_str("Esc"), KbKey::Delete => s.push_str("Del"), KbKey::Insert => s.push_str("Ins"), KbKey::PageUp => s.push_str("PgUp"), KbKey::PageDown => s.push_str("PgDn"), // These names match LibreOffice. KbKey::ArrowLeft => s.push_str("Left"), KbKey::ArrowRight => s.push_str("Right"), KbKey::ArrowUp => s.push_str("Up"), KbKey::ArrowDown => s.push_str("Down"), _ => write!(s, "{}", key.key) .unwrap_or_else(|err| tracing::warn!("Failed to convert hotkey to string: {}", err)), } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/error.rs
druid-shell/src/backend/windows/error.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Errors at the application shell level. use std::fmt; use std::ptr::{null, null_mut}; use winapi::shared::minwindef::{DWORD, HLOCAL}; use winapi::shared::ntdef::LPWSTR; use winapi::shared::winerror::HRESULT; use winapi::um::winbase::{ FormatMessageW, LocalFree, FORMAT_MESSAGE_ALLOCATE_BUFFER, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS, FORMAT_MESSAGE_MAX_WIDTH_MASK, }; use super::util::FromWide; /// Windows backend error. #[derive(Debug, Clone)] pub enum Error { /// Windows error code. Hr(HRESULT), // Maybe include the full error from the direct2d crate. Direct2D, /// A function is available on newer version of windows. OldWindows, /// The `hwnd` pointer was null. NullHwnd, } fn hresult_description(hr: HRESULT) -> Option<String> { unsafe { let mut message_buffer: LPWSTR = std::ptr::null_mut(); let format_result = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, null(), hr as DWORD, 0, &mut message_buffer as *mut LPWSTR as LPWSTR, 0, null_mut(), ); if format_result == 0 || message_buffer.is_null() { return None; } let result = message_buffer.to_string(); LocalFree(message_buffer as HLOCAL); result } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { Error::Hr(hr) => { write!(f, "HRESULT 0x{hr:x}")?; if let Some(description) = hresult_description(*hr) { write!(f, ": {description}")?; } Ok(()) } Error::Direct2D => write!(f, "Direct2D error"), Error::OldWindows => write!(f, "Attempted newer API on older Windows"), Error::NullHwnd => write!(f, "Window handle is Null"), } } } impl std::error::Error for Error {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/application.rs
druid-shell/src/backend/windows/application.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Windows implementation of features at the application scope. use std::cell::RefCell; use std::collections::HashSet; use std::mem; use std::ptr; use std::rc::Rc; use std::sync::atomic::{AtomicBool, Ordering}; use winapi::shared::minwindef::{FALSE, HINSTANCE}; use winapi::shared::ntdef::LPCWSTR; use winapi::shared::windef::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, HCURSOR, HWND}; use winapi::shared::winerror::HRESULT_FROM_WIN32; use winapi::um::errhandlingapi::GetLastError; use winapi::um::libloaderapi::GetModuleHandleW; use winapi::um::shellscalingapi::PROCESS_PER_MONITOR_DPI_AWARE; use winapi::um::winnls::GetUserDefaultLocaleName; use winapi::um::winnt::LOCALE_NAME_MAX_LENGTH; use winapi::um::winuser::{ DispatchMessageW, GetAncestor, GetMessageW, LoadIconW, PeekMessageW, PostMessageW, PostQuitMessage, RegisterClassW, TranslateAcceleratorW, TranslateMessage, GA_ROOT, MAKEINTRESOURCEW, MSG, PM_NOREMOVE, WM_TIMER, WNDCLASSW, }; use piet_common::D2DLoadedFonts; use crate::application::AppHandler; use super::accels; use super::clipboard::Clipboard; use super::error::Error; use super::util::{self, FromWide, ToWide, CLASS_NAME, OPTIONAL_FUNCTIONS}; use super::window::{self, DS_REQUEST_DESTROY}; #[derive(Clone)] pub(crate) struct Application { state: Rc<RefCell<State>>, pub(crate) fonts: D2DLoadedFonts, } struct State { quitting: bool, windows: HashSet<HWND>, } /// Used to ensure the window class is registered only once per process. static WINDOW_CLASS_REGISTERED: AtomicBool = AtomicBool::new(false); impl Application { pub fn new() -> Result<Application, Error> { Application::init()?; let state = Rc::new(RefCell::new(State { quitting: false, windows: HashSet::new(), })); let fonts = D2DLoadedFonts::default(); Ok(Application { state, fonts }) } /// Initialize the app. At the moment, this is mostly needed for hi-dpi. // TODO: Report back an error instead of panicking #[allow(clippy::unnecessary_wraps)] fn init() -> Result<(), Error> { util::attach_console(); if let Some(func) = OPTIONAL_FUNCTIONS.SetProcessDpiAwarenessContext { // This function is only supported on windows 10 unsafe { func(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); } } else if let Some(func) = OPTIONAL_FUNCTIONS.SetProcessDpiAwareness { unsafe { func(PROCESS_PER_MONITOR_DPI_AWARE); } } if WINDOW_CLASS_REGISTERED .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .is_ok() { let class_name = CLASS_NAME.to_wide(); let icon = unsafe { LoadIconW(GetModuleHandleW(0 as LPCWSTR), MAKEINTRESOURCEW(1)) }; let wnd = WNDCLASSW { style: 0, lpfnWndProc: Some(window::win_proc_dispatch), cbClsExtra: 0, cbWndExtra: 0, hInstance: 0 as HINSTANCE, hIcon: icon, hCursor: 0 as HCURSOR, hbrBackground: ptr::null_mut(), // We control all the painting lpszMenuName: 0 as LPCWSTR, lpszClassName: class_name.as_ptr(), }; let class_atom = unsafe { RegisterClassW(&wnd) }; if class_atom == 0 { panic!("Error registering class"); } } Ok(()) } pub fn add_window(&self, hwnd: HWND) -> bool { self.state.borrow_mut().windows.insert(hwnd) } pub fn remove_window(&self, hwnd: HWND) -> bool { self.state.borrow_mut().windows.remove(&hwnd) } pub fn run(self, _handler: Option<Box<dyn AppHandler>>) { unsafe { // Handle windows messages. // // NOTE: Code here will not run when we aren't in charge of the message loop. That // will include when moving or resizing the window, and when showing modal dialogs. loop { let mut msg = mem::MaybeUninit::uninit(); // Timer messages have a low priority and tend to get delayed. Peeking for them // helps for some reason; see // https://devblogs.microsoft.com/oldnewthing/20191108-00/?p=103080 PeekMessageW( msg.as_mut_ptr(), ptr::null_mut(), WM_TIMER, WM_TIMER, PM_NOREMOVE, ); let res = GetMessageW(msg.as_mut_ptr(), ptr::null_mut(), 0, 0); if res <= 0 { if res == -1 { tracing::error!( "GetMessageW failed: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } break; } let mut msg: MSG = msg.assume_init(); let accels = accels::find_accels(GetAncestor(msg.hwnd, GA_ROOT)); let translated = accels .is_some_and(|it| TranslateAcceleratorW(msg.hwnd, it.handle(), &mut msg) != 0); if !translated { TranslateMessage(&msg); DispatchMessageW(&msg); } } } } pub fn quit(&self) { if let Ok(mut state) = self.state.try_borrow_mut() { if !state.quitting { state.quitting = true; unsafe { // We want to queue up the destruction of all our windows. // Failure to do so will lead to resource leaks // and an eventual error code exit for the process. for hwnd in &state.windows { if PostMessageW(*hwnd, DS_REQUEST_DESTROY, 0, 0) == FALSE { tracing::warn!( "PostMessageW DS_REQUEST_DESTROY failed: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } } // PostQuitMessage sets a quit request flag in the OS. // The actual WM_QUIT message is queued but won't be sent // until all other important events have been handled. PostQuitMessage(0); } } } else { tracing::warn!("Application state already borrowed"); } } pub fn clipboard(&self) -> Clipboard { Clipboard } pub fn get_locale() -> String { let mut buf = [0u16; LOCALE_NAME_MAX_LENGTH]; let len_with_null = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as _) as usize }; let locale = if len_with_null > 0 { buf.get(..len_with_null - 1).and_then(FromWide::to_string) } else { None }; locale.unwrap_or_else(|| { tracing::warn!("Failed to get user locale"); "en-US".into() }) } } pub fn init_harness() {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/util.rs
druid-shell/src/backend/windows/util.rs
// Copyright 2017 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Various utilities for working with windows. Includes utilities for converting between Windows //! and Rust types, including strings. //! Also includes some code to dynamically load functions at runtime. This is needed for functions //! which are only supported on certain versions of windows. use std::ffi::{CString, OsStr, OsString}; use std::mem; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr; use std::slice; use once_cell::sync::Lazy; use winapi::ctypes::c_void; use winapi::shared::dxgi::IDXGIDevice; use winapi::shared::guiddef::REFIID; use winapi::shared::minwindef::{BOOL, HMODULE, UINT}; use winapi::shared::ntdef::{HRESULT, LPWSTR}; use winapi::shared::windef::{HMONITOR, HWND, RECT}; use winapi::shared::winerror::SUCCEEDED; use winapi::um::fileapi::{CreateFileA, GetFileType, OPEN_EXISTING}; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::libloaderapi::{GetModuleHandleW, GetProcAddress, LoadLibraryW}; use winapi::um::processenv::{GetStdHandle, SetStdHandle}; use winapi::um::shellscalingapi::{MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS}; use winapi::um::winbase::{FILE_TYPE_UNKNOWN, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE}; use winapi::um::wincon::{AttachConsole, ATTACH_PARENT_PROCESS}; use winapi::um::winnt::{FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE}; use crate::kurbo::Rect; use crate::region::Region; use crate::scale::{Scalable, Scale}; use super::error::Error; pub fn as_result(hr: HRESULT) -> Result<(), Error> { if SUCCEEDED(hr) { Ok(()) } else { Err(Error::Hr(hr)) } } impl From<HRESULT> for Error { fn from(hr: HRESULT) -> Error { Error::Hr(hr) } } pub trait ToWide { #[allow(dead_code)] fn to_wide_sized(&self) -> Vec<u16>; fn to_wide(&self) -> Vec<u16>; } impl<T> ToWide for T where T: AsRef<OsStr>, { fn to_wide_sized(&self) -> Vec<u16> { self.as_ref().encode_wide().collect() } fn to_wide(&self) -> Vec<u16> { self.as_ref().encode_wide().chain(Some(0)).collect() } } pub trait FromWide { fn to_u16_slice(&self) -> &[u16]; fn to_os_string(&self) -> OsString { OsStringExt::from_wide(self.to_u16_slice()) } fn to_string(&self) -> Option<String> { String::from_utf16(self.to_u16_slice()).ok() } } impl FromWide for LPWSTR { fn to_u16_slice(&self) -> &[u16] { unsafe { let mut len = 0; while *self.offset(len) != 0 { len += 1; } slice::from_raw_parts(*self, len as usize) } } } impl FromWide for [u16] { fn to_u16_slice(&self) -> &[u16] { self } } /// Converts a `Rect` to a winapi `RECT`. #[inline] pub(crate) fn rect_to_recti(rect: Rect) -> RECT { RECT { left: rect.x0 as i32, top: rect.y0 as i32, right: rect.x1 as i32, bottom: rect.y1 as i32, } } /// Converts a winapi `RECT` to a `Rect`. #[inline] pub(crate) fn recti_to_rect(rect: RECT) -> Rect { Rect::new( rect.left as f64, rect.top as f64, rect.right as f64, rect.bottom as f64, ) } /// Converts a `Region` into a vec of winapi `RECT`, with a scaling applied. /// If necessary, the rectangles are rounded to the nearest pixel border. pub(crate) fn region_to_rectis(region: &Region, scale: Scale) -> Vec<RECT> { region .rects() .iter() .map(|r| rect_to_recti(r.to_px(scale).round())) .collect() } // Types for functions we want to load, which are only supported on newer windows versions // from user32.dll type GetDpiForSystem = unsafe extern "system" fn() -> UINT; type GetDpiForWindow = unsafe extern "system" fn(HWND) -> UINT; type SetProcessDpiAwarenessContext = unsafe extern "system" fn(winapi::shared::windef::DPI_AWARENESS_CONTEXT) -> BOOL; type GetSystemMetricsForDpi = unsafe extern "system" fn(winapi::ctypes::c_int, UINT) -> winapi::ctypes::c_int; // from shcore.dll type GetDpiForMonitor = unsafe extern "system" fn(HMONITOR, MONITOR_DPI_TYPE, *mut UINT, *mut UINT); type SetProcessDpiAwareness = unsafe extern "system" fn(PROCESS_DPI_AWARENESS) -> HRESULT; #[allow(non_snake_case)] type DCompositionCreateDevice = unsafe extern "system" fn( dxgiDevice: *const IDXGIDevice, iid: REFIID, dcompositionDevice: *mut *mut c_void, ) -> HRESULT; #[allow(non_snake_case)] // For member fields pub struct OptionalFunctions { #[allow(dead_code)] pub GetDpiForSystem: Option<GetDpiForSystem>, pub GetDpiForWindow: Option<GetDpiForWindow>, pub SetProcessDpiAwarenessContext: Option<SetProcessDpiAwarenessContext>, pub GetDpiForMonitor: Option<GetDpiForMonitor>, pub SetProcessDpiAwareness: Option<SetProcessDpiAwareness>, pub GetSystemMetricsForDpi: Option<GetSystemMetricsForDpi>, pub DCompositionCreateDevice: Option<DCompositionCreateDevice>, } #[allow(non_snake_case)] // For local variables fn load_optional_functions() -> OptionalFunctions { // Tries to load $function from $lib. $function should be one of the types defined just before // `load_optional_functions`. This sets the corresponding local field to `Some(function pointer)` // if it manages to load the function. macro_rules! load_function { ($lib: expr, $function: ident, $min_windows_version: expr) => {{ let name = stringify!($function); // The `unwrap` is fine, because we only call this macro for winapi functions, which // have simple ascii-only names let cstr = CString::new(name).unwrap(); let function_ptr = unsafe { GetProcAddress($lib, cstr.as_ptr()) }; if function_ptr.is_null() { tracing::info!( "Could not load `{}`. Windows {} or later is needed", name, $min_windows_version ); } else { #[allow(clippy::missing_transmute_annotations)] let function = unsafe { mem::transmute::<_, $function>(function_ptr) }; $function = Some(function); } }}; } fn load_library(name: &str) -> HMODULE { let encoded_name = name.to_wide(); // If we already have loaded the library (somewhere else in the process) we don't need to // call LoadLibrary again let library = unsafe { GetModuleHandleW(encoded_name.as_ptr()) }; if !library.is_null() { return library; } unsafe { LoadLibraryW(encoded_name.as_ptr()) } } let shcore = load_library("shcore.dll"); let user32 = load_library("user32.dll"); let dcomp = load_library("dcomp.dll"); let mut GetDpiForSystem = None; let mut GetDpiForMonitor = None; let mut GetDpiForWindow = None; let mut SetProcessDpiAwarenessContext = None; let mut SetProcessDpiAwareness = None; let mut GetSystemMetricsForDpi = None; let mut DCompositionCreateDevice = None; if shcore.is_null() { tracing::info!("No shcore.dll"); } else { load_function!(shcore, SetProcessDpiAwareness, "8.1"); load_function!(shcore, GetDpiForMonitor, "8.1"); } if user32.is_null() { tracing::info!("No user32.dll"); } else { load_function!(user32, GetDpiForSystem, "10"); load_function!(user32, GetDpiForWindow, "10"); load_function!(user32, SetProcessDpiAwarenessContext, "10"); load_function!(user32, GetSystemMetricsForDpi, "10"); } if dcomp.is_null() { tracing::info!("No dcomp.dll"); } else { load_function!(dcomp, DCompositionCreateDevice, "8.1"); } OptionalFunctions { GetDpiForSystem, GetDpiForWindow, SetProcessDpiAwarenessContext, GetDpiForMonitor, SetProcessDpiAwareness, GetSystemMetricsForDpi, DCompositionCreateDevice, } } pub static OPTIONAL_FUNCTIONS: Lazy<OptionalFunctions> = Lazy::new(load_optional_functions); pub(crate) const CLASS_NAME: &str = "druid"; /// Convenience macro for defining accelerator tables. #[macro_export] macro_rules! accel { ( $( $fVirt:expr, $key:expr, $cmd:expr, )* ) => { [ $( ACCEL { fVirt: $fVirt | FVIRTKEY, key: $key as WORD, cmd: $cmd as WORD }, )* ] } } /// Attach the process to the console of the parent process. This allows xi-win to /// correctly print to a console when run from powershell or cmd. /// If no console is available, allocate a new console. pub(crate) fn attach_console() { unsafe { let stdout = GetStdHandle(STD_OUTPUT_HANDLE); if stdout != INVALID_HANDLE_VALUE && GetFileType(stdout) != FILE_TYPE_UNKNOWN { // We already have a perfectly valid stdout and must not attach. // This happens, for example in MingW consoles like git bash. return; } if AttachConsole(ATTACH_PARENT_PROCESS) > 0 { let name = CString::new("CONOUT$").unwrap(); let chnd = CreateFileA( name.as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, ptr::null_mut(), OPEN_EXISTING, 0, ptr::null_mut(), ); if chnd == INVALID_HANDLE_VALUE { // CreateFileA failed. return; } SetStdHandle(STD_OUTPUT_HANDLE, chnd); SetStdHandle(STD_ERROR_HANDLE, chnd); } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/mod.rs
druid-shell/src/backend/windows/mod.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Windows implementation of `druid-shell`. mod accels; pub mod application; pub mod clipboard; pub mod dcomp; pub mod dialog; pub mod error; mod keyboard; pub mod menu; pub mod paint; pub mod screen; mod timers; pub mod util; pub mod window; // https://docs.microsoft.com/en-us/windows/win32/direct2d/render-targets-overview // ID2D1RenderTarget is the interface. The other resources inherit from it. // // A Render Target creates resources for drawing and performs drawing operations. // // - ID2D1HwndRenderTarget objects render content to a window. // - ID2D1DCRenderTarget objects render to a GDI device context. // - bitmap render target objects render to off-screen bitmap. // - DXGI render target objects render to a DXGI surface for use with Direct3D. // // https://docs.microsoft.com/en-us/windows/win32/direct2d/devices-and-device-contexts // A Device Context, ID2D1DeviceContext, is available as of windows 7 platform update. This // is the minimum compatibility target for Druid. We are not making an effort to do // RenderTarget only. // // Basically, go from HwndRenderTarget or DxgiSurfaceRenderTarget (2d or 3d) to a Device Context. // Go back up for particular needs. use piet_common::d2d::DeviceContext; use std::fmt::{Debug, Display, Formatter}; use winapi::shared::winerror::HRESULT; use winapi::um::d2d1::ID2D1RenderTarget; use wio::com::ComPtr; #[derive(Clone)] pub struct DxgiSurfaceRenderTarget { ptr: ComPtr<ID2D1RenderTarget>, } impl DxgiSurfaceRenderTarget { /// construct from raw ptr /// /// # Safety /// TODO pub unsafe fn from_raw(raw: *mut ID2D1RenderTarget) -> Self { DxgiSurfaceRenderTarget { ptr: ComPtr::from_raw(raw), } } /// cast to DeviceContext /// /// # Safety /// TODO pub unsafe fn as_device_context(&self) -> Option<DeviceContext> { self.ptr .cast() .ok() .map(|com_ptr| DeviceContext::new(com_ptr)) } } // error handling #[allow(dead_code)] pub enum Error { WinapiError(HRESULT), } impl From<HRESULT> for Error { fn from(hr: HRESULT) -> Error { Error::WinapiError(hr) } } impl Debug for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { Error::WinapiError(hr) => write!(f, "hresult {hr:x}"), } } } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { Error::WinapiError(hr) => write!(f, "hresult {hr:x}"), } } } impl std::error::Error for Error { fn description(&self) -> &str { "winapi error" } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/window.rs
druid-shell/src/backend/windows/window.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Creation and management of windows. #![allow(non_snake_case, clippy::cast_lossless)] use std::cell::{Cell, RefCell}; use std::mem; use std::panic::Location; use std::ptr::{null, null_mut}; use std::rc::{Rc, Weak}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use scopeguard::defer; use tracing::{debug, error, warn}; use winapi::ctypes::{c_int, c_void}; use winapi::shared::dxgi::*; use winapi::shared::dxgi1_2::*; use winapi::shared::dxgiformat::*; use winapi::shared::dxgitype::*; use winapi::shared::minwindef::*; use winapi::shared::windef::*; use winapi::shared::winerror::*; use winapi::um::dcomp::{IDCompositionDevice, IDCompositionTarget, IDCompositionVisual}; use winapi::um::dwmapi::{DwmExtendFrameIntoClientArea, DwmSetWindowAttribute}; use winapi::um::errhandlingapi::GetLastError; use winapi::um::shellscalingapi::MDT_EFFECTIVE_DPI; use winapi::um::unknwnbase::*; use winapi::um::uxtheme::*; use winapi::um::wingdi::*; use winapi::um::winnt::*; use winapi::um::winreg::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD}; use winapi::um::winuser::*; use winapi::Interface; use wio::com::ComPtr; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, Win32WindowHandle}; use piet_common::d2d::{D2DFactory, DeviceContext}; use piet_common::dwrite::DwriteFactory; use crate::kurbo::{Insets, Point, Rect, Size, Vec2}; use crate::piet::{Piet, PietText, RenderContext}; use super::accels::register_accel; use super::application::Application; use super::dcomp::D3D11Device; use super::dialog::get_file_dialog_path; use super::error::Error; use super::keyboard::{self, KeyboardState}; use super::menu::Menu; use super::paint; use super::timers::TimerSlots; use super::util::{self, as_result, FromWide, ToWide, OPTIONAL_FUNCTIONS}; use crate::common_util::IdleCallback; use crate::dialog::{FileDialogOptions, FileDialogType, FileInfo}; use crate::error::Error as ShellError; use crate::keyboard::{KbKey, KeyState}; use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent}; use crate::region::Region; use crate::scale::{Scalable, Scale, ScaledArea}; use crate::text::{simulate_input, Event}; use crate::window; use crate::window::{ FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel, }; /// The backend target DPI. /// /// Windows considers 96 the default value which represents a 1.0 scale factor. pub(crate) const SCALE_TARGET_DPI: f64 = 96.0; /// Builder abstraction for creating new windows. pub(crate) struct WindowBuilder { app: Application, handler: Option<Box<dyn WinHandler>>, title: String, menu: Option<Menu>, present_strategy: PresentStrategy, resizable: bool, show_titlebar: bool, size: Option<Size>, transparent: bool, min_size: Option<Size>, position: Option<Point>, level: Option<WindowLevel>, always_on_top: bool, mouse_pass_through: bool, state: window::WindowState, } #[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] /// It's very tricky to get smooth dynamics (especially resizing) and /// good performance on Windows. This setting lets clients experiment /// with different strategies. #[allow(dead_code)] pub enum PresentStrategy { /// Corresponds to the swap effect DXGI_SWAP_EFFECT_SEQUENTIAL. It /// is compatible with GDI (such as menus), but is not the best in /// performance. /// /// In earlier testing, it exhibited diagonal banding artifacts (most /// likely because of bugs in Nvidia Optimus configurations) and did /// not do incremental present, but in more recent testing, at least /// incremental present seems to work fine. /// /// Also note, this swap effect is not compatible with DX12. #[default] Sequential, /// Corresponds to the swap effect DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL. /// In testing, it seems to perform well, but isn't compatible with /// GDI. Resize can probably be made to work reasonably smoothly with /// additional synchronization work, but has some artifacts. Flip, /// Corresponds to the swap effect DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL /// but with a redirection surface for GDI compatibility. Resize is /// very laggy and artifacty. FlipRedirect, } /// An enumeration of operations that might need to be deferred until the `WinHandler` is dropped. /// /// We work hard to avoid calling into `WinHandler` re-entrantly. Since we use /// the system's event loop, and since the `WinHandler` gets a `WindowHandle` to use, this implies /// that none of the `WindowHandle`'s methods can return control to the system's event loop /// (because if it did, the system could call back into `druid-shell` with some mouse event, and then /// we'd try to call the `WinHandler` again). /// /// The solution is that for every `WindowHandle` method that *wants* to return control to the /// system's event loop, instead of doing that we queue up a deferred operation and return /// immediately. The deferred operations will run whenever the currently running `WinHandler` /// method returns. /// /// An example call trace might look like: /// 1. the system hands a mouse click event to `druid-shell` /// 2. `druid-shell` calls `WinHandler::mouse_up` /// 3. after some processing, the `WinHandler` calls `WindowHandle::save_as`, which schedules a /// deferred op and returns immediately /// 4. after some more processing, `WinHandler::mouse_up` returns /// 5. `druid-shell` displays the "save as" dialog that was requested in step 3. enum DeferredOp { SaveAs(FileDialogOptions, FileDialogToken), Open(FileDialogOptions, FileDialogToken), ContextMenu(Menu, Point), ShowTitlebar(bool), SetPosition(Point), SetSize(Size), SetResizable(bool), SetWindowState(window::WindowState), ShowWindow(bool), ReleaseMouseCapture, SetRegion(Option<Region>), SetAlwaysOnTop(bool), SetMousePassThrough(bool), } #[derive(Clone, Debug)] pub struct WindowHandle { text: PietText, state: Weak<WindowState>, } impl PartialEq for WindowHandle { fn eq(&self, other: &Self) -> bool { match (self.state.upgrade(), other.state.upgrade()) { (None, None) => true, (Some(s), Some(o)) => std::rc::Rc::ptr_eq(&s, &o), (_, _) => false, } } } impl Eq for WindowHandle {} #[cfg(feature = "raw-win-handle")] unsafe impl HasRawWindowHandle for WindowHandle { fn raw_window_handle(&self) -> RawWindowHandle { if let Some(hwnd) = self.get_hwnd() { let mut handle = Win32WindowHandle::empty(); handle.hwnd = hwnd as *mut core::ffi::c_void; handle.hinstance = unsafe { winapi::um::libloaderapi::GetModuleHandleW(0 as winapi::um::winnt::LPCWSTR) as *mut core::ffi::c_void }; RawWindowHandle::Win32(handle) } else { error!("Cannot retrieved HWND for window."); RawWindowHandle::Win32(Win32WindowHandle::empty()) } } } /// A handle that can get used to schedule an idle handler. Note that /// this handle is thread safe. If the handle is used after the hwnd /// has been destroyed, probably not much will go wrong (the DS_RUN_IDLE /// message may be sent to a stray window). #[derive(Clone)] pub struct IdleHandle { pub(crate) hwnd: HWND, queue: Arc<Mutex<Vec<IdleKind>>>, } /// This represents different Idle Callback Mechanism enum IdleKind { Callback(Box<dyn IdleCallback>), Token(IdleToken), } /// This is the low level window state. All mutable contents are protected /// by interior mutability, so we can handle reentrant calls. struct WindowState { hwnd: Cell<HWND>, scale: Cell<Scale>, area: Cell<ScaledArea>, invalid: RefCell<Region>, has_menu: Cell<bool>, wndproc: Box<dyn WndProc>, idle_queue: Arc<Mutex<Vec<IdleKind>>>, timers: Arc<Mutex<TimerSlots>>, deferred_queue: RefCell<Vec<DeferredOp>>, has_titlebar: Cell<bool>, is_transparent: Cell<bool>, // For resizable borders, window can still be resized with code. is_resizable: Cell<bool>, handle_titlebar: Cell<bool>, active_text_input: Cell<Option<TextFieldToken>>, // Is the window focusable ("activatable" in Win32 terminology)? // False for tooltips, to prevent stealing focus from owner window. is_focusable: bool, window_level: WindowLevel, is_always_on_top: Cell<bool>, is_mouse_pass_through: Cell<bool>, } impl std::fmt::Debug for WindowState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { f.write_str("WindowState{\n")?; f.write_str(format!("{:p}", self.hwnd.get()).as_str())?; f.write_str("}")?; Ok(()) } } /// Generic handler trait for the winapi window procedure entry point. trait WndProc { fn connect(&self, handle: &WindowHandle, state: WndState); fn cleanup(&self, hwnd: HWND); fn window_proc(&self, hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) -> Option<LRESULT>; } // State and logic for the winapi window procedure entry point. Note that this level // implements policies such as the use of Direct2D for painting. struct MyWndProc { app: Application, handle: RefCell<WindowHandle>, d2d_factory: D2DFactory, text: PietText, state: RefCell<Option<WndState>>, present_strategy: PresentStrategy, } /// The mutable state of the window. struct WndState { handler: Box<dyn WinHandler>, render_target: Option<DeviceContext>, dxgi_state: Option<DxgiState>, min_size: Option<Size>, keyboard_state: KeyboardState, // Stores a set of all mouse buttons that are currently holding mouse // capture. When the first mouse button is down on our window we enter // capture, and we hold it until the last mouse button is up. captured_mouse_buttons: MouseButtons, transparent: bool, // Is this window the topmost window under the mouse cursor has_mouse_focus: bool, //TODO: track surrogate orphan last_click_time: Instant, last_click_pos: (i32, i32), click_count: u8, } /// State for DXGI swapchains. struct DxgiState { swap_chain: *mut IDXGISwapChain1, // These ComPtrs must live as long as the window #[allow(dead_code)] composition_device: Option<ComPtr<IDCompositionDevice>>, #[allow(dead_code)] composition_target: Option<ComPtr<IDCompositionTarget>>, #[allow(dead_code)] composition_visual: Option<ComPtr<IDCompositionVisual>>, } #[derive(Clone, PartialEq, Eq)] pub struct CustomCursor(Rc<HCursor>); #[derive(PartialEq, Eq)] struct HCursor(HCURSOR); impl Drop for HCursor { fn drop(&mut self) { unsafe { DestroyIcon(self.0); } } } /// Message indicating there are idle tasks to run. const DS_RUN_IDLE: UINT = WM_USER; /// Message relaying a request to destroy the window. /// /// Calling `DestroyWindow` from inside the handler is problematic /// because it will recursively cause a `WM_DESTROY` message to be /// sent to the window procedure, even while the handler is borrowed. /// Thus, the message is dropped and the handler doesn't run. /// /// As a solution, instead of immediately calling `DestroyWindow`, we /// send this message to request destroying the window, so that at the /// time it is handled, we can successfully borrow the handler. pub(crate) const DS_REQUEST_DESTROY: UINT = WM_USER + 1; /// Extract the buttons that are being held down from wparam in mouse events. fn get_buttons(wparam: WPARAM) -> MouseButtons { let mut buttons = MouseButtons::new(); if wparam & MK_LBUTTON != 0 { buttons.insert(MouseButton::Left); } if wparam & MK_RBUTTON != 0 { buttons.insert(MouseButton::Right); } if wparam & MK_MBUTTON != 0 { buttons.insert(MouseButton::Middle); } if wparam & MK_XBUTTON1 != 0 { buttons.insert(MouseButton::X1); } if wparam & MK_XBUTTON2 != 0 { buttons.insert(MouseButton::X2); } buttons } fn is_point_in_client_rect(hwnd: HWND, x: i32, y: i32) -> bool { unsafe { let mut client_rect = mem::MaybeUninit::uninit(); if GetClientRect(hwnd, client_rect.as_mut_ptr()) == FALSE { warn!( "failed to get client rect: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); return false; } let client_rect = client_rect.assume_init(); let mouse_point = POINT { x, y }; PtInRect(&client_rect, mouse_point) != FALSE } } fn set_style(hwnd: HWND, resizable: bool, titlebar: bool) { unsafe { let mut style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; if style == 0 { warn!( "failed to get window style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); return; } if !resizable { style &= !(WS_THICKFRAME | WS_MAXIMIZEBOX); } else { style |= WS_THICKFRAME | WS_MAXIMIZEBOX; } if !titlebar { style &= !(WS_SYSMENU | WS_OVERLAPPED); } else { style |= WS_MINIMIZEBOX | WS_SYSMENU | WS_OVERLAPPED; } if SetWindowLongPtrW(hwnd, GWL_STYLE, style as _) == 0 { warn!( "failed to set the window style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } if SetWindowPos( hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOACTIVATE, ) == 0 { warn!( "failed to update window style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); }; } } /// The ex style is different from the non-ex styles. fn set_ex_style(hwnd: HWND, always_on_top: bool) { unsafe { let mut style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32; if style == 0 { warn!( "failed to get window ex style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); return; } if !always_on_top { style &= !WS_EX_TOPMOST; } else { style |= WS_EX_TOPMOST; } if SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style as _) == 0 { warn!( "failed to set the window ex style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } // This is necessary to ensure it properly changes the z order. let z_insert_after = if always_on_top { HWND_TOPMOST } else { HWND_NOTOPMOST }; // Since ES_EX_TOPMOST can change the z order, don't disable changing the z order on SetWindowPos if SetWindowPos( hwnd, z_insert_after, 0, 0, 0, 0, SWP_NOMOVE | SWP_FRAMECHANGED | SWP_NOSIZE | SWP_NOACTIVATE, ) == 0 { warn!( "failed to update window ex style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); }; } } fn set_mouse_pass_through(hwnd: HWND, mouse_pass_through: bool) { unsafe { let mut style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32; if style == 0 { warn!( "failed to get window ex style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); return; } if !mouse_pass_through { // Not removing WS_EX_LAYERED because it may still be needed if Opacity != 1. style &= !WS_EX_TRANSPARENT; } else if (style & (WS_EX_LAYERED | WS_EX_TRANSPARENT)) != (WS_EX_LAYERED | WS_EX_TRANSPARENT) { // We have to add WS_EX_LAYERED, because WS_EX_TRANSPARENT won't work otherwise. style |= WS_EX_LAYERED | WS_EX_TRANSPARENT; } else { // nothing to do return; } if SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style as _) == 0 { warn!( "failed to set the window ex style: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } } } impl WndState { fn rebuild_render_target(&mut self, d2d: &D2DFactory, scale: Scale) -> Result<(), Error> { unsafe { let swap_chain = self.dxgi_state.as_ref().unwrap().swap_chain; match paint::create_render_target_dxgi(d2d, swap_chain, scale, self.transparent) { Ok(rt) => { self.render_target = Some(rt.as_device_context().expect("TODO remove this expect")); Ok(()) } Err(e) => Err(e), } } } // Renders but does not present. fn render(&mut self, d2d: &D2DFactory, text: &PietText, invalid: &Region) { let rt = self.render_target.as_mut().unwrap(); rt.begin_draw(); { let mut piet_ctx = Piet::new(d2d, text.clone(), rt); // The documentation on DXGI_PRESENT_PARAMETERS says we "must not update any // pixel outside of the dirty rectangles." piet_ctx.clip(invalid.to_bez_path()); self.handler.paint(&mut piet_ctx, invalid); if let Err(e) = piet_ctx.finish() { error!("piet error on render: {:?}", e); } } // Maybe should deal with lost device here... let res = rt.end_draw(); if let Err(e) = res { error!("EndDraw error: {:?}", e); } } fn enter_mouse_capture(&mut self, hwnd: HWND, button: MouseButton) { if self.captured_mouse_buttons.is_empty() { unsafe { SetCapture(hwnd); } } self.captured_mouse_buttons.insert(button); } fn exit_mouse_capture(&mut self, button: MouseButton) -> bool { self.captured_mouse_buttons.remove(button); self.captured_mouse_buttons.is_empty() } } impl MyWndProc { fn with_window_state<F, R>(&self, f: F) -> R where F: FnOnce(Rc<WindowState>) -> R, { f(self .handle // There are no mutable borrows to this: we only use a mutable borrow during // initialization. .borrow() .state .upgrade() .unwrap()) // WindowState drops after WM_NCDESTROY, so it's always here. } #[track_caller] fn with_wnd_state<F, R>(&self, f: F) -> Option<R> where F: FnOnce(&mut WndState) -> R, { let ret = if let Ok(mut s) = self.state.try_borrow_mut() { (*s).as_mut().map(f) } else { error!("failed to borrow WndState at {}", Location::caller()); None }; if ret.is_some() { self.handle_deferred_queue(); } ret } fn scale(&self) -> Scale { self.with_window_state(|state| state.scale.get()) } fn set_scale(&self, scale: Scale) { self.with_window_state(move |state| state.scale.set(scale)) } /// Takes the invalid region and returns it, replacing it with the empty region. fn take_invalid(&self) -> Region { self.with_window_state(|state| { std::mem::replace(&mut *state.invalid.borrow_mut(), Region::EMPTY) }) } fn invalidate_rect(&self, rect: Rect) { self.with_window_state(|state| state.invalid.borrow_mut().add_rect(rect)); } fn set_area(&self, area: ScaledArea) { self.with_window_state(move |state| state.area.set(area)) } fn has_menu(&self) -> bool { self.with_window_state(|state| state.has_menu.get()) } fn has_titlebar(&self) -> bool { self.with_window_state(|state| state.has_titlebar.get()) } fn resizable(&self) -> bool { self.with_window_state(|state| state.is_resizable.get()) } fn is_transparent(&self) -> bool { self.with_window_state(|state| state.is_transparent.get()) } fn handle_deferred_queue(&self) { let q = self.with_window_state(move |state| state.deferred_queue.replace(Vec::new())); for op in q { self.handle_deferred(op); } } fn handle_deferred(&self, op: DeferredOp) { if let Some(hwnd) = self.handle.borrow().get_hwnd() { match op { DeferredOp::SetSize(size_dp) => unsafe { let area = ScaledArea::from_dp(size_dp, self.scale()); let size_px = area.size_px(); if SetWindowPos( hwnd, HWND_TOPMOST, 0, 0, size_px.width as i32, size_px.height as i32, SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE, ) == 0 { warn!( "failed to resize window: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); }; }, DeferredOp::SetPosition(pos_dp) => unsafe { let pos_px = pos_dp.to_px(self.scale()); if SetWindowPos( hwnd, HWND_TOPMOST, pos_px.x.round() as i32, pos_px.y.round() as i32, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE, ) == 0 { warn!( "failed to move window: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); }; }, DeferredOp::ShowTitlebar(titlebar) => { self.with_window_state(|s| s.has_titlebar.set(titlebar)); set_style(hwnd, self.resizable(), titlebar); } DeferredOp::SetResizable(resizable) => { self.with_window_state(|s| s.is_resizable.set(resizable)); set_style(hwnd, resizable, self.has_titlebar()); } DeferredOp::SetAlwaysOnTop(always_on_top) => { self.with_window_state(|s| s.is_always_on_top.set(always_on_top)); set_ex_style(hwnd, always_on_top); } DeferredOp::SetMousePassThrough(mouse_pass_through) => { self.with_window_state(|s| s.is_mouse_pass_through.set(mouse_pass_through)); set_mouse_pass_through(hwnd, mouse_pass_through); } DeferredOp::SetWindowState(val) => { let show = if self.handle.borrow().is_focusable() { match val { window::WindowState::Maximized => SW_MAXIMIZE, window::WindowState::Minimized => SW_MINIMIZE, window::WindowState::Restored => SW_RESTORE, } } else { SW_SHOWNOACTIVATE }; unsafe { ShowWindow(hwnd, show); } } DeferredOp::ShowWindow(should_show) => { let show = if should_show { SW_SHOW } else { SW_HIDE }; unsafe { ShowWindow(hwnd, show); if should_show { SetForegroundWindow(hwnd); } } } DeferredOp::SaveAs(options, token) => { let info = unsafe { get_file_dialog_path(hwnd, FileDialogType::Save, options) .ok() .map(|os_str| FileInfo { path: os_str.into(), format: None, }) }; self.with_wnd_state(|s| s.handler.save_as(token, info)); } DeferredOp::Open(options, token) => { let info = unsafe { get_file_dialog_path(hwnd, FileDialogType::Open, options) .ok() .map(|s| FileInfo { path: s.into(), format: None, }) }; self.with_wnd_state(|s| s.handler.open_file(token, info)); } DeferredOp::ContextMenu(menu, pos) => { let hmenu = menu.into_hmenu(); let pos = pos.to_px(self.scale()).round(); unsafe { let mut point = POINT { x: pos.x as i32, y: pos.y as i32, }; ClientToScreen(hwnd, &mut point); if TrackPopupMenu(hmenu, TPM_LEFTALIGN, point.x, point.y, 0, hwnd, null()) == FALSE { warn!("failed to track popup menu"); } } } DeferredOp::ReleaseMouseCapture => unsafe { if ReleaseCapture() == FALSE { let result = HRESULT_FROM_WIN32(GetLastError()); // When result is zero, it appears to just mean that the capture was already released // (which can easily happen since this is deferred). if result != 0 { warn!("failed to release mouse capture: {}", Error::Hr(result)); } } }, DeferredOp::SetRegion(region) => { unsafe { match region { Some(region) => { let (x_offset, y_offset, client_width) = self.get_client_area_specs(hwnd); let win32_region: HRGN = CreateRectRgn(0, 0, 0, 0); if win32_region.is_null() { warn!( "Error creating RectRgn in SetRegion deferred op: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } // Add header if there is a frame if self.has_titlebar() { let region_tmp = win32_region; let header_rect = CreateRectRgn(0, 0, client_width, y_offset); if header_rect.is_null() { warn!( "Error creating RectRgn in SetRegion deferred op for titlebar: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } else { let result = CombineRgn( win32_region, header_rect, region_tmp, RGN_OR, ); DeleteObject(header_rect as _); if result == ERROR { warn!( "Error combining regions in SetRegion deferred op for titlebar: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } } } let scale = self.scale(); for rect in region.rects() { // Create the region as win32 expects it. Round down for low coords and up for high coords let region_part = CreateRectRgn( (rect.x0 * scale.x()).floor() as i32 + x_offset, (rect.y0 * scale.y()).floor() as i32 + y_offset, (rect.x1 * scale.x()).ceil() as i32 + x_offset, (rect.y1 * scale.y()).ceil() as i32 + y_offset, ); if region_part.is_null() { warn!( "Error creating RectRgn for section of region in SetRegion deferred op: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); continue; // Try the next. Don't try to combine a null region. } let region_tmp = win32_region; let result = CombineRgn( win32_region, region_part, region_tmp, RGN_OR, /* area from both */ ); // Delete the region part, as it is now incorporated into the combined region. // Deleting the temp region deletes the combined region. DeleteObject(region_part as _); if result == ERROR { warn!( "Error combining regions in SetRegion deferred op: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } } let result = SetWindowRgn(hwnd, win32_region, 1); if result == ERROR { DeleteObject(win32_region as _); // Must delete it if and only if it fails. warn!( "Error calling SetWindowRgn in SetRegion deferred op: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } } None => { // Set it to have no region let result = SetWindowRgn(hwnd, null_mut(), 1); if result == ERROR { // No region to delete since we're just passing in a null region. warn!( "Error calling SetWindowRgn to null in SetRegion deferred op: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); } } } } } } } else { warn!("Could not get HWND"); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/accels.rs
druid-shell/src/backend/windows/accels.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Wrappers for Windows of Accelerate Table. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use once_cell::sync::Lazy; use winapi::ctypes::c_int; use winapi::shared::windef::*; use winapi::um::winuser::*; // NOTE: // https://docs.microsoft.com/en-us/windows/win32/wsw/thread-safety // All handles you obtain from functions in Kernel32 are thread-safe, // unless the MSDN Library article for the function explicitly mentions it is not. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] struct WindowHandle(HWND); unsafe impl Send for WindowHandle {} #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] struct AccelHandle(HACCEL); unsafe impl Send for AccelHandle {} unsafe impl Sync for AccelHandle {} static ACCEL_TABLES: Lazy<Mutex<HashMap<WindowHandle, Arc<AccelTable>>>> = Lazy::new(|| Mutex::new(HashMap::default())); /// A Accelerators Table for Windows #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub(crate) struct AccelTable { accel: AccelHandle, } impl AccelTable { fn new(accel: &[ACCEL]) -> AccelTable { let accel = unsafe { CreateAcceleratorTableW(accel as *const _ as *mut _, accel.len() as c_int) }; AccelTable { accel: AccelHandle(accel), } } pub(crate) fn handle(&self) -> HACCEL { self.accel.0 } } pub(crate) fn register_accel(hwnd: HWND, accel: &[ACCEL]) { let mut table = ACCEL_TABLES.lock().unwrap(); table.insert(WindowHandle(hwnd), Arc::new(AccelTable::new(accel))); } impl Drop for AccelTable { fn drop(&mut self) { unsafe { DestroyAcceleratorTable(self.accel.0); } } } pub(crate) fn find_accels(hwnd: HWND) -> Option<Arc<AccelTable>> { let table = ACCEL_TABLES.lock().unwrap(); table.get(&WindowHandle(hwnd)).cloned() }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/dcomp.rs
druid-shell/src/backend/windows/dcomp.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Safe-ish wrappers for DirectComposition and related interfaces. // This module could become a general wrapper for DirectComposition, but // for now we're just using what we need to get a swapchain up. use std::ptr::{null, null_mut}; use tracing::error; use winapi::shared::winerror::SUCCEEDED; use winapi::um::d3d11::*; use winapi::um::d3dcommon::{D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP}; use winapi::um::winnt::HRESULT; use winapi::Interface; use wio::com::ComPtr; unsafe fn wrap<T, U, F>(hr: HRESULT, ptr: *mut T, f: F) -> Result<U, HRESULT> where F: Fn(ComPtr<T>) -> U, T: Interface, { if SUCCEEDED(hr) { Ok(f(ComPtr::from_raw(ptr))) } else { Err(hr) } } pub struct D3D11Device(ComPtr<ID3D11Device>); impl D3D11Device { /// Creates a new device with basic defaults. pub(crate) fn new_simple() -> Result<D3D11Device, HRESULT> { let mut hr = 0; unsafe { let mut d3d11_device: *mut ID3D11Device = null_mut(); // Note: could probably set single threaded in flags for small performance boost. let flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; // Prefer hardware but use warp if it's the only driver available. for driver_type in &[D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP] { hr = D3D11CreateDevice( null_mut(), *driver_type, null_mut(), flags, null(), 0, D3D11_SDK_VERSION, &mut d3d11_device, null_mut(), null_mut(), ); if SUCCEEDED(hr) { break; } } if !SUCCEEDED(hr) { error!("D3D11CreateDevice: 0x{:x}", hr); } wrap(hr, d3d11_device, D3D11Device) } } pub(crate) fn raw_ptr(&mut self) -> *mut ID3D11Device { self.0.as_raw() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/keyboard.rs
druid-shell/src/backend/windows/keyboard.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Key event handling. use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::convert::TryInto; use std::mem; use std::ops::RangeInclusive; use crate::keyboard::{Code, KbKey, KeyEvent, KeyState, Location, Modifiers}; use winapi::shared::minwindef::{HKL, INT, LPARAM, UINT, WPARAM}; use winapi::shared::ntdef::SHORT; use winapi::shared::windef::HWND; use winapi::um::winuser::{ GetKeyState, GetKeyboardLayout, MapVirtualKeyExW, PeekMessageW, ToUnicodeEx, VkKeyScanW, MAPVK_VK_TO_CHAR, MAPVK_VSC_TO_VK_EX, PM_NOREMOVE, VK_ACCEPT, VK_ADD, VK_APPS, VK_ATTN, VK_BACK, VK_BROWSER_BACK, VK_BROWSER_FAVORITES, VK_BROWSER_FORWARD, VK_BROWSER_HOME, VK_BROWSER_REFRESH, VK_BROWSER_SEARCH, VK_BROWSER_STOP, VK_CANCEL, VK_CAPITAL, VK_CLEAR, VK_CONTROL, VK_CONVERT, VK_CRSEL, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_END, VK_EREOF, VK_ESCAPE, VK_EXECUTE, VK_EXSEL, VK_F1, VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_FINAL, VK_HELP, VK_HOME, VK_INSERT, VK_JUNJA, VK_KANA, VK_KANJI, VK_LAUNCH_APP1, VK_LAUNCH_APP2, VK_LAUNCH_MAIL, VK_LAUNCH_MEDIA_SELECT, VK_LCONTROL, VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MEDIA_NEXT_TRACK, VK_MEDIA_PLAY_PAUSE, VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU, VK_MODECHANGE, VK_MULTIPLY, VK_NEXT, VK_NONCONVERT, VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_OEM_ATTN, VK_OEM_CLEAR, VK_PAUSE, VK_PLAY, VK_PRINT, VK_PRIOR, VK_PROCESSKEY, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SCROLL, VK_SELECT, VK_SHIFT, VK_SLEEP, VK_SNAPSHOT, VK_SUBTRACT, VK_TAB, VK_UP, VK_VOLUME_DOWN, VK_VOLUME_MUTE, VK_VOLUME_UP, VK_ZOOM, WM_CHAR, WM_INPUTLANGCHANGE, WM_KEYDOWN, WM_KEYUP, WM_SYSCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP, }; const VK_ABNT_C2: INT = 0xc2; /// A (non-extended) virtual key code. type VkCode = u8; // This is really bitfields. type ShiftState = u8; const SHIFT_STATE_SHIFT: ShiftState = 1; const SHIFT_STATE_ALTGR: ShiftState = 2; const N_SHIFT_STATE: ShiftState = 4; /// Per-window keyboard state. pub(crate) struct KeyboardState { hkl: HKL, // A map from (vk, is_shifted) to string val key_vals: HashMap<(VkCode, ShiftState), String>, dead_keys: HashSet<(VkCode, ShiftState)>, has_altgr: bool, stash_vk: Option<VkCode>, stash_utf16: Vec<u16>, } /// Virtual key codes that are considered printable. /// /// This logic is borrowed from KeyboardLayout::GetKeyIndex /// in Mozilla. const PRINTABLE_VKS: &[RangeInclusive<VkCode>] = &[ 0x20..=0x20, 0x30..=0x39, 0x41..=0x5A, 0x60..=0x6B, 0x6D..=0x6F, 0xBA..=0xC2, 0xDB..=0xDF, 0xE1..=0xE4, ]; /// Bits of lparam indicating scan code, including extended bit. const SCAN_MASK: LPARAM = 0x1ff_0000; /// Determine whether there are more messages in the queue for this key event. /// /// When this function returns `false`, there is another message in the queue /// with a matching scan code, therefore it is reasonable to stash the data /// from this message and defer til later to actually produce the event. pub(super) unsafe fn is_last_message(hwnd: HWND, msg: UINT, lparam: LPARAM) -> bool { let expected_msg = match msg { WM_KEYDOWN | WM_CHAR => WM_CHAR, WM_SYSKEYDOWN | WM_SYSCHAR => WM_SYSCHAR, _ => { // Not applicable, but don't require the caller to know that. return false; } }; let mut msg = mem::zeroed(); let avail = PeekMessageW(&mut msg, hwnd, expected_msg, expected_msg, PM_NOREMOVE); avail == 0 || msg.lParam & SCAN_MASK != lparam & SCAN_MASK } const MODIFIER_MAP: &[(INT, Modifiers, SHORT)] = &[ (VK_MENU, Modifiers::ALT, 0x80), (VK_CAPITAL, Modifiers::CAPS_LOCK, 0x1), (VK_CONTROL, Modifiers::CONTROL, 0x80), (VK_NUMLOCK, Modifiers::NUM_LOCK, 0x1), (VK_SCROLL, Modifiers::SCROLL_LOCK, 0x1), (VK_SHIFT, Modifiers::SHIFT, 0x80), ]; /// Convert scan code to W3C standard code. /// /// It's hard to get an authoritative source for this; it's mostly based /// on NativeKeyToDOMCodeName.h in Mozilla. fn scan_to_code(scan_code: u32) -> Code { use Code::*; match scan_code { 0x1 => Escape, 0x2 => Digit1, 0x3 => Digit2, 0x4 => Digit3, 0x5 => Digit4, 0x6 => Digit5, 0x7 => Digit6, 0x8 => Digit7, 0x9 => Digit8, 0xA => Digit9, 0xB => Digit0, 0xC => Minus, 0xD => Equal, 0xE => Backspace, 0xF => Tab, 0x10 => KeyQ, 0x11 => KeyW, 0x12 => KeyE, 0x13 => KeyR, 0x14 => KeyT, 0x15 => KeyY, 0x16 => KeyU, 0x17 => KeyI, 0x18 => KeyO, 0x19 => KeyP, 0x1A => BracketLeft, 0x1B => BracketRight, 0x1C => Enter, 0x1D => ControlLeft, 0x1E => KeyA, 0x1F => KeyS, 0x20 => KeyD, 0x21 => KeyF, 0x22 => KeyG, 0x23 => KeyH, 0x24 => KeyJ, 0x25 => KeyK, 0x26 => KeyL, 0x27 => Semicolon, 0x28 => Quote, 0x29 => Backquote, 0x2A => ShiftLeft, 0x2B => Backslash, 0x2C => KeyZ, 0x2D => KeyX, 0x2E => KeyC, 0x2F => KeyV, 0x30 => KeyB, 0x31 => KeyN, 0x32 => KeyM, 0x33 => Comma, 0x34 => Period, 0x35 => Slash, 0x36 => ShiftRight, 0x37 => NumpadMultiply, 0x38 => AltLeft, 0x39 => Space, 0x3A => CapsLock, 0x3B => F1, 0x3C => F2, 0x3D => F3, 0x3E => F4, 0x3F => F5, 0x40 => F6, 0x41 => F7, 0x42 => F8, 0x43 => F9, 0x44 => F10, 0x45 => Pause, 0x46 => ScrollLock, 0x47 => Numpad7, 0x48 => Numpad8, 0x49 => Numpad9, 0x4A => NumpadSubtract, 0x4B => Numpad4, 0x4C => Numpad5, 0x4D => Numpad6, 0x4E => NumpadAdd, 0x4F => Numpad1, 0x50 => Numpad2, 0x51 => Numpad3, 0x52 => Numpad0, 0x53 => NumpadDecimal, 0x54 => PrintScreen, 0x56 => IntlBackslash, 0x57 => F11, 0x58 => F12, 0x59 => NumpadEqual, 0x64 => F13, 0x65 => F14, 0x66 => F15, 0x67 => F16, 0x68 => F17, 0x69 => F18, 0x6A => F19, 0x6B => F20, 0x6C => F21, 0x6D => F22, 0x6E => F23, 0x70 => KanaMode, 0x71 => Lang2, 0x72 => Lang1, 0x73 => IntlRo, 0x76 => F24, 0x77 => Lang4, 0x78 => Lang3, 0x79 => Convert, 0x7B => NonConvert, 0x7D => IntlYen, 0x7E => NumpadComma, 0x108 => Undo, 0x10A => Paste, 0x110 => MediaTrackPrevious, 0x117 => Cut, 0x118 => Copy, 0x119 => MediaTrackNext, 0x11C => NumpadEnter, 0x11D => ControlRight, 0x11E => LaunchMail, 0x120 => AudioVolumeMute, 0x121 => LaunchApp2, 0x122 => MediaPlayPause, 0x124 => MediaStop, 0x12C => Eject, 0x12E => AudioVolumeDown, 0x130 => AudioVolumeUp, 0x132 => BrowserHome, 0x135 => NumpadDivide, 0x137 => PrintScreen, 0x138 => AltRight, 0x13B => Help, 0x145 => NumLock, 0x146 => Pause, 0x147 => Home, 0x148 => ArrowUp, 0x149 => PageUp, 0x14B => ArrowLeft, 0x14D => ArrowRight, 0x14F => End, 0x150 => ArrowDown, 0x151 => PageDown, 0x152 => Insert, 0x153 => Delete, 0x15B => MetaLeft, 0x15C => MetaRight, 0x15D => ContextMenu, 0x15E => Power, 0x15F => Sleep, 0x163 => WakeUp, 0x165 => BrowserSearch, 0x166 => BrowserFavorites, 0x167 => BrowserRefresh, 0x168 => BrowserStop, 0x169 => BrowserForward, 0x16A => BrowserBack, 0x16B => LaunchApp1, 0x16C => LaunchMail, 0x16D => MediaSelect, 0x1F1 => Lang2, 0x1F2 => Lang1, _ => Unidentified, } } fn vk_to_key(vk: VkCode) -> Option<KbKey> { Some(match vk as INT { VK_CANCEL => KbKey::Cancel, VK_BACK => KbKey::Backspace, VK_TAB => KbKey::Tab, VK_CLEAR => KbKey::Clear, VK_RETURN => KbKey::Enter, VK_SHIFT | VK_LSHIFT | VK_RSHIFT => KbKey::Shift, VK_CONTROL | VK_LCONTROL | VK_RCONTROL => KbKey::Control, VK_MENU | VK_LMENU | VK_RMENU => KbKey::Alt, VK_PAUSE => KbKey::Pause, VK_CAPITAL => KbKey::CapsLock, // TODO: disambiguate kana and hangul? same vk VK_KANA => KbKey::KanaMode, VK_JUNJA => KbKey::JunjaMode, VK_FINAL => KbKey::FinalMode, VK_KANJI => KbKey::KanjiMode, VK_ESCAPE => KbKey::Escape, VK_NONCONVERT => KbKey::NonConvert, VK_ACCEPT => KbKey::Accept, VK_PRIOR => KbKey::PageUp, VK_NEXT => KbKey::PageDown, VK_END => KbKey::End, VK_HOME => KbKey::Home, VK_LEFT => KbKey::ArrowLeft, VK_UP => KbKey::ArrowUp, VK_RIGHT => KbKey::ArrowRight, VK_DOWN => KbKey::ArrowDown, VK_SELECT => KbKey::Select, VK_PRINT => KbKey::Print, VK_EXECUTE => KbKey::Execute, VK_SNAPSHOT => KbKey::PrintScreen, VK_INSERT => KbKey::Insert, VK_DELETE => KbKey::Delete, VK_HELP => KbKey::Help, VK_LWIN | VK_RWIN => KbKey::Meta, VK_APPS => KbKey::ContextMenu, VK_SLEEP => KbKey::Standby, VK_F1 => KbKey::F1, VK_F2 => KbKey::F2, VK_F3 => KbKey::F3, VK_F4 => KbKey::F4, VK_F5 => KbKey::F5, VK_F6 => KbKey::F6, VK_F7 => KbKey::F7, VK_F8 => KbKey::F8, VK_F9 => KbKey::F9, VK_F10 => KbKey::F10, VK_F11 => KbKey::F11, VK_F12 => KbKey::F12, VK_NUMLOCK => KbKey::NumLock, VK_SCROLL => KbKey::ScrollLock, VK_BROWSER_BACK => KbKey::BrowserBack, VK_BROWSER_FORWARD => KbKey::BrowserForward, VK_BROWSER_REFRESH => KbKey::BrowserRefresh, VK_BROWSER_STOP => KbKey::BrowserStop, VK_BROWSER_SEARCH => KbKey::BrowserSearch, VK_BROWSER_FAVORITES => KbKey::BrowserFavorites, VK_BROWSER_HOME => KbKey::BrowserHome, VK_VOLUME_MUTE => KbKey::AudioVolumeMute, VK_VOLUME_DOWN => KbKey::AudioVolumeDown, VK_VOLUME_UP => KbKey::AudioVolumeUp, VK_MEDIA_NEXT_TRACK => KbKey::MediaTrackNext, VK_MEDIA_PREV_TRACK => KbKey::MediaTrackPrevious, VK_MEDIA_STOP => KbKey::MediaStop, VK_MEDIA_PLAY_PAUSE => KbKey::MediaPlayPause, VK_LAUNCH_MAIL => KbKey::LaunchMail, VK_LAUNCH_MEDIA_SELECT => KbKey::LaunchMediaPlayer, VK_LAUNCH_APP1 => KbKey::LaunchApplication1, VK_LAUNCH_APP2 => KbKey::LaunchApplication2, VK_OEM_ATTN => KbKey::Alphanumeric, VK_CONVERT => KbKey::Convert, VK_MODECHANGE => KbKey::ModeChange, VK_PROCESSKEY => KbKey::Process, VK_ATTN => KbKey::Attn, VK_CRSEL => KbKey::CrSel, VK_EXSEL => KbKey::ExSel, VK_EREOF => KbKey::EraseEof, VK_PLAY => KbKey::Play, VK_ZOOM => KbKey::ZoomToggle, VK_OEM_CLEAR => KbKey::Clear, _ => return None, }) } /// Convert a key to a virtual key code. /// /// The virtual key code is needed in various winapi interfaces, including /// accelerators. This provides the virtual key code in the current keyboard /// map. /// /// The virtual key code can have modifiers in the higher order byte when the /// argument is a `Character` variant. See [VkKeyScanW][]. /// /// [VkKeyScanW]: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-vkkeyscanw pub(crate) fn key_to_vk(key: &KbKey) -> Option<i32> { Some(match key { KbKey::Character(s) => { if let Some(code_point) = s.chars().next() { if let Ok(wchar) = (code_point as u32).try_into() { unsafe { VkKeyScanW(wchar) as i32 } } else { return None; } } else { return None; } } KbKey::Cancel => VK_CANCEL, KbKey::Backspace => VK_BACK, KbKey::Tab => VK_TAB, KbKey::Clear => VK_CLEAR, KbKey::Enter => VK_RETURN, KbKey::Shift => VK_SHIFT, KbKey::Control => VK_CONTROL, KbKey::Alt => VK_MENU, KbKey::Pause => VK_PAUSE, KbKey::CapsLock => VK_CAPITAL, // TODO: disambiguate kana and hangul? same vk KbKey::KanaMode => VK_KANA, KbKey::JunjaMode => VK_JUNJA, KbKey::FinalMode => VK_FINAL, KbKey::KanjiMode => VK_KANJI, KbKey::Escape => VK_ESCAPE, KbKey::NonConvert => VK_NONCONVERT, KbKey::Accept => VK_ACCEPT, KbKey::PageUp => VK_PRIOR, KbKey::PageDown => VK_NEXT, KbKey::End => VK_END, KbKey::Home => VK_HOME, KbKey::ArrowLeft => VK_LEFT, KbKey::ArrowUp => VK_UP, KbKey::ArrowRight => VK_RIGHT, KbKey::ArrowDown => VK_DOWN, KbKey::Select => VK_SELECT, KbKey::Print => VK_PRINT, KbKey::Execute => VK_EXECUTE, KbKey::PrintScreen => VK_SNAPSHOT, KbKey::Insert => VK_INSERT, KbKey::Delete => VK_DELETE, KbKey::Help => VK_HELP, KbKey::Meta => VK_LWIN, KbKey::ContextMenu => VK_APPS, KbKey::Standby => VK_SLEEP, KbKey::F1 => VK_F1, KbKey::F2 => VK_F2, KbKey::F3 => VK_F3, KbKey::F4 => VK_F4, KbKey::F5 => VK_F5, KbKey::F6 => VK_F6, KbKey::F7 => VK_F7, KbKey::F8 => VK_F8, KbKey::F9 => VK_F9, KbKey::F10 => VK_F10, KbKey::F11 => VK_F11, KbKey::F12 => VK_F12, KbKey::F13 => VK_F13, KbKey::F14 => VK_F14, KbKey::F15 => VK_F15, KbKey::F16 => VK_F16, KbKey::F17 => VK_F17, KbKey::F18 => VK_F18, KbKey::F19 => VK_F19, KbKey::F20 => VK_F20, KbKey::F21 => VK_F21, KbKey::F22 => VK_F22, KbKey::F23 => VK_F23, KbKey::F24 => VK_F24, KbKey::NumLock => VK_NUMLOCK, KbKey::ScrollLock => VK_SCROLL, KbKey::BrowserBack => VK_BROWSER_BACK, KbKey::BrowserForward => VK_BROWSER_FORWARD, KbKey::BrowserRefresh => VK_BROWSER_REFRESH, KbKey::BrowserStop => VK_BROWSER_STOP, KbKey::BrowserSearch => VK_BROWSER_SEARCH, KbKey::BrowserFavorites => VK_BROWSER_FAVORITES, KbKey::BrowserHome => VK_BROWSER_HOME, KbKey::AudioVolumeMute => VK_VOLUME_MUTE, KbKey::AudioVolumeDown => VK_VOLUME_DOWN, KbKey::AudioVolumeUp => VK_VOLUME_UP, KbKey::MediaTrackNext => VK_MEDIA_NEXT_TRACK, KbKey::MediaTrackPrevious => VK_MEDIA_PREV_TRACK, KbKey::MediaStop => VK_MEDIA_STOP, KbKey::MediaPlayPause => VK_MEDIA_PLAY_PAUSE, KbKey::LaunchMail => VK_LAUNCH_MAIL, KbKey::LaunchMediaPlayer => VK_LAUNCH_MEDIA_SELECT, KbKey::LaunchApplication1 => VK_LAUNCH_APP1, KbKey::LaunchApplication2 => VK_LAUNCH_APP2, KbKey::Alphanumeric => VK_OEM_ATTN, KbKey::Convert => VK_CONVERT, KbKey::ModeChange => VK_MODECHANGE, KbKey::Process => VK_PROCESSKEY, KbKey::Attn => VK_ATTN, KbKey::CrSel => VK_CRSEL, KbKey::ExSel => VK_EXSEL, KbKey::EraseEof => VK_EREOF, KbKey::Play => VK_PLAY, KbKey::ZoomToggle => VK_ZOOM, _ => return None, }) } fn code_unit_to_key(code_unit: u32) -> KbKey { match code_unit { 0x8 | 0x7F => KbKey::Backspace, 0x9 => KbKey::Tab, 0xA | 0xD => KbKey::Enter, 0x1B => KbKey::Escape, _ if code_unit >= 0x20 => { if let Some(c) = std::char::from_u32(code_unit) { KbKey::Character(c.to_string()) } else { // UTF-16 error, very unlikely KbKey::Unidentified } } _ => KbKey::Unidentified, } } /// Get location from virtual key code. /// /// This logic is based on NativeKbKey::GetKeyLocation from Mozilla. fn vk_to_location(vk: VkCode, is_extended: bool) -> Location { match vk as INT { VK_LSHIFT | VK_LCONTROL | VK_LMENU | VK_LWIN => Location::Left, VK_RSHIFT | VK_RCONTROL | VK_RMENU | VK_RWIN => Location::Right, VK_RETURN if is_extended => Location::Numpad, VK_INSERT | VK_DELETE | VK_END | VK_DOWN | VK_NEXT | VK_LEFT | VK_CLEAR | VK_RIGHT | VK_HOME | VK_UP | VK_PRIOR => { if is_extended { Location::Standard } else { Location::Numpad } } VK_NUMPAD0 | VK_NUMPAD1 | VK_NUMPAD2 | VK_NUMPAD3 | VK_NUMPAD4 | VK_NUMPAD5 | VK_NUMPAD6 | VK_NUMPAD7 | VK_NUMPAD8 | VK_NUMPAD9 | VK_DECIMAL | VK_DIVIDE | VK_MULTIPLY | VK_SUBTRACT | VK_ADD | VK_ABNT_C2 => Location::Numpad, _ => Location::Standard, } } impl KeyboardState { /// Create a new keyboard state. /// /// There should be one of these per window. It loads the current keyboard /// layout and retains some mapping information from it. pub(crate) fn new() -> KeyboardState { unsafe { let hkl = GetKeyboardLayout(0); let key_vals = HashMap::new(); let dead_keys = HashSet::new(); let stash_vk = None; let stash_utf16 = Vec::new(); let has_altgr = false; let mut result = KeyboardState { hkl, key_vals, dead_keys, has_altgr, stash_vk, stash_utf16, }; result.load_keyboard_layout(); result } } /// Process one message from the platform. /// /// This is the main interface point for generating cooked keyboard events /// from raw platform messages. It should be called for each relevant message, /// which comprises: `WM_KEYDOWN`, `WM_KEYUP`, `WM_CHAR`, `WM_SYSKEYDOWN`, /// `WM_SYSKEYUP`, `WM_SYSCHAR`, and `WM_INPUTLANGCHANGE`. /// /// As a general theory, many keyboard events generate a sequence of platform /// messages. In these cases, we stash information from all messages but the /// last, and generate the event from the last (using `PeekMessage` to detect /// that case). Mozilla handling is slightly different; it actually tries to /// do the processing on the first message, fetching the subsequent messages /// from the queue. We believe our handling is simpler and more robust. /// /// A simple example of a multi-message sequence is the key "=". In a US layout, /// we'd expect `WM_KEYDOWN` with `wparam = VK_OEM_PLUS` and lparam encoding the /// keycode that translates into `Code::Equal`, followed by a `WM_CHAR` with /// `wparam = b"="` and the same scancode. /// /// A more complex example of a multi-message sequence is the second press of /// that key in a German layout, where it's mapped to the dead key for accent /// acute. Then we expect `WM_KEYDOWN` with `wparam = VK_OEM_6` followed by /// two `WM_CHAR` with `wparam = 0xB4` (corresponding to U+00B4 = acute accent). /// In this case, the result (produced on the final message in the sequence) is /// a key event with `key = KbKey::Character("´´")`, which also matches browser /// behavior. /// /// # Safety /// /// The `hwnd` argument must be a valid `HWND`. Similarly, the `lparam` must be /// a valid `HKL` reference in the `WM_INPUTLANGCHANGE` message. Actual danger /// is likely low, though. pub(crate) unsafe fn process_message( &mut self, msg: UINT, wparam: WPARAM, lparam: LPARAM, is_last: bool, ) -> Option<KeyEvent> { match msg { WM_KEYDOWN | WM_SYSKEYDOWN => { //println!("keydown wparam {:x} lparam {:x}", wparam, lparam); let scan_code = ((lparam & SCAN_MASK) >> 16) as u32; let vk = self.refine_vk(wparam as u8, scan_code); if is_last { let mods = self.get_modifiers(); let code = scan_to_code(scan_code); let key = vk_to_key(vk).unwrap_or_else(|| self.get_base_key(vk, mods)); let repeat = (lparam & 0x4000_0000) != 0; let is_extended = (lparam & 0x100_0000) != 0; let location = vk_to_location(vk, is_extended); let state = KeyState::Down; let event = KeyEvent { state, mods, code, key, is_composing: false, location, repeat, }; Some(event) } else { self.stash_vk = Some(vk); None } } WM_KEYUP | WM_SYSKEYUP => { let scan_code = ((lparam & SCAN_MASK) >> 16) as u32; let vk = self.refine_vk(wparam as u8, scan_code); let mods = self.get_modifiers(); let code = scan_to_code(scan_code); let key = vk_to_key(vk).unwrap_or_else(|| self.get_base_key(vk, mods)); let repeat = false; let is_extended = (lparam & 0x100_0000) != 0; let location = vk_to_location(vk, is_extended); let state = KeyState::Up; let event = KeyEvent { state, mods, code, key, is_composing: false, location, repeat, }; Some(event) } WM_CHAR | WM_SYSCHAR => { //println!("char wparam {:x} lparam {:x}", wparam, lparam); if is_last { let stash_vk = self.stash_vk.take(); let mods = self.get_modifiers(); let scan_code = ((lparam & SCAN_MASK) >> 16) as u32; let vk = self.refine_vk(stash_vk.unwrap_or(0), scan_code); let code = scan_to_code(scan_code); let key = if self.stash_utf16.is_empty() && (wparam < 0x20 || wparam == 0x7f) { vk_to_key(vk).unwrap_or_else(|| self.get_base_key(vk, mods)) } else { self.stash_utf16.push(wparam as u16); if let Ok(s) = String::from_utf16(&self.stash_utf16) { KbKey::Character(s) } else { KbKey::Unidentified } }; self.stash_utf16.clear(); let repeat = (lparam & 0x4000_0000) != 0; let is_extended = (lparam & 0x100_0000) != 0; let location = vk_to_location(vk, is_extended); let state = KeyState::Down; let event = KeyEvent { state, mods, code, key, is_composing: false, location, repeat, }; Some(event) } else { self.stash_utf16.push(wparam as u16); None } } WM_INPUTLANGCHANGE => { self.hkl = lparam as HKL; self.load_keyboard_layout(); None } _ => None, } } /// Get the modifier state. /// /// This function is designed to be called from a message handler, and /// gives the modifier state at the time of the message (ie is the /// synchronous variant). See [`GetKeyState`] for more context. /// /// The interpretation of modifiers depends on the keyboard layout, as /// some layouts have [AltGr] and others do not. /// /// [`GetKeyState`]: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeystate /// [AltGr]: https://en.wikipedia.org/wiki/AltGr_key pub(crate) fn get_modifiers(&self) -> Modifiers { unsafe { let mut modifiers = Modifiers::empty(); for &(vk, modifier, mask) in MODIFIER_MAP { if GetKeyState(vk) & mask != 0 { modifiers |= modifier; } } if self.has_altgr && GetKeyState(VK_RMENU) & 0x80 != 0 { modifiers |= Modifiers::ALT_GRAPH; modifiers &= !(Modifiers::CONTROL | Modifiers::ALT); } modifiers } } /// Load a keyboard layout. /// /// We need to retain a map of virtual key codes in various modifier /// states, because it's not practical to query that at keyboard event /// time (the main culprit is that `ToUnicodeEx` is stateful). /// /// The logic is based on Mozilla KeyboardLayout::LoadLayout but is /// considerably simplified. fn load_keyboard_layout(&mut self) { unsafe { self.key_vals.clear(); self.dead_keys.clear(); self.has_altgr = false; let mut key_state = [0u8; 256]; let mut uni_chars = [0u16; 5]; // Right now, we're only getting the values for base and shifted // variants. Mozilla goes through 16 mod states. for shift_state in 0..N_SHIFT_STATE { let has_shift = shift_state & SHIFT_STATE_SHIFT != 0; let has_altgr = shift_state & SHIFT_STATE_ALTGR != 0; key_state[VK_SHIFT as usize] = if has_shift { 0x80 } else { 0 }; key_state[VK_CONTROL as usize] = if has_altgr { 0x80 } else { 0 }; key_state[VK_LCONTROL as usize] = if has_altgr { 0x80 } else { 0 }; key_state[VK_MENU as usize] = if has_altgr { 0x80 } else { 0 }; key_state[VK_RMENU as usize] = if has_altgr { 0x80 } else { 0 }; for vk in PRINTABLE_VKS.iter().cloned().flatten() { let ret = ToUnicodeEx( vk as UINT, 0, key_state.as_ptr(), uni_chars.as_mut_ptr(), uni_chars.len() as _, 0, self.hkl, ); match ret.cmp(&0) { Ordering::Greater => { let utf16_slice = &uni_chars[..ret as usize]; if let Ok(strval) = String::from_utf16(utf16_slice) { self.key_vals.insert((vk, shift_state), strval); } // If the AltGr version of the key has a different string than // the base, then the layout has AltGr. Note that Mozilla also // checks dead keys for change. if has_altgr && !self.has_altgr && self.key_vals.get(&(vk, shift_state)) != self.key_vals.get(&(vk, shift_state & !SHIFT_STATE_ALTGR)) { self.has_altgr = true; } } Ordering::Less => { // It's a dead key, press it again to reset the state. self.dead_keys.insert((vk, shift_state)); let _ = ToUnicodeEx( vk as UINT, 0, key_state.as_ptr(), uni_chars.as_mut_ptr(), uni_chars.len() as _, 0, self.hkl, ); } _ => (), } } } } } fn get_base_key(&self, vk: VkCode, modifiers: Modifiers) -> KbKey { let mut shift_state = 0; if modifiers.shift() { shift_state |= SHIFT_STATE_SHIFT; } if modifiers.contains(Modifiers::ALT_GRAPH) { shift_state |= SHIFT_STATE_ALTGR; } if let Some(s) = self.key_vals.get(&(vk, shift_state)) { KbKey::Character(s.clone()) } else { let mapped = self.map_vk(vk); if mapped >= (1 << 31) { KbKey::Dead } else { code_unit_to_key(mapped) } } } /// Map a virtual key code to a code unit, also indicate if dead key. /// /// Bit 31 is set if the mapping is to a dead key. The bottom bits contain the code unit. fn map_vk(&self, vk: VkCode) -> u32 { unsafe { MapVirtualKeyExW(vk as _, MAPVK_VK_TO_CHAR, self.hkl) } } /// Refine a virtual key code to distinguish left and right. /// /// This only does the mapping if the original code is ambiguous, as otherwise the /// virtual key code reported in `wparam` is more reliable. fn refine_vk(&self, vk: VkCode, mut scan_code: u32) -> VkCode { match vk as INT { 0 | VK_SHIFT | VK_CONTROL | VK_MENU => { if scan_code >= 0x100 { scan_code += 0xE000 - 0x100; } unsafe { MapVirtualKeyExW(scan_code, MAPVK_VSC_TO_VK_EX, self.hkl) as u8 } } _ => vk, } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/timers.rs
druid-shell/src/backend/windows/timers.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Timer state. use std::collections::BTreeSet; use std::time::Instant; use crate::window::TimerToken; pub struct TimerSlots { // Note: we can remove this when checked_duration_since lands. next_fresh_id: u64, free_slots: BTreeSet<u64>, } impl TimerSlots { pub fn new(starting_ix: u64) -> TimerSlots { TimerSlots { next_fresh_id: starting_ix, free_slots: Default::default(), } } pub fn alloc(&mut self) -> TimerToken { if let Some(first) = self.free_slots.iter().next().cloned() { self.free_slots.remove(&first); TimerToken::from_raw(first) } else { let result = self.next_fresh_id; self.next_fresh_id += 1; TimerToken::from_raw(result) } } pub fn free(&mut self, token: TimerToken) { let id = token.into_raw(); if self.next_fresh_id == id + 1 { self.next_fresh_id -= 1; } else { self.free_slots.insert(id); } } /// Compute an elapsed value for SetTimer (in ms) pub fn compute_elapsed(&self, deadline: Instant) -> u32 { deadline .checked_duration_since(Instant::now()) .map(|d| d.as_millis() as u32) .unwrap_or(0) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/backend/windows/screen.rs
druid-shell/src/backend/windows/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Windows Monitors and Screen information. use super::error::Error; use std::mem::size_of; use std::ptr::null_mut; use tracing::warn; use winapi::shared::minwindef::*; use winapi::shared::windef::*; use winapi::shared::winerror::*; use winapi::um::errhandlingapi::GetLastError; use winapi::um::winuser::*; use crate::kurbo::Rect; use crate::screen::Monitor; unsafe extern "system" fn monitorenumproc( hmonitor: HMONITOR, _hdc: HDC, _lprect: LPRECT, _lparam: LPARAM, ) -> BOOL { let rect = RECT { left: 0, top: 0, right: 0, bottom: 0, }; let mut info = MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, rcMonitor: rect, rcWork: rect, dwFlags: 0, }; if GetMonitorInfoW(hmonitor, &mut info) == 0 { warn!( "failed to get Monitor Info: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); }; let primary = info.dwFlags == MONITORINFOF_PRIMARY; let rect = Rect::new( info.rcMonitor.left as f64, info.rcMonitor.top as f64, info.rcMonitor.right as f64, info.rcMonitor.bottom as f64, ); let work_rect = Rect::new( info.rcWork.left as f64, info.rcWork.top as f64, info.rcWork.right as f64, info.rcWork.bottom as f64, ); let monitors = _lparam as *mut Vec<Monitor>; (*monitors).push(Monitor::new(primary, rect, work_rect)); TRUE } pub(crate) fn get_monitors() -> Vec<Monitor> { unsafe { let monitors = Vec::<Monitor>::new(); let ptr = &monitors as *const Vec<Monitor>; if EnumDisplayMonitors(null_mut(), null_mut(), Some(monitorenumproc), ptr as isize) == 0 { warn!( "Failed to Enumerate Display Monitors: {}", Error::Hr(HRESULT_FROM_WIN32(GetLastError())) ); }; monitors } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false