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-shell/src/backend/shared/timer.rs
druid-shell/src/backend/shared/timer.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::TimerToken; use std::{cmp::Ordering, time::Instant}; /// A timer is a deadline (`std::Time::Instant`) and a `TimerToken`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct Timer<T> { deadline: Instant, token: TimerToken, pub data: T, } impl<T> Timer<T> { pub(crate) fn new(deadline: Instant, data: T) -> Self { let token = TimerToken::next(); Self { deadline, token, data, } } pub(crate) fn deadline(&self) -> Instant { self.deadline } pub(crate) fn token(&self) -> TimerToken { self.token } } impl<T: Eq + PartialEq> Ord for Timer<T> { /// 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) -> Ordering { self.deadline.cmp(&other.deadline).reverse() } } impl<T: Eq + PartialEq> PartialOrd for Timer<T> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } }
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/shared/mod.rs
druid-shell/src/backend/shared/mod.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Logic that is shared by more than one backend. cfg_if::cfg_if! { if #[cfg(any(target_os = "freebsd", target_os = "macos", target_os = "linux", target_os = "openbsd"))] { mod keyboard; pub use keyboard::*; } } cfg_if::cfg_if! { if #[cfg(all(any(target_os = "freebsd", target_os = "linux"), any(feature = "x11", feature = "wayland")))] { mod timer; pub(crate) use timer::*; pub(crate) mod xkb; pub(crate) mod linux; } }
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/shared/keyboard.rs
druid-shell/src/backend/shared/keyboard.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Keyboard logic that is shared by more than one backend. #[allow(unused)] use keyboard_types::{Code, Location}; #[cfg(any( all( any(feature = "x11", feature = "wayland"), any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ), target_os = "macos" ))] /// Map key code to location. /// /// The logic for this is adapted from InitKeyEvent in TextInputHandler (in the Mozilla /// mac port). /// /// Note: in the original, this is based on kVK constants, but since we don't have those /// readily available, we use the mapping to code (which should be effectively lossless). pub fn code_to_location(code: Code) -> Location { match code { Code::MetaLeft | Code::ShiftLeft | Code::AltLeft | Code::ControlLeft => Location::Left, Code::MetaRight | Code::ShiftRight | Code::AltRight | Code::ControlRight => Location::Right, Code::Numpad0 | Code::Numpad1 | Code::Numpad2 | Code::Numpad3 | Code::Numpad4 | Code::Numpad5 | Code::Numpad6 | Code::Numpad7 | Code::Numpad8 | Code::Numpad9 | Code::NumpadAdd | Code::NumpadComma | Code::NumpadDecimal | Code::NumpadDivide | Code::NumpadEnter | Code::NumpadEqual | Code::NumpadMultiply | Code::NumpadSubtract => Location::Numpad, _ => Location::Standard, } } #[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] /// Map hardware keycode to code. /// /// In theory, the hardware keycode is device dependent, but in /// practice it's probably pretty reliable. /// /// The logic is based on NativeKeyToDOMCodeName.h in Mozilla. pub fn hardware_keycode_to_code(hw_keycode: u16) -> Code { match hw_keycode { 0x0009 => Code::Escape, 0x000A => Code::Digit1, 0x000B => Code::Digit2, 0x000C => Code::Digit3, 0x000D => Code::Digit4, 0x000E => Code::Digit5, 0x000F => Code::Digit6, 0x0010 => Code::Digit7, 0x0011 => Code::Digit8, 0x0012 => Code::Digit9, 0x0013 => Code::Digit0, 0x0014 => Code::Minus, 0x0015 => Code::Equal, 0x0016 => Code::Backspace, 0x0017 => Code::Tab, 0x0018 => Code::KeyQ, 0x0019 => Code::KeyW, 0x001A => Code::KeyE, 0x001B => Code::KeyR, 0x001C => Code::KeyT, 0x001D => Code::KeyY, 0x001E => Code::KeyU, 0x001F => Code::KeyI, 0x0020 => Code::KeyO, 0x0021 => Code::KeyP, 0x0022 => Code::BracketLeft, 0x0023 => Code::BracketRight, 0x0024 => Code::Enter, 0x0025 => Code::ControlLeft, 0x0026 => Code::KeyA, 0x0027 => Code::KeyS, 0x0028 => Code::KeyD, 0x0029 => Code::KeyF, 0x002A => Code::KeyG, 0x002B => Code::KeyH, 0x002C => Code::KeyJ, 0x002D => Code::KeyK, 0x002E => Code::KeyL, 0x002F => Code::Semicolon, 0x0030 => Code::Quote, 0x0031 => Code::Backquote, 0x0032 => Code::ShiftLeft, 0x0033 => Code::Backslash, 0x0034 => Code::KeyZ, 0x0035 => Code::KeyX, 0x0036 => Code::KeyC, 0x0037 => Code::KeyV, 0x0038 => Code::KeyB, 0x0039 => Code::KeyN, 0x003A => Code::KeyM, 0x003B => Code::Comma, 0x003C => Code::Period, 0x003D => Code::Slash, 0x003E => Code::ShiftRight, 0x003F => Code::NumpadMultiply, 0x0040 => Code::AltLeft, 0x0041 => Code::Space, 0x0042 => Code::CapsLock, 0x0043 => Code::F1, 0x0044 => Code::F2, 0x0045 => Code::F3, 0x0046 => Code::F4, 0x0047 => Code::F5, 0x0048 => Code::F6, 0x0049 => Code::F7, 0x004A => Code::F8, 0x004B => Code::F9, 0x004C => Code::F10, 0x004D => Code::NumLock, 0x004E => Code::ScrollLock, 0x004F => Code::Numpad7, 0x0050 => Code::Numpad8, 0x0051 => Code::Numpad9, 0x0052 => Code::NumpadSubtract, 0x0053 => Code::Numpad4, 0x0054 => Code::Numpad5, 0x0055 => Code::Numpad6, 0x0056 => Code::NumpadAdd, 0x0057 => Code::Numpad1, 0x0058 => Code::Numpad2, 0x0059 => Code::Numpad3, 0x005A => Code::Numpad0, 0x005B => Code::NumpadDecimal, 0x005D => Code::Lang5, 0x005E => Code::IntlBackslash, 0x005F => Code::F11, 0x0060 => Code::F12, 0x0061 => Code::IntlRo, 0x0062 => Code::Lang3, 0x0063 => Code::Lang4, 0x0064 => Code::Convert, 0x0065 => Code::KanaMode, 0x0066 => Code::NonConvert, 0x0068 => Code::NumpadEnter, 0x0069 => Code::ControlRight, 0x006A => Code::NumpadDivide, 0x006B => Code::PrintScreen, 0x006C => Code::AltRight, 0x006E => Code::Home, 0x006F => Code::ArrowUp, 0x0070 => Code::PageUp, 0x0071 => Code::ArrowLeft, 0x0072 => Code::ArrowRight, 0x0073 => Code::End, 0x0074 => Code::ArrowDown, 0x0075 => Code::PageDown, 0x0076 => Code::Insert, 0x0077 => Code::Delete, 0x0079 => Code::AudioVolumeMute, 0x007A => Code::AudioVolumeDown, 0x007B => Code::AudioVolumeUp, 0x007C => Code::Power, 0x007D => Code::NumpadEqual, 0x007F => Code::Pause, 0x0080 => Code::ShowAllWindows, 0x0081 => Code::NumpadComma, 0x0082 => Code::Lang1, 0x0083 => Code::Lang2, 0x0084 => Code::IntlYen, 0x0085 => Code::MetaLeft, 0x0086 => Code::MetaRight, 0x0087 => Code::ContextMenu, 0x0088 => Code::BrowserStop, 0x0089 => Code::Again, 0x008A => Code::Props, 0x008B => Code::Undo, 0x008C => Code::Select, 0x008D => Code::Copy, 0x008E => Code::Open, 0x008F => Code::Paste, 0x0090 => Code::Find, 0x0091 => Code::Cut, 0x0092 => Code::Help, 0x0094 => Code::LaunchApp2, 0x0096 => Code::Sleep, 0x0097 => Code::WakeUp, 0x0098 => Code::LaunchApp1, // key to right of volume controls on T430s produces 0x9C // but no documentation of what it should map to :/ 0x00A3 => Code::LaunchMail, 0x00A4 => Code::BrowserFavorites, 0x00A6 => Code::BrowserBack, 0x00A7 => Code::BrowserForward, 0x00A9 => Code::Eject, 0x00AB => Code::MediaTrackNext, 0x00AC => Code::MediaPlayPause, 0x00AD => Code::MediaTrackPrevious, 0x00AE => Code::MediaStop, 0x00AF => Code::MediaRecord, 0x00B0 => Code::MediaRewind, 0x00B3 => Code::MediaSelect, 0x00B4 => Code::BrowserHome, 0x00B5 => Code::BrowserRefresh, 0x00BB => Code::NumpadParenLeft, 0x00BC => Code::NumpadParenRight, 0x00BF => Code::F13, 0x00C0 => Code::F14, 0x00C1 => Code::F15, 0x00C2 => Code::F16, 0x00C3 => Code::F17, 0x00C4 => Code::F18, 0x00C5 => Code::F19, 0x00C6 => Code::F20, 0x00C7 => Code::F21, 0x00C8 => Code::F22, 0x00C9 => Code::F23, 0x00CA => Code::F24, 0x00D1 => Code::MediaPause, 0x00D7 => Code::MediaPlay, 0x00D8 => Code::MediaFastForward, 0x00E1 => Code::BrowserSearch, 0x00E8 => Code::BrightnessDown, 0x00E9 => Code::BrightnessUp, 0x00EB => Code::DisplayToggleIntExt, 0x00EF => Code::MailSend, 0x00F0 => Code::MailReply, 0x00F1 => Code::MailForward, 0x0100 => Code::MicrophoneMuteToggle, 0x017C => Code::ZoomToggle, 0x024B => Code::LaunchControlPanel, 0x024C => Code::SelectTask, 0x024D => Code::LaunchScreenSaver, 0x024F => Code::LaunchAssistant, 0x0250 => Code::KeyboardLayoutSelect, 0x0281 => Code::PrivacyScreenToggle, _ => Code::Unidentified, } }
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/shared/linux/env.rs
druid-shell/src/backend/shared/linux/env.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 pub fn locale() -> String { fn locale_env_var(var: &str) -> Option<String> { match std::env::var(var) { Ok(s) if s.is_empty() => { tracing::debug!("locale: ignoring empty env var {}", var); None } Ok(s) => { tracing::debug!("locale: env var {} found: {:?}", var, &s); Some(s) } Err(std::env::VarError::NotPresent) => { tracing::debug!("locale: env var {} not found", var); None } Err(std::env::VarError::NotUnicode(_)) => { tracing::debug!("locale: ignoring invalid unicode env var {}", var); None } } } // from gettext manual // https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html#Locale-Environment-Variables let mut locale = locale_env_var("LANGUAGE") // the LANGUAGE value is priority list separated by : // See: https://www.gnu.org/software/gettext/manual/html_node/The-LANGUAGE-variable.html#The-LANGUAGE-variable .and_then(|locale| locale.split(':').next().map(String::from)) .or_else(|| locale_env_var("LC_ALL")) .or_else(|| locale_env_var("LC_MESSAGES")) .or_else(|| locale_env_var("LANG")) .unwrap_or_else(|| "en-US".to_string()); // 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 }
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/shared/linux/mod.rs
druid-shell/src/backend/shared/linux/mod.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 // environment based utilities pub mod env;
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/shared/xkb/keycodes.rs
druid-shell/src/backend/shared/xkb/keycodes.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #![allow(non_upper_case_globals)] use keyboard_types::Key; use super::xkbcommon_sys::*; /// Map from an xkb_common key code to a key, if possible. pub fn map_key(keysym: u32) -> Key { use Key::*; match keysym { XKB_KEY_v => Key::Character("v".to_string()), XKB_KEY_BackSpace => Backspace, XKB_KEY_Tab | XKB_KEY_KP_Tab | XKB_KEY_ISO_Left_Tab => Tab, XKB_KEY_Clear | XKB_KEY_KP_Begin | XKB_KEY_XF86Clear => Clear, XKB_KEY_Return | XKB_KEY_KP_Enter => Enter, XKB_KEY_Linefeed => Enter, XKB_KEY_Pause => Pause, XKB_KEY_Scroll_Lock => ScrollLock, XKB_KEY_Escape => Escape, XKB_KEY_Multi_key => Compose, XKB_KEY_Kanji => KanjiMode, XKB_KEY_Muhenkan => NonConvert, XKB_KEY_Henkan_Mode => Convert, XKB_KEY_Romaji => Romaji, XKB_KEY_Hiragana => Hiragana, XKB_KEY_Katakana => Katakana, XKB_KEY_Hiragana_Katakana => HiraganaKatakana, XKB_KEY_Zenkaku => Zenkaku, XKB_KEY_Hankaku => Hankaku, XKB_KEY_Zenkaku_Hankaku => ZenkakuHankaku, XKB_KEY_Kana_Lock => KanaMode, XKB_KEY_Eisu_Shift | XKB_KEY_Eisu_toggle => Alphanumeric, XKB_KEY_Hangul => HangulMode, XKB_KEY_Hangul_Hanja => HanjaMode, XKB_KEY_Codeinput => CodeInput, XKB_KEY_SingleCandidate => SingleCandidate, XKB_KEY_MultipleCandidate => AllCandidates, XKB_KEY_PreviousCandidate => PreviousCandidate, XKB_KEY_Home | XKB_KEY_KP_Home => Home, XKB_KEY_Left | XKB_KEY_KP_Left => ArrowLeft, XKB_KEY_Up | XKB_KEY_KP_Up => ArrowUp, XKB_KEY_Right | XKB_KEY_KP_Right => ArrowRight, XKB_KEY_Down | XKB_KEY_KP_Down => ArrowDown, XKB_KEY_Prior | XKB_KEY_KP_Prior => PageUp, XKB_KEY_Next | XKB_KEY_KP_Next | XKB_KEY_XF86ScrollDown => PageDown, XKB_KEY_End | XKB_KEY_KP_End | XKB_KEY_XF86ScrollUp => End, XKB_KEY_Select => Select, // Treat Print/PrintScreen as PrintScreen https://crbug.com/683097. XKB_KEY_Print | XKB_KEY_3270_PrintScreen => PrintScreen, XKB_KEY_Execute => Execute, XKB_KEY_Insert | XKB_KEY_KP_Insert => Insert, XKB_KEY_Undo => Undo, XKB_KEY_Redo => Redo, XKB_KEY_Menu => ContextMenu, XKB_KEY_Find => Find, XKB_KEY_Cancel => Cancel, XKB_KEY_Help => Help, XKB_KEY_Break | XKB_KEY_3270_Attn => Attn, XKB_KEY_Mode_switch => ModeChange, XKB_KEY_Num_Lock => NumLock, XKB_KEY_F1 | XKB_KEY_KP_F1 => F1, XKB_KEY_F2 | XKB_KEY_KP_F2 => F2, XKB_KEY_F3 | XKB_KEY_KP_F3 => F3, XKB_KEY_F4 | XKB_KEY_KP_F4 => F4, XKB_KEY_F5 => F5, XKB_KEY_F6 => F6, XKB_KEY_F7 => F7, XKB_KEY_F8 => F8, XKB_KEY_F9 => F9, XKB_KEY_F10 => F10, XKB_KEY_F11 => F11, XKB_KEY_F12 => F12, XKB_KEY_XF86Tools | XKB_KEY_F13 => F13, XKB_KEY_F14 | XKB_KEY_XF86Launch5 => F14, XKB_KEY_F15 | XKB_KEY_XF86Launch6 => F15, XKB_KEY_F16 | XKB_KEY_XF86Launch7 => F16, XKB_KEY_F17 | XKB_KEY_XF86Launch8 => F17, XKB_KEY_F18 | XKB_KEY_XF86Launch9 => F18, XKB_KEY_F19 => F19, XKB_KEY_F20 => F20, XKB_KEY_F21 => F21, XKB_KEY_F22 => F22, XKB_KEY_F23 => F23, XKB_KEY_F24 => F24, // not available in keyboard-types // XKB_KEY_XF86Calculator => LaunchCalculator, // XKB_KEY_XF86MyComputer | XKB_KEY_XF86Explorer => LaunchMyComputer, // XKB_KEY_ISO_Level3_Latch => AltGraphLatch, // XKB_KEY_ISO_Level5_Shift => ShiftLevel5, XKB_KEY_Shift_L | XKB_KEY_Shift_R => Shift, XKB_KEY_Control_L | XKB_KEY_Control_R => Control, XKB_KEY_Caps_Lock => CapsLock, XKB_KEY_Meta_L | XKB_KEY_Meta_R => Meta, XKB_KEY_Alt_L | XKB_KEY_Alt_R => Alt, XKB_KEY_Super_L | XKB_KEY_Super_R => Meta, XKB_KEY_Hyper_L | XKB_KEY_Hyper_R => Hyper, XKB_KEY_Delete => Delete, XKB_KEY_SunProps => Props, XKB_KEY_XF86Next_VMode => VideoModeNext, XKB_KEY_XF86MonBrightnessUp => BrightnessUp, XKB_KEY_XF86MonBrightnessDown => BrightnessDown, XKB_KEY_XF86Standby | XKB_KEY_XF86Sleep | XKB_KEY_XF86Suspend => Standby, XKB_KEY_XF86AudioLowerVolume => AudioVolumeDown, XKB_KEY_XF86AudioMute => AudioVolumeMute, XKB_KEY_XF86AudioRaiseVolume => AudioVolumeUp, XKB_KEY_XF86AudioPlay => MediaPlayPause, XKB_KEY_XF86AudioStop => MediaStop, XKB_KEY_XF86AudioPrev => MediaTrackPrevious, XKB_KEY_XF86AudioNext => MediaTrackNext, XKB_KEY_XF86HomePage => BrowserHome, XKB_KEY_XF86Mail => LaunchMail, XKB_KEY_XF86Search => BrowserSearch, XKB_KEY_XF86AudioRecord => MediaRecord, XKB_KEY_XF86Calendar => LaunchCalendar, XKB_KEY_XF86Back => BrowserBack, XKB_KEY_XF86Forward => BrowserForward, XKB_KEY_XF86Stop => BrowserStop, XKB_KEY_XF86Refresh | XKB_KEY_XF86Reload => BrowserRefresh, XKB_KEY_XF86PowerOff => PowerOff, XKB_KEY_XF86WakeUp => WakeUp, XKB_KEY_XF86Eject => Eject, XKB_KEY_XF86ScreenSaver => LaunchScreenSaver, XKB_KEY_XF86WWW => LaunchWebBrowser, XKB_KEY_XF86Favorites => BrowserFavorites, XKB_KEY_XF86AudioPause => MediaPause, XKB_KEY_XF86AudioMedia | XKB_KEY_XF86Music => LaunchMusicPlayer, XKB_KEY_XF86AudioRewind => MediaRewind, XKB_KEY_XF86CD | XKB_KEY_XF86Video => LaunchMediaPlayer, XKB_KEY_XF86Close => Close, XKB_KEY_XF86Copy | XKB_KEY_SunCopy => Copy, XKB_KEY_XF86Cut | XKB_KEY_SunCut => Cut, XKB_KEY_XF86Display => DisplaySwap, XKB_KEY_XF86Excel => LaunchSpreadsheet, XKB_KEY_XF86LogOff => LogOff, XKB_KEY_XF86New => New, XKB_KEY_XF86Open | XKB_KEY_SunOpen => Open, XKB_KEY_XF86Paste | XKB_KEY_SunPaste => Paste, XKB_KEY_XF86Reply => MailReply, XKB_KEY_XF86Save => Save, XKB_KEY_XF86Send => MailSend, XKB_KEY_XF86Spell => SpellCheck, XKB_KEY_XF86SplitScreen => SplitScreenToggle, XKB_KEY_XF86Word | XKB_KEY_XF86OfficeHome => LaunchWordProcessor, XKB_KEY_XF86ZoomIn => ZoomIn, XKB_KEY_XF86ZoomOut => ZoomOut, XKB_KEY_XF86WebCam => LaunchWebCam, XKB_KEY_XF86MailForward => MailForward, XKB_KEY_XF86AudioForward => MediaFastForward, XKB_KEY_XF86AudioRandomPlay => RandomToggle, XKB_KEY_XF86Subtitle => Subtitle, XKB_KEY_XF86Hibernate => Hibernate, XKB_KEY_3270_EraseEOF => EraseEof, XKB_KEY_3270_Play => Play, XKB_KEY_3270_ExSelect => ExSel, XKB_KEY_3270_CursorSelect => CrSel, XKB_KEY_ISO_Level3_Shift => AltGraph, XKB_KEY_ISO_Next_Group => GroupNext, XKB_KEY_ISO_Prev_Group => GroupPrevious, XKB_KEY_ISO_First_Group => GroupFirst, XKB_KEY_ISO_Last_Group => GroupLast, XKB_KEY_dead_grave | XKB_KEY_dead_acute | XKB_KEY_dead_circumflex | XKB_KEY_dead_tilde | XKB_KEY_dead_macron | XKB_KEY_dead_breve | XKB_KEY_dead_abovedot | XKB_KEY_dead_diaeresis | XKB_KEY_dead_abovering | XKB_KEY_dead_doubleacute | XKB_KEY_dead_caron | XKB_KEY_dead_cedilla | XKB_KEY_dead_ogonek | XKB_KEY_dead_iota | XKB_KEY_dead_voiced_sound | XKB_KEY_dead_semivoiced_sound | XKB_KEY_dead_belowdot | XKB_KEY_dead_hook | XKB_KEY_dead_horn | XKB_KEY_dead_stroke | XKB_KEY_dead_abovecomma | XKB_KEY_dead_abovereversedcomma | XKB_KEY_dead_doublegrave | XKB_KEY_dead_belowring | XKB_KEY_dead_belowmacron | XKB_KEY_dead_belowcircumflex | XKB_KEY_dead_belowtilde | XKB_KEY_dead_belowbreve | XKB_KEY_dead_belowdiaeresis | XKB_KEY_dead_invertedbreve | XKB_KEY_dead_belowcomma | XKB_KEY_dead_currency | XKB_KEY_dead_greek => Dead, _ => Unidentified, } }
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/shared/xkb/mod.rs
druid-shell/src/backend/shared/xkb/mod.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A minimal wrapper around Xkb for our use. mod keycodes; mod xkbcommon_sys; use crate::{ backend::shared::{code_to_location, hardware_keycode_to_code}, KeyEvent, KeyState, Modifiers, }; use keyboard_types::{Code, Key}; use std::convert::TryFrom; use std::os::raw::c_char; use std::ptr; use xkbcommon_sys::*; #[cfg(feature = "x11")] use x11rb::xcb_ffi::XCBConnection; #[cfg(feature = "x11")] pub struct DeviceId(std::os::raw::c_int); /// A global xkb context object. /// /// Reference counted under the hood. // Assume this isn't threadsafe unless proved otherwise. (e.g. don't implement Send/Sync) pub struct Context(*mut xkb_context); impl Context { /// Create a new xkb context. /// /// The returned object is lightweight and clones will point at the same context internally. pub fn new() -> Self { unsafe { Self(xkb_context_new(XKB_CONTEXT_NO_FLAGS)) } } #[cfg(feature = "x11")] pub fn core_keyboard_device_id(&self, conn: &XCBConnection) -> Option<DeviceId> { let id = unsafe { xkb_x11_get_core_keyboard_device_id( conn.get_raw_xcb_connection() as *mut xcb_connection_t ) }; if id != -1 { Some(DeviceId(id)) } else { None } } #[cfg(feature = "x11")] pub fn keymap_from_device(&self, conn: &XCBConnection, device: DeviceId) -> Option<Keymap> { let key_map = unsafe { xkb_x11_keymap_new_from_device( self.0, conn.get_raw_xcb_connection() as *mut xcb_connection_t, device.0, XKB_KEYMAP_COMPILE_NO_FLAGS, ) }; if key_map.is_null() { return None; } Some(Keymap(key_map)) } /// Create a keymap from some given data. /// /// Uses `xkb_keymap_new_from_buffer` under the hood. #[cfg(feature = "wayland")] pub fn keymap_from_slice(&self, buffer: &[u8]) -> Keymap { // TODO we hope that the keymap doesn't borrow the underlying data. If it does' we need to // use Rc. We'll find out soon enough if we get a segfault. // TODO we hope that the keymap inc's the reference count of the context. assert!( buffer.iter().copied().any(|byte| byte == 0), "`keymap_from_slice` expects a null-terminated string" ); unsafe { let keymap = xkb_keymap_new_from_string( self.0, buffer.as_ptr() as *const i8, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS, ); assert!(!keymap.is_null()); Keymap(keymap) } } /// Set the log level using `tracing` levels. /// /// Because `xkb` has a `critical` error, each rust error maps to 1 above (e.g. error -> /// critical, warn -> error etc.) #[allow(unused)] pub fn set_log_level(&self, level: tracing::Level) { use tracing::Level; let level = match level { Level::ERROR => XKB_LOG_LEVEL_CRITICAL, Level::WARN => XKB_LOG_LEVEL_ERROR, Level::INFO => XKB_LOG_LEVEL_WARNING, Level::DEBUG => XKB_LOG_LEVEL_INFO, Level::TRACE => XKB_LOG_LEVEL_DEBUG, }; unsafe { xkb_context_set_log_level(self.0, level); } } } impl Clone for Context { fn clone(&self) -> Self { Self(unsafe { xkb_context_ref(self.0) }) } } impl Drop for Context { fn drop(&mut self) { unsafe { xkb_context_unref(self.0); } } } pub struct Keymap(*mut xkb_keymap); impl Keymap { pub fn state(&self) -> State { State::new(self) } } impl Clone for Keymap { fn clone(&self) -> Self { Self(unsafe { xkb_keymap_ref(self.0) }) } } impl Drop for Keymap { fn drop(&mut self) { unsafe { xkb_keymap_unref(self.0); } } } pub struct State { state: *mut xkb_state, mods: ModsIndices, } #[derive(Clone, Copy)] pub struct ModsIndices { control: xkb_mod_index_t, shift: xkb_mod_index_t, alt: xkb_mod_index_t, super_: xkb_mod_index_t, caps_lock: xkb_mod_index_t, num_lock: xkb_mod_index_t, } impl State { pub fn new(keymap: &Keymap) -> Self { let keymap = keymap.0; let state = unsafe { xkb_state_new(keymap) }; let mod_idx = |str: &'static [u8]| unsafe { xkb_keymap_mod_get_index(keymap, str.as_ptr() as *mut c_char) }; Self { state, mods: ModsIndices { control: mod_idx(XKB_MOD_NAME_CTRL), shift: mod_idx(XKB_MOD_NAME_SHIFT), alt: mod_idx(XKB_MOD_NAME_ALT), super_: mod_idx(XKB_MOD_NAME_LOGO), caps_lock: mod_idx(XKB_MOD_NAME_CAPS), num_lock: mod_idx(XKB_MOD_NAME_NUM), }, } } pub fn key_event(&mut self, scancode: u32, state: KeyState, repeat: bool) -> KeyEvent { let code = u16::try_from(scancode) .map(hardware_keycode_to_code) .unwrap_or(Code::Unidentified); let key = self.get_logical_key(scancode); // TODO this is lazy - really should use xkb i.e. augment the get_logical_key method. let location = code_to_location(code); // TODO not sure how to get this let is_composing = false; let mut mods = Modifiers::empty(); // Update xkb's state (e.g. return capitals if we've pressed shift) unsafe { if !repeat { xkb_state_update_key( self.state, scancode, match state { KeyState::Down => XKB_KEY_DOWN, KeyState::Up => XKB_KEY_UP, }, ); } // compiler will unroll this loop // FIXME(msrv): remove .iter().cloned() when msrv is >= 1.53 for (idx, mod_) in [ (self.mods.control, Modifiers::CONTROL), (self.mods.shift, Modifiers::SHIFT), (self.mods.super_, Modifiers::SUPER), (self.mods.alt, Modifiers::ALT), (self.mods.caps_lock, Modifiers::CAPS_LOCK), (self.mods.num_lock, Modifiers::NUM_LOCK), ] .iter() .cloned() { if xkb_state_mod_index_is_active(self.state, idx, XKB_STATE_MODS_EFFECTIVE) != 0 { mods |= mod_; } } } KeyEvent { state, key, code, location, mods, repeat, is_composing, } } fn get_logical_key(&mut self, scancode: u32) -> Key { let mut key = keycodes::map_key(self.key_get_one_sym(scancode)); if matches!(key, Key::Unidentified) { if let Some(s) = self.key_get_utf8(scancode) { key = Key::Character(s); } } key } fn key_get_one_sym(&mut self, scancode: u32) -> u32 { unsafe { xkb_state_key_get_one_sym(self.state, scancode) } } /// Get the string representation of a key. // TODO `keyboard_types` forces us to return a String, but it would be nicer if we could stay // on the stack, especially since we expect most results to be pretty small. fn key_get_utf8(&mut self, scancode: u32) -> Option<String> { unsafe { // First get the size we will need let len = xkb_state_key_get_utf8(self.state, scancode, ptr::null_mut(), 0); if len == 0 { return None; } // add 1 because we will get a null-terminated string. let len = usize::try_from(len).unwrap() + 1; let mut buf: Vec<u8> = vec![0; len]; xkb_state_key_get_utf8(self.state, scancode, buf.as_mut_ptr() as *mut c_char, len); assert!(buf[buf.len() - 1] == 0); buf.pop(); Some(String::from_utf8(buf).unwrap()) } } } impl Clone for State { fn clone(&self) -> Self { Self { state: unsafe { xkb_state_ref(self.state) }, mods: self.mods, } } } impl Drop for State { fn drop(&mut self) { unsafe { xkb_state_unref(self.state); } } }
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/shared/xkb/xkbcommon_sys.rs
druid-shell/src/backend/shared/xkb/xkbcommon_sys.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 #![allow(unused, non_upper_case_globals, non_camel_case_types, non_snake_case)] // unknown lints to make compile on older rust versions #![cfg_attr(test, allow(unknown_lints, deref_nullptr))] // generated code has some redundant static lifetimes, I don't think we can change that. #![allow(clippy::redundant_static_lifetimes)] use nix::libc::FILE; include!(concat!(env!("OUT_DIR"), "/xkbcommon_sys.rs"));
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/web/keycodes.rs
druid-shell/src/backend/web/keycodes.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Web keycode handling. use web_sys::KeyboardEvent; use crate::keyboard::{Code, KbKey, KeyEvent, KeyState, Location, Modifiers}; /// Convert a web-sys KeyboardEvent into a keyboard-types one. pub(crate) fn convert_keyboard_event( event: &KeyboardEvent, mods: Modifiers, state: KeyState, ) -> KeyEvent { KeyEvent { state, key: event.key().parse().unwrap_or(KbKey::Unidentified), code: convert_code(&event.code()), location: convert_location(event.location()), mods, repeat: event.repeat(), is_composing: event.is_composing(), } } fn convert_code(code: &str) -> Code { code.parse().unwrap_or(Code::Unidentified) } fn convert_location(loc: u32) -> Location { match loc { KeyboardEvent::DOM_KEY_LOCATION_LEFT => Location::Left, KeyboardEvent::DOM_KEY_LOCATION_RIGHT => Location::Right, KeyboardEvent::DOM_KEY_LOCATION_NUMPAD => Location::Numpad, // Should be exhaustive but in case not, use reasonable default _ => Location::Standard, } }
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/web/clipboard.rs
druid-shell/src/backend/web/clipboard.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Interactions with the browser pasteboard. use crate::clipboard::{ClipboardFormat, FormatId}; /// The browser clipboard. #[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>) { tracing::warn!("unimplemented"); } /// Put multi-format data on the system clipboard. pub fn put_formats(&mut self, _formats: &[ClipboardFormat]) { tracing::warn!("unimplemented"); } /// Get a string from the system clipboard, if one is available. pub fn get_string(&self) -> Option<String> { tracing::warn!("unimplemented"); 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!("unimplemented"); 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>> { tracing::warn!("unimplemented"); None } pub fn available_type_names(&self) -> Vec<String> { tracing::warn!("unimplemented"); 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/web/menu.rs
druid-shell/src/backend/web/menu.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Safe wrapper for menus. use crate::hotkey::HotKey; /// A menu object, which can be either a top-level menubar or a /// submenu. pub struct Menu; impl Drop for Menu { fn drop(&mut self) { // TODO } } 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/web/error.rs
druid-shell/src/backend/web/error.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Web backend errors. use wasm_bindgen::JsValue; #[derive(Debug, Clone)] pub enum Error { NoWindow, NoDocument, Js(JsValue), JsCast, NoElementById(String), NoContext, Unimplemented, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::NoWindow => write!(f, "No global window found"), Error::NoDocument => write!(f, "No global document found"), Error::Js(err) => write!(f, "JavaScript error: {:?}", err.as_string()), Error::JsCast => write!(f, "JavaScript cast error"), Error::NoElementById(err) => write!(f, "get_element_by_id error: {err}"), Error::NoContext => write!(f, "Failed to get a draw context"), Error::Unimplemented => write!(f, "Requested an unimplemented feature"), } } } impl From<JsValue> for Error { fn from(js: JsValue) -> Error { Error::Js(js) } } 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/web/application.rs
druid-shell/src/backend/web/application.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Web implementation of features at the application scope. use crate::application::AppHandler; use super::clipboard::Clipboard; use super::error::Error; #[derive(Clone)] pub(crate) struct Application; impl Application { pub fn new() -> Result<Application, Error> { Ok(Application) } pub fn run(self, _handler: Option<Box<dyn AppHandler>>) {} pub fn quit(&self) {} pub fn clipboard(&self) -> Clipboard { Clipboard } pub fn get_locale() -> String { web_sys::window() .and_then(|w| w.navigator().language()) .unwrap_or_else(|| "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/web/mod.rs
druid-shell/src/backend/web/mod.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Web-based backend support pub mod application; pub mod clipboard; pub mod error; pub mod keycodes; 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/web/window.rs
druid-shell/src/backend/web/window.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Web window creation and management. use std::cell::{Cell, RefCell}; use std::ffi::OsString; use std::rc::{Rc, Weak}; use std::sync::{Arc, Mutex}; use instant::Instant; use tracing::{error, warn}; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, WebWindowHandle}; use crate::kurbo::{Insets, Point, Rect, Size, Vec2}; use crate::piet::{PietText, RenderContext}; use super::application::Application; use super::error::Error; use super::keycodes::convert_keyboard_event; use super::menu::Menu; use crate::common_util::{ClickCounter, IdleCallback}; use crate::dialog::{FileDialogOptions, FileDialogType}; use crate::error::Error as ShellError; use crate::scale::{Scale, ScaledArea}; use crate::keyboard::{KeyState, Modifiers}; use crate::mouse::{Cursor, CursorDesc, MouseButton, MouseButtons, MouseEvent}; use crate::region::Region; use crate::text::{simulate_input, Event}; use crate::window; use crate::window::{ FileDialogToken, IdleToken, TextFieldToken, TimerToken, WinHandler, WindowLevel, }; // This is a macro instead of a function since KeyboardEvent and MouseEvent has identical functions // to query modifier key states. macro_rules! get_modifiers { ($event:ident) => {{ let mut result = Modifiers::default(); result.set(Modifiers::SHIFT, $event.shift_key()); result.set(Modifiers::ALT, $event.alt_key()); result.set(Modifiers::CONTROL, $event.ctrl_key()); result.set(Modifiers::META, $event.meta_key()); result.set(Modifiers::ALT_GRAPH, $event.get_modifier_state("AltGraph")); result.set(Modifiers::CAPS_LOCK, $event.get_modifier_state("CapsLock")); result.set(Modifiers::NUM_LOCK, $event.get_modifier_state("NumLock")); result.set( Modifiers::SCROLL_LOCK, $event.get_modifier_state("ScrollLock"), ); result }}; } /// Builder abstraction for creating new windows. pub(crate) struct WindowBuilder { handler: Option<Box<dyn WinHandler>>, title: String, cursor: Cursor, menu: Option<Menu>, } #[derive(Clone, Default)] pub struct WindowHandle(Weak<WindowState>); impl PartialEq for WindowHandle { fn eq(&self, other: &Self) -> bool { match (self.0.upgrade(), other.0.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 { error!("HasRawWindowHandle trait not implemented for wasm."); RawWindowHandle::Web(WebWindowHandle::empty()) } } /// A handle that can get used to schedule an idle handler. Note that /// this handle is thread safe. #[derive(Clone)] pub struct IdleHandle { state: Weak<WindowState>, queue: Arc<Mutex<Vec<IdleKind>>>, } enum IdleKind { Callback(Box<dyn IdleCallback>), Token(IdleToken), } struct WindowState { scale: Cell<Scale>, area: Cell<ScaledArea>, idle_queue: Arc<Mutex<Vec<IdleKind>>>, handler: RefCell<Box<dyn WinHandler>>, window: web_sys::Window, canvas: web_sys::HtmlCanvasElement, canvas_size: Option<Size>, context: web_sys::CanvasRenderingContext2d, invalid: RefCell<Region>, click_counter: ClickCounter, active_text_input: Cell<Option<TextFieldToken>>, rendering_soon: Cell<bool>, } // TODO: support custom cursors #[derive(Clone, PartialEq, Eq)] pub struct CustomCursor; impl WindowState { fn render(&self) { self.handler.borrow_mut().prepare_paint(); let mut piet_ctx = piet_common::Piet::new(self.context.clone(), self.window.clone()); if let Err(e) = piet_ctx.with_save(|ctx| { let invalid = self.invalid.borrow(); ctx.clip(invalid.to_bez_path()); self.handler.borrow_mut().paint(ctx, &invalid); Ok(()) }) { error!("piet error on render: {:?}", e); } if let Err(e) = piet_ctx.finish() { error!("piet error finishing render: {:?}", e); } self.invalid.borrow_mut().clear(); } fn process_idle_queue(&self) { let mut queue = self.idle_queue.lock().expect("process_idle_queue"); for item in queue.drain(..) { match item { IdleKind::Callback(cb) => cb.call(&mut **self.handler.borrow_mut()), IdleKind::Token(tok) => self.handler.borrow_mut().idle(tok), } } } fn request_animation_frame(&self, f: impl FnOnce() + 'static) -> Result<i32, Error> { Ok(self .window .request_animation_frame(Closure::once_into_js(f).as_ref().unchecked_ref())?) } /// Returns the window size in css units fn get_window_size_and_dpr(&self) -> (f64, f64, f64) { let w = &self.window; let dpr = w.device_pixel_ratio(); match self.canvas_size { Some(Size { width, height }) => (width, height, dpr), _ => { let width = w.inner_width().unwrap().as_f64().unwrap(); let height = w.inner_height().unwrap().as_f64().unwrap(); (width, height, dpr) } } } /// Updates the canvas size and scale factor and returns `Scale` and `ScaledArea`. fn update_scale_and_area(&self) -> (Scale, ScaledArea) { let (css_width, css_height, dpr) = self.get_window_size_and_dpr(); let scale = Scale::new(dpr, dpr); let area = ScaledArea::from_dp(Size::new(css_width, css_height), scale); let size_px = area.size_px(); self.canvas.set_width(size_px.width as u32); self.canvas.set_height(size_px.height as u32); let _ = self.context.scale(scale.x(), scale.y()); self.scale.set(scale); self.area.set(area); (scale, area) } } fn setup_mouse_down_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_canvas_event_listener(ws, "mousedown", move |event: web_sys::MouseEvent| { if let Some(button) = mouse_button(event.button()) { let pos = Point::new(event.offset_x() as f64, event.offset_y() as f64); let count = state.click_counter.count_for_click(pos); let buttons = mouse_buttons(event.buttons()); let event = MouseEvent { pos, buttons, mods: get_modifiers!(event), count, focus: false, button, wheel_delta: Vec2::ZERO, }; state.handler.borrow_mut().mouse_down(&event); } }); } fn setup_mouse_up_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_canvas_event_listener(ws, "mouseup", move |event: web_sys::MouseEvent| { if let Some(button) = mouse_button(event.button()) { let buttons = mouse_buttons(event.buttons()); let event = MouseEvent { pos: Point::new(event.offset_x() as f64, event.offset_y() as f64), buttons, mods: get_modifiers!(event), count: 0, focus: false, button, wheel_delta: Vec2::ZERO, }; state.handler.borrow_mut().mouse_up(&event); } }); } fn setup_mouse_move_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_canvas_event_listener(ws, "mousemove", move |event: web_sys::MouseEvent| { let buttons = mouse_buttons(event.buttons()); let event = MouseEvent { pos: Point::new(event.offset_x() as f64, event.offset_y() as f64), buttons, mods: get_modifiers!(event), count: 0, focus: false, button: MouseButton::None, wheel_delta: Vec2::ZERO, }; state.handler.borrow_mut().mouse_move(&event); }); } fn setup_scroll_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_canvas_event_listener(ws, "wheel", move |event: web_sys::WheelEvent| { let delta_mode = event.delta_mode(); let dx = event.delta_x(); let dy = event.delta_y(); // The value 35.0 was manually picked to produce similar behavior to mac/linux. let wheel_delta = match delta_mode { web_sys::WheelEvent::DOM_DELTA_PIXEL => Vec2::new(dx, dy), web_sys::WheelEvent::DOM_DELTA_LINE => Vec2::new(35.0 * dx, 35.0 * dy), web_sys::WheelEvent::DOM_DELTA_PAGE => { let size_dp = state.area.get().size_dp(); Vec2::new(size_dp.width * dx, size_dp.height * dy) } _ => { warn!("Invalid deltaMode in WheelEvent: {}", delta_mode); return; } }; let event = MouseEvent { pos: Point::new(event.offset_x() as f64, event.offset_y() as f64), buttons: mouse_buttons(event.buttons()), mods: get_modifiers!(event), count: 0, focus: false, button: MouseButton::None, wheel_delta, }; state.handler.borrow_mut().wheel(&event); }); } fn setup_resize_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_window_event_listener(ws, "resize", move |_: web_sys::UiEvent| { let (scale, area) = state.update_scale_and_area(); // TODO: For performance, only call the handler when these values actually changed. state.handler.borrow_mut().scale(scale); state.handler.borrow_mut().size(area.size_dp()); }); } fn setup_keyup_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_window_event_listener(ws, "keyup", move |event: web_sys::KeyboardEvent| { let modifiers = get_modifiers!(event); let kb_event = convert_keyboard_event(&event, modifiers, KeyState::Up); state.handler.borrow_mut().key_up(kb_event); }); } fn setup_keydown_callback(ws: &Rc<WindowState>) { let state = ws.clone(); register_window_event_listener(ws, "keydown", move |event: web_sys::KeyboardEvent| { let modifiers = get_modifiers!(event); let kb_event = convert_keyboard_event(&event, modifiers, KeyState::Down); let mut handler = state.handler.borrow_mut(); if simulate_input(&mut **handler, state.active_text_input.get(), kb_event) { event.prevent_default(); } }); } /// A helper function to register a window event listener with `addEventListener`. fn register_window_event_listener<F, E>(window_state: &Rc<WindowState>, event_type: &str, f: F) where F: 'static + FnMut(E), E: 'static + wasm_bindgen::convert::FromWasmAbi, { let closure = Closure::wrap(Box::new(f) as Box<dyn FnMut(_)>); window_state .window .add_event_listener_with_callback(event_type, closure.as_ref().unchecked_ref()) .unwrap(); closure.forget(); } /// A helper function to register a canvas event listener with `addEventListener`. fn register_canvas_event_listener<F, E>(window_state: &Rc<WindowState>, event_type: &str, f: F) where F: 'static + FnMut(E), E: 'static + wasm_bindgen::convert::FromWasmAbi, { let closure = Closure::wrap(Box::new(f) as Box<dyn FnMut(_)>); window_state .canvas .add_event_listener_with_callback(event_type, closure.as_ref().unchecked_ref()) .unwrap(); closure.forget(); } fn setup_web_callbacks(window_state: &Rc<WindowState>) { setup_mouse_down_callback(window_state); setup_mouse_move_callback(window_state); setup_mouse_up_callback(window_state); setup_resize_callback(window_state); setup_scroll_callback(window_state); setup_keyup_callback(window_state); setup_keydown_callback(window_state); } impl WindowBuilder { pub fn new(_app: Application) -> WindowBuilder { WindowBuilder { handler: None, title: String::new(), cursor: Cursor::Arrow, menu: None, } } /// This takes ownership, and is typically used with UiMain pub fn set_handler(&mut self, handler: Box<dyn WinHandler>) { self.handler = Some(handler); } pub fn set_size(&mut self, _: Size) { // Ignored } pub fn set_min_size(&mut self, _: Size) { // Ignored } pub fn resizable(&mut self, _resizable: bool) { // Ignored } pub fn show_titlebar(&mut self, _show_titlebar: bool) { // Ignored } pub fn set_transparent(&mut self, _transparent: bool) { // Ignored } pub fn set_position(&mut self, _position: Point) { // Ignored } pub fn set_always_on_top(&self, _always_on_top: bool) { // Ignored } pub fn set_window_state(&self, _state: window::WindowState) { // Ignored } pub fn set_level(&mut self, _level: WindowLevel) { // ignored } pub fn set_title<S: Into<String>>(&mut self, title: S) { self.title = title.into(); } pub fn set_menu(&mut self, menu: Menu) { self.menu = Some(menu); } pub fn build(self) -> Result<WindowHandle, Error> { let window = web_sys::window().ok_or(Error::NoWindow)?; let canvas = window .document() .ok_or(Error::NoDocument)? .get_element_by_id("canvas") .ok_or_else(|| Error::NoElementById("canvas".to_string()))? .dyn_into::<web_sys::HtmlCanvasElement>() .map_err(|_| Error::JsCast)?; let cnv_attr = |attr| { canvas .get_attribute(attr) .and_then(|value| value.parse().ok()) }; let canvas_size = match (cnv_attr("width"), cnv_attr("height")) { (Some(width), Some(height)) => Some(Size::new(width, height)), _ => None, }; let context = canvas .get_context("2d")? .ok_or(Error::NoContext)? .dyn_into::<web_sys::CanvasRenderingContext2d>() .map_err(|_| Error::JsCast)?; // Create the Scale for resolution scaling let scale = { let dpr = window.device_pixel_ratio(); Scale::new(dpr, dpr) }; let area = { // The initial size in display points isn't necessarily the final size in display points let size_dp = Size::new(canvas.offset_width() as f64, canvas.offset_height() as f64); ScaledArea::from_dp(size_dp, scale) }; let size_px = area.size_px(); canvas.set_width(size_px.width as u32); canvas.set_height(size_px.height as u32); let _ = context.scale(scale.x(), scale.y()); let size_dp = area.size_dp(); set_cursor(&canvas, &self.cursor); let handler = self.handler.unwrap(); let window = Rc::new(WindowState { scale: Cell::new(scale), area: Cell::new(area), idle_queue: Default::default(), handler: RefCell::new(handler), window, canvas, canvas_size, context, invalid: RefCell::new(Region::EMPTY), click_counter: ClickCounter::default(), active_text_input: Cell::new(None), rendering_soon: Cell::new(false), }); setup_web_callbacks(&window); // Register the scale & size with the window handler. let wh = window.clone(); window .request_animation_frame(move || { wh.handler.borrow_mut().scale(scale); wh.handler.borrow_mut().size(size_dp); }) .expect("Failed to request animation frame"); let handle = WindowHandle(Rc::downgrade(&window)); window.handler.borrow_mut().connect(&handle.clone().into()); Ok(handle) } } impl WindowHandle { pub fn show(&self) { self.render_soon(); } pub fn resizable(&self, _resizable: bool) { warn!("resizable unimplemented for web"); } pub fn show_titlebar(&self, _show_titlebar: bool) { warn!("show_titlebar unimplemented for web"); } pub fn set_position(&self, _position: Point) { warn!("WindowHandle::set_position unimplemented for web"); } pub fn set_input_region(&self, _region: Option<Region>) { warn!("WindowHandle::set_input_region unimplemented for web"); } pub fn set_always_on_top(&self, _always_on_top: bool) { warn!("WindowHandle::set_always_on_top unimplemented for web"); } pub fn set_mouse_pass_through(&self, _mouse_pass_thorugh: bool) { warn!("WindowHandle::set_mouse_pass_through unimplemented for web"); } pub fn get_position(&self) -> Point { warn!("WindowHandle::get_position unimplemented for web."); Point::new(0.0, 0.0) } pub fn set_size(&self, _size: Size) { warn!("WindowHandle::set_size unimplemented for web."); } pub fn get_size(&self) -> Size { warn!("WindowHandle::get_size unimplemented for web."); Size::new(0.0, 0.0) } pub fn is_foreground_window(&self) -> bool { true } pub fn content_insets(&self) -> Insets { warn!("WindowHandle::content_insets unimplemented for web."); Insets::ZERO } pub fn set_window_state(&self, _state: window::WindowState) { warn!("WindowHandle::set_window_state unimplemented for web."); } pub fn get_window_state(&self) -> window::WindowState { warn!("WindowHandle::get_window_state unimplemented for web."); window::WindowState::Restored } pub fn handle_titlebar(&self, _val: bool) { warn!("WindowHandle::handle_titlebar unimplemented for web."); } pub fn close(&self) { // TODO } pub fn hide(&self) { warn!("hide unimplemented for web"); } pub fn bring_to_front_and_focus(&self) { warn!("bring_to_frontand_focus unimplemented for web"); } pub fn request_anim_frame(&self) { self.render_soon(); } pub fn invalidate_rect(&self, rect: Rect) { if let Some(s) = self.0.upgrade() { s.invalid.borrow_mut().add_rect(rect); } self.render_soon(); } pub fn invalidate(&self) { if let Some(s) = self.0.upgrade() { s.invalid .borrow_mut() .add_rect(s.area.get().size_dp().to_rect()); } self.render_soon(); } pub fn text(&self) -> PietText { let s = self .0 .upgrade() .unwrap_or_else(|| panic!("Failed to produce a text context")); PietText::new(s.context.clone()) } pub fn add_text_field(&self) -> TextFieldToken { TextFieldToken::next() } pub fn remove_text_field(&self, token: TextFieldToken) { if let Some(state) = self.0.upgrade() { if state.active_text_input.get() == Some(token) { state.active_text_input.set(None); } } } pub fn set_focused_text_field(&self, active_field: Option<TextFieldToken>) { if let Some(state) = self.0.upgrade() { state.active_text_input.set(active_field); } } pub fn update_text_field(&self, _token: TextFieldToken, _update: Event) { // no-op for now, until we get a properly implemented text input } pub fn request_timer(&self, deadline: Instant) -> TimerToken { let interval = deadline.duration_since(Instant::now()).as_millis(); let interval = match i32::try_from(interval) { Ok(iv) => iv, Err(_) => { warn!("Timer duration exceeds 32 bit integer max"); i32::MAX } }; let token = TimerToken::next(); if let Some(state) = self.0.upgrade() { let s = state.clone(); let f = move || { if let Ok(mut handler_borrow) = s.handler.try_borrow_mut() { handler_borrow.timer(token); } }; state .window .set_timeout_with_callback_and_timeout_and_arguments_0( Closure::once_into_js(f).as_ref().unchecked_ref(), interval, ) .expect("Failed to call setTimeout with a callback"); } token } pub fn set_cursor(&mut self, cursor: &Cursor) { if let Some(s) = self.0.upgrade() { set_cursor(&s.canvas, cursor); } } pub fn make_cursor(&self, _cursor_desc: &CursorDesc) -> Option<Cursor> { warn!("Custom cursors are not yet supported in the web backend"); None } pub fn open_file(&mut self, _options: FileDialogOptions) -> Option<FileDialogToken> { warn!("open_file is currently unimplemented for web."); None } pub fn save_as(&mut self, _options: FileDialogOptions) -> Option<FileDialogToken> { warn!("save_as is currently unimplemented for web."); None } fn render_soon(&self) { if let Some(s) = self.0.upgrade() { let state = s.clone(); if !state.rendering_soon.get() { state.rendering_soon.set(true); s.request_animation_frame(move || { state.rendering_soon.set(false); state.render(); }) .expect("Failed to request animation frame"); } } } pub fn file_dialog( &self, _ty: FileDialogType, _options: FileDialogOptions, ) -> Result<OsString, ShellError> { Err(ShellError::Platform(Error::Unimplemented)) } /// Get a handle that can be used to schedule an idle task. pub fn get_idle_handle(&self) -> Option<IdleHandle> { self.0.upgrade().map(|w| IdleHandle { state: Rc::downgrade(&w), queue: w.idle_queue.clone(), }) } /// Get the `Scale` of the window. pub fn get_scale(&self) -> Result<Scale, ShellError> { Ok(self .0 .upgrade() .ok_or(ShellError::WindowDropped)? .scale .get()) } pub fn set_menu(&self, _menu: Menu) { warn!("set_menu unimplemented for web"); } pub fn show_context_menu(&self, _menu: Menu, _pos: Point) { warn!("show_context_menu unimplemented for web"); } pub fn set_title(&self, title: impl Into<String>) { if let Some(state) = self.0.upgrade() { state.canvas.set_title(&(title.into())) } } } unsafe impl Send for IdleHandle {} unsafe impl Sync for IdleHandle {} impl IdleHandle { /// Add an idle handler, which is called (once) when the main thread is idle. pub fn add_idle_callback<F>(&self, callback: F) where F: FnOnce(&mut dyn WinHandler) + Send + 'static, { let mut queue = self.queue.lock().expect("IdleHandle::add_idle queue"); queue.push(IdleKind::Callback(Box::new(callback))); if queue.len() == 1 { if let Some(window_state) = self.state.upgrade() { let state = window_state.clone(); window_state .request_animation_frame(move || { state.process_idle_queue(); }) .expect("request_animation_frame failed"); } } } pub fn add_idle_token(&self, token: IdleToken) { let mut queue = self.queue.lock().expect("IdleHandle::add_idle queue"); queue.push(IdleKind::Token(token)); if queue.len() == 1 { if let Some(window_state) = self.state.upgrade() { let state = window_state.clone(); window_state .request_animation_frame(move || { state.process_idle_queue(); }) .expect("request_animation_frame failed"); } } } } fn mouse_button(button: i16) -> Option<MouseButton> { match button { 0 => Some(MouseButton::Left), 1 => Some(MouseButton::Middle), 2 => Some(MouseButton::Right), 3 => Some(MouseButton::X1), 4 => Some(MouseButton::X2), _ => None, } } fn mouse_buttons(mask: u16) -> 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 } fn set_cursor(canvas: &web_sys::HtmlCanvasElement, cursor: &Cursor) { canvas .style() .set_property( "cursor", #[allow(deprecated)] match cursor { Cursor::Arrow => "default", Cursor::IBeam => "text", Cursor::Pointer => "pointer", Cursor::Crosshair => "crosshair", Cursor::OpenHand => "grab", Cursor::NotAllowed => "not-allowed", Cursor::ResizeLeftRight => "ew-resize", Cursor::ResizeUpDown => "ns-resize", // TODO: support custom cursors Cursor::Custom(_) => "default", }, ) .unwrap_or_else(|_| warn!("Failed to set cursor")); }
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/web/screen.rs
druid-shell/src/backend/web/screen.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Monitor and Screen information ignored for web. use crate::screen::Monitor; pub(crate) fn get_monitors() -> Vec<Monitor> { tracing::warn!("Screen::get_monitors() is not implemented for web."); 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/platform/linux.rs
druid-shell/src/platform/linux.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Linux specific extensions. use crate::Clipboard; /// Linux specific extensions to [`Application`] /// /// [`Application`]: crate::Application pub trait ApplicationExt { /// Returns a handle to the primary system clipboard. /// /// This is useful for middle mouse paste. fn primary_clipboard(&self) -> Clipboard; } #[cfg(test)] #[allow(unused_imports)] mod test { use crate::Application; use super::*; use static_assertions as sa; // TODO: impl ApplicationExt for wayland #[cfg(not(feature = "wayland"))] sa::assert_impl_all!(Application: ApplicationExt); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/platform/mod.rs
druid-shell/src/platform/mod.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Platorm specific extensions. #[cfg(any( doc, any(target_os = "freebsd", target_os = "linux", target_os = "openbsd") ))] pub mod linux; #[cfg(any(doc, target_os = "macos"))] pub mod mac;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/src/platform/mac.rs
druid-shell/src/platform/mac.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! macOS specific extensions. /// macOS specific extensions to [`Application`] /// /// [`Application`]: crate::Application pub trait ApplicationExt { /// Hide the application this window belongs to. (cmd+H) fn hide(&self); /// Hide all other applications. (cmd+opt+H) fn hide_others(&self); /// Sets the global application menu, on platforms where there is one. /// /// On platforms with no global application menu, this has no effect. fn set_menu(&self, menu: crate::Menu); } #[cfg(test)] mod test { use crate::Application; use super::*; use static_assertions as sa; sa::assert_impl_all!(Application: ApplicationExt); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/examples/shello.rs
druid-shell/examples/shello.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::any::Any; use druid_shell::kurbo::{Line, Size}; use druid_shell::piet::{Color, RenderContext}; use druid_shell::{ Application, Cursor, FileDialogOptions, FileDialogToken, FileInfo, FileSpec, HotKey, KeyEvent, Menu, MouseEvent, Region, SysMods, TimerToken, WinHandler, WindowBuilder, WindowHandle, }; const BG_COLOR: Color = Color::rgb8(0x27, 0x28, 0x22); const FG_COLOR: Color = Color::rgb8(0xf0, 0xf0, 0xea); #[derive(Default)] struct HelloState { size: Size, handle: WindowHandle, } impl WinHandler for HelloState { fn connect(&mut self, handle: &WindowHandle) { self.handle = handle.clone(); } fn prepare_paint(&mut self) {} fn paint(&mut self, piet: &mut piet_common::Piet, _: &Region) { let rect = self.size.to_rect(); piet.fill(rect, &BG_COLOR); piet.stroke(Line::new((10.0, 50.0), (90.0, 90.0)), &FG_COLOR, 1.0); } fn command(&mut self, id: u32) { match id { 0x100 => { self.handle.close(); Application::global().quit() } 0x101 => { let options = FileDialogOptions::new().show_hidden().allowed_types(vec![ FileSpec::new("Rust Files", &["rs", "toml"]), FileSpec::TEXT, FileSpec::JPG, ]); self.handle.open_file(options); } 0x102 => { let options = FileDialogOptions::new().show_hidden().allowed_types(vec![ FileSpec::new("Rust Files", &["rs", "toml"]), FileSpec::TEXT, FileSpec::JPG, ]); self.handle.save_as(options); } _ => println!("unexpected id {id}"), } } fn open_file(&mut self, _token: FileDialogToken, file_info: Option<FileInfo>) { println!("open file result: {file_info:?}"); } fn save_as(&mut self, _token: FileDialogToken, file: Option<FileInfo>) { println!("save file result: {file:?}"); } fn key_down(&mut self, event: KeyEvent) -> bool { println!("keydown: {event:?}"); false } fn key_up(&mut self, event: KeyEvent) { println!("keyup: {event:?}"); } fn wheel(&mut self, event: &MouseEvent) { println!("mouse_wheel {event:?}"); } fn mouse_move(&mut self, event: &MouseEvent) { self.handle.set_cursor(&Cursor::Arrow); println!("mouse_move {event:?}"); } fn mouse_down(&mut self, event: &MouseEvent) { println!("mouse_down {event:?}"); } fn mouse_up(&mut self, event: &MouseEvent) { println!("mouse_up {event:?}"); } fn timer(&mut self, id: TimerToken) { println!("timer fired: {id:?}"); } fn size(&mut self, size: Size) { self.size = size; } fn got_focus(&mut self) { println!("Got focus"); } fn lost_focus(&mut self) { println!("Lost focus"); } fn request_close(&mut self) { self.handle.close(); } fn destroy(&mut self) { Application::global().quit() } fn as_any(&mut self) -> &mut dyn Any { self } } fn main() { tracing_subscriber::fmt().init(); let mut file_menu = Menu::new(); file_menu.add_item( 0x100, "E&xit", Some(&HotKey::new(SysMods::Cmd, "q")), None, true, ); file_menu.add_item( 0x101, "O&pen", Some(&HotKey::new(SysMods::Cmd, "o")), None, true, ); file_menu.add_item( 0x102, "S&ave", Some(&HotKey::new(SysMods::Cmd, "s")), None, true, ); let mut menubar = Menu::new(); menubar.add_dropdown(Menu::new(), "Application", true); menubar.add_dropdown(file_menu, "&File", true); let app = Application::new().unwrap(); let mut builder = WindowBuilder::new(app.clone()); builder.set_handler(Box::<HelloState>::default()); builder.set_title("Hello example"); builder.set_menu(menubar); let window = builder.build().unwrap(); window.show(); app.run(None); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/examples/edit_text.rs
druid-shell/examples/edit_text.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! This example shows a how a single-line text field might be implemented for `druid-shell`. //! Beyond the omission of multiple lines and text wrapping, it also is missing many motions //! (like "move to previous word") and bidirectional text support. use std::any::Any; use std::borrow::Cow; use std::cell::RefCell; use std::ops::Range; use std::rc::Rc; use unicode_segmentation::GraphemeCursor; use druid_shell::kurbo::Size; use druid_shell::piet::{ Color, FontFamily, HitTestPoint, PietText, PietTextLayout, RenderContext, Text, TextLayout, TextLayoutBuilder, }; use druid_shell::{ keyboard_types::Key, text, text::Action, text::Event, text::InputHandler, text::Selection, text::VerticalMovement, Application, KeyEvent, Region, TextFieldToken, WinHandler, WindowBuilder, WindowHandle, }; use druid_shell::kurbo::{Point, Rect}; const BG_COLOR: Color = Color::rgb8(0xff, 0xff, 0xff); const COMPOSITION_BG_COLOR: Color = Color::rgb8(0xff, 0xd8, 0x6e); const SELECTION_BG_COLOR: Color = Color::rgb8(0x87, 0xc5, 0xff); const CARET_COLOR: Color = Color::rgb8(0x00, 0x82, 0xfc); const FONT: FontFamily = FontFamily::SANS_SERIF; const FONT_SIZE: f64 = 16.0; #[derive(Default)] struct AppState { size: Size, handle: WindowHandle, document: Rc<RefCell<DocumentState>>, text_input_token: Option<TextFieldToken>, } #[derive(Default)] struct DocumentState { text: String, selection: Selection, composition: Option<Range<usize>>, text_engine: Option<PietText>, layout: Option<PietTextLayout>, } impl DocumentState { fn refresh_layout(&mut self) { let text_engine = self.text_engine.as_mut().unwrap(); self.layout = Some( text_engine .new_text_layout(self.text.clone()) .font(FONT, FONT_SIZE) .build() .unwrap(), ); } } impl WinHandler for AppState { fn connect(&mut self, handle: &WindowHandle) { self.handle = handle.clone(); let token = self.handle.add_text_field(); self.handle.set_focused_text_field(Some(token)); self.text_input_token = Some(token); let mut doc = self.document.borrow_mut(); doc.text_engine = Some(handle.text()); doc.refresh_layout(); } fn prepare_paint(&mut self) { self.handle.invalidate(); } fn paint(&mut self, piet: &mut piet_common::Piet, _: &Region) { let rect = self.size.to_rect(); piet.fill(rect, &BG_COLOR); let doc = self.document.borrow(); let layout = doc.layout.as_ref().unwrap(); // TODO(lord): rects for range on layout if let Some(composition_range) = doc.composition.as_ref() { for rect in layout.rects_for_range(composition_range.clone()) { piet.fill(rect, &COMPOSITION_BG_COLOR); } } if !doc.selection.is_caret() { for rect in layout.rects_for_range(doc.selection.range()) { piet.fill(rect, &SELECTION_BG_COLOR); } } piet.draw_text(layout, (0.0, 0.0)); // draw caret let caret_x = layout.hit_test_text_position(doc.selection.active).point.x; piet.fill( Rect::new(caret_x - 1.0, 0.0, caret_x + 1.0, FONT_SIZE), &CARET_COLOR, ); } fn command(&mut self, id: u32) { match id { 0x100 => { self.handle.close(); Application::global().quit() } _ => println!("unexpected id {id}"), } } fn key_down(&mut self, event: KeyEvent) -> bool { if event.key == Key::Character("c".to_string()) { // custom hotkey for pressing "c" println!("user pressed c! wow! setting selection to 0"); // update internal selection state self.document.borrow_mut().selection = Selection::caret(0); // notify the OS that we've updated the selection self.handle .update_text_field(self.text_input_token.unwrap(), Event::SelectionChanged); // repaint window self.handle.request_anim_frame(); // return true prevents the keypress event from being handled as text input return true; } false } fn acquire_input_lock( &mut self, _token: TextFieldToken, _mutable: bool, ) -> Box<dyn InputHandler> { Box::new(AppInputHandler { state: self.document.clone(), window_size: self.size, window_handle: self.handle.clone(), }) } fn release_input_lock(&mut self, _token: TextFieldToken) { // no action required; this example is simple enough that this // state is not actually shared. } fn size(&mut self, size: Size) { self.size = size; } fn request_close(&mut self) { self.handle.close(); } fn destroy(&mut self) { Application::global().quit() } fn as_any(&mut self) -> &mut dyn Any { self } } struct AppInputHandler { state: Rc<RefCell<DocumentState>>, window_size: Size, window_handle: WindowHandle, } impl InputHandler for AppInputHandler { fn selection(&self) -> Selection { self.state.borrow().selection } fn composition_range(&self) -> Option<Range<usize>> { self.state.borrow().composition.clone() } fn set_selection(&mut self, range: Selection) { self.state.borrow_mut().selection = range; self.window_handle.request_anim_frame(); } fn set_composition_range(&mut self, range: Option<Range<usize>>) { self.state.borrow_mut().composition = range; self.window_handle.request_anim_frame(); } fn replace_range(&mut self, range: Range<usize>, text: &str) { let mut doc = self.state.borrow_mut(); doc.text.replace_range(range.clone(), text); if doc.selection.anchor < range.start && doc.selection.active < range.start { // no need to update selection } else if doc.selection.anchor > range.end && doc.selection.active > range.end { doc.selection.anchor -= range.len(); doc.selection.active -= range.len(); doc.selection.anchor += text.len(); doc.selection.active += text.len(); } else { doc.selection.anchor = range.start + text.len(); doc.selection.active = range.start + text.len(); } doc.refresh_layout(); doc.composition = None; self.window_handle.request_anim_frame(); } fn slice(&self, range: Range<usize>) -> Cow<'_, str> { self.state.borrow().text[range].to_string().into() } fn is_char_boundary(&self, i: usize) -> bool { self.state.borrow().text.is_char_boundary(i) } fn len(&self) -> usize { self.state.borrow().text.len() } fn hit_test_point(&self, point: Point) -> HitTestPoint { self.state .borrow() .layout .as_ref() .unwrap() .hit_test_point(point) } fn bounding_box(&self) -> Option<Rect> { Some(Rect::new( 0.0, 0.0, self.window_size.width, self.window_size.height, )) } fn slice_bounding_box(&self, range: Range<usize>) -> Option<Rect> { let doc = self.state.borrow(); let layout = doc.layout.as_ref().unwrap(); let range_start_x = layout.hit_test_text_position(range.start).point.x; let range_end_x = layout.hit_test_text_position(range.end).point.x; Some(Rect::new(range_start_x, 0.0, range_end_x, FONT_SIZE)) } fn line_range(&self, _char_index: usize, _affinity: text::Affinity) -> Range<usize> { // we don't have multiple lines, so no matter the input, output is the whole document 0..self.state.borrow().text.len() } fn handle_action(&mut self, action: Action) { let handled = apply_default_behavior(self, action); println!("action: {action:?} handled: {handled:?}"); } } fn apply_default_behavior(handler: &mut AppInputHandler, action: Action) -> bool { let is_caret = handler.selection().is_caret(); match action { Action::Move(movement) => { let selection = handler.selection(); let index = if movement_goes_downstream(movement) { selection.max() } else { selection.min() }; let updated_index = if let (false, text::Movement::Grapheme(_)) = (is_caret, movement) { // handle special cases of pressing left/right when the selection is not a caret index } else { match apply_movement(handler, movement, index) { Some(v) => v, None => return false, } }; handler.set_selection(Selection::caret(updated_index)); } Action::MoveSelecting(movement) => { let mut selection = handler.selection(); selection.active = match apply_movement(handler, movement, selection.active) { Some(v) => v, None => return false, }; handler.set_selection(selection); } Action::SelectAll => { let len = handler.len(); let selection = Selection::new(0, len); handler.set_selection(selection); } Action::Delete(_) if !is_caret => { // movement is ignored for non-caret selections let selection = handler.selection(); handler.replace_range(selection.range(), ""); } Action::Delete(movement) => { let mut selection = handler.selection(); selection.active = match apply_movement(handler, movement, selection.active) { Some(v) => v, None => return false, }; handler.replace_range(selection.range(), ""); } _ => return false, } true } fn movement_goes_downstream(movement: text::Movement) -> bool { match movement { text::Movement::Grapheme(dir) => direction_goes_downstream(dir), text::Movement::Word(dir) => direction_goes_downstream(dir), text::Movement::Line(dir) => direction_goes_downstream(dir), text::Movement::ParagraphEnd => true, text::Movement::Vertical(VerticalMovement::LineDown) => true, text::Movement::Vertical(VerticalMovement::PageDown) => true, text::Movement::Vertical(VerticalMovement::DocumentEnd) => true, _ => false, } } fn direction_goes_downstream(direction: text::Direction) -> bool { match direction { text::Direction::Left => false, text::Direction::Right => true, text::Direction::Upstream => false, text::Direction::Downstream => true, } } fn apply_movement( edit_lock: &mut AppInputHandler, movement: text::Movement, index: usize, ) -> Option<usize> { match movement { text::Movement::Grapheme(dir) => { let doc_len = edit_lock.len(); let mut cursor = GraphemeCursor::new(index, doc_len, true); let doc = edit_lock.slice(0..doc_len); if direction_goes_downstream(dir) { cursor.next_boundary(&doc, 0).unwrap() } else { cursor.prev_boundary(&doc, 0).unwrap() } } _ => None, } } fn main() { let app = Application::new().unwrap(); let mut builder = WindowBuilder::new(app.clone()); builder.set_handler(Box::<AppState>::default()); builder.set_title("Text editing example"); let window = builder.build().unwrap(); window.show(); app.run(None); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/examples/quit.rs
druid-shell/examples/quit.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::any::Any; use druid_shell::kurbo::{Line, Size}; use druid_shell::piet::{Color, RenderContext}; use druid_shell::{ Application, HotKey, Menu, Region, SysMods, WinHandler, WindowBuilder, WindowHandle, }; const BG_COLOR: Color = Color::rgb8(0x27, 0x28, 0x22); const FG_COLOR: Color = Color::rgb8(0xf0, 0xf0, 0xea); #[derive(Default)] struct QuitState { quit_count: u32, size: Size, handle: WindowHandle, } impl WinHandler for QuitState { fn connect(&mut self, handle: &WindowHandle) { self.handle = handle.clone(); } fn prepare_paint(&mut self) {} fn paint(&mut self, piet: &mut piet_common::Piet, _: &Region) { let rect = self.size.to_rect(); piet.fill(rect, &BG_COLOR); piet.stroke(Line::new((10.0, 50.0), (90.0, 90.0)), &FG_COLOR, 1.0); } fn size(&mut self, size: Size) { self.size = size; } fn request_close(&mut self) { self.quit_count += 1; if self.quit_count >= 5 { self.handle.close(); } else { tracing::info!("Don't wanna quit"); } } fn destroy(&mut self) { Application::global().quit() } fn as_any(&mut self) -> &mut dyn Any { self } } fn main() { tracing_subscriber::fmt().init(); let app = Application::new().unwrap(); let mut file_menu = Menu::new(); file_menu.add_item( 0x100, "E&xit", Some(&HotKey::new(SysMods::Cmd, "q")), None, true, ); let mut menubar = Menu::new(); menubar.add_dropdown(file_menu, "Application", true); let mut builder = WindowBuilder::new(app.clone()); builder.set_handler(Box::<QuitState>::default()); builder.set_title("Quit example"); builder.set_menu(menubar); let window = builder.build().unwrap(); window.show(); app.run(None); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/examples/perftest.rs
druid-shell/examples/perftest.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::any::Any; use std::time::Instant; use piet_common::kurbo::{Line, Size}; use piet_common::{Color, FontFamily, Piet, RenderContext, Text, TextLayoutBuilder}; use druid_shell::{Application, KeyEvent, Region, WinHandler, WindowBuilder, WindowHandle}; const BG_COLOR: Color = Color::rgb8(0x27, 0x28, 0x22); const FG_COLOR: Color = Color::rgb8(0xf0, 0xf0, 0xea); const RED: Color = Color::rgb8(0xff, 0x80, 0x80); const CYAN: Color = Color::rgb8(0x80, 0xff, 0xff); struct PerfTest { handle: WindowHandle, size: Size, start_time: Instant, last_time: Instant, red: bool, } impl WinHandler for PerfTest { fn connect(&mut self, handle: &WindowHandle) { self.handle = handle.clone(); } fn prepare_paint(&mut self) { self.handle.invalidate(); } fn paint(&mut self, piet: &mut Piet, _: &Region) { let rect = self.size.to_rect(); piet.fill(rect, &BG_COLOR); piet.stroke( Line::new((0.0, self.size.height), (self.size.width, 0.0)), &FG_COLOR, 1.0, ); let current_ns = (Instant::now() - self.start_time).as_nanos(); let th = ::std::f64::consts::PI * (current_ns as f64) * 2e-9; let dx = 100.0 * th.sin(); let dy = 100.0 * th.cos(); piet.stroke( Line::new((100.0, 100.0), (100.0 + dx, 100.0 - dy)), &FG_COLOR, 1.0, ); let now = Instant::now(); let msg = format!("{}ms", (now - self.last_time).as_millis()); self.last_time = now; let layout = piet .text() .new_text_layout(msg) .font(FontFamily::MONOSPACE, 15.0) .text_color(FG_COLOR) .build() .unwrap(); piet.draw_text(&layout, (10.0, 210.0)); let msg = "VSYNC"; let color = if self.red { RED } else { CYAN }; let layout = piet .text() .new_text_layout(msg) .text_color(color) .font(FontFamily::MONOSPACE, 48.0) .build() .unwrap(); piet.draw_text(&layout, (10.0, 280.0)); self.red = !self.red; let msg = "Hello DWrite! This is a somewhat longer string of text intended to provoke slightly longer draw times."; let layout = piet .text() .new_text_layout(msg) .font(FontFamily::MONOSPACE, 15.0) .text_color(FG_COLOR) .build() .unwrap(); let dy = 15.0; let x0 = 210.0; let y0 = 10.0; for i in 0..60 { let y = y0 + (i as f64) * dy; piet.draw_text(&layout, (x0, y)); } self.handle.request_anim_frame(); } fn command(&mut self, id: u32) { match id { 0x100 => self.handle.close(), _ => println!("unexpected id {id}"), } } fn key_down(&mut self, event: KeyEvent) -> bool { println!("keydown: {event:?}"); false } fn size(&mut self, size: Size) { self.size = size; } fn request_close(&mut self) { self.handle.close(); } fn destroy(&mut self) { Application::global().quit() } fn as_any(&mut self) -> &mut dyn Any { self } } fn main() { tracing_subscriber::fmt().init(); let app = Application::new().unwrap(); let mut builder = WindowBuilder::new(app.clone()); let perf_test = PerfTest { size: Size::ZERO, handle: Default::default(), start_time: Instant::now(), last_time: Instant::now(), red: true, }; builder.set_handler(Box::new(perf_test)); builder.set_title("Performance tester"); let window = builder.build().unwrap(); window.show(); app.run(None); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid-shell/examples/invalidate.rs
druid-shell/examples/invalidate.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::any::Any; use std::time::Instant; use druid_shell::kurbo::{Point, Rect, Size}; use druid_shell::piet::{Color, Piet, RenderContext}; use druid_shell::{Application, Region, WinHandler, WindowBuilder, WindowHandle}; struct InvalidateTest { handle: WindowHandle, size: Size, start_time: Instant, color: Color, rect: Rect, cursor: Rect, } impl InvalidateTest { fn update_color_and_rect(&mut self) { let time_since_start = (Instant::now() - self.start_time).as_millis(); let (r, g, b, _) = self.color.as_rgba8(); self.color = match (time_since_start % 2, time_since_start % 3) { (0, _) => Color::rgb8(r.wrapping_add(10), g, b), (_, 0) => Color::rgb8(r, g.wrapping_add(10), b), (_, _) => Color::rgb8(r, g, b.wrapping_add(10)), }; self.rect.x0 = (self.rect.x0 + 5.0) % self.size.width; self.rect.x1 = (self.rect.x1 + 5.5) % self.size.width; self.rect.y0 = (self.rect.y0 + 3.0) % self.size.height; self.rect.y1 = (self.rect.y1 + 3.5) % self.size.height; // Invalidate the old and new cursor positions. self.handle.invalidate_rect(self.cursor); self.cursor.x0 += 4.0; self.cursor.x1 += 4.0; if self.cursor.x0 > self.size.width { self.cursor.x1 = self.cursor.width(); self.cursor.x0 = 0.0; } self.handle.invalidate_rect(self.cursor); } } impl WinHandler for InvalidateTest { fn connect(&mut self, handle: &WindowHandle) { self.handle = handle.clone(); } fn prepare_paint(&mut self) { self.update_color_and_rect(); self.handle.invalidate_rect(self.rect); } fn paint(&mut self, piet: &mut Piet, region: &Region) { // We can ask to draw something bigger than our rect, but things outside // the invalidation region won't draw. (So they'll draw if and only if // they intersect the cursor's invalidated region or the rect that we // invalidated.) piet.fill(region.bounding_box(), &self.color); piet.fill(self.cursor, &Color::WHITE); self.handle.request_anim_frame(); } fn size(&mut self, size: Size) { self.size = size; } fn command(&mut self, id: u32) { match id { 0x100 => self.handle.close(), _ => println!("unexpected id {id}"), } } fn request_close(&mut self) { self.handle.close(); } fn destroy(&mut self) { Application::global().quit() } fn as_any(&mut self) -> &mut dyn Any { self } } fn main() { tracing_subscriber::fmt().init(); let app = Application::new().unwrap(); let mut builder = WindowBuilder::new(app.clone()); let inv_test = InvalidateTest { size: Size::ZERO, handle: Default::default(), start_time: Instant::now(), rect: Rect::from_origin_size(Point::ZERO, (10.0, 20.0)), cursor: Rect::from_origin_size(Point::ZERO, (2.0, 100.0)), color: Color::WHITE, }; builder.set_handler(Box::new(inv_test)); builder.set_title("Invalidate tester"); let window = builder.build().unwrap(); window.show(); app.run(None); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/lib.rs
docs/book_examples/src/lib.rs
//! Code samples used in the book, stored here so they are easier to test in CI. #![allow(dead_code, unused_variables)] mod custom_widgets_md; mod data_md; mod env_md; mod getting_started_2_md; mod getting_started_md; mod lens_md; mod widget_md;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/getting_started_md.rs
docs/book_examples/src/getting_started_md.rs
#![allow(clippy::let_unit_value)] // ANCHOR: example_1_imports use druid::widget::Label; use druid::{AppLauncher, Widget, WindowDesc}; // ANCHOR_END: example_1_imports // ANCHOR: example_2_imports use druid::widget::{Container, Flex, Split}; use druid::Color; // ANCHOR_END: example_2_imports // ANCHOR: example_3_imports use im::Vector; // ANCHOR_END: example_3_imports // ANCHOR: example_3b_imports use druid::widget::List; // ANCHOR_END: example_3b_imports // ANCHOR: example_4_imports use im::vector; // ANCHOR_END: example_4_imports // ANCHOR: example_5_imports use druid::widget::Button; // ANCHOR_END: example_5_imports // ANCHOR: example_1 fn build_ui() -> impl Widget<()> { Label::new("Hello world") } fn main() { let main_window = WindowDesc::new(build_ui()) .window_size((600.0, 400.0)) .title("My first Druid App"); let initial_data = (); AppLauncher::with_window(main_window) .launch(initial_data) .expect("Failed to launch application"); } // ANCHOR_END: example_1 fn build_example_2() -> impl Widget<()> { // ANCHOR: example_2_builder Split::columns( Container::new( Flex::column() .with_flex_child(Label::new("first item"), 1.0) .with_flex_child(Label::new("second item"), 1.0) .with_flex_child(Label::new("third item"), 1.0) .with_flex_child(Label::new("fourth item"), 1.0), ) .border(Color::grey(0.6), 2.0), Container::new( Flex::column() .with_flex_child(Label::new("Button placeholder"), 1.0) .with_flex_child(Label::new("Textbox placeholder"), 1.0), ) .border(Color::grey(0.6), 2.0), ) // ANCHOR_END: example_2_builder } type TodoList = Vector<String>; fn build_example_3() -> impl Widget<TodoList> { // ANCHOR: example_3_builder Split::columns( Container::new( // Dynamic list of Widgets List::new(|| Label::dynamic(|data, _| format!("List item: {data}"))), ) .border(Color::grey(0.6), 2.0), Container::new( Flex::column() .with_flex_child(Label::new("Button placeholder"), 1.0) .with_flex_child(Label::new("Textbox placeholder"), 1.0), ) .border(Color::grey(0.6), 2.0), ) // ANCHOR_END: example_3_builder } fn example_4_main() { fn build_ui() -> impl Widget<TodoList> { build_example_3() } // ANCHOR: example_4_main let main_window = WindowDesc::new(build_ui()) .window_size((600.0, 400.0)) .title("My first Druid App"); let initial_data = vector![ "first item".into(), "second item".into(), "third item".into(), "foo".into(), "bar".into(), ]; AppLauncher::with_window(main_window) .launch(initial_data) .expect("Failed to launch application"); // ANCHOR_END: example_4_main } fn build_example_5a() -> impl Widget<TodoList> { // ANCHOR: example_5a_button // Replace `Label::new("Button placeholder")` with Button::new("Add item") // ANCHOR_END: example_5a_button } fn build_example_5b() -> impl Widget<TodoList> { // ANCHOR: example_5b_button Button::new("Add item") .on_click(|_, data: &mut Vector<String>, _| data.push_back("New item".into())) // ANCHOR_END: example_5b_button }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/env_md.rs
docs/book_examples/src/env_md.rs
use druid::widget::Label; use druid::{Color, Key, WidgetExt}; // ANCHOR: key_or_value const IMPORTANT_LABEL_COLOR: Key<Color> = Key::new("org.linebender.example.important-label-color"); const RED: Color = Color::rgb8(0xFF, 0, 0); fn make_labels() { let with_value = Label::<()>::new("Warning!").with_text_color(RED); let with_key = Label::<()>::new("Warning!").with_text_color(IMPORTANT_LABEL_COLOR); } // ANCHOR_END: key_or_value // ANCHOR: env_scope fn scoped_label() { let my_label = Label::<()>::new("Warning!").env_scope(|env, _| { env.set(druid::theme::TEXT_COLOR, Color::BLACK); env.set(druid::theme::TEXT_SIZE_NORMAL, 18.0); }); } // ANCHOR_END: env_scope
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/custom_widgets_md.rs
docs/book_examples/src/custom_widgets_md.rs
use druid::keyboard_types::Key; use druid::widget::{Controller, Label, Painter, SizedBox, TextBox}; use druid::{ Color, Env, Event, EventCtx, PaintCtx, RenderContext, Selector, TimerToken, Widget, WidgetExt, }; use std::time::Duration; const CORNER_RADIUS: f64 = 4.0; const STROKE_WIDTH: f64 = 2.0; // ANCHOR: color_swatch fn make_color_swatch() -> Painter<Color> { Painter::new(|ctx: &mut PaintCtx, data: &Color, env: &Env| { let bounds = ctx.size().to_rect(); let rounded = bounds.to_rounded_rect(CORNER_RADIUS); ctx.fill(rounded, data); ctx.stroke(rounded, &env.get(druid::theme::PRIMARY_DARK), STROKE_WIDTH); }) } // ANCHOR_END: color_swatch // ANCHOR: sized_swatch fn sized_swatch() -> impl Widget<Color> { SizedBox::new(make_color_swatch()).width(20.0).height(20.0) } // ANCHOR_END: sized_swatch // ANCHOR: background_label fn background_label() -> impl Widget<Color> { Label::dynamic(|color: &Color, _| { let (r, g, b, _) = color.as_rgba8(); format!("#{r:X}{g:X}{b:X}") }) .background(make_color_swatch()) } // ANCHOR_END: background_label // ANCHOR: annoying_textbox const ACTION: Selector = Selector::new("hello.textbox-action"); const DELAY: Duration = Duration::from_millis(300); struct TextBoxActionController { timer: Option<TimerToken>, } impl TextBoxActionController { pub fn new() -> Self { TextBoxActionController { timer: None } } } impl Controller<String, TextBox<String>> for TextBoxActionController { fn event( &mut self, child: &mut TextBox<String>, ctx: &mut EventCtx, event: &Event, data: &mut String, env: &Env, ) { match event { Event::KeyDown(k) if k.key == Key::Enter => { ctx.submit_command(ACTION); } Event::KeyUp(k) if k.key == Key::Enter => { self.timer = Some(ctx.request_timer(DELAY)); child.event(ctx, event, data, env); } Event::Timer(token) if Some(*token) == self.timer => { ctx.submit_command(ACTION); } _ => child.event(ctx, event, data, env), } } } // ANCHOR_END: annoying_textbox
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/lens_md.rs
docs/book_examples/src/lens_md.rs
use druid::{Data, Lens}; #[rustfmt::skip] mod todo_item_lens { use druid::Data; // ANCHOR: todo_item /// A single todo item. #[derive(Clone, Data)] struct TodoItem { title: String, completed: bool, urgent: bool, } // ANCHOR_END: todo_item } // ANCHOR: todo_item_lens /// A single todo item. #[derive(Clone, Data, Lens)] struct TodoItem { title: String, completed: bool, urgent: bool, } // ANCHOR_END: todo_item_lens // ANCHOR: simple_lens trait SimpleLens<In, Out> { fn focus(&self, data: &In) -> Out; } // ANCHOR_END: simple_lens // ANCHOR: completed_lens /// This is the type of the lens itself; in this case it has no state. struct CompletedLens; impl SimpleLens<TodoItem, bool> for CompletedLens { fn focus(&self, data: &TodoItem) -> bool { data.completed } } // ANCHOR_END: completed_lens #[rustfmt::skip] mod lens_impl { // ANCHOR: lens pub trait Lens<In, Out> { /// Get non-mut access to the field. fn with<R, F: FnOnce(&Out) -> R>(&self, data: &In, f: F) -> R; /// Get mut access to the field. fn with_mut<R, F: FnOnce(&mut Out) -> R>(&self, data: &mut In, f: F) -> R; } // ANCHOR_END: lens use super::TodoItem; // ANCHOR: completed_lens_real struct CompletedLens; impl Lens<TodoItem, bool> for CompletedLens { fn with<R, F: FnOnce(&bool) -> R>(&self, data: &TodoItem, f: F) -> R { f(&data.completed) } fn with_mut<R, F: FnOnce(&mut bool) -> R>(&self, data: &mut TodoItem, f: F) -> R { f(&mut data.completed) } } // ANCHOR_END: completed_lens_real } // // ANCHOR: lens_name #[derive(Lens)] struct Item { #[lens(name = "count_lens")] count: usize, #[lens(ignore)] complete: bool, } // This works now: impl Item { fn count(&self) -> usize { self.count } fn complete(&mut self) { self.complete = true; } } // ANCHOR_END: lens_name // ANCHOR: build_ui use druid::widget::{Checkbox, Flex, Label, Widget, WidgetExt}; fn make_todo_item() -> impl Widget<TodoItem> { // A label that generates its text based on the data: let title = Label::dynamic(|text: &String, _| text.to_string()).lens(TodoItem::title); let completed = Checkbox::new("Completed:").lens(TodoItem::completed); let urgent = Checkbox::new("Urgent:").lens(TodoItem::urgent); Flex::column() // label on top .with_child(title) // two checkboxes below .with_child(Flex::row().with_child(completed).with_child(urgent)) } // ANCHOR_END: build_ui use std::collections::HashMap; use std::sync::Arc; // ANCHOR: contact #[derive(Clone, Data)] struct Contact { // fields } type ContactId = u64; #[derive(Clone, Data)] struct Contacts { inner: Arc<HashMap<ContactId, Contact>>, } // Lets write a lens that returns a specific contact based on its id, if it exists. struct ContactIdLens(ContactId); impl Lens<Contacts, Option<Contact>> for ContactIdLens { fn with<R, F: FnOnce(&Option<Contact>) -> R>(&self, data: &Contacts, f: F) -> R { let contact = data.inner.get(&self.0).cloned(); f(&contact) } fn with_mut<R, F: FnOnce(&mut Option<Contact>) -> R>(&self, data: &mut Contacts, f: F) -> R { // get an immutable copy let mut contact = data.inner.get(&self.0).cloned(); let result = f(&mut contact); // only actually mutate the collection if our result is mutated; let changed = match (contact.as_ref(), data.inner.get(&self.0)) { (Some(one), Some(two)) => !one.same(two), (None, None) => false, _ => true, }; if changed { // if !data.inner.get(&self.0).same(&contact.as_ref()) { let contacts = Arc::make_mut(&mut data.inner); // if we're none, we were deleted, and remove from the map; else replace match contact { Some(contact) => contacts.insert(self.0, contact), None => contacts.remove(&self.0), }; } result } } // ANCHOR_END: contact // ANCHOR: conversion struct MilesToKm; const KM_PER_MILE: f64 = 1.609_344; impl Lens<f64, f64> for MilesToKm { fn with<R, F: FnOnce(&f64) -> R>(&self, data: &f64, f: F) -> R { let kms = *data * KM_PER_MILE; f(&kms) } fn with_mut<R, F: FnOnce(&mut f64) -> R>(&self, data: &mut f64, f: F) -> R { let mut kms = *data * KM_PER_MILE; let kms_2 = kms; let result = f(&mut kms); // avoid doing the conversion if unchanged, it might be lossy? if !kms.same(&kms_2) { let miles = kms * KM_PER_MILE.recip(); *data = miles; } result } } // ANCHOR_END: conversion
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/getting_started_2_md.rs
docs/book_examples/src/getting_started_2_md.rs
#![allow(unused)] // ANCHOR: example_1_imports use druid::widget::Label; use druid::{AppLauncher, Widget, WindowDesc}; // ANCHOR_END: example_1_imports // ANCHOR: example_2_imports use druid::widget::{Container, Flex, Split}; use druid::Color; // ANCHOR_END: example_2_imports // ANCHOR: example_3_imports use im::Vector; // ANCHOR_END: example_3_imports // ANCHOR: example_3b_imports use druid::widget::List; // ANCHOR_END: example_3b_imports // ANCHOR: example_4_imports use im::vector; // ANCHOR_END: example_4_imports // ANCHOR: example_5_imports use druid::widget::Button; // ANCHOR_END: example_5_imports // --- // ANCHOR: example_6_imports use druid::{Data, Lens}; // ANCHOR_END: example_6_imports // ANCHOR: example_6_derive #[derive(Clone, Data, Lens)] // ANCHOR_END: example_6_derive // ANCHOR: example_6_struct struct TodoList { items: Vector<String>, next_item: String, } // ANCHOR_END: example_6_struct // ANCHOR: example_7_imports use druid::widget::LensWrap; // ANCHOR_END: example_7_imports fn build_example_7() -> impl Widget<TodoList> { // ANCHOR: example_7 // Replace previous List with: LensWrap::new( List::new(|| Label::dynamic(|data, _| format!("List item: {data}"))), TodoList::items, ) // ANCHOR_END: example_7 } fn build_example_7b() -> impl Widget<TodoList> { // ANCHOR: example_7b // Replace previous Button with: Button::new("Add item").on_click(|_, data: &mut TodoList, _| { data.items.push_back(data.next_item.clone()); data.next_item = String::new(); }) // ANCHOR_END: example_7b } // ANCHOR: example_8_imports use druid::widget::TextBox; // ANCHOR_END: example_8_imports fn build_example_8() -> impl Widget<TodoList> { // ANCHOR: example_8 // Replace `Label::new("Textbox placeholder")` with LensWrap::new(TextBox::new(), TodoList::next_item) // ANCHOR_END: example_8 } // ANCHOR: complete_code fn build_ui() -> impl Widget<TodoList> { Split::columns( Container::new( // Dynamic list of Widgets LensWrap::new( List::new(|| Label::dynamic(|data, _| format!("List item: {data}"))), TodoList::items, ), ) .border(Color::grey(0.6), 2.0), Container::new( Flex::column() .with_flex_child( Button::new("Add item").on_click(|_, data: &mut TodoList, _| { data.items.push_back(data.next_item.clone()); data.next_item = String::new(); }), 1.0, ) .with_flex_child(LensWrap::new(TextBox::new(), TodoList::next_item), 1.0), ) .border(Color::grey(0.6), 2.0), ) } fn main() { let main_window = WindowDesc::new(build_ui()) .window_size((600.0, 400.0)) .title("My first Druid App"); let initial_data = TodoList { items: vector![ "first item".into(), "second item".into(), "third item".into(), "foo".into(), "bar".into(), ], next_item: String::new(), }; AppLauncher::with_window(main_window) .launch(initial_data) .expect("Failed to launch application"); } // ANCHOR_END: complete_code
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/data_md.rs
docs/book_examples/src/data_md.rs
#![allow(clippy::rc_buffer)] #[derive(Clone, PartialEq)] struct DateTime(std::time::Instant); // ANCHOR: derive use druid::Data; use std::sync::Arc; #[derive(Clone, Data)] /// The main model for a todo list application. struct TodoList { items: Arc<Vec<TodoItem>>, } #[derive(Clone, Data)] /// A single todo item. struct TodoItem { category: Category, title: String, note: Option<String>, completed: bool, // `Data` is implemented for any `Arc`. due_date: Option<Arc<DateTime>>, // You can specify a custom comparison fn // (anything with the signature (&T, &T) -> bool). #[data(same_fn = "PartialEq::eq")] added_date: DateTime, // You can specify that a field should // be skipped when computing same-ness #[data(ignore)] debug_timestamp: usize, } #[derive(Clone, Data, PartialEq)] /// The three types of tasks in the world. enum Category { Work, Play, Revolution, } // ANCHOR_END: derive
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/docs/book_examples/src/widget_md.rs
docs/book_examples/src/widget_md.rs
// ANCHOR: padded_label use druid::widget::{Label, Padding}; fn padded_label() { let label: Label<()> = Label::new("Humour me"); let padded = Padding::new((4.0, 8.0), label); } // ANCHOR_END: padded_label // ANCHOR: align_center use druid::widget::Align; fn align_center() { let label: Label<()> = Label::new("Center me"); let centered = Align::centered(label); } // ANCHOR_END: align_center // ANCHOR: stepper_builder use druid::widget::Stepper; fn steppers() { // A Stepper with default parameters let stepper1 = Stepper::new(); // A Stepper that operates over a custom range let stepper2 = Stepper::new().with_range(10.0, 50.0); // A Stepper with a custom range *and* a custom step size, that // wraps around past its min and max values: let stepper3 = Stepper::new() .with_range(10.0, 50.0) .with_step(2.5) .with_wraparound(true); } // ANCHOR_END: stepper_builder #[rustfmt::skip] mod padded_stepper_raw { // ANCHOR: padded_stepper_raw use druid::widget::{Align, Padding, Stepper}; fn padded_stepper() { let stepper = Stepper::new().with_range(10.0, 50.0); let padding = Padding::new(8.0, stepper); let padded_and_center_aligned_stepper = Align::centered(padding); } // ANCHOR_END: padded_stepper_raw } #[rustfmt::skip] mod padded_stepper_widgetext { // ANCHOR: padded_stepper_widgetext use druid::widget::{Stepper, WidgetExt}; fn padded_stepper() { let padded_and_center_aligned_stepper = Stepper::new().with_range(10.0, 50.0).padding(8.0).center(); } // ANCHOR_END: padded_stepper_widgetext } // ANCHOR: flex_builder use druid::widget::Flex; fn flex_builder() -> Flex<()> { Flex::column() .with_child(Label::new("Number One")) .with_child(Label::new("Number Two")) .with_child(Label::new("Some Other Number")) } // ANCHOR_END: flex_builder
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/app.rs
druid/src/app.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Window building and app lifecycle. use crate::ext_event::{ExtEventHost, ExtEventSink}; use crate::kurbo::{Point, Size}; use crate::menu::MenuManager; use crate::shell::{Application, Error as PlatformError, WindowBuilder, WindowHandle, WindowLevel}; use crate::widget::LabelText; use crate::win_handler::{AppHandler, AppState}; use crate::window::WindowId; use crate::{AppDelegate, Data, Env, LocalizedString, Menu, Widget}; use tracing::warn; use druid_shell::WindowState; /// A function that modifies the initial environment. type EnvSetupFn<T> = dyn FnOnce(&mut Env, &T); /// Handles initial setup of an application, and starts the runloop. pub struct AppLauncher<T> { windows: Vec<WindowDesc<T>>, env_setup: Option<Box<EnvSetupFn<T>>>, l10n_resources: Option<(Vec<String>, String)>, delegate: Option<Box<dyn AppDelegate<T>>>, ext_event_host: ExtEventHost, } /// Defines how a windows size should be determined #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum WindowSizePolicy { /// Use the content of the window to determine the size. /// /// If you use this option, your root widget will be passed infinite constraints; /// you are responsible for ensuring that your content picks an appropriate size. Content, /// Use the provided window size User, } /// Window configuration that can be applied to a WindowBuilder, or to an existing WindowHandle. /// It does not include anything related to app data. #[derive(PartialEq)] pub struct WindowConfig { pub(crate) size_policy: WindowSizePolicy, pub(crate) size: Option<Size>, pub(crate) min_size: Option<Size>, pub(crate) position: Option<Point>, pub(crate) resizable: Option<bool>, pub(crate) transparent: Option<bool>, pub(crate) show_titlebar: Option<bool>, pub(crate) level: Option<WindowLevel>, pub(crate) always_on_top: Option<bool>, pub(crate) state: Option<WindowState>, } /// A description of a window to be instantiated. /// /// This struct has builder methods to specify some window properties. Each of /// these methods usually corresponds to a platform API call when constructing the /// function. Except for `title()`, they have no default values and the APIS /// won't be called if the method is not used. pub struct WindowDesc<T> { pub(crate) pending: PendingWindow<T>, pub(crate) config: WindowConfig, /// The `WindowId` that will be assigned to this window. /// /// This can be used to track a window from when it is launched and when /// it actually connects. pub id: WindowId, } /// The parts of a window, pending construction, that are dependent on top level app state /// or are not part of the `druid-shell`'s windowing abstraction. /// This includes the boxed root widget, as well as other window properties such as the title. pub struct PendingWindow<T> { pub(crate) root: Box<dyn Widget<T>>, pub(crate) title: LabelText<T>, pub(crate) transparent: bool, pub(crate) menu: Option<MenuManager<T>>, pub(crate) size_policy: WindowSizePolicy, // This is copied over from the WindowConfig // when the native window is constructed. } impl<T: Data> PendingWindow<T> { /// Create a pending window from any widget. pub fn new<W>(root: W) -> PendingWindow<T> where W: Widget<T> + 'static, { // This just makes our API slightly cleaner; callers don't need to explicitly box. PendingWindow { root: Box::new(root), title: LocalizedString::new("app-name").into(), menu: MenuManager::platform_default(), transparent: false, size_policy: WindowSizePolicy::User, } } /// Set the title for this window. This is a [`LabelText`]; it can be either /// a `String`, a [`LocalizedString`], or a closure that computes a string; /// it will be kept up to date as the application's state changes. pub fn title(mut self, title: impl Into<LabelText<T>>) -> Self { self.title = title.into(); self } /// Set whether the background should be transparent pub fn transparent(mut self, transparent: bool) -> Self { self.transparent = transparent; self } /// Set the menu for this window. /// /// `menu` is a callback for creating the menu. Its first argument is the id of the window that /// will have the menu, or `None` if it's creating the root application menu for an app with no /// menus (which can happen, for example, on macOS). pub fn menu( mut self, menu: impl FnMut(Option<WindowId>, &T, &Env) -> Menu<T> + 'static, ) -> Self { self.menu = Some(MenuManager::new(menu)); self } } impl<T: Data> AppLauncher<T> { /// Create a new `AppLauncher` with the provided window. pub fn with_window(window: WindowDesc<T>) -> Self { AppLauncher { windows: vec![window], env_setup: None, l10n_resources: None, delegate: None, ext_event_host: ExtEventHost::new(), } } /// Provide an optional closure that will be given mutable access to /// the environment and immutable access to the app state before launch. /// /// This can be used to set or override theme values. pub fn configure_env(mut self, f: impl Fn(&mut Env, &T) + 'static) -> Self { self.env_setup = Some(Box::new(f)); self } /// Set the [`AppDelegate`]. pub fn delegate(mut self, delegate: impl AppDelegate<T> + 'static) -> Self { self.delegate = Some(Box::new(delegate)); self } /// Initialize a minimal logger with DEBUG max level for printing logs out to stderr. /// /// This is meant for use during development only. /// /// # Panics /// /// Panics if the logger fails to initialize. #[doc(hidden)] #[deprecated(since = "0.8.0", note = "Use log_to_console instead")] pub fn use_simple_logger(self) -> Self { self.log_to_console() } /// Initialize a minimal tracing subscriber with DEBUG max level for printing logs out to /// stderr. /// /// This is meant for quick-and-dirty debugging. If you want more serious trace handling, /// it's probably better to implement it yourself. /// /// # Panics /// /// Panics if `enable` is `true` and the subscriber fails to initialize, /// for example if a `tracing`/`tracing_wasm` global logger was already set. /// /// Never panics when `enable` is `false`, or have any other side effect. /// /// Passing in false is useful if you want to enable a global logger as feature /// but log to console otherwise. pub fn start_console_logging(self, enable: bool) -> Self { if !enable { return self; } #[cfg(not(target_arch = "wasm32"))] { use tracing_subscriber::prelude::*; let filter_layer = tracing_subscriber::filter::LevelFilter::DEBUG; let fmt_layer = tracing_subscriber::fmt::layer() // Display target (eg "my_crate::some_mod::submod") with logs .with_target(true); tracing_subscriber::registry() .with(filter_layer) .with(fmt_layer) .init(); } // Note - tracing-wasm might not work in headless Node.js. Probably doesn't matter anyway, // because this is a GUI framework, so wasm targets will virtually always be browsers. #[cfg(target_arch = "wasm32")] { console_error_panic_hook::set_once(); let config = tracing_wasm::WASMLayerConfigBuilder::new() .set_max_level(tracing::Level::DEBUG) .build(); tracing_wasm::set_as_global_default_with_config(config) } self } /// Calls `start_console_logging` with `true`. pub fn log_to_console(self) -> Self { self.start_console_logging(true) } /// Use custom localization resource /// /// `resources` is a list of file names that contain strings. `base_dir` /// is a path to a directory that includes per-locale subdirectories. /// /// This directory should be of the structure `base_dir/{locale}/{resource}`, /// where '{locale}' is a valid BCP47 language tag, and {resource} is a `.ftl` /// included in `resources`. pub fn localization_resources(mut self, resources: Vec<String>, base_dir: String) -> Self { self.l10n_resources = Some((resources, base_dir)); self } /// Returns an [`ExtEventSink`] that can be moved between threads, /// and can be used to submit commands back to the application. pub fn get_external_handle(&self) -> ExtEventSink { self.ext_event_host.make_sink() } /// Build the windows and start the runloop. /// /// Returns an error if a window cannot be instantiated. This is usually /// a fatal error. pub fn launch(mut self, data: T) -> Result<(), PlatformError> { let app = Application::new()?; let mut env = self .l10n_resources .map(|it| Env::with_i10n(it.0, &it.1)) .unwrap_or_else(Env::with_default_i10n); if let Some(f) = self.env_setup.take() { f(&mut env, &data); } let mut state = AppState::new( app.clone(), data, env, self.delegate.take(), self.ext_event_host, ); for desc in self.windows { let window = desc.build_native(&mut state)?; window.show(); } let handler = AppHandler::new(state); app.run(Some(Box::new(handler))); Ok(()) } } impl Default for WindowConfig { fn default() -> Self { WindowConfig { size_policy: WindowSizePolicy::User, size: None, min_size: None, position: None, resizable: None, show_titlebar: None, transparent: None, level: None, always_on_top: None, state: None, } } } impl WindowConfig { /// Set the window size policy. pub fn window_size_policy(mut self, size_policy: WindowSizePolicy) -> Self { #[cfg(windows)] { // On Windows content_insets doesn't work on window with no initial size // so the window size can't be adapted to the content, to fix this a // non null initial size is set here. if size_policy == WindowSizePolicy::Content { self.size = Some(Size::new(1., 1.)) } } self.size_policy = size_policy; self } /// Set the window's initial drawing area size in [display points]. /// /// You can pass in a tuple `(width, height)` or a [`Size`], /// e.g. to create a window with a drawing area 1000dp wide and 500dp high: /// /// ```ignore /// window.window_size((1000.0, 500.0)); /// ``` /// /// 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 increase the size a tiny bit due to DPI. /// /// [`Size`]: Size /// [display points]: crate::Scale pub fn window_size(mut self, size: impl Into<Size>) -> Self { self.size = Some(size.into()); self } /// 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. /// /// To set the window's initial drawing area size use [`window_size`]. /// /// [`window_size`]: #method.window_size /// [display points]: crate::Scale pub fn with_min_size(mut self, size: impl Into<Size>) -> Self { self.min_size = Some(size.into()); self } /// Set whether the window should be resizable. pub fn resizable(mut self, resizable: bool) -> Self { self.resizable = Some(resizable); self } /// Set whether the window should have a titlebar and decorations. pub fn show_titlebar(mut self, show_titlebar: bool) -> Self { self.show_titlebar = Some(show_titlebar); self } /// Sets the window position in virtual screen coordinates. /// [`position`] Position in pixels. /// /// [`position`]: Point pub fn set_position(mut self, position: Point) -> Self { self.position = Some(position); self } /// Sets the [`WindowLevel`] of the window pub fn set_level(mut self, level: WindowLevel) -> Self { self.level = Some(level); self } /// Sets whether the window is always on top. /// /// An always on top window stays on top, even after clicking off of it. pub fn set_always_on_top(mut self, always_on_top: bool) -> Self { self.always_on_top = Some(always_on_top); self } /// Sets the [`WindowState`] of the window. pub fn set_window_state(mut self, state: WindowState) -> Self { self.state = Some(state); self } /// Set whether the window background should be transparent pub fn transparent(mut self, transparent: bool) -> Self { self.transparent = Some(transparent); self } /// Apply this window configuration to the passed in WindowBuilder pub fn apply_to_builder(&self, builder: &mut WindowBuilder) { if let Some(resizable) = self.resizable { builder.resizable(resizable); } if let Some(show_titlebar) = self.show_titlebar { builder.show_titlebar(show_titlebar); } if let Some(size) = self.size { builder.set_size(size); } else if let WindowSizePolicy::Content = self.size_policy { builder.set_size(Size::new(0., 0.)); } if let Some(position) = self.position { builder.set_position(position); } if let Some(transparent) = self.transparent { builder.set_transparent(transparent); } if let Some(level) = self.level.clone() { builder.set_level(level) } if let Some(always_on_top) = self.always_on_top { builder.set_always_on_top(always_on_top) } if let Some(state) = self.state { builder.set_window_state(state); } if let Some(min_size) = self.min_size { builder.set_min_size(min_size); } } /// Apply this window configuration to the passed in WindowHandle pub fn apply_to_handle(&self, win_handle: &mut WindowHandle) { if let Some(resizable) = self.resizable { win_handle.resizable(resizable); } if let Some(show_titlebar) = self.show_titlebar { win_handle.show_titlebar(show_titlebar); } if let Some(size) = self.size { win_handle.set_size(size); } // Can't apply min size currently as window handle // does not support it. if let Some(position) = self.position { win_handle.set_position(position); } if self.level.is_some() { warn!("Applying a level can only be done on window builders"); } if let Some(state) = self.state { win_handle.set_window_state(state); } } } impl<T: Data> WindowDesc<T> { /// Create a new `WindowDesc`, taking the root [`Widget`] for this window. pub fn new<W>(root: W) -> WindowDesc<T> where W: Widget<T> + 'static, { WindowDesc { pending: PendingWindow::new(root), config: WindowConfig::default(), id: WindowId::next(), } } /// Set the title for this window. This is a [`LabelText`]; it can be either /// a `String`, a [`LocalizedString`], or a closure that computes a string; /// it will be kept up to date as the application's state changes. /// /// If this method isn't called, the default title will be `LocalizedString::new("app-name")`. pub fn title(mut self, title: impl Into<LabelText<T>>) -> Self { self.pending = self.pending.title(title); self } /// Set the menu for this window. /// /// `menu` is a callback for creating the menu. Its first argument is the id of the window that /// will have the menu, or `None` if it's creating the root application menu for an app with no /// menus (which can happen, for example, on macOS). pub fn menu( mut self, menu: impl FnMut(Option<WindowId>, &T, &Env) -> Menu<T> + 'static, ) -> Self { self.pending = self.pending.menu(menu); self } /// Set the window size policy pub fn window_size_policy(mut self, size_policy: WindowSizePolicy) -> Self { #[cfg(windows)] { // On Windows content_insets doesn't work on window with no initial size // so the window size can't be adapted to the content, to fix this a // non null initial size is set here. if size_policy == WindowSizePolicy::Content { self.config.size = Some(Size::new(1., 1.)) } } self.config.size_policy = size_policy; self } /// Set the window's initial drawing area size in [display points]. /// /// You can pass in a tuple `(width, height)` or a [`Size`], /// e.g. to create a window with a drawing area 1000dp wide and 500dp high: /// /// ```ignore /// window.window_size((1000.0, 500.0)); /// ``` /// /// 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 increase the size a tiny bit due to DPI. /// /// [display points]: crate::Scale pub fn window_size(mut self, size: impl Into<Size>) -> Self { self.config.size = Some(size.into()); self } /// 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. /// /// To set the window's initial drawing area size use [`window_size`]. /// /// [`window_size`]: #method.window_size /// [display points]: crate::Scale pub fn with_min_size(mut self, size: impl Into<Size>) -> Self { self.config = self.config.with_min_size(size); self } /// Builder-style method to set whether this window can be resized. pub fn resizable(mut self, resizable: bool) -> Self { self.config = self.config.resizable(resizable); self } /// Builder-style method to set whether this window's titlebar is visible. pub fn show_titlebar(mut self, show_titlebar: bool) -> Self { self.config = self.config.show_titlebar(show_titlebar); self } /// Builder-style method to set whether this window's background should be /// transparent. pub fn transparent(mut self, transparent: bool) -> Self { self.config = self.config.transparent(transparent); self.pending = self.pending.transparent(transparent); self } /// Sets the initial window position in [display points], relative to the origin /// of the [virtual screen]. /// /// [display points]: crate::Scale /// [virtual screen]: crate::Screen pub fn set_position(mut self, position: impl Into<Point>) -> Self { self.config = self.config.set_position(position.into()); self } /// Sets the [`WindowLevel`] of the window /// /// [`WindowLevel`]: WindowLevel pub fn set_level(mut self, level: WindowLevel) -> Self { self.config = self.config.set_level(level); self } /// Sets whether the window is always on top. /// /// An always on top window stays on top, even after clicking off of it. pub fn set_always_on_top(mut self, always_on_top: bool) -> Self { self.config = self.config.set_always_on_top(always_on_top); self } /// Set initial state for the window. pub fn set_window_state(mut self, state: WindowState) -> Self { self.config = self.config.set_window_state(state); self } /// Set the [`WindowConfig`] of window. pub fn with_config(mut self, config: WindowConfig) -> Self { self.config = config; self } /// Attempt to create a platform window from this `WindowDesc`. pub(crate) fn build_native( self, state: &mut AppState<T>, ) -> Result<WindowHandle, PlatformError> { state.build_native_window(self.id, self.pending, self.config) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/sub_window.rs
druid/src/sub_window.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::app::{PendingWindow, WindowConfig}; use crate::commands::{SUB_WINDOW_HOST_TO_PARENT, SUB_WINDOW_PARENT_TO_HOST}; use crate::lens::Unit; use crate::widget::prelude::*; use crate::win_handler::AppState; use crate::{Data, Point, Widget, WidgetExt, WidgetId, WidgetPod, WindowHandle, WindowId}; use druid_shell::Error; use std::any::Any; use tracing::{instrument, warn}; // We can't have any type arguments here, as both ends would need to know them // ahead of time in order to instantiate correctly. // So we erase everything to () /// The required information to create a sub window, including the widget it should host, and the /// config of the window to be created. pub(crate) struct SubWindowDesc { pub(crate) host_id: WidgetId, pub(crate) sub_window_root: Box<dyn Widget<()>>, pub(crate) window_config: WindowConfig, /// The window id that the sub window will have once it is created. Can be used to send commands to. pub window_id: WindowId, } pub(crate) struct SubWindowUpdate { pub(crate) data: Option<Box<dyn Any>>, pub(crate) env: Option<Env>, } impl SubWindowDesc { /// Creates a subwindow requirement that hosts the provided widget within a sub window host. /// It will synchronise data updates with the provided parent_id if "sync" is true, and it will expect to be sent /// SUB_WINDOW_PARENT_TO_HOST commands to update the provided data for the widget. pub fn new<U, W>( parent_id: WidgetId, window_config: WindowConfig, widget: W, data: U, env: Env, ) -> SubWindowDesc where W: Widget<U> + 'static, U: Data, { let host_id = WidgetId::next(); let sub_window_host = SubWindowHost::new(host_id, parent_id, widget, data, env).boxed(); SubWindowDesc { host_id, sub_window_root: sub_window_host, window_config, window_id: WindowId::next(), } } pub(crate) fn make_sub_window<T: Data>( self, app_state: &mut AppState<T>, ) -> Result<WindowHandle, Error> { let sub_window_root = self.sub_window_root; let pending = PendingWindow::new(sub_window_root.lens(Unit)); app_state.build_native_window(self.window_id, pending, self.window_config) } } struct SubWindowHost<U, W: Widget<U>> { id: WidgetId, parent_id: WidgetId, child: WidgetPod<U, W>, data: U, env: Env, } impl<U, W: Widget<U>> SubWindowHost<U, W> { pub(crate) fn new(id: WidgetId, parent_id: WidgetId, widget: W, data: U, env: Env) -> Self { SubWindowHost { id, parent_id, data, env, child: WidgetPod::new(widget), } } } impl<U: Data, W: Widget<U>> Widget<()> for SubWindowHost<U, W> { #[instrument( name = "SubWindowHost", level = "trace", skip(self, ctx, event, _data, _env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut (), _env: &Env) { match event { Event::Command(cmd) if cmd.is(SUB_WINDOW_PARENT_TO_HOST) => { let update = cmd.get_unchecked(SUB_WINDOW_PARENT_TO_HOST); if let Some(data_update) = &update.data { if let Some(dc) = data_update.downcast_ref::<U>() { self.data = dc.clone(); ctx.request_update(); } else { warn!("Received a sub window parent to host command that could not be unwrapped. \ This could mean that the sub window you requested and the enclosing widget pod that you opened it from do not share a common data type. \ Make sure you have a widget pod between your requesting widget and any lenses." ) } } if let Some(env_update) = &update.env { self.env = env_update.clone() } ctx.set_handled(); } _ => { let old = self.data.clone(); // Could avoid this by keeping two bit of data or if we could ask widget pod? self.child.event(ctx, event, &mut self.data, &self.env); if !old.same(&self.data) { ctx.submit_command( SUB_WINDOW_HOST_TO_PARENT .with(Box::new(self.data.clone())) .to(self.parent_id), ) } } } } #[instrument( name = "SubWindowHost", level = "trace", skip(self, ctx, event, _data, _env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &(), _env: &Env) { self.child.lifecycle(ctx, event, &self.data, &self.env) } #[instrument( name = "SubWindowHost", level = "trace", skip(self, ctx, _old_data, _data, _env) )] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &(), _data: &(), _env: &Env) { if ctx.has_requested_update() { self.child.update(ctx, &self.data, &self.env); } } #[instrument( name = "SubWindowHost", level = "trace", skip(self, ctx, bc, _data, _env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &(), _env: &Env) -> Size { let size = self.child.layout(ctx, bc, &self.data, &self.env); self.child.set_origin(ctx, Point::ORIGIN); size } #[instrument(name = "SubWindowHost", level = "trace", skip(self, ctx, _data, _env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &(), _env: &Env) { self.child.paint_raw(ctx, &self.data, &self.env); } fn id(&self) -> Option<WidgetId> { Some(self.id) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/event.rs
druid/src/event.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Events. use std::ops::{Add, Sub}; use druid_shell::{Clipboard, KeyEvent, TimerToken}; use crate::kurbo::{Rect, Size}; use crate::mouse::MouseEvent; use crate::{Command, Notification, Point, Scale, WidgetId}; /// An event, propagated downwards during event flow. /// /// With two exceptions ([`Event::Command`] and [`Event::Notification`], which /// have special considerations outlined in their own docs) each event /// corresponds to some user action or other message received from the platform. /// /// Events are things that happen that can change the state of widgets. /// An important category is events plumbed from the platform windowing /// system, which includes mouse and keyboard events, but also (in the /// future) status changes such as window focus changes. /// /// Events can also be higher level concepts indicating state changes /// within the widget hierarchy, for example when a widget gains or loses /// focus or "hot" (also known as hover) status. /// /// Events are a key part of what is called "event flow", which is /// basically the propagation of an event through the widget hierarchy /// through the [`event`] widget method. A container widget will /// generally pass the event to its children, mediated through the /// [`WidgetPod`] container, which is where most of the event flow logic /// is applied (especially the decision whether or not to propagate). /// /// This enum is expected to grow considerably, as there are many, many /// different kinds of events that are relevant in a GUI. /// /// [`event`]: crate::Widget::event /// [`WidgetPod`]: crate::WidgetPod #[derive(Debug, Clone)] pub enum Event { /// Sent to all widgets in a given window when that window is first instantiated. /// /// This should always be the first `Event` received, although widgets will /// receive [`LifeCycle::WidgetAdded`] first. /// /// Widgets should handle this event if they need to do some addition setup /// when a window is first created. /// /// [`LifeCycle::WidgetAdded`]: enum.LifeCycle.html#variant.WidgetAdded WindowConnected, /// Sent to all widgets in a given window when the system requests to close the window. /// /// If the event is handled (with [`set_handled`]), the window will not be closed. /// All widgets are given an opportunity to handle this event; your widget should not assume /// that the window *will* close just because this event is received; for instance, you should /// avoid destructive side effects such as cleaning up resources. /// /// [`set_handled`]: crate::EventCtx::set_handled WindowCloseRequested, /// Sent to all widgets in a given window when the system is going to close that window. /// /// This event means the window *will* go away; it is safe to dispose of resources and /// do any other cleanup. WindowDisconnected, /// Called when the window's [`Scale`] changes. /// /// This information can be used to switch between different resolution image assets. /// /// [`Scale`]: crate::Scale WindowScale(Scale), /// Called on the root widget when the window size changes. /// /// Discussion: it's not obvious this should be propagated to user /// widgets. It *is* propagated through the RootWidget and handled /// in the WindowPod, but after that it might be considered better /// to just handle it in `layout`. WindowSize(Size), /// Called when a mouse button is pressed. MouseDown(MouseEvent), /// Called when a mouse button is released. MouseUp(MouseEvent), /// Called when the mouse is moved. /// /// The `MouseMove` event is propagated to the active widget, if /// there is one, otherwise to hot widgets (see [`HotChanged`]). /// If a widget loses its hot status due to `MouseMove` then that specific /// `MouseMove` event is also still sent to that widget. However a widget /// can lose its hot status even without a `MouseMove` event, so make /// sure to also handle [`HotChanged`] if you care about the hot status. /// /// The `MouseMove` event is also the primary mechanism for widgets /// to set a cursor, for example to an I-bar inside a text widget. A /// simple tactic is for the widget to unconditionally call /// [`set_cursor`] in the MouseMove handler, as `MouseMove` is only /// propagated to active or hot widgets. /// /// [`HotChanged`]: LifeCycle::HotChanged /// [`set_cursor`]: crate::EventCtx::set_cursor MouseMove(MouseEvent), /// Called when the mouse wheel or trackpad is scrolled. Wheel(MouseEvent), /// Called when a key is pressed. KeyDown(KeyEvent), /// Called when a key is released. /// /// Because of repeat, there may be a number `KeyDown` events before /// a corresponding `KeyUp` is sent. KeyUp(KeyEvent), /// Called when a paste command is received. Paste(Clipboard), /// Called when the trackpad is pinched. /// /// The value is a delta. Zoom(f64), /// Called on a timer event. /// /// Request a timer event through [`EventCtx::request_timer`]. That will /// cause a timer event later. /// /// Note that timer events from other widgets may be delivered as well. Use /// the token returned from the `request_timer` call to filter events more /// precisely. /// /// [`EventCtx::request_timer`]: crate::EventCtx::request_timer Timer(TimerToken), /// Called at the beginning of a new animation frame. /// /// On the first frame when transitioning from idle to animating, `interval` /// will be 0. (This logic is presently per-window but might change to /// per-widget to make it more consistent). Otherwise it is in nanoseconds. /// /// Receiving `AnimFrame` does not inherently mean a `paint` invocation will follow. /// If you want something actually painted you need to explicitly call [`request_paint`] /// or [`request_paint_rect`]. /// /// If you do that, then the `paint` method will be called shortly after this event is finished. /// As a result, you should try to avoid doing anything computationally /// intensive in response to an `AnimFrame` event: it might make Druid miss /// the monitor's refresh, causing lag or jerky animation. /// /// You can request an `AnimFrame` via [`request_anim_frame`]. /// /// [`request_paint`]: crate::EventCtx::request_paint /// [`request_paint_rect`]: crate::EventCtx::request_paint_rect /// [`request_anim_frame`]: crate::EventCtx::request_anim_frame AnimFrame(u64), /// An event containing a [`Command`] to be handled by the widget. /// /// [`Command`]s are messages, optionally with attached data, that can /// may be generated from a number of sources: /// /// - If your application uses menus (either window or context menus) /// then the [`MenuItem`]s in the menu will each correspond to a `Command`. /// When the menu item is selected, that [`Command`] will be delivered to /// the root widget of the appropriate window. /// - If you are doing work in another thread (using an [`ExtEventSink`]) /// then [`Command`]s are the mechanism by which you communicate back to /// the main thread. /// - Widgets and other Druid components can send custom [`Command`]s at /// runtime, via methods such as [`EventCtx::submit_command`]. /// /// [`Widget`]: crate::Widget /// [`EventCtx::submit_command`]: crate::EventCtx::submit_command /// [`ExtEventSink`]: crate::ExtEventSink /// [`MenuItem`]: crate::MenuItem Command(Command), /// A [`Notification`] from one of this widget's descendants. /// /// While handling events, widgets can submit notifications to be /// delivered to their ancestors immediately after they return. /// /// If you handle a [`Notification`], you should call [`EventCtx::set_handled`] /// to stop the notification from being delivered to further ancestors. /// /// ## Special considerations /// /// Notifications are slightly different from other events; they originate /// inside Druid, and they are delivered as part of the handling of another /// event. In this sense, they can sort of be thought of as an augmentation /// of an event; they are a way for multiple widgets to coordinate the /// handling of an event. /// /// [`EventCtx::set_handled`]: crate::EventCtx::set_handled Notification(Notification), /// Sent to a widget when the platform may have mutated shared IME state. /// /// This is sent to a widget that has an attached IME session anytime the /// platform has released a mutable lock on shared state. /// /// This does not *mean* that any state has changed, but the widget /// should check the shared state, perform invalidation, and update `Data` /// as necessary. ImeStateChange, /// Internal Druid event. /// /// This should always be passed down to descendant [`WidgetPod`]s. /// /// [`WidgetPod`]: crate::WidgetPod Internal(InternalEvent), } /// Internal events used by Druid inside [`WidgetPod`]. /// /// These events are translated into regular [`Event`]s /// and should not be used directly. /// /// [`WidgetPod`]: crate::WidgetPod #[derive(Debug, Clone)] pub enum InternalEvent { /// Sent in some cases when the mouse has left the window. /// /// This is used in cases when the platform no longer sends mouse events, /// but we know that we've stopped receiving the mouse events. MouseLeave, /// A command still in the process of being dispatched. TargetedCommand(Command), /// Used for routing timer events. RouteTimer(TimerToken, WidgetId), /// Route an IME change event. RouteImeStateChange(WidgetId), } /// Application life cycle events. /// /// Unlike [`Event`]s, [`LifeCycle`] events are generated by Druid, and /// may occur at different times during a given pass of the event loop. The /// [`LifeCycle::WidgetAdded`] event, for instance, may occur when the app /// first launches (during the handling of [`Event::WindowConnected`]) or it /// may occur during [`update`] cycle, if some widget has been added there. /// /// Similarly the [`LifeCycle::Size`] method occurs during [`layout`], and /// [`LifeCycle::HotChanged`] can occur both during [`event`] (if the mouse /// moves over a widget) or in response to [`LifeCycle::ViewContextChanged`], /// if a widget is moved away from under the mouse. /// /// [`event`]: crate::Widget::event /// [`update`]: crate::Widget::update /// [`layout`]: crate::Widget::layout #[derive(Debug, Clone)] pub enum LifeCycle { /// Sent to a `Widget` when it is added to the widget tree. This should be /// the first message that each widget receives. /// /// Widgets should handle this event in order to do any initial setup. /// /// In addition to setup, this event is also used by the framework to /// track certain types of important widget state. /// /// ## Registering children /// /// Container widgets (widgets which use [`WidgetPod`] to manage children) /// must ensure that this event is forwarded to those children. The [`WidgetPod`] /// itself will handle registering those children with the system; this is /// required for things like correct routing of events. /// /// [`WidgetPod`]: crate::WidgetPod WidgetAdded, /// Called when the [`Size`] of the widget changes. /// /// This will be called after [`Widget::layout`], if the [`Size`] returned /// by the widget differs from its previous size. /// /// [`Size`]: crate::Size /// [`Widget::layout`]: crate::Widget::layout Size(Size), /// Called when the Disabled state of the widgets is changed. /// /// To check if a widget is disabled, see [`is_disabled`]. /// /// To change a widget's disabled state, see [`set_disabled`]. /// /// [`is_disabled`]: crate::EventCtx::is_disabled /// [`set_disabled`]: crate::EventCtx::set_disabled DisabledChanged(bool), /// Called when the "hot" status changes. /// /// This will always be called _before_ the event that triggered it; that is, /// when the mouse moves over a widget, that widget will receive /// [`LifeCycle::HotChanged`] before it receives [`Event::MouseMove`]. /// /// See [`is_hot`](crate::EventCtx::is_hot) for /// discussion about the hot status. HotChanged(bool), /// This is called when the widget-tree changes and Druid wants to rebuild the /// Focus-chain. /// /// It is the only place from which [`register_for_focus`] should be called. /// By doing so the widget can get focused by other widgets using [`focus_next`] or [`focus_prev`]. /// /// [`register_for_focus`]: crate::LifeCycleCtx::register_for_focus /// [`focus_next`]: crate::EventCtx::focus_next /// [`focus_prev`]: crate::EventCtx::focus_prev BuildFocusChain, /// Called when the focus status changes. /// /// This will always be called immediately after a new widget gains focus. /// The newly focused widget will receive this with `true` and the widget /// that lost focus will receive this with `false`. /// /// See [`EventCtx::is_focused`] for more information about focus. /// /// [`EventCtx::is_focused`]: crate::EventCtx::is_focused FocusChanged(bool), /// Called when the [`ViewContext`] of this widget changed. /// /// See [`view_context_changed`] on how and when to request this event. /// /// [`view_context_changed`]: crate::EventCtx::view_context_changed ViewContextChanged(ViewContext), /// Internal Druid lifecycle event. /// /// This should always be passed down to descendant [`WidgetPod`]s. /// /// [`WidgetPod`]: crate::WidgetPod Internal(InternalLifeCycle), } /// Internal lifecycle events used by Druid inside [`WidgetPod`]. /// /// These events are translated into regular [`LifeCycle`] events /// and should not be used directly. /// /// [`WidgetPod`]: crate::WidgetPod #[derive(Debug, Clone)] pub enum InternalLifeCycle { /// Used to route the `WidgetAdded` event to the required widgets. RouteWidgetAdded, /// Used to route the `FocusChanged` event. RouteFocusChanged { /// the widget that is losing focus, if any old: Option<WidgetId>, /// the widget that is gaining focus, if any new: Option<WidgetId>, }, /// Used to route the `DisabledChanged` event to the required widgets. RouteDisabledChanged, /// Used to route the `ViewContextChanged` event to the required widgets. RouteViewContextChanged(ViewContext), /// For testing: request the `WidgetState` of a specific widget. /// /// During testing, you may wish to verify that the state of a widget /// somewhere in the tree is as expected. In that case you can dispatch /// this event, specifying the widget in question, and that widget will /// set its state in the provided `Cell`, if it exists. DebugRequestState { /// the widget whose state is requested widget: WidgetId, /// a cell used to store the a widget's state state_cell: StateCell, }, /// For testing: request the `DebugState` of a specific widget. /// /// This is useful if you need to get a best-effort description of the /// state of this widget and its children. You can dispatch this event, /// specifying the widget in question, and that widget will /// set its state in the provided `Cell`, if it exists. DebugRequestDebugState { /// the widget whose state is requested widget: WidgetId, /// a cell used to store the a widget's state state_cell: DebugStateCell, }, /// For testing: apply the given function on every widget. DebugInspectState(StateCheckFn), } /// Information about the widget's surroundings. /// /// The global origin is also saved in the widget state. /// /// When the `ViewContext` of a widget changes it receives a `ViewContextChanged` event. #[derive(Debug, Copy, Clone)] pub struct ViewContext { /// The origin of this widget relative to the window. /// /// This is written from the perspective of the Widget and not the Pod. /// For the Pod this is its parent's window origin. pub window_origin: Point, /// The last position the cursor was at, relative to the widget. pub last_mouse_position: Option<Point>, /// The visible area, this widget is contained in, relative to the widget. /// /// The area may be larger than the widget's `paint_rect`. pub clip: Rect, } impl Event { /// Whether this event should be sent to widgets which are currently not visible and not /// accessible. /// /// For example: the hidden tabs in a tabs widget are `hidden` whereas the non-visible /// widgets in a scroll are not, since you can bring them into view by scrolling. /// /// This distinction between scroll and tabs is due to one of the main purposes of /// this method: determining which widgets are allowed to receive focus. As a rule /// of thumb a widget counts as `hidden` if it makes no sense for it to receive focus /// when the user presses the 'tab' key. /// /// If a widget changes which children are hidden it must call [`children_changed`]. /// /// See also [`LifeCycle::should_propagate_to_hidden`]. /// /// [`children_changed`]: crate::EventCtx::children_changed /// [`LifeCycle::should_propagate_to_hidden`]: LifeCycle::should_propagate_to_hidden pub fn should_propagate_to_hidden(&self) -> bool { match self { Event::WindowConnected | Event::WindowCloseRequested | Event::WindowDisconnected | Event::WindowScale(_) | Event::WindowSize(_) | Event::Timer(_) | Event::AnimFrame(_) | Event::Command(_) | Event::Notification(_) | Event::Internal(_) => true, Event::MouseDown(_) | Event::MouseUp(_) | Event::MouseMove(_) | Event::Wheel(_) | Event::KeyDown(_) | Event::KeyUp(_) | Event::Paste(_) | Event::ImeStateChange | Event::Zoom(_) => false, } } /// Returns true if the event involves a cursor. /// /// These events interact with the hot state and pub fn is_pointer_event(&self) -> bool { matches!( self, Event::MouseDown(_) | Event::MouseUp(_) | Event::MouseMove(_) | Event::Wheel(_) ) } } impl LifeCycle { /// Whether this event should be sent to widgets which are currently not visible and not /// accessible. /// /// If a widget changes which children are `hidden` it must call [`children_changed`]. /// For a more detailed explanation of the `hidden` state, see [`Event::should_propagate_to_hidden`]. /// /// [`children_changed`]: crate::EventCtx::children_changed /// [`Event::should_propagate_to_hidden`]: Event::should_propagate_to_hidden pub fn should_propagate_to_hidden(&self) -> bool { match self { LifeCycle::Internal(internal) => internal.should_propagate_to_hidden(), LifeCycle::WidgetAdded | LifeCycle::DisabledChanged(_) => true, LifeCycle::Size(_) | LifeCycle::HotChanged(_) | LifeCycle::FocusChanged(_) | LifeCycle::BuildFocusChain | LifeCycle::ViewContextChanged { .. } => false, } } /// Returns an event for a widget which maybe is overlapped by another widget. /// /// When `ignore` is set to `true` the widget will set its hot state to `false` even if the cursor /// is inside its bounds. pub fn ignore_hot(&self, ignore: bool) -> Self { if ignore { match self { LifeCycle::ViewContextChanged(view_ctx) => { let mut view_ctx = view_ctx.to_owned(); view_ctx.last_mouse_position = None; LifeCycle::ViewContextChanged(view_ctx) } LifeCycle::Internal(InternalLifeCycle::RouteViewContextChanged(view_ctx)) => { let mut view_ctx = view_ctx.to_owned(); view_ctx.last_mouse_position = None; LifeCycle::Internal(InternalLifeCycle::RouteViewContextChanged(view_ctx)) } _ => self.to_owned(), } } else { self.to_owned() } } } impl InternalLifeCycle { /// Whether this event should be sent to widgets which are currently not visible and not /// accessible. /// /// If a widget changes which children are `hidden` it must call [`children_changed`]. /// For a more detailed explanation of the `hidden` state, see [`Event::should_propagate_to_hidden`]. /// /// [`children_changed`]: crate::EventCtx::children_changed /// [`Event::should_propagate_to_hidden`]: Event::should_propagate_to_hidden pub fn should_propagate_to_hidden(&self) -> bool { match self { InternalLifeCycle::RouteWidgetAdded | InternalLifeCycle::RouteFocusChanged { .. } | InternalLifeCycle::RouteDisabledChanged => true, InternalLifeCycle::RouteViewContextChanged { .. } => false, InternalLifeCycle::DebugRequestState { .. } | InternalLifeCycle::DebugRequestDebugState { .. } | InternalLifeCycle::DebugInspectState(_) => true, } } } impl ViewContext { /// Transforms the `ViewContext` into the coordinate space of its child. pub(crate) fn for_child_widget(&self, child_origin: Point) -> Self { let child_origin = child_origin.to_vec2(); ViewContext { window_origin: self.window_origin.add(child_origin), last_mouse_position: self.last_mouse_position.map(|pos| pos.sub(child_origin)), clip: self.clip.sub(child_origin), } } } pub(crate) use state_cell::{DebugStateCell, StateCell, StateCheckFn}; mod state_cell { use crate::core::WidgetState; use crate::debug_state::DebugState; use crate::WidgetId; use std::{cell::RefCell, rc::Rc}; /// An interior-mutable struct for fetching WidgetState. #[derive(Clone, Default)] pub struct StateCell(Rc<RefCell<Option<WidgetState>>>); /// An interior-mutable struct for fetching DebugState. #[derive(Clone, Default)] pub struct DebugStateCell(Rc<RefCell<Option<DebugState>>>); #[derive(Clone)] pub struct StateCheckFn(Rc<dyn Fn(&WidgetState)>); /// a hacky way of printing the widget id if we panic struct WidgetDrop(bool, WidgetId); impl Drop for WidgetDrop { fn drop(&mut self) { if self.0 { eprintln!("panic in {:?}", self.1); } } } impl StateCell { /// Set the state. This will panic if it is called twice. pub(crate) fn set(&self, state: WidgetState) { assert!( self.0.borrow_mut().replace(state).is_none(), "StateCell already set" ) } #[allow(dead_code)] pub(crate) fn take(&self) -> Option<WidgetState> { self.0.borrow_mut().take() } } impl DebugStateCell { /// Set the state. This will panic if it is called twice. pub(crate) fn set(&self, state: DebugState) { assert!( self.0.borrow_mut().replace(state).is_none(), "DebugStateCell already set" ) } #[allow(dead_code)] pub(crate) fn take(&self) -> Option<DebugState> { self.0.borrow_mut().take() } } impl StateCheckFn { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn new(f: impl Fn(&WidgetState) + 'static) -> Self { StateCheckFn(Rc::new(f)) } pub(crate) fn call(&self, state: &WidgetState) { let mut panic_reporter = WidgetDrop(true, state.id); (self.0)(state); panic_reporter.0 = false; } } // TODO - Use fmt.debug_tuple? impl std::fmt::Debug for StateCell { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let inner = if self.0.borrow().is_some() { "Some" } else { "None" }; write!(f, "StateCell({inner})") } } impl std::fmt::Debug for DebugStateCell { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let inner = if self.0.borrow().is_some() { "Some" } else { "None" }; write!(f, "DebugStateCell({inner})") } } impl std::fmt::Debug for StateCheckFn { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "StateCheckFn") } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/app_delegate.rs
druid/src/app_delegate.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Customizing application-level behaviour. use std::any::{Any, TypeId}; use crate::{ commands, core::CommandQueue, ext_event::ExtEventHost, Command, Data, Env, Event, ExtEventSink, Handled, SingleUse, Target, WindowDesc, WindowHandle, WindowId, }; /// A context passed in to [`AppDelegate`] functions. pub struct DelegateCtx<'a> { pub(crate) command_queue: &'a mut CommandQueue, pub(crate) ext_event_host: &'a ExtEventHost, pub(crate) app_data_type: TypeId, } impl<'a> DelegateCtx<'a> { /// Submit a [`Command`] to be run after this event is handled. /// /// Commands are run in the order they are submitted; all commands /// submitted during the handling of an event are executed before /// the [`update`] method is called. /// /// [`Target::Auto`] commands will be sent to every window (`Target::Global`). /// /// [`update`]: crate::Widget::update pub fn submit_command(&mut self, command: impl Into<Command>) { self.command_queue .push_back(command.into().default_to(Target::Global)) } /// Returns an [`ExtEventSink`] that can be moved between threads, /// and can be used to submit commands back to the application. pub fn get_external_handle(&self) -> ExtEventSink { self.ext_event_host.make_sink() } /// Create a new window. /// `T` must be the application's root `Data` type (the type provided to [`AppLauncher::launch`]). /// /// [`AppLauncher::launch`]: crate::AppLauncher::launch pub fn new_window<T: Any>(&mut self, desc: WindowDesc<T>) { if self.app_data_type == TypeId::of::<T>() { self.submit_command( commands::NEW_WINDOW .with(SingleUse::new(Box::new(desc))) .to(Target::Global), ); } else { debug_panic!("DelegateCtx::new_window<T> - T must match the application data type."); } } } /// A type that provides hooks for handling and modifying top-level events. /// /// The `AppDelegate` is a trait that is allowed to handle and modify /// events before they are passed down the widget tree. /// /// It is a natural place for things like window and menu management. /// /// You customize the `AppDelegate` by implementing its methods on your own type. #[allow(unused)] pub trait AppDelegate<T: Data> { /// The `AppDelegate`'s event handler. This function receives all /// non-command events, before they are passed down the tree. /// /// The return value of this function will be passed down the tree. This can /// be the event that was passed in, a different event, or no event. In all cases, /// the [`update`] method will be called as usual. /// /// [`update`]: crate::Widget::update fn event( &mut self, ctx: &mut DelegateCtx, window_id: WindowId, event: Event, data: &mut T, env: &Env, ) -> Option<Event> { Some(event) } /// The `AppDelegate`s [`Command`] handler. /// /// This function is called with each ([`Target`], [`Command`]) pair before /// they are sent down the tree. /// /// If your implementation returns `Handled::No`, the command will be sent down /// the widget tree. Otherwise it will not. /// /// To do anything fancier than this, you can submit arbitrary commands /// via [`DelegateCtx::submit_command`]. /// /// [`DelegateCtx::submit_command`]: DelegateCtx::submit_command fn command( &mut self, ctx: &mut DelegateCtx, target: Target, cmd: &Command, data: &mut T, env: &Env, ) -> Handled { Handled::No } /// The handler for window creation events. /// This function is called after a window has been added, /// allowing you to customize the window creation behavior of your app. fn window_added( &mut self, id: WindowId, handle: WindowHandle, data: &mut T, env: &Env, ctx: &mut DelegateCtx, ) { } /// The handler for window deletion events. /// This function is called after a window has been removed. fn window_removed(&mut self, id: WindowId, data: &mut T, env: &Env, ctx: &mut DelegateCtx) {} }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/lib.rs
druid/src/lib.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Simple data-oriented GUI. //! //! Druid lets you build simple interactive graphical applications that //! can be deployed on Windows, macOS, Linux, OpenBSD, FreeBSD and the web. //! //! Druid is built on top of [`druid-shell`], which implements all of the //! lower-level, platform-specific code, providing a common abstraction //! for things like key and mouse events, creating windows, and launching //! an application. Below [`druid-shell`] is [`piet`], which is a cross-platform //! 2D graphics library, providing a simple and familiar drawing API that can be //! implemented for various platforms. //! //! Druid is a data-driven, declarative framework. You describe your application //! model in terms of the [`Data`] trait, and then you build up a tree of //! [`widget`] s that can display and modify your data. //! //! Your widgets handle [`Event`]s, such as mouse movement, and can modify the data; //! these changes are then delivered to relevant widgets, which can update //! their state and redraw. //! //! As your application grows, you can use [`Lens`]es to expose only certain //! subsets of your data model to certain subsets of your widget tree. //! //! For more information you should read the [Druid book]. //! //! # Examples //! //! For many more examples, see [`druid/examples`]. //! //! ```no_run //! use druid::widget::{Align, Flex, Label, TextBox}; //! use druid::{AppLauncher, Data, Env, Lens, LocalizedString, Widget, WindowDesc, WidgetExt}; //! //! const VERTICAL_WIDGET_SPACING: f64 = 20.0; //! const TEXT_BOX_WIDTH: f64 = 200.0; //! const WINDOW_TITLE: LocalizedString<HelloState> = LocalizedString::new("Hello World!"); //! //! #[derive(Clone, Data, Lens)] //! struct HelloState { //! name: String, //! } //! //! fn main() { //! // describe the main window //! let main_window = WindowDesc::new(build_root_widget()) //! .title(WINDOW_TITLE) //! .window_size((400.0, 400.0)); //! //! // create the initial app state //! let initial_state = HelloState { //! name: "World".into(), //! }; //! //! // start the application //! AppLauncher::with_window(main_window) //! .launch(initial_state) //! .expect("Failed to launch application"); //! } //! //! fn build_root_widget() -> impl Widget<HelloState> { //! // a label that will determine its text based on the current app data. //! let label = Label::new(|data: &HelloState, _env: &Env| format!("Hello {}!", data.name)); //! // a textbox that modifies `name`. //! let textbox = TextBox::new() //! .with_placeholder("Who are we greeting?") //! .fix_width(TEXT_BOX_WIDTH) //! .lens(HelloState::name); //! //! // arrange the two widgets vertically, with some padding //! let layout = Flex::column() //! .with_child(label) //! .with_spacer(VERTICAL_WIDGET_SPACING) //! .with_child(textbox); //! //! // center the two widgets in the available space //! Align::centered(layout) //! } //! ``` //! //! # Optional Features //! //! Utility features: //! //! * `im` - Efficient immutable data structures using the [`im` crate], //! which is made available via the [`im` module]. //! * `svg` - Scalable Vector Graphics for icons and other scalable images using the [`usvg` crate]. //! * `image` - Bitmap image support using the [`image` crate]. //! * `x11` - Work-in-progress X11 backend instead of GTK. //! * `wayland` - Work-in-progress Wayland backend, very experimental. //! * `serde` - Serde support for some internal types (most Kurbo primitives). //! //! Image format features: //! //! - png //! - jpeg //! - gif //! - bmp //! - ico //! - tiff //! - webp //! - pnm //! - dds //! - tga //! - hdr //! //! You can enable all these formats with `image-all`. //! //! Features can be added with `cargo`. For example, in your `Cargo.toml`: //! ```no_compile //! [dependencies.druid] //! version = "0.8.3" //! features = ["im", "svg", "image"] //! ``` //! //! # Note for Windows apps //! //! By default, Windows will open a console with your application's window. If you don't want //! the console to be shown, use `#![windows_subsystem = "windows"]` at the beginning of your //! crate. //! //! [`druid-shell`]: druid_shell //! [`druid/examples`]: https://github.com/linebender/druid/tree/v0.8.3/druid/examples //! [Druid book]: https://linebender.org/druid/ //! [`im` crate]: https://crates.io/crates/im //! [`im` module]: im/index.html //! [`usvg` crate]: https://crates.io/crates/usvg //! [`image` crate]: https://crates.io/crates/image #![deny( rustdoc::broken_intra_doc_links, unsafe_code, clippy::trivially_copy_pass_by_ref )] #![warn(missing_docs)] #![allow(clippy::new_ret_no_self, clippy::needless_doctest_main)] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://raw.githubusercontent.com/linebender/druid/screenshots/images/doc_logo.png" )] // Allows to use macros from druid_derive in this crate extern crate self as druid; pub use druid_derive::Lens; use druid_shell as shell; #[doc(inline)] pub use druid_shell::{kurbo, piet}; // the im crate provides immutable data structures that play well with druid #[cfg(feature = "im")] #[doc(inline)] pub use im; #[macro_use] pub mod lens; #[macro_use] mod util; mod app; mod app_delegate; mod bloom; mod box_constraints; mod command; mod contexts; mod core; mod data; pub mod debug_state; mod dialog; pub mod env; mod event; mod ext_event; mod localization; pub mod menu; mod mouse; pub mod scroll_component; mod sub_window; #[cfg(not(target_arch = "wasm32"))] pub mod tests; pub mod text; pub mod theme; pub mod widget; mod win_handler; mod window; // Types from kurbo & piet that are required by public API. pub use kurbo::{Affine, Insets, Point, Rect, RoundedRectRadii, Size, Vec2}; pub use piet::{Color, ImageBuf, LinearGradient, RadialGradient, RenderContext, UnitPoint}; // these are the types from shell that we expose; others we only use internally. #[cfg(feature = "image")] pub use shell::image; pub use shell::keyboard_types; pub use shell::{ Application, Clipboard, ClipboardFormat, Code, Cursor, CursorDesc, Error as PlatformError, FileInfo, FileSpec, FormatId, HotKey, KbKey, KeyEvent, Location, Modifiers, Monitor, MouseButton, MouseButtons, RawMods, Region, Scalable, Scale, ScaledArea, Screen, SysMods, TimerToken, WindowHandle, WindowLevel, WindowState, }; #[cfg(feature = "raw-win-handle")] pub use crate::shell::raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; pub use crate::core::{WidgetPod, WidgetState}; pub use app::{AppLauncher, WindowConfig, WindowDesc, WindowSizePolicy}; pub use app_delegate::{AppDelegate, DelegateCtx}; pub use box_constraints::BoxConstraints; pub use command::{sys as commands, Command, Notification, Selector, SingleUse, Target}; pub use contexts::{EventCtx, LayoutCtx, LifeCycleCtx, PaintCtx, UpdateCtx}; pub use data::*; // Wildcard because rustdoc has trouble inlining docs of two things called Data pub use dialog::FileDialogOptions; #[doc(inline)] pub use env::{Env, Key, KeyOrValue, Value, ValueType, ValueTypeError}; pub use event::{Event, InternalEvent, InternalLifeCycle, LifeCycle, ViewContext}; pub use ext_event::{ExtEventError, ExtEventSink}; pub use lens::{Lens, LensExt}; pub use localization::LocalizedString; #[doc(inline)] pub use menu::{sys as platform_menus, Menu, MenuItem}; pub use mouse::MouseEvent; pub use util::Handled; pub use widget::{Widget, WidgetExt, WidgetId}; pub use win_handler::DruidHandler; pub use window::{Window, WindowId}; #[cfg(not(target_arch = "wasm32"))] pub(crate) use event::{DebugStateCell, StateCell, StateCheckFn}; #[doc(hidden)] #[deprecated(since = "0.8.0", note = "import from druid::text module instead")] pub use piet::{FontFamily, FontStyle, FontWeight, TextAlignment}; #[doc(hidden)] #[deprecated(since = "0.8.0", note = "import from druid::text module instead")] pub use text::{ArcStr, FontDescriptor, TextLayout}; /// The meaning (mapped value) of a keypress. /// /// Note that in previous versions, the `KeyCode` field referred to the /// physical position of the key, rather than the mapped value. In most /// cases, applications should dispatch based on the value instead. This /// alias is provided to make that transition easy, but in any case make /// an explicit choice whether to use meaning or physical location and /// use the appropriate type. #[doc(hidden)] #[deprecated(since = "0.7.0", note = "Use KbKey instead")] pub type KeyCode = KbKey; #[doc(hidden)] #[deprecated(since = "0.7.0", note = "Use Modifiers instead")] /// See [`Modifiers`](struct.Modifiers.html). pub type KeyModifiers = Modifiers;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/command.rs
druid/src/command.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Custom commands. use std::any::{self, Any}; use std::{ marker::PhantomData, sync::{Arc, Mutex}, }; use crate::{WidgetId, WindowId}; /// The identity of a [`Selector`]. /// /// [`Selector`]: struct.Selector.html pub(crate) type SelectorSymbol = &'static str; /// An identifier for a particular command. /// /// This should be a unique string identifier. /// Having multiple selectors with the same identifier but different payload /// types is not allowed and can cause [`Command::get`] and [`get_unchecked`] to panic. /// /// The type parameter `T` specifies the command's payload type. /// See [`Command`] for more information. /// /// Certain `Selector`s are defined by Druid, and have special meaning /// to the framework; these are listed in the [`druid::commands`] module. /// /// [`Command`]: struct.Command.html /// [`Command::get`]: struct.Command.html#method.get /// [`get_unchecked`]: struct.Command.html#method.get_unchecked #[derive(Debug, PartialEq, Eq)] pub struct Selector<T = ()>(SelectorSymbol, PhantomData<T>); /// An arbitrary command. /// /// A `Command` consists of a [`Selector`], that indicates what the command is /// and what type of payload it carries, as well as the actual payload. /// /// If the payload can't or shouldn't be cloned, /// wrapping it with [`SingleUse`] allows you to `take` the payload. /// The [`SingleUse`] docs give an example on how to do this. /// /// Generic payloads can be achieved with `Selector<Box<dyn Any>>`. /// In this case it could make sense to use utility functions to construct /// such commands in order to maintain as much static typing as possible. /// The [`EventCtx::new_window`] method is an example of this. /// /// # Examples /// ``` /// use druid::{Command, Selector, Target}; /// /// let selector = Selector::new("process_rows"); /// let rows = vec![1, 3, 10, 12]; /// let command = selector.with(rows); /// /// assert_eq!(command.get(selector), Some(&vec![1, 3, 10, 12])); /// ``` /// /// [`EventCtx::new_window`]: crate::EventCtx::new_window #[derive(Debug, Clone)] pub struct Command { symbol: SelectorSymbol, payload: Arc<dyn Any>, target: Target, } /// A message passed up the tree from a [`Widget`] to its ancestors. /// /// In the course of handling an event, a [`Widget`] may change some internal /// state that is of interest to one of its ancestors. In this case, the widget /// may submit a [`Notification`]. /// /// In practice, a [`Notification`] is very similar to a [`Command`]; the /// main distinction relates to delivery. [`Command`]s are delivered from the /// root of the tree down towards the target, and this delivery occurs after /// the originating event call has returned. [`Notification`]s are delivered *up* /// the tree, and this occurs *during* event handling; immediately after the /// child widget's [`event`] method returns, the notification will be delivered /// to the child's parent, and then the parent's parent, until the notification /// is handled. /// /// [`Widget`]: crate::Widget /// [`event`]: crate::Widget::event #[derive(Clone)] pub struct Notification { symbol: SelectorSymbol, payload: Arc<dyn Any>, source: WidgetId, route: WidgetId, warn_if_unused: bool, } /// A wrapper type for [`Command`] payloads that should only be used once. /// /// This is useful if you have some resource that cannot be /// cloned, and you wish to send it to another widget. /// /// # Examples /// ``` /// use druid::{Command, Selector, SingleUse, Target}; /// /// struct CantClone(u8); /// /// let selector = Selector::new("use-once"); /// let num = CantClone(42); /// let command = selector.with(SingleUse::new(num)); /// /// let payload: &SingleUse<CantClone> = command.get_unchecked(selector); /// if let Some(num) = payload.take() { /// // now you own the data /// assert_eq!(num.0, 42); /// } /// /// // subsequent calls will return `None` /// assert!(payload.take().is_none()); /// ``` pub struct SingleUse<T>(Mutex<Option<T>>); /// The target of a [`Command`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Target { /// The target is the top-level application. /// /// The `Command` will be delivered to all open windows, and all widgets /// in each window. Delivery will stop if the event is [`handled`]. /// /// [`handled`]: crate::EventCtx::set_handled Global, /// The target is a specific window. /// /// The `Command` will be delivered to all widgets in that window. /// Delivery will stop if the event is [`handled`]. /// /// [`handled`]: crate::EventCtx::set_handled Window(WindowId), /// The target is a specific widget. Widget(WidgetId), /// The target will be determined automatically. /// /// How this behaves depends on the context used to submit the command. /// If the command is submitted within a `Widget` method, then it will be sent to the host /// window for that widget. If it is from outside the application, via [`ExtEventSink`], /// or from the root [`AppDelegate`] then it will be sent to [`Target::Global`] . /// /// [`ExtEventSink`]: crate::ExtEventSink /// [`AppDelegate`]: crate::AppDelegate Auto, } /// Commands with special meaning, defined by Druid. /// /// See [`Command`] for more info. pub mod sys { use std::any::Any; use super::Selector; use crate::{ sub_window::{SubWindowDesc, SubWindowUpdate}, FileDialogOptions, FileInfo, Rect, SingleUse, WidgetId, WindowConfig, }; /// Quit the running application. This command is handled by the Druid library. pub const QUIT_APP: Selector = Selector::new("druid-builtin.quit-app"); /// Hide the application. (mac only) #[cfg_attr( not(target_os = "macos"), deprecated = "HIDE_APPLICATION is only supported on macOS" )] pub const HIDE_APPLICATION: Selector = Selector::new("druid-builtin.menu-hide-application"); /// Hide all other applications. (mac only) #[cfg_attr( not(target_os = "macos"), deprecated = "HIDE_OTHERS is only supported on macOS" )] pub const HIDE_OTHERS: Selector = Selector::new("druid-builtin.menu-hide-others"); /// The selector for a command to create a new window. pub(crate) const NEW_WINDOW: Selector<SingleUse<Box<dyn Any>>> = Selector::new("druid-builtin.new-window"); /// The selector for a command to close a window. /// /// The command must target a specific window. /// When calling `submit_command` on a `Widget`s context, passing `None` as target /// will automatically target the window containing the widget. pub const CLOSE_WINDOW: Selector = Selector::new("druid-builtin.close-window"); /// Close all windows. pub const CLOSE_ALL_WINDOWS: Selector = Selector::new("druid-builtin.close-all-windows"); /// The selector for a command to bring a window to the front, and give it focus. /// /// The command must target a specific window. /// When calling `submit_command` on a `Widget`s context, passing `None` as target /// will automatically target the window containing the widget. pub const SHOW_WINDOW: Selector = Selector::new("druid-builtin.show-window"); /// The selector for a command to hide a specific window /// /// The command must target a specific window. /// When calling `submit_command` on a `Widget`s context, passing `None` as target /// will automatically target the window containing the widget. pub const HIDE_WINDOW: Selector = Selector::new("druid-builtin.hide-window"); /// Apply the configuration payload to an existing window. The target should be a WindowId. pub const CONFIGURE_WINDOW: Selector<WindowConfig> = Selector::new("druid-builtin.configure-window"); /// Display a context (right-click) menu. The payload must be the [`ContextMenu`] /// object to be displayed. /// /// [`ContextMenu`]: crate::menu::ContextMenu pub(crate) const SHOW_CONTEXT_MENU: Selector<SingleUse<Box<dyn Any>>> = Selector::new("druid-builtin.show-context-menu"); /// This is sent to the window handler to create a new sub window. pub(crate) const NEW_SUB_WINDOW: Selector<SingleUse<SubWindowDesc>> = Selector::new("druid-builtin.new-sub-window"); /// This is sent from a WidgetPod to any attached SubWindowHosts when a data update occurs pub(crate) const SUB_WINDOW_PARENT_TO_HOST: Selector<SubWindowUpdate> = Selector::new("druid-builtin.parent_to_host"); /// This is sent from a SubWindowHost to its parent WidgetPod after it has processed events, /// if that processing changed the data value. pub(crate) const SUB_WINDOW_HOST_TO_PARENT: Selector<Box<dyn Any>> = Selector::new("druid-builtin.host_to_parent"); /// Show the application preferences. pub const SHOW_PREFERENCES: Selector = Selector::new("druid-builtin.menu-show-preferences"); /// Show the application's "about" window. pub const SHOW_ABOUT: Selector = Selector::new("druid-builtin.menu-show-about"); /// Show all applications. pub const SHOW_ALL: Selector = Selector::new("druid-builtin.menu-show-all"); /// Show the new file dialog. pub const NEW_FILE: Selector = Selector::new("druid-builtin.menu-file-new"); /// When submitted by the application, a file picker dialog will be shown to the user, /// and an [`OPEN_FILE`] command will be sent if a path is chosen. /// /// [`OPEN_FILE`]: constant.OPEN_FILE.html pub const SHOW_OPEN_PANEL: Selector<FileDialogOptions> = Selector::new("druid-builtin.menu-file-open"); /// Sent when the user cancels an open file panel. pub const OPEN_PANEL_CANCELLED: Selector = Selector::new("druid-builtin.open-panel-cancelled"); /// Open a path, must be handled by the application. /// /// [`FileInfo`]: ../struct.FileInfo.html pub const OPEN_FILE: Selector<FileInfo> = Selector::new("druid-builtin.open-file-path"); /// Open a set of paths, must be handled by the application. /// /// [`FileInfo`]: ../struct.FileInfo.html pub const OPEN_FILES: Selector<Vec<FileInfo>> = Selector::new("druid-builtin.open-files-path"); /// When submitted by the application, the system will show the 'save as' panel, /// and if a path is selected the system will issue a [`SAVE_FILE`] command /// with the selected path as the payload. /// /// [`SAVE_FILE`]: constant.SAVE_FILE.html pub const SHOW_SAVE_PANEL: Selector<FileDialogOptions> = Selector::new("druid-builtin.menu-file-save-as"); /// Sent when the user cancels a save file panel. pub const SAVE_PANEL_CANCELLED: Selector = Selector::new("druid-builtin.save-panel-cancelled"); /// Save the current path. /// /// The application should save its data, to a path that should be determined by the /// application. Usually, this will be the most recent path provided by a [`SAVE_FILE_AS`] /// or [`OPEN_FILE`] command. pub const SAVE_FILE: Selector<()> = Selector::new("druid-builtin.save-file"); /// Save to a given location. /// /// This command is emitted by druid whenever a save file dialog successfully completes. The /// application should save its data to the path proved, and should store the path in order to /// handle [`SAVE_FILE`] commands in the future. /// /// The path might be a file or a directory, so always check whether it matches your /// expectations. pub const SAVE_FILE_AS: Selector<FileInfo> = Selector::new("druid-builtin.save-file-as"); /// Show the print-setup window. pub const PRINT_SETUP: Selector = Selector::new("druid-builtin.menu-file-print-setup"); /// Show the print dialog. pub const PRINT: Selector = Selector::new("druid-builtin.menu-file-print"); /// Show the print preview. pub const PRINT_PREVIEW: Selector = Selector::new("druid-builtin.menu-file-print"); /// Cut the current selection. pub const CUT: Selector = Selector::new("druid-builtin.menu-cut"); /// Copy the current selection. pub const COPY: Selector = Selector::new("druid-builtin.menu-copy"); /// Paste. pub const PASTE: Selector = Selector::new("druid-builtin.menu-paste"); /// Undo. pub const UNDO: Selector = Selector::new("druid-builtin.menu-undo"); /// Redo. pub const REDO: Selector = Selector::new("druid-builtin.menu-redo"); /// Select all. pub const SELECT_ALL: Selector = Selector::new("druid-builtin.menu-select-all"); /// Text input state has changed, and we need to notify the platform. pub(crate) const INVALIDATE_IME: Selector<ImeInvalidation> = Selector::new("druid-builtin.invalidate-ime"); /// Informs this widget that a child wants a specific region to be shown. The payload is the /// requested region in global coordinates. /// /// This notification is sent when [`scroll_to_view`] or [`scroll_area_to_view`] /// is called. /// /// Widgets which hide their children should always call `ctx.set_handled()` when receiving this to /// avoid unintended behaviour from widgets further down the tree. /// If possible the widget should move its children to bring the area into view and then submit /// a new `SCROLL_TO_VIEW` notification with the same region relative to the new child position. /// /// When building a new widget using ClipBox, take a look at [`ClipBox::managed`] and /// [`Viewport::default_scroll_to_view_handling`]. /// /// [`scroll_to_view`]: crate::EventCtx::scroll_to_view() /// [`scroll_area_to_view`]: crate::EventCtx::scroll_area_to_view() /// [`ClipBox::managed`]: crate::widget::ClipBox::managed() /// [`Viewport::default_scroll_to_view_handling`]: crate::widget::Viewport::default_scroll_to_view_handling() pub const SCROLL_TO_VIEW: Selector<Rect> = Selector::new("druid-builtin.scroll-to"); /// A change that has occurred to text state, and needs to be /// communicated to the platform. pub(crate) struct ImeInvalidation { pub widget: WidgetId, pub event: crate::shell::text::Event, } } impl Selector<()> { /// A selector that does nothing. pub const NOOP: Selector = Selector::new(""); /// Turns this into a command with the specified [`Target`]. /// /// [`Target`]: enum.Target.html pub fn to(self, target: impl Into<Target>) -> Command { Command::from(self).to(target.into()) } } impl<T> Selector<T> { /// Create a new `Selector` with the given string. pub const fn new(s: &'static str) -> Selector<T> { Selector(s, PhantomData) } /// Returns the `SelectorSymbol` identifying this `Selector`. pub(crate) const fn symbol(self) -> SelectorSymbol { self.0 } } impl<T: Any> Selector<T> { /// Convenience method for [`Command::new`] with this selector. /// /// If the payload is `()` there is no need to call this, /// as `Selector<()>` implements `Into<Command>`. /// /// By default, the command will have [`Target::Auto`]. /// The [`Selector::to`] method can be used to override this. pub fn with(self, payload: T) -> Command { Command::new(self, payload, Target::Auto) } } impl Command { /// Create a new `Command` with a payload and a [`Target`]. /// /// [`Selector::with`] should be used to create `Command`s more conveniently. /// /// If you do not need a payload, [`Selector`] implements `Into<Command>`. pub fn new<T: Any>(selector: Selector<T>, payload: T, target: impl Into<Target>) -> Self { Command { symbol: selector.symbol(), payload: Arc::new(payload), target: target.into(), } } /// Used to create a `Command` from the types sent via an `ExtEventSink`. pub(crate) fn from_ext(symbol: SelectorSymbol, payload: Box<dyn Any>, target: Target) -> Self { Command { symbol, payload: payload.into(), target, } .default_to(Target::Global) } /// A helper method for creating a `Notification` from a `Command`. /// /// This is slightly icky; it lets us do `SOME_SELECTOR.with(SOME_PAYLOAD)` /// (which generates a command) and then privately convert it to a /// notification. pub(crate) fn into_notification(self, source: WidgetId) -> Notification { Notification { symbol: self.symbol, payload: self.payload, source, route: source, warn_if_unused: true, } } /// Set the `Command`'s [`Target`]. /// /// [`Command::target`] can be used to get the current [`Target`]. /// /// [`Command::target`]: #method.target /// [`Target`]: enum.Target.html pub fn to(mut self, target: impl Into<Target>) -> Self { self.target = target.into(); self } /// Set the correct default target when target is `Auto`. pub(crate) fn default_to(mut self, target: Target) -> Self { self.target.default(target); self } /// Returns the `Command`'s [`Target`]. /// /// [`Command::to`] can be used to change the [`Target`]. /// /// [`Command::to`]: #method.to /// [`Target`]: enum.Target.html pub fn target(&self) -> Target { self.target } /// Returns `true` if `self` matches this `selector`. pub fn is<T>(&self, selector: Selector<T>) -> bool { self.symbol == selector.symbol() } /// Returns `Some(&T)` (this `Command`'s payload) if the selector matches. /// /// Returns `None` when `self.is(selector) == false`. /// /// Alternatively you can check the selector with [`is`] and then use [`get_unchecked`]. /// /// # Panics /// /// Panics when the payload has a different type, than what the selector is supposed to carry. /// This can happen when two selectors with different types but the same key are used. /// /// [`is`]: #method.is /// [`get_unchecked`]: #method.get_unchecked pub fn get<T: Any>(&self, selector: Selector<T>) -> Option<&T> { if self.symbol == selector.symbol() { Some(self.payload.downcast_ref().unwrap_or_else(|| { panic!( "The selector \"{}\" exists twice with different types. See druid::Command::get for more information", selector.symbol() ); })) } else { None } } /// Returns a reference to this `Command`'s payload. /// /// If the selector has already been checked with [`is`], then `get_unchecked` can be used safely. /// Otherwise you should use [`get`] instead. /// /// # Panics /// /// Panics when `self.is(selector) == false`. /// /// Panics when the payload has a different type, than what the selector is supposed to carry. /// This can happen when two selectors with different types but the same key are used. /// /// [`is`]: #method.is /// [`get`]: #method.get pub fn get_unchecked<T: Any>(&self, selector: Selector<T>) -> &T { self.get(selector).unwrap_or_else(|| { panic!( "Expected selector \"{}\" but the command was \"{}\".", selector.symbol(), self.symbol ) }) } } impl Notification { /// Returns `true` if `self` matches this [`Selector`]. pub fn is<T>(&self, selector: Selector<T>) -> bool { self.symbol == selector.symbol() } /// Returns the payload for this [`Selector`], if the selector matches. /// /// # Panics /// /// Panics when the payload has a different type, than what the selector /// is supposed to carry. This can happen when two selectors with different /// types but the same key are used. /// /// [`is`]: #method.is pub fn get<T: Any>(&self, selector: Selector<T>) -> Option<&T> { if self.symbol == selector.symbol() { Some(self.payload.downcast_ref().unwrap_or_else(|| { panic!( "The selector \"{}\" exists twice with different types. \ See druid::Command::get for more information", selector.symbol() ); })) } else { None } } /// The [`WidgetId`] of the [`Widget`] that sent this [`Notification`]. /// /// [`Widget`]: crate::Widget pub fn source(&self) -> WidgetId { self.source } /// Builder-style method to set `warn_if_unused`. /// /// The default is `true`. pub fn warn_if_unused(mut self, warn_if_unused: bool) -> Self { self.warn_if_unused = warn_if_unused; self } /// Returns whether there should be a warning when no widget handles this notification. pub fn warn_if_unused_set(&self) -> bool { self.warn_if_unused } /// Change the route id pub(crate) fn with_route(mut self, widget_id: WidgetId) -> Self { self.route = widget_id; self } /// The [`WidgetId`] of the last [`Widget`] that this [`Notification`] was passed through. /// /// # Example /// /// ```ignore /// fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut (), env: &Env) { /// if let Event::Notification(notification) = event { /// if notification.route() == self.widget1.id() { /// // the notification came from inside of widget1 /// } /// if notification.route() == self.widget2.id() { /// // the notification came from inside of widget2 /// } /// } /// } /// ``` /// /// [`Widget`]: crate::Widget pub fn route(&self) -> WidgetId { self.route } } impl<T: Any> SingleUse<T> { /// Create a new single-use payload. pub fn new(data: T) -> Self { SingleUse(Mutex::new(Some(data))) } /// Takes the value, leaving a None in its place. pub fn take(&self) -> Option<T> { self.0.lock().unwrap().take() } } impl From<Selector> for Command { fn from(selector: Selector) -> Command { Command { symbol: selector.symbol(), payload: Arc::new(()), target: Target::Auto, } } } impl<T> std::fmt::Display for Selector<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Selector(\"{}\", {})", self.0, any::type_name::<T>()) } } // This has do be done explicitly, to avoid the Copy bound on `T`. // See https://doc.rust-lang.org/std/marker/trait.Copy.html#how-can-i-implement-copy . impl<T> Copy for Selector<T> {} impl<T> Clone for Selector<T> { fn clone(&self) -> Self { *self } } impl Target { /// If `self` is `Auto` it will be replaced with `target`. pub(crate) fn default(&mut self, target: Target) { if self == &Target::Auto { *self = target; } } } impl From<WindowId> for Target { fn from(id: WindowId) -> Target { Target::Window(id) } } impl From<WidgetId> for Target { fn from(id: WidgetId) -> Target { Target::Widget(id) } } impl From<WindowId> for Option<Target> { fn from(id: WindowId) -> Self { Some(Target::Window(id)) } } impl From<WidgetId> for Option<Target> { fn from(id: WidgetId) -> Self { Some(Target::Widget(id)) } } impl std::fmt::Debug for Notification { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Notification: Selector {} from {:?}", self.symbol, self.source ) } } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn get_payload() { let sel = Selector::new("my-selector"); let payload = vec![0, 1, 2]; let command = sel.with(payload); assert_eq!(command.get(sel), Some(&vec![0, 1, 2])); } #[test] fn selector_is_send_and_sync() { fn assert_send_sync<T: Send + Sync>() {} assert_send_sync::<Selector>(); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/theme.rs
druid/src/theme.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Theme keys and initial values. #![allow(missing_docs)] use crate::kurbo::RoundedRectRadii; use crate::piet::Color; use crate::{Env, FontDescriptor, FontFamily, FontStyle, FontWeight, Insets, Key}; pub const WINDOW_BACKGROUND_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.window_background_color"); #[doc(hidden)] #[deprecated(since = "0.8.0", note = "renamed to TEXT_COLOR")] pub const LABEL_COLOR: Key<Color> = TEXT_COLOR; pub const TEXT_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.label_color"); pub const DISABLED_TEXT_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.disabled_label_color"); pub const PLACEHOLDER_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.placeholder_color"); pub const PRIMARY_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.primary_light"); pub const PRIMARY_DARK: Key<Color> = Key::new("org.linebender.druid.theme.primary_dark"); pub const PROGRESS_BAR_RADIUS: Key<RoundedRectRadii> = Key::new("org.linebender.druid.theme.progress_bar_radius"); pub const BACKGROUND_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.background_light"); pub const BACKGROUND_DARK: Key<Color> = Key::new("org.linebender.druid.theme.background_dark"); pub const FOREGROUND_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.foreground_light"); pub const FOREGROUND_DARK: Key<Color> = Key::new("org.linebender.druid.theme.foreground_dark"); pub const DISABLED_FOREGROUND_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.disabled_foreground_light"); pub const DISABLED_FOREGROUND_DARK: Key<Color> = Key::new("org.linebender.druid.theme.disabled_foreground_dark"); pub const BUTTON_DARK: Key<Color> = Key::new("org.linebender.druid.theme.button_dark"); pub const BUTTON_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.button_light"); pub const DISABLED_BUTTON_DARK: Key<Color> = Key::new("org.linebender.druid.theme.disabled_button_dark"); pub const DISABLED_BUTTON_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.disabled_button_light"); pub const BUTTON_BORDER_RADIUS: Key<RoundedRectRadii> = Key::new("org.linebender.druid.theme.button_radius"); pub const BUTTON_BORDER_WIDTH: Key<f64> = Key::new("org.linebender.druid.theme.button_border_width"); pub const BORDER_DARK: Key<Color> = Key::new("org.linebender.druid.theme.border_dark"); pub const BORDER_LIGHT: Key<Color> = Key::new("org.linebender.druid.theme.border_light"); #[doc(hidden)] #[deprecated(since = "0.8.0", note = "use SELECTED_TEXT_BACKGROUND_COLOR instead")] pub const SELECTION_COLOR: Key<Color> = SELECTED_TEXT_BACKGROUND_COLOR; pub const SELECTED_TEXT_BACKGROUND_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.selection_color"); pub const SELECTED_TEXT_INACTIVE_BACKGROUND_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.selection_color_inactive"); pub const SELECTION_TEXT_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.selection_text_color"); pub const CURSOR_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.cursor_color"); pub const TEXT_SIZE_NORMAL: Key<f64> = Key::new("org.linebender.druid.theme.text_size_normal"); pub const TEXT_SIZE_LARGE: Key<f64> = Key::new("org.linebender.druid.theme.text_size_large"); pub const BASIC_WIDGET_HEIGHT: Key<f64> = Key::new("org.linebender.druid.theme.basic_widget_height"); /// The default font for labels, buttons, text boxes, and other UI elements. pub const UI_FONT: Key<FontDescriptor> = Key::new("org.linebender.druid.theme.ui-font"); /// A bold version of the default UI font. pub const UI_FONT_BOLD: Key<FontDescriptor> = Key::new("org.linebender.druid.theme.ui-font-bold"); /// An Italic version of the default UI font. pub const UI_FONT_ITALIC: Key<FontDescriptor> = Key::new("org.linebender.druid.theme.ui-font-italic"); /// The default minimum width for a 'wide' widget; a textbox, slider, progress bar, etc. pub const WIDE_WIDGET_WIDTH: Key<f64> = Key::new("org.linebender.druid.theme.long-widget-width"); pub const BORDERED_WIDGET_HEIGHT: Key<f64> = Key::new("org.linebender.druid.theme.bordered_widget_height"); pub const TEXTBOX_BORDER_RADIUS: Key<RoundedRectRadii> = Key::new("org.linebender.druid.theme.textbox_border_radius"); pub const TEXTBOX_BORDER_WIDTH: Key<f64> = Key::new("org.linebender.druid.theme.textbox_border_width"); pub const TEXTBOX_INSETS: Key<Insets> = Key::new("org.linebender.druid.theme.textbox_insets"); /// The default horizontal spacing between widgets. pub const WIDGET_PADDING_HORIZONTAL: Key<f64> = Key::new("org.linebender.druid.theme.widget-padding-h"); /// The default vertical spacing between widgets. pub const WIDGET_PADDING_VERTICAL: Key<f64> = Key::new("org.linebender.druid.theme.widget-padding-v"); /// The default internal (horizontal) padding for visually distinct components /// of a widget; for instance between a checkbox and its label. pub const WIDGET_CONTROL_COMPONENT_PADDING: Key<f64> = Key::new("org.linebender.druid.theme.widget-padding-control-label"); pub const SCROLLBAR_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.scrollbar_color"); pub const SCROLLBAR_BORDER_COLOR: Key<Color> = Key::new("org.linebender.druid.theme.scrollbar_border_color"); pub const SCROLLBAR_MAX_OPACITY: Key<f64> = Key::new("org.linebender.druid.theme.scrollbar_max_opacity"); pub const SCROLLBAR_FADE_DELAY: Key<u64> = Key::new("org.linebender.druid.theme.scrollbar_fade_time"); pub const SCROLLBAR_WIDTH: Key<f64> = Key::new("org.linebender.druid.theme.scrollbar_width"); pub const SCROLLBAR_PAD: Key<f64> = Key::new("org.linebender.druid.theme.scrollbar_pad"); pub const SCROLLBAR_RADIUS: Key<RoundedRectRadii> = Key::new("org.linebender.druid.theme.scrollbar_radius"); pub const SCROLLBAR_EDGE_WIDTH: Key<f64> = Key::new("org.linebender.druid.theme.scrollbar_edge_width"); /// Minimum length for any scrollbar to be when measured on that /// scrollbar's primary axis. pub const SCROLLBAR_MIN_SIZE: Key<f64> = Key::new("org.linebender.theme.scrollbar_min_size"); /// An initial theme. pub(crate) fn add_to_env(env: Env) -> Env { env.adding(WINDOW_BACKGROUND_COLOR, Color::rgb8(0x29, 0x29, 0x29)) .adding(TEXT_COLOR, Color::rgb8(0xf0, 0xf0, 0xea)) .adding(DISABLED_TEXT_COLOR, Color::rgb8(0xa0, 0xa0, 0x9a)) .adding(PLACEHOLDER_COLOR, Color::rgb8(0x80, 0x80, 0x80)) .adding(PRIMARY_LIGHT, Color::rgb8(0x5c, 0xc4, 0xff)) .adding(PRIMARY_DARK, Color::rgb8(0x00, 0x8d, 0xdd)) .adding(PROGRESS_BAR_RADIUS, 4.) .adding(BACKGROUND_LIGHT, Color::rgb8(0x3a, 0x3a, 0x3a)) .adding(BACKGROUND_DARK, Color::rgb8(0x31, 0x31, 0x31)) .adding(FOREGROUND_LIGHT, Color::rgb8(0xf9, 0xf9, 0xf9)) .adding(FOREGROUND_DARK, Color::rgb8(0xbf, 0xbf, 0xbf)) .adding(DISABLED_FOREGROUND_LIGHT, Color::rgb8(0x89, 0x89, 0x89)) .adding(DISABLED_FOREGROUND_DARK, Color::rgb8(0x6f, 0x6f, 0x6f)) .adding(BUTTON_DARK, Color::BLACK) .adding(BUTTON_LIGHT, Color::rgb8(0x21, 0x21, 0x21)) .adding(DISABLED_BUTTON_DARK, Color::grey8(0x28)) .adding(DISABLED_BUTTON_LIGHT, Color::grey8(0x38)) .adding(BUTTON_BORDER_RADIUS, 4.) .adding(BUTTON_BORDER_WIDTH, 2.) .adding(BORDER_DARK, Color::rgb8(0x3a, 0x3a, 0x3a)) .adding(BORDER_LIGHT, Color::rgb8(0xa1, 0xa1, 0xa1)) .adding( SELECTED_TEXT_BACKGROUND_COLOR, Color::rgb8(0x43, 0x70, 0xA8), ) .adding(SELECTED_TEXT_INACTIVE_BACKGROUND_COLOR, Color::grey8(0x74)) .adding(SELECTION_TEXT_COLOR, Color::rgb8(0x00, 0x00, 0x00)) .adding(CURSOR_COLOR, Color::WHITE) .adding(TEXT_SIZE_NORMAL, 15.0) .adding(TEXT_SIZE_LARGE, 24.0) .adding(BASIC_WIDGET_HEIGHT, 18.0) .adding(WIDE_WIDGET_WIDTH, 100.) .adding(BORDERED_WIDGET_HEIGHT, 24.0) .adding(TEXTBOX_BORDER_RADIUS, 2.) .adding(TEXTBOX_BORDER_WIDTH, 1.) .adding(TEXTBOX_INSETS, Insets::new(4.0, 4.0, 4.0, 4.0)) .adding(SCROLLBAR_COLOR, Color::rgb8(0xff, 0xff, 0xff)) .adding(SCROLLBAR_BORDER_COLOR, Color::rgb8(0x77, 0x77, 0x77)) .adding(SCROLLBAR_MAX_OPACITY, 0.7) .adding(SCROLLBAR_FADE_DELAY, 1500u64) .adding(SCROLLBAR_WIDTH, 8.) .adding(SCROLLBAR_PAD, 2.) .adding(SCROLLBAR_MIN_SIZE, 45.) .adding(SCROLLBAR_RADIUS, 5.) .adding(SCROLLBAR_EDGE_WIDTH, 1.) .adding(WIDGET_PADDING_VERTICAL, 10.0) .adding(WIDGET_PADDING_HORIZONTAL, 8.0) .adding(WIDGET_CONTROL_COMPONENT_PADDING, 4.0) .adding( UI_FONT, FontDescriptor::new(FontFamily::SYSTEM_UI).with_size(15.0), ) .adding( UI_FONT_BOLD, FontDescriptor::new(FontFamily::SYSTEM_UI) .with_weight(FontWeight::BOLD) .with_size(15.0), ) .adding( UI_FONT_ITALIC, FontDescriptor::new(FontFamily::SYSTEM_UI) .with_style(FontStyle::Italic) .with_size(15.0), ) }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/mouse.rs
druid/src/mouse.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The mousey bits use crate::kurbo::{Point, Vec2}; use crate::{Cursor, Data, Modifiers, MouseButton, MouseButtons}; /// The state of the mouse for a click, mouse-up, move, or wheel event. /// /// In `druid`, unlike in `druid_shell`, we treat the widget's coordinate /// space and the window's coordinate space separately. /// /// Every mouse event can have a new position. There is no guarantee of /// receiving an [`Event::MouseMove`] before another mouse event. /// /// When comparing to the position that was reported by [`Event::MouseMove`], /// the position in relation to the window might have changed because /// the window moved or the platform just didn't inform us of the move. /// The position may also have changed in relation to the receiver, /// because the receiver's location changed without the mouse moving. /// /// [`Event::MouseMove`]: crate::Event::MouseMove #[derive(Debug, Clone)] pub struct MouseEvent { /// The position of the mouse in the coordinate space of the receiver. pub pos: Point, /// The position of the mouse in the coordinate space of the window. pub window_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. /// /// This is primarily used in relation to text selection. /// If there is some text selected in some text widget and it receives a click /// with `focus` set to `true` then the widget should gain focus (i.e. start blinking a cursor) /// but it should not change the text selection. Text selection should only be changed /// when the click has `focus` set to `false`. 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, } impl From<druid_shell::MouseEvent> for MouseEvent { fn from(src: druid_shell::MouseEvent) -> MouseEvent { let druid_shell::MouseEvent { pos, buttons, mods, count, focus, button, wheel_delta, } = src; MouseEvent { pos, window_pos: pos, buttons, mods, count, focus, button, wheel_delta, } } } impl Data for Cursor { fn same(&self, other: &Cursor) -> bool { self == other } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/ext_event.rs
druid/src/ext_event.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Simple handle for submitting external events. use std::any::Any; use std::collections::VecDeque; use std::sync::{Arc, Mutex}; use crate::command::SelectorSymbol; use crate::shell::IdleHandle; use crate::win_handler::EXT_EVENT_IDLE_TOKEN; use crate::{Command, Data, DruidHandler, Selector, Target, WindowId}; pub(crate) type ExtCommand = (SelectorSymbol, Box<dyn Any + Send>, Target); /// A thing that can move into other threads and be used to submit commands back /// to the running application. /// /// This API is preliminary, and may be changed or removed without warning. #[derive(Clone)] pub struct ExtEventSink { queue: Arc<Mutex<VecDeque<ExtCommand>>>, handle: Arc<Mutex<Option<IdleHandle>>>, } /// The stuff that we hold onto inside the app that is related to the /// handling of external events. #[derive(Default)] pub(crate) struct ExtEventHost { /// A shared queue of items that have been sent to us. queue: Arc<Mutex<VecDeque<ExtCommand>>>, /// This doesn't exist when the app starts and it can go away if a window closes, so we keep a /// reference here and can update it when needed. Note that this reference is shared with all /// [`ExtEventSink`]s, so that we can update them too. handle: Arc<Mutex<Option<IdleHandle>>>, /// The window that the handle belongs to, so we can keep track of when /// we need to get a new handle. pub(crate) handle_window_id: Option<WindowId>, } /// An error that occurs if an external event cannot be submitted. /// This probably means that the application has gone away. #[derive(Debug, Clone)] pub struct ExtEventError; impl ExtEventHost { pub(crate) fn new() -> Self { Default::default() } pub(crate) fn make_sink(&self) -> ExtEventSink { ExtEventSink { queue: self.queue.clone(), handle: self.handle.clone(), } } pub(crate) fn set_idle(&mut self, handle: IdleHandle, window_id: WindowId) { self.handle.lock().unwrap().replace(handle); self.handle_window_id = Some(window_id); } pub(crate) fn has_pending_items(&self) -> bool { !self.queue.lock().unwrap().is_empty() } pub(crate) fn recv(&mut self) -> Option<Command> { self.queue .lock() .unwrap() .pop_front() .map(|(selector, payload, target)| Command::from_ext(selector, payload, target)) } } impl ExtEventSink { /// Submit a [`Command`] to the running application. /// /// [`Command`] is not thread safe, so you cannot submit it directly; /// instead you have to pass the [`Selector`] and the payload /// separately, and it will be turned into a [`Command`] when it is received. /// /// The `payload` must implement `Any + Send`. /// /// If the [`Target::Auto`] is equivalent to [`Target::Global`]. pub fn submit_command<T: Any + Send>( &self, selector: Selector<T>, payload: impl Into<Box<T>>, target: impl Into<Target>, ) -> Result<(), ExtEventError> { let target = target.into(); let payload = payload.into(); if let Some(handle) = self.handle.lock().unwrap().as_mut() { handle.schedule_idle(EXT_EVENT_IDLE_TOKEN); } self.queue.lock().map_err(|_| ExtEventError)?.push_back(( selector.symbol(), payload, target, )); Ok(()) } /// Schedule an idle callback. /// /// `T` must be the application's root `Data` type (the type provided to [`AppLauncher::launch`]). /// /// Add an idle callback, which is called (once) when the message loop /// is empty. The idle callback will be run from the main UI thread. /// /// 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. /// /// [`AppLauncher::launch`]: crate::AppLauncher::launch pub fn add_idle_callback<T: 'static + Data>(&self, cb: impl FnOnce(&mut T) + Send + 'static) { let mut handle = self.handle.lock().unwrap(); if let Some(handle) = handle.as_mut() { handle.add_idle(|win_handler| { if let Some(win_handler) = win_handler.as_any().downcast_mut::<DruidHandler<T>>() { win_handler.app_state.handle_idle_callback(cb); } else { debug_panic!( "{} is not the type of root data", std::any::type_name::<T>() ); } }); } } } impl std::fmt::Display for ExtEventError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Window missing for external event") } } impl std::error::Error for ExtEventError {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/dialog.rs
druid/src/dialog.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Configuration for open and save file dialogs. //! //! This is a wrapper around [`druid_shell::FileDialogOptions`] with a few extra Druid specifics. //! As such, many of the docs are copied from `druid_shell`, and should be kept in sync. use std::path::PathBuf; use druid_shell::FileDialogOptions as ShellOptions; use crate::{FileInfo, FileSpec, Selector}; /// 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`. /// /// ## Have a really good save dialog default type /// /// There is no way for the user to choose which extension they want to save a file as via the UI. /// They have no way of knowing which extensions are even supported and must manually type it out. /// /// *Hopefully it's a temporary problem and we can find a way to show the file formats in the UI. /// This is being tracked in [druid#998].* /// /// [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 /// [druid#998]: https://github.com/xi-editor/druid/issues/998 #[derive(Debug, Clone, Default)] pub struct FileDialogOptions { pub(crate) opt: ShellOptions, pub(crate) accept_cmd: Option<Selector<FileInfo>>, pub(crate) accept_multiple_cmd: Option<Selector<Vec<FileInfo>>>, pub(crate) cancel_cmd: Option<Selector<()>>, } 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.opt = self.opt.show_hidden(); self } /// Set directories to be selectable instead of files. /// /// This is only relevant for open dialogs. pub fn select_directories(mut self) -> Self { self.opt = self.opt.select_directories(); 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.opt = self.opt.packages_as_directories(); self } /// Set multiple items to be selectable. /// /// This is only relevant for open dialogs. pub fn multi_selection(mut self) -> Self { self.opt = self.opt.multi_selection(); 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 { self.opt = self.opt.allowed_types(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.opt = self.opt.default_type(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.opt = self.opt.default_name(default_name); 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.opt = self.opt.name_label(name_label); self } /// Set the title text of the dialog. pub fn title(mut self, title: impl Into<String>) -> Self { self.opt = self.opt.title(title); self } /// Set the text of the Open/Save button. pub fn button_text(mut self, text: impl Into<String>) -> Self { self.opt = self.opt.button_text(text); 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.opt = self.opt.force_starting_directory(path); self } /// Sets a custom command to use when the file dialog succeeds. /// /// By default, an "open" dialog sends the [`OPEN_FILE`] command when it succeeds, and a "save" /// dialog sends the [`SAVE_FILE_AS`] command. Using this method, you can configure a different /// command to be used. /// /// [`OPEN_FILE`]: crate::commands::OPEN_FILE /// [`SAVE_FILE_AS`]: crate::commands::SAVE_FILE_AS pub fn accept_command(mut self, cmd: Selector<FileInfo>) -> Self { self.accept_cmd = Some(cmd); self } /// Sets a custom command to use when the file dialog succeeds with multi selection. /// /// This only works for "open" dialogs configured for multiselection. pub fn accept_multiple_command(mut self, cmd: Selector<Vec<FileInfo>>) -> Self { self.accept_multiple_cmd = Some(cmd); self } /// Sets a custom command to use when the file dialog is cancelled. /// /// By default, an "open" dialog sends the [`OPEN_PANEL_CANCELLED`] command when it is cancelled, and a "save" /// dialog sends the [`SAVE_PANEL_CANCELLED`] command. Using this method, you can configure a different /// command to be used. /// /// [`OPEN_PANEL_CANCELLED`]: crate::commands::OPEN_PANEL_CANCELLED /// [`SAVE_PANEL_CANCELLED`]: crate::commands::SAVE_PANEL_CANCELLED pub fn cancel_command(mut self, cmd: Selector<()>) -> Self { self.cancel_cmd = Some(cmd); self } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/localization.rs
druid/src/localization.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Localization handling. //! //! Localization is backed by [Fluent], via [fluent-rs]. //! //! In Druid, the main way you will deal with localization is via the //! [`LocalizedString`] struct. //! //! You construct a [`LocalizedString`] with a key, which identifies a 'message' //! in your `.flt` files. If your string requires arguments, you supply it with //! closures that can extract those arguments from the current [`Env`] and //! [`Data`]. //! //! At runtime, you resolve your [`LocalizedString`] into an actual string, //! passing it the current [`Env`] and [`Data`]. //! //! //! [Fluent]: https://projectfluent.org //! [fluent-rs]: https://github.com/projectfluent/fluent-rs //! [`Data`]: crate::Data use std::collections::HashMap; use std::sync::Arc; use std::{fs, io}; use tracing::{debug, error, warn}; use crate::{Application, ArcStr, Env}; use fluent_bundle::{ FluentArgs, FluentBundle, FluentError, FluentMessage, FluentResource, FluentValue, }; use fluent_langneg::{negotiate_languages, NegotiationStrategy}; use fluent_syntax::ast::Pattern as FluentPattern; use unic_langid::LanguageIdentifier; // Localization looks for string files in druid/resources, but this path is hardcoded; // it will only work if you're running an example from the druid/ directory. // At some point we will need to bundle strings with applications, and choose // the path dynamically. static FALLBACK_STRINGS: &str = include_str!("../resources/i18n/en-US/builtin.ftl"); /// Provides access to the localization strings for the current locale. #[allow(dead_code)] pub(crate) struct L10nManager { // these two are not currently used; will be used when we let the user // add additional localization files. res_mgr: ResourceManager, resources: Vec<String>, current_bundle: BundleStack, current_locale: LanguageIdentifier, } /// Manages a collection of localization files. struct ResourceManager { resources: HashMap<String, Arc<FluentResource>>, locales: Vec<LanguageIdentifier>, default_locale: LanguageIdentifier, path_scheme: String, } //NOTE: instead of a closure, at some point we can use something like a lens for this. //TODO: this is an Arc so that it can be clone, which is a bound on things like `Menu`. /// A closure that generates a localization value. type ArgClosure<T> = Arc<dyn Fn(&T, &Env) -> FluentValue<'static> + 'static>; /// Wraps a closure that generates an argument for localization. #[derive(Clone)] struct ArgSource<T>(ArgClosure<T>); /// A string that can be localized based on the current locale. /// /// At its simplest, a `LocalizedString` is a key that can be resolved /// against a map of localized strings for a given locale. #[derive(Debug, Clone)] pub struct LocalizedString<T> { pub(crate) key: &'static str, placeholder: Option<ArcStr>, args: Option<Vec<(&'static str, ArgSource<T>)>>, resolved: Option<ArcStr>, resolved_lang: Option<LanguageIdentifier>, } /// A stack of localization resources, used for fallback. struct BundleStack(Vec<FluentBundle<Arc<FluentResource>>>); impl BundleStack { fn get_message(&self, id: &str) -> Option<FluentMessage<'_>> { self.0.iter().flat_map(|b| b.get_message(id)).next() } fn format_pattern( &self, id: &str, pattern: &FluentPattern<&str>, args: Option<&FluentArgs>, errors: &mut Vec<FluentError>, ) -> String { for bundle in self.0.iter() { if bundle.has_message(id) { return bundle.format_pattern(pattern, args, errors).to_string(); } } format!("localization failed for key '{id}'") } } //NOTE: much of this is adapted from https://github.com/projectfluent/fluent-rs/blob/master/fluent-resmgr/src/resource_manager.rs impl ResourceManager { /// Loads a new localization resource from disk, as needed. fn get_resource(&mut self, res_id: &str, locale: &str) -> Arc<FluentResource> { let path = self .path_scheme .replace("{locale}", locale) .replace("{res_id}", res_id); if let Some(res) = self.resources.get(&path) { res.clone() } else { let string = fs::read_to_string(&path).unwrap_or_else(|_| { if (res_id, locale) == ("builtin.ftl", "en-US") { FALLBACK_STRINGS.to_string() } else { error!("missing resource {}/{}", locale, res_id); String::new() } }); let res = match FluentResource::try_new(string) { Ok(res) => Arc::new(res), Err((res, _err)) => Arc::new(res), }; self.resources.insert(path, res.clone()); res } } /// Return the best localization bundle for the provided `LanguageIdentifier`. fn get_bundle(&mut self, locale: &LanguageIdentifier, resource_ids: &[String]) -> BundleStack { let resolved_locales = self.resolve_locales(locale.clone()); debug!("resolved: {}", PrintLocales(resolved_locales.as_slice())); let mut stack = Vec::new(); for locale in &resolved_locales { let mut bundle = FluentBundle::new(resolved_locales.clone()); for res_id in resource_ids { let res = self.get_resource(res_id, &locale.to_string()); bundle.add_resource(res).unwrap(); } stack.push(bundle); } BundleStack(stack) } /// Given a locale, returns the best set of available locales. pub(crate) fn resolve_locales(&self, locale: LanguageIdentifier) -> Vec<LanguageIdentifier> { negotiate_languages( &[locale], &self.locales, Some(&self.default_locale), NegotiationStrategy::Filtering, ) .into_iter() .map(|l| l.to_owned()) .collect() } } impl L10nManager { /// Create a new localization manager. /// /// `resources` is a list of file names that contain strings. `base_dir` /// is a path to a directory that includes per-locale subdirectories. /// /// This directory should be of the structure `base_dir/{locale}/{resource}`, /// where '{locale}' is a valid BCP47 language tag, and {resource} is a `.ftl` /// included in `resources`. pub fn new(resources: Vec<String>, base_dir: &str) -> Self { fn get_available_locales(base_dir: &str) -> Result<Vec<LanguageIdentifier>, io::Error> { let mut locales = vec![]; let res_dir = fs::read_dir(base_dir)?; for entry in res_dir.flatten() { let path = entry.path(); if path.is_dir() { if let Some(name) = path.file_name() { if let Some(name) = name.to_str() { let langid: LanguageIdentifier = name.parse().expect("Parsing failed."); locales.push(langid); } } } } Ok(locales) } let default_locale: LanguageIdentifier = "en-US".parse().expect("failed to parse default locale"); let current_locale = Application::get_locale() .parse() .unwrap_or_else(|_| default_locale.clone()); let locales = get_available_locales(base_dir).unwrap_or_default(); debug!( "available locales {}, current {}", PrintLocales(&locales), current_locale, ); let mut path_scheme = base_dir.to_string(); path_scheme.push_str("/{locale}/{res_id}"); let mut res_mgr = ResourceManager { resources: HashMap::new(), path_scheme, default_locale, locales, }; let current_bundle = res_mgr.get_bundle(&current_locale, &resources); L10nManager { res_mgr, resources, current_bundle, current_locale, } } /// Fetch a localized string from the current bundle by key. /// /// In general, this should not be used directly; [`LocalizedString`] /// should be used for localization, and you should call /// [`LocalizedString::resolve`] to update the string as required. /// ///[`LocalizedString`]: struct.LocalizedString.html ///[`LocalizedString::resolve`]: struct.LocalizedString.html#method.resolve pub fn localize<'args>( &'args self, key: &str, args: impl Into<Option<&'args FluentArgs<'args>>>, ) -> Option<ArcStr> { let args = args.into(); let value = self .current_bundle .get_message(key) .and_then(|msg| msg.value())?; let mut errs = Vec::new(); let result = self .current_bundle .format_pattern(key, value, args, &mut errs); for err in errs { warn!("localization error {:?}", err); } // fluent inserts bidi controls when interpolating, and they can // cause rendering issues; for now we just strip them. // https://www.w3.org/International/questions/qa-bidi-unicode-controls#basedirection const START_ISOLATE: char = '\u{2068}'; const END_ISOLATE: char = '\u{2069}'; if args.is_some() && result.chars().any(|c| c == START_ISOLATE) { Some( result .chars() .filter(|c| c != &START_ISOLATE && c != &END_ISOLATE) .collect::<String>() .into(), ) } else { Some(result.into()) } } //TODO: handle locale change } impl std::fmt::Debug for L10nManager { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("L10nManager") .field("resources", &self.resources) .field("res_mgr.locales", &self.res_mgr.locales) .field("current_locale", &self.current_locale) .finish() } } impl<T> LocalizedString<T> { /// Create a new `LocalizedString` with the given key. pub const fn new(key: &'static str) -> Self { LocalizedString { key, args: None, placeholder: None, resolved: None, resolved_lang: None, } } /// Add a placeholder value. This will be used if localization fails. /// /// This is intended for use during prototyping. pub fn with_placeholder(mut self, placeholder: impl Into<ArcStr>) -> Self { self.placeholder = Some(placeholder.into()); self } /// Return the localized value for this string, or the placeholder, if /// the localization is missing, or the key if there is no placeholder. pub fn localized_str(&self) -> ArcStr { self.resolved .clone() .or_else(|| self.placeholder.clone()) .unwrap_or_else(|| self.key.into()) } /// Add a named argument and a corresponding closure. This closure /// is a function that will return a value for the given key from the current /// environment and data. pub fn with_arg( mut self, key: &'static str, f: impl Fn(&T, &Env) -> FluentValue<'static> + 'static, ) -> Self { self.args .get_or_insert(Vec::new()) .push((key, ArgSource(Arc::new(f)))); self } /// Lazily compute the localized value for this string based on the provided /// environment and data. /// /// Returns `true` if the current value of the string has changed. pub fn resolve(&mut self, data: &T, env: &Env) -> bool { //TODO: this recomputes the string if either the language has changed, //or *anytime* we have arguments. Ideally we would be using a lens //to only recompute when our actual data has changed. let manager = match env.localization_manager() { Some(manager) => manager, None => return false, }; if self.args.is_some() || self.resolved_lang.as_ref() != Some(&manager.current_locale) { let args: Option<FluentArgs> = self .args .as_ref() .map(|a| a.iter().map(|(k, v)| (*k, (v.0)(data, env))).collect()); self.resolved_lang = Some(manager.current_locale.clone()); let next = manager.localize(self.key, args.as_ref()); let result = next != self.resolved; self.resolved = next; result } else { false } } } impl<T> std::fmt::Debug for ArgSource<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Arg Resolver {:p}", self.0) } } /// Helper to impl display for slices of displayable things. struct PrintLocales<'a, T>(&'a [T]); impl<'a, T: std::fmt::Display> std::fmt::Display for PrintLocales<'a, T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[")?; let mut prev = false; for l in self.0 { if prev { write!(f, ", ")?; } prev = true; write!(f, "{l}")?; } write!(f, "]") } } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn resolve() { let en_us: LanguageIdentifier = "en-US".parse().unwrap(); let en_ca: LanguageIdentifier = "en-CA".parse().unwrap(); let en_gb: LanguageIdentifier = "en-GB".parse().unwrap(); let fr_fr: LanguageIdentifier = "fr-FR".parse().unwrap(); let pt_pt: LanguageIdentifier = "pt-PT".parse().unwrap(); let resmgr = ResourceManager { resources: HashMap::new(), locales: vec![en_us.clone(), en_ca.clone(), en_gb.clone(), fr_fr.clone()], default_locale: en_us.clone(), path_scheme: String::new(), }; let en_za: LanguageIdentifier = "en-GB".parse().unwrap(); let cn_hk: LanguageIdentifier = "cn-HK".parse().unwrap(); let fr_ca: LanguageIdentifier = "fr-CA".parse().unwrap(); assert_eq!( resmgr.resolve_locales(en_ca.clone()), vec![en_ca.clone(), en_us.clone(), en_gb.clone()] ); assert_eq!( resmgr.resolve_locales(en_za), vec![en_gb, en_us.clone(), en_ca] ); assert_eq!( resmgr.resolve_locales(fr_ca), vec![fr_fr.clone(), en_us.clone()] ); assert_eq!( resmgr.resolve_locales(fr_fr.clone()), vec![fr_fr, en_us.clone()] ); assert_eq!(resmgr.resolve_locales(cn_hk), vec![en_us.clone()]); assert_eq!(resmgr.resolve_locales(pt_pt), vec![en_us]); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/scroll_component.rs
druid/src/scroll_component.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A component for embedding in another widget to provide consistent and //! extendable scrolling behavior use std::time::Duration; use crate::kurbo::{Point, Rect, Vec2}; use crate::theme; use crate::widget::{Axis, Viewport}; use crate::{Env, Event, EventCtx, LifeCycle, LifeCycleCtx, PaintCtx, RenderContext, TimerToken}; #[derive(Default, Debug, Copy, Clone)] /// Which scroll bars of a scroll area are currently enabled. pub enum ScrollbarsEnabled { /// No scrollbars are enabled None, /// Scrolling on the x axis is allowed Horizontal, /// Scrolling on the y axis is allowed Vertical, /// Bidirectional scrolling is allowed #[default] Both, } impl ScrollbarsEnabled { fn is_enabled(self, axis: Axis) -> bool { matches!( (self, axis), (ScrollbarsEnabled::Both, _) | (ScrollbarsEnabled::Horizontal, Axis::Horizontal) | (ScrollbarsEnabled::Vertical, Axis::Vertical) ) } fn is_none(self) -> bool { matches!(self, ScrollbarsEnabled::None) } /// Set whether the horizontal scrollbar is enabled. pub fn set_horizontal_scrollbar_enabled(&mut self, enabled: bool) { *self = match (*self, enabled) { (ScrollbarsEnabled::None, true) | (ScrollbarsEnabled::Horizontal, true) => { ScrollbarsEnabled::Horizontal } (ScrollbarsEnabled::Both, true) | (ScrollbarsEnabled::Vertical, true) => { ScrollbarsEnabled::Both } (ScrollbarsEnabled::None, false) | (ScrollbarsEnabled::Horizontal, false) => { ScrollbarsEnabled::None } (ScrollbarsEnabled::Vertical, false) | (ScrollbarsEnabled::Both, false) => { ScrollbarsEnabled::Vertical } } } /// Set whether the vertical scrollbar is enabled. pub fn set_vertical_scrollbar_enabled(&mut self, enabled: bool) { *self = match (*self, enabled) { (ScrollbarsEnabled::None, true) | (ScrollbarsEnabled::Vertical, true) => { ScrollbarsEnabled::Vertical } (ScrollbarsEnabled::Both, true) | (ScrollbarsEnabled::Horizontal, true) => { ScrollbarsEnabled::Both } (ScrollbarsEnabled::None, false) | (ScrollbarsEnabled::Vertical, false) => { ScrollbarsEnabled::None } (ScrollbarsEnabled::Horizontal, false) | (ScrollbarsEnabled::Both, false) => { ScrollbarsEnabled::Horizontal } } } } /// Denotes which scrollbar, if any, is currently being hovered over /// by the mouse. #[derive(Debug, Copy, Clone)] pub enum BarHoveredState { /// Neither scrollbar is being hovered by the mouse. None, /// The vertical scrollbar is being hovered by the mouse. Vertical, /// The horizontal scrollbar is being hovered by the mouse. Horizontal, } impl BarHoveredState { /// Determines if any scrollbar is currently being hovered by the mouse. pub fn is_hovered(self) -> bool { matches!( self, BarHoveredState::Vertical | BarHoveredState::Horizontal ) } } /// Denotes which scrollbar, if any, is currently being dragged. #[derive(Debug, Copy, Clone)] pub enum BarHeldState { /// Neither scrollbar is being dragged. None, /// Vertical scrollbar is being dragged. Contains an `f64` with /// the initial y-offset of the dragging input. Vertical(f64), /// Horizontal scrollbar is being dragged. Contains an `f64` with /// the initial x-offset of the dragging input. Horizontal(f64), } /// Embeddable component exposing reusable scroll handling logic. /// /// In most situations composing [`Scroll`] is a better idea /// for general UI construction. However some cases are not covered by /// composing those widgets, such as when a widget needs fine grained /// control over its scrolling state or doesn't make sense to exist alone /// without scrolling behavior. /// /// `ScrollComponent` contains the input-handling and scrollbar-positioning logic used by /// [`Scroll`]. It can be used to add this logic to a custom widget when the need arises. /// /// It can be used like this: /// - Store an instance of `ScrollComponent` in your widget's struct, and wrap the child widget to /// be scrolled in a [`ClipBox`]. /// - Call [`event`] and [`lifecycle`] with all event and lifecycle events before propagating them /// to children. /// - Call [`handle_scroll`] with all events after handling / propagating them. /// - Call [`draw_bars`] to draw the scrollbars. /// /// Taking a look at the [`Scroll`] source code can be helpful. You can also do scrolling /// without wrapping a child in a [`ClipBox`], but you will need to do certain event and /// paint transformations yourself; see the [`ClipBox`] source code for an example. /// /// [`Scroll`]: ../widget/struct.Scroll.html /// [`List`]: ../widget/struct.List.html /// [`ClipBox`]: ../widget/struct.ClipBox.html /// [`event`]: struct.ScrollComponent.html#method.event /// [`handle_scroll`]: struct.ScrollComponent.html#method.handle_scroll /// [`draw_bars`]: #method.draw_bars /// [`lifecycle`]: struct.ScrollComponent.html#method.lifecycle #[derive(Debug, Copy, Clone)] pub struct ScrollComponent { /// Current opacity for both scrollbars pub opacity: f64, /// ID for the timer which schedules scrollbar fade out pub timer_id: TimerToken, /// Which if any scrollbar is currently hovered by the mouse pub hovered: BarHoveredState, /// Which if any scrollbar is currently being dragged by the mouse pub held: BarHeldState, /// Which scrollbars are enabled pub enabled: ScrollbarsEnabled, } impl Default for ScrollComponent { fn default() -> Self { Self { opacity: 0.0, timer_id: TimerToken::INVALID, hovered: BarHoveredState::None, held: BarHeldState::None, enabled: ScrollbarsEnabled::Both, } } } impl ScrollComponent { /// Constructs a new [`ScrollComponent`](struct.ScrollComponent.html) for use. pub fn new() -> ScrollComponent { Default::default() } /// true if either scrollbar is currently held down/being dragged pub fn are_bars_held(&self) -> bool { !matches!(self.held, BarHeldState::None) } /// Makes the scrollbars visible, and resets the fade timer. pub fn reset_scrollbar_fade<F>(&mut self, request_timer: F, env: &Env) where F: FnOnce(Duration) -> TimerToken, { self.opacity = env.get(theme::SCROLLBAR_MAX_OPACITY); let fade_delay = env.get(theme::SCROLLBAR_FADE_DELAY); let deadline = Duration::from_millis(fade_delay); self.timer_id = request_timer(deadline); } /// Calculates the paint rect of the vertical scrollbar, or `None` if the vertical scrollbar is /// not visible. pub fn calc_vertical_bar_bounds(&self, port: &Viewport, env: &Env) -> Option<Rect> { self.calc_bar_bounds(Axis::Vertical, port, env) } /// Calculates the paint rect of the horizontal scrollbar, or `None` if the horizontal /// scrollbar is not visible. pub fn calc_horizontal_bar_bounds(&self, port: &Viewport, env: &Env) -> Option<Rect> { self.calc_bar_bounds(Axis::Horizontal, port, env) } fn calc_bar_bounds(&self, axis: Axis, port: &Viewport, env: &Env) -> Option<Rect> { let viewport_size = port.view_size; let content_size = port.content_size; let scroll_offset = port.view_origin.to_vec2(); let viewport_major = axis.major(viewport_size); let content_major = axis.major(content_size); if viewport_major >= content_major { return None; } let bar_width = env.get(theme::SCROLLBAR_WIDTH); let bar_pad = env.get(theme::SCROLLBAR_PAD); let bar_min_size = env.get(theme::SCROLLBAR_MIN_SIZE); let percent_visible = viewport_major / content_major; let percent_scrolled = axis.major_vec(scroll_offset) / (content_major - viewport_major); let major_padding = if self.enabled.is_enabled(axis.cross()) { bar_pad + bar_pad + bar_width } else { bar_pad + bar_pad }; let usable_space = viewport_major - major_padding; let length = (percent_visible * viewport_major).ceil(); #[allow(clippy::manual_clamp)] // Usable space could be below the minimum bar size. let length = length.max(bar_min_size).min(usable_space); let left_x_offset = bar_pad + ((usable_space - length) * percent_scrolled).ceil(); let right_x_offset = left_x_offset + length; let (x0, y0) = axis.pack( left_x_offset, axis.minor(viewport_size) - bar_width - bar_pad, ); let (x1, y1) = axis.pack(right_x_offset, axis.minor(viewport_size) - bar_pad); if x0 >= x1 || y0 >= y1 { return None; } Some(Rect::new(x0, y0, x1, y1) + scroll_offset) } /// Draw scroll bars. pub fn draw_bars(&self, ctx: &mut PaintCtx, port: &Viewport, env: &Env) { let scroll_offset = port.view_origin.to_vec2(); if self.enabled.is_none() || self.opacity <= 0.0 { return; } let brush = ctx .render_ctx .solid_brush(env.get(theme::SCROLLBAR_COLOR).with_alpha(self.opacity)); let border_brush = ctx.render_ctx.solid_brush( env.get(theme::SCROLLBAR_BORDER_COLOR) .with_alpha(self.opacity), ); let radius = env.get(theme::SCROLLBAR_RADIUS); let edge_width = env.get(theme::SCROLLBAR_EDGE_WIDTH); // Vertical bar if self.enabled.is_enabled(Axis::Vertical) { if let Some(bounds) = self.calc_vertical_bar_bounds(port, env) { let rect = (bounds - scroll_offset) .inset(-edge_width / 2.0) .to_rounded_rect(radius); ctx.render_ctx.fill(rect, &brush); ctx.render_ctx.stroke(rect, &border_brush, edge_width); } } // Horizontal bar if self.enabled.is_enabled(Axis::Horizontal) { if let Some(bounds) = self.calc_horizontal_bar_bounds(port, env) { let rect = (bounds - scroll_offset) .inset(-edge_width / 2.0) .to_rounded_rect(radius); ctx.render_ctx.fill(rect, &brush); ctx.render_ctx.stroke(rect, &border_brush, edge_width); } } } /// Tests if the specified point overlaps the vertical scrollbar /// /// Returns false if the vertical scrollbar is not visible pub fn point_hits_vertical_bar(&self, port: &Viewport, pos: Point, env: &Env) -> bool { if !self.enabled.is_enabled(Axis::Vertical) { return false; } let viewport_size = port.view_size; let scroll_offset = port.view_origin.to_vec2(); if let Some(mut bounds) = self.calc_vertical_bar_bounds(port, env) { // Stretch hitbox to edge of widget bounds.x1 = scroll_offset.x + viewport_size.width; bounds.contains(pos) } else { false } } /// Tests if the specified point overlaps the horizontal scrollbar /// /// Returns false if the horizontal scrollbar is not visible pub fn point_hits_horizontal_bar(&self, port: &Viewport, pos: Point, env: &Env) -> bool { if !self.enabled.is_enabled(Axis::Horizontal) { return false; } let viewport_size = port.view_size; let scroll_offset = port.view_origin.to_vec2(); if let Some(mut bounds) = self.calc_horizontal_bar_bounds(port, env) { // Stretch hitbox to edge of widget bounds.y1 = scroll_offset.y + viewport_size.height; bounds.contains(pos) } else { false } } /// Checks if the event applies to the scroll behavior, uses it, and marks it handled /// /// Make sure to call on every event pub fn event(&mut self, port: &mut Viewport, ctx: &mut EventCtx, event: &Event, env: &Env) { let viewport_size = port.view_size; let content_size = port.content_size; let scroll_offset = port.view_origin.to_vec2(); let scrollbar_is_hovered = match event { Event::MouseMove(e) | Event::MouseUp(e) | Event::MouseDown(e) => { let offset_pos = e.pos + scroll_offset; self.point_hits_vertical_bar(port, offset_pos, env) || self.point_hits_horizontal_bar(port, offset_pos, env) } _ => false, }; if self.are_bars_held() { // if we're dragging a scrollbar match event { Event::MouseMove(event) => { match self.held { BarHeldState::Vertical(offset) => { let scale_y = viewport_size.height / content_size.height; let bounds = self .calc_vertical_bar_bounds(port, env) .unwrap_or(Rect::ZERO); let mouse_y = event.pos.y + scroll_offset.y; let delta = mouse_y - bounds.y0 - offset; port.pan_by(Vec2::new(0f64, (delta / scale_y).ceil())); ctx.set_handled(); } BarHeldState::Horizontal(offset) => { let scale_x = viewport_size.width / content_size.width; let bounds = self .calc_horizontal_bar_bounds(port, env) .unwrap_or(Rect::ZERO); let mouse_x = event.pos.x + scroll_offset.x; let delta = mouse_x - bounds.x0 - offset; port.pan_by(Vec2::new((delta / scale_x).ceil(), 0f64)); ctx.set_handled(); } _ => (), } ctx.request_paint(); } Event::MouseUp(_) => { self.held = BarHeldState::None; ctx.set_active(false); if !scrollbar_is_hovered { self.hovered = BarHoveredState::None; self.reset_scrollbar_fade(|d| ctx.request_timer(d), env); } ctx.set_handled(); } _ => (), // other events are a noop } } else if scrollbar_is_hovered { // if we're over a scrollbar but not dragging match event { Event::MouseMove(event) => { let offset_pos = event.pos + scroll_offset; if self.point_hits_vertical_bar(port, offset_pos, env) { self.hovered = BarHoveredState::Vertical; } else if self.point_hits_horizontal_bar(port, offset_pos, env) { self.hovered = BarHoveredState::Horizontal; } else { unreachable!(); } self.opacity = env.get(theme::SCROLLBAR_MAX_OPACITY); self.timer_id = TimerToken::INVALID; // Cancel any fade out in progress ctx.request_paint(); ctx.set_handled(); } Event::MouseDown(event) => { let pos = event.pos + scroll_offset; if self.point_hits_vertical_bar(port, pos, env) { ctx.set_active(true); self.held = BarHeldState::Vertical( // The bounds must be non-empty, because the point hits the scrollbar. pos.y - self.calc_vertical_bar_bounds(port, env).unwrap().y0, ); } else if self.point_hits_horizontal_bar(port, pos, env) { ctx.set_active(true); self.held = BarHeldState::Horizontal( // The bounds must be non-empty, because the point hits the scrollbar. pos.x - self.calc_horizontal_bar_bounds(port, env).unwrap().x0, ); } else { unreachable!(); } ctx.set_handled(); } // if the mouse was downed elsewhere, moved over a scroll bar and released: noop. Event::MouseUp(_) => (), _ => unreachable!(), } } else { match event { Event::MouseMove(_) => { // if we have just stopped hovering if self.hovered.is_hovered() && !scrollbar_is_hovered { self.hovered = BarHoveredState::None; self.reset_scrollbar_fade(|d| ctx.request_timer(d), env); } } Event::Timer(id) if *id == self.timer_id => { // Schedule scroll bars animation ctx.request_anim_frame(); self.timer_id = TimerToken::INVALID; ctx.set_handled(); } Event::AnimFrame(interval) => { // Guard by the timer id being invalid, otherwise the scroll bars would fade // immediately if some other widget started animating. if self.timer_id == TimerToken::INVALID { // Animate scroll bars opacity let diff = 2.0 * (*interval as f64) * 1e-9; self.opacity -= diff; if self.opacity > 0.0 { ctx.request_anim_frame(); } if let Some(bounds) = self.calc_horizontal_bar_bounds(port, env) { ctx.request_paint_rect(bounds - scroll_offset); } if let Some(bounds) = self.calc_vertical_bar_bounds(port, env) { ctx.request_paint_rect(bounds - scroll_offset); } } } _ => (), } } } /// Applies mousewheel scrolling if the event has not already been handled pub fn handle_scroll( &mut self, port: &mut Viewport, ctx: &mut EventCtx, event: &Event, env: &Env, ) { if !ctx.is_handled() { if let Event::Wheel(mouse) = event { if port.pan_by(mouse.wheel_delta) { ctx.request_paint(); ctx.set_handled(); self.reset_scrollbar_fade(|d| ctx.request_timer(d), env); } } } } /// Perform any necessary action prompted by a lifecycle event /// /// Make sure to call on every lifecycle event pub fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, env: &Env) { match event { LifeCycle::Size(_) => { // Show the scrollbars any time our size changes self.reset_scrollbar_fade(|d| ctx.request_timer(d), env); } LifeCycle::HotChanged(false) => { if self.hovered.is_hovered() { self.hovered = BarHoveredState::None; self.reset_scrollbar_fade(|d| ctx.request_timer(d), env); } } _ => (), } } } #[cfg(test)] mod tests { use float_cmp::assert_approx_eq; use super::*; use crate::kurbo::Size; const TEST_SCROLLBAR_WIDTH: f64 = 11.0; const TEST_SCROLLBAR_PAD: f64 = 3.0; const TEST_SCROLLBAR_MIN_SIZE: f64 = 17.0; #[test] fn scrollbar_layout() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: (0.0, 25.0).into(), view_size: (100.0, 50.0).into(), }; let scrollbar_rect = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert!( rect_contains( viewport.view_rect().inset(TEST_SCROLLBAR_PAD), scrollbar_rect ), "scrollbar should be contained by viewport" ); assert_eq!(scrollbar_rect, Rect::new(86.0, 38.0, 97.0, 63.0)); } #[test] fn scrollbar_layout_at_start() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: Point::ZERO, view_size: (100.0, 50.0).into(), }; let scrollbar_rect = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert!( rect_contains( viewport.view_rect().inset(TEST_SCROLLBAR_PAD), scrollbar_rect ), "scrollbar should be contained by viewport" ); // scrollbar should be at start of viewport assert_approx_eq!( f64, scrollbar_rect.y0, viewport.view_rect().y0 + TEST_SCROLLBAR_PAD ); assert_eq!(scrollbar_rect, Rect::new(86.0, 3.0, 97.0, 28.0)); } #[test] fn scrollbar_layout_at_end() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: (0.0, 50.0).into(), view_size: (100.0, 50.0).into(), }; let scrollbar_rect = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert!( rect_contains( viewport.view_rect().inset(TEST_SCROLLBAR_PAD), scrollbar_rect ), "scrollbar should be contained by viewport" ); // scrollbar should be at end of viewport assert_approx_eq!( f64, scrollbar_rect.y1, viewport.view_rect().y1 - TEST_SCROLLBAR_PAD ); assert_eq!(scrollbar_rect, Rect::new(86.0, 72.0, 97.0, 97.0)); } #[test] fn scrollbar_layout_change_viewport_position() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let mut viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: (0.0, 25.0).into(), view_size: (100.0, 50.0).into(), }; let scrollbar_rect_1 = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); viewport.view_origin += Vec2::new(0.0, 15.0); let scrollbar_rect_2 = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert_eq!( scrollbar_rect_1.size(), scrollbar_rect_2.size(), "moving the viewport should not change scrollbar size" ); } #[test] fn scrollbar_layout_padding_for_other_bar() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Both; let viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: (0.0, 50.0).into(), view_size: (100.0, 50.0).into(), }; let scrollbar_rect = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert!( rect_contains( viewport.view_rect().inset(TEST_SCROLLBAR_PAD), scrollbar_rect ), "scrollbar should be contained by viewport" ); assert!( scrollbar_rect.y1 + TEST_SCROLLBAR_WIDTH <= viewport.view_rect().y1, "vertical scrollbar should leave space for the horizontal scrollbar when both enabled" ); assert_eq!(scrollbar_rect, Rect::new(86.0, 61.0, 97.0, 86.0)); } #[test] fn scrollbar_layout_min_bar_size() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let viewport = Viewport { content_size: Size::new(100.0, 1000.0), view_origin: (0.0, 25.0).into(), view_size: (100.0, 50.0).into(), }; let scrollbar_rect = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert!( rect_contains( viewport.view_rect().inset(TEST_SCROLLBAR_PAD), scrollbar_rect ), "scrollbar should be contained by viewport" ); // scrollbar should use SCROLLBAR_MIN_SIZE when content is much bigger than viewport assert_approx_eq!(f64, scrollbar_rect.height(), TEST_SCROLLBAR_MIN_SIZE); assert_eq!(scrollbar_rect, Rect::new(86.0, 29.0, 97.0, 46.0)); } #[test] fn scrollbar_layout_viewport_too_small_for_min_bar_size() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: (0.0, 25.0).into(), view_size: (100.0, 10.0).into(), }; let scrollbar_rect = scroll_component .calc_vertical_bar_bounds(&viewport, &test_env()) .unwrap(); assert!( rect_contains( viewport.view_rect().inset(TEST_SCROLLBAR_PAD), scrollbar_rect ), "scrollbar should be contained by viewport" ); // scrollbar should fill viewport if too small for SCROLLBAR_MIN_SIZE assert_approx_eq!( f64, scrollbar_rect.y0, viewport.view_rect().y0 + TEST_SCROLLBAR_PAD ); assert_approx_eq!( f64, scrollbar_rect.y1, viewport.view_rect().y1 - TEST_SCROLLBAR_PAD ); } #[test] fn scrollbar_layout_viewport_too_small_for_bar() { let mut scroll_component = ScrollComponent::new(); scroll_component.enabled = ScrollbarsEnabled::Vertical; let viewport = Viewport { content_size: Size::new(100.0, 100.0), view_origin: (0.0, 25.0).into(), view_size: (100.0, 3.0).into(), }; let scrollbar_rect = scroll_component.calc_vertical_bar_bounds(&viewport, &test_env()); assert_eq!( scrollbar_rect, None, "scrollbar should not be drawn if viewport is too small" ); } fn rect_contains(outer: Rect, inner: Rect) -> bool { outer.union(inner) == outer } fn test_env() -> Env { Env::empty() .adding(theme::SCROLLBAR_WIDTH, TEST_SCROLLBAR_WIDTH) .adding(theme::SCROLLBAR_PAD, TEST_SCROLLBAR_PAD) .adding(theme::SCROLLBAR_MIN_SIZE, TEST_SCROLLBAR_MIN_SIZE) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/core.rs
druid/src/core.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The fundamental Druid types. use std::collections::VecDeque; use tracing::{trace, trace_span, warn}; use crate::bloom::Bloom; use crate::command::sys::{CLOSE_WINDOW, SUB_WINDOW_HOST_TO_PARENT, SUB_WINDOW_PARENT_TO_HOST}; use crate::commands::SCROLL_TO_VIEW; use crate::contexts::{ChangeCtx, ContextState}; use crate::kurbo::{Affine, Insets, Point, Rect, Shape, Size}; use crate::sub_window::SubWindowUpdate; use crate::{ ArcStr, BoxConstraints, Color, Command, Cursor, Data, Env, Event, EventCtx, InternalEvent, InternalLifeCycle, LayoutCtx, LifeCycle, LifeCycleCtx, Notification, PaintCtx, Region, RenderContext, Target, TextLayout, UpdateCtx, Widget, WidgetId, WindowId, }; /// Our queue type pub(crate) type CommandQueue = VecDeque<Command>; /// A container for one widget in the hierarchy. /// /// Generally, container widgets don't contain other widgets directly, /// but rather contain a `WidgetPod`, which has additional state needed /// for layout and for the widget to participate in event flow. /// /// `WidgetPod` will translate internal Druid events to regular events, /// synthesize additional events of interest, and stop propagation when it makes sense. /// /// This struct also contains the previous data for a widget, which is /// essential for the [`update`] method, both to decide when the update /// needs to propagate, and to provide the previous data so that a /// widget can process a diff between the old value and the new. /// /// [`update`]: Widget::update pub struct WidgetPod<T, W> { state: WidgetState, old_data: Option<T>, env: Option<Env>, inner: W, // stashed layout so we don't recompute this when debugging debug_widget_text: TextLayout<ArcStr>, } /// Generic state for all widgets in the hierarchy. /// /// This struct contains the widget's layout rect, flags /// indicating when the widget is active or focused, and other /// state necessary for the widget to participate in event /// flow. /// /// It is provided to [`paint`] calls as a non-mutable reference, /// largely so a widget can know its size, also because active /// and focus state can affect the widget's appearance. Other than /// that, widgets will generally not interact with it directly, /// but it is an important part of the [`WidgetPod`] struct. /// /// [`paint`]: Widget::paint #[derive(Clone)] pub struct WidgetState { pub(crate) id: WidgetId, /// The size of the child; this is the value returned by the child's layout /// method. size: Size, /// The origin of the child in the parent's coordinate space; together with /// `size` these constitute the child's layout rect. origin: Point, /// The origin of the parent in the window coordinate space. /// /// Note that this value can be stale after `set_origin` was called /// but before [`LifeCycle::ViewContextChanged`] has fully propagated. pub(crate) parent_window_origin: Point, /// A flag used to track and debug missing calls to set_origin. is_expecting_set_origin_call: bool, /// The insets applied to the layout rect to generate the paint rect. /// In general, these will be zero; the exception is for things like /// drop shadows or overflowing text. pub(crate) paint_insets: Insets, /// The offset of the baseline relative to the bottom of the widget. /// /// In general, this will be zero; the bottom of the widget will be considered /// the baseline. Widgets that contain text or controls that expect to be /// laid out alongside text can set this as appropriate. pub(crate) baseline_offset: f64, // The region that needs to be repainted, relative to the widget's bounds. pub(crate) invalid: Region, // TODO: consider using bitflags for the booleans. // `true` if a descendent of this widget changed its disabled state and should receive // LifeCycle::DisabledChanged or InternalLifeCycle::RouteDisabledChanged pub(crate) children_disabled_changed: bool, // `true` if one of our ancestors is disabled (meaning we are also disabled). pub(crate) ancestor_disabled: bool, // `true` if this widget has been explicitly disabled. // A widget can be disabled without being *explicitly* disabled if an ancestor is disabled. pub(crate) is_explicitly_disabled: bool, // `true` if this widget has been explicitly disabled, but has not yet seen one of // LifeCycle::DisabledChanged or InternalLifeCycle::RouteDisabledChanged pub(crate) is_explicitly_disabled_new: bool, pub(crate) is_hot: bool, pub(crate) is_active: bool, pub(crate) needs_layout: bool, /// Some of our children have the `view_context_changed` flag set. pub(crate) children_view_context_changed: bool, /// indicate that the [`ViewContext`] changed. /// /// When this flag is set, the associated widget will receive a `LifeCycle::ViewContextChanged` /// event. /// /// [`ViewContext`]: crate::ViewContext pub(crate) view_context_changed: bool, /// Any descendant is active. has_active: bool, /// In the focused path, starting from window and ending at the focused widget. /// Descendants of the focused widget are not in the focused path. pub(crate) has_focus: bool, /// Any descendant has requested an animation frame. pub(crate) request_anim: bool, /// Any descendant has requested update. pub(crate) request_update: bool, pub(crate) update_focus_chain: bool, pub(crate) focus_chain: Vec<WidgetId>, pub(crate) request_focus: Option<FocusChange>, pub(crate) children: Bloom<WidgetId>, pub(crate) children_changed: bool, /// The cursor that was set using one of the context methods. pub(crate) cursor_change: CursorChange, /// The result of merging up children cursors. This gets cleared when merging state up (unlike /// cursor_change, which is persistent). pub(crate) cursor: Option<Cursor>, // Port -> Host pub(crate) sub_window_hosts: Vec<(WindowId, WidgetId)>, } /// Methods by which a widget can attempt to change focus state. #[derive(Debug, Clone, Copy)] pub(crate) enum FocusChange { /// The focused widget is giving up focus. Resign, /// A specific widget wants focus Focus(WidgetId), /// Focus should pass to the next focusable widget Next, /// Focus should pass to the previous focusable widget Previous, } /// The possible cursor states for a widget. #[derive(Clone, Debug)] pub(crate) enum CursorChange { /// No cursor has been set. Default, /// Someone set a cursor, but if a child widget also set their cursor then we'll use theirs /// instead of ours. Set(Cursor), /// Someone set a cursor, and we'll use it regardless of what the children say. Override(Cursor), } impl<T, W: Widget<T>> WidgetPod<T, W> { /// Create a new widget pod. /// /// In a widget hierarchy, each widget is wrapped in a `WidgetPod` /// so it can participate in layout and event flow. The process of /// adding a child widget to a container should call this method. pub fn new(inner: W) -> WidgetPod<T, W> { let mut state = WidgetState::new(inner.id().unwrap_or_else(WidgetId::next), None); state.children_changed = true; state.needs_layout = true; WidgetPod { state, old_data: None, env: None, inner, debug_widget_text: TextLayout::new(), } } /// Read-only access to state. We don't mark the field as `pub` because /// we want to control mutation. pub(crate) fn state(&self) -> &WidgetState { &self.state } /// Returns `true` if the widget has received [`LifeCycle::WidgetAdded`]. /// /// [`LifeCycle::WidgetAdded`]: LifeCycle::WidgetAdded pub fn is_initialized(&self) -> bool { self.old_data.is_some() } /// Returns `true` if widget or any descendent is focused pub fn has_focus(&self) -> bool { self.state.has_focus } /// The "active" (aka pressed) status of a widget. /// /// Active status generally corresponds to a mouse button down. Widgets /// with behavior similar to a button will call [`set_active`] on mouse /// down and then up. /// /// The active status can only be set manually. Druid doesn't automatically /// set it to `false` on mouse release or anything like that. /// /// There is no special handling of the active status for multi-pointer devices. /// /// When a widget is active, it gets mouse events even when the mouse /// is dragged away. /// /// [`set_active`]: EventCtx::set_active pub fn is_active(&self) -> bool { self.state.is_active } /// Returns `true` if any descendant is [`active`]. /// /// [`active`]: WidgetPod::is_active pub fn has_active(&self) -> bool { self.state.has_active } /// The "hot" (aka hover) status of a widget. /// /// A widget is "hot" when the mouse is hovered over it. Some Widgets (eg buttons) /// will change their appearance when hot as a visual indication that they /// will respond to mouse interaction. /// /// The hot status is automatically computed from the widget's layout rect. In a /// container hierarchy, all widgets with layout rects containing the mouse position /// have hot status. The hot status cannot be set manually. /// /// There is no special handling of the hot status for multi-pointer devices. /// /// Note: a widget can be hot while another is [`active`] (for example, when /// clicking a button and dragging the cursor to another widget). /// /// [`active`]: WidgetPod::is_active pub fn is_hot(&self) -> bool { self.state.is_hot } /// Get the identity of the widget. pub fn id(&self) -> WidgetId { self.state.id } /// This widget or any of its children have requested layout. pub fn layout_requested(&self) -> bool { self.state.needs_layout } /// Set the origin of this widget, in the parent's coordinate space. /// /// A container widget should call the [`Widget::layout`] method on its children in /// its own [`Widget::layout`] implementation, and then call `set_origin` to /// position those children. /// /// The changed origin won't be fully in effect until [`LifeCycle::ViewContextChanged`] has /// finished propagating. Specifically methods that depend on the widget's origin in relation /// to the window will return stale results during the period after calling `set_origin` but /// before [`LifeCycle::ViewContextChanged`] has finished propagating. /// /// The widget container can also call `set_origin` from other context, but calling `set_origin` /// after the widget received [`LifeCycle::ViewContextChanged`] and before the next event results /// in an inconsistent state of the widget tree. /// /// The child will receive the [`LifeCycle::Size`] event informing them of the final [`Size`]. pub fn set_origin(&mut self, ctx: &mut impl ChangeCtx, origin: Point) { self.state.is_expecting_set_origin_call = false; if origin != self.state.origin { self.state.origin = origin; self.state.view_context_changed = true; // Instead of calling merge_up we directly propagate the flag we care about, to gain performance ctx.state().widget_state.children_view_context_changed = true; } } /// Returns the layout [`Rect`]. /// /// This will be a [`Rect`] with a [`Size`] determined by the child's [`layout`] /// method, and the origin that was set by [`set_origin`]. /// /// [`layout`]: Widget::layout /// [`set_origin`]: WidgetPod::set_origin pub fn layout_rect(&self) -> Rect { self.state.layout_rect() } /// Get the widget's paint [`Rect`]. /// /// This is the [`Rect`] that widget has indicated it needs to paint in. /// This is the same as the [`layout_rect`] with the [`paint_insets`] applied; /// in the general case it is the same as the [`layout_rect`]. /// /// [`layout_rect`]: #method.layout_rect /// [`paint_insets`]: #method.paint_insets pub fn paint_rect(&self) -> Rect { self.state.paint_rect() } /// Return the paint [`Insets`] for this widget. /// /// If these [`Insets`] are nonzero, they describe the area beyond a widget's /// layout rect where it needs to paint. /// /// These are generally zero; exceptions are widgets that do things like /// paint a drop shadow. /// /// A widget can set its insets by calling [`set_paint_insets`] during its /// [`layout`] method. /// /// [`set_paint_insets`]: LayoutCtx::set_paint_insets /// [`layout`]: Widget::layout pub fn paint_insets(&self) -> Insets { self.state.paint_insets } /// Given a parents layout size, determine the appropriate paint [`Insets`] /// for the parent. /// /// This is a convenience method to be used from the [`layout`] method /// of a [`Widget`] that manages a child; it allows the parent to correctly /// propagate a child's desired paint rect, if it extends beyond the bounds /// of the parent's layout rect. /// /// [`layout`]: Widget::layout pub fn compute_parent_paint_insets(&self, parent_size: Size) -> Insets { let parent_bounds = Rect::ZERO.with_size(parent_size); let union_pant_rect = self.paint_rect().union(parent_bounds); union_pant_rect - parent_bounds } /// The distance from the bottom of this widget to the baseline. pub fn baseline_offset(&self) -> f64 { self.state.baseline_offset } /// Determines if the provided `mouse_pos` is inside the widget's `layout_rect` /// and if so updates the hot state and sends [`LifeCycle::HotChanged`]. /// /// Returns `true` if the hot state changed. /// /// The `WidgetPod` should merge up its state when `true` is returned. fn set_hot_state( &mut self, state: &mut ContextState, mouse_pos: Option<Point>, data: &T, env: &Env, ) -> bool { let rect = self.layout_rect(); let had_hot = self.state.is_hot; self.state.is_hot = match mouse_pos { Some(pos) => rect.winding(pos) != 0, None => false, }; if had_hot != self.state.is_hot { trace!( "Widget {:?}: set hot state to {}", self.state.id, self.state.is_hot ); let hot_changed_event = LifeCycle::HotChanged(self.state.is_hot); let mut child_ctx = LifeCycleCtx { state, widget_state: &mut self.state, }; // We add a span so that inner logs are marked as being in a lifecycle pass let widget = &mut self.inner; trace_span!("lifecycle") .in_scope(|| widget.lifecycle(&mut child_ctx, &hot_changed_event, data, env)); // if hot changes and we're showing widget ids, always repaint if env.get(Env::DEBUG_WIDGET_ID) { child_ctx.request_paint(); } return true; } false } } impl<T: Data, W: Widget<T>> WidgetPod<T, W> { /// Paint a child widget. /// /// Generally called by container widgets as part of their [`Widget::paint`] /// method. /// /// Note that this method does not apply the offset of the layout rect. /// If that is desired, use [`paint`] instead. /// /// [`layout`]: Widget::layout /// [`paint`]: #method.paint pub fn paint_raw(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { // we need to do this before we borrow from self if env.get(Env::DEBUG_WIDGET_ID) { self.make_widget_id_layout_if_needed(self.state.id, ctx, env); } let mut inner_ctx = PaintCtx { render_ctx: ctx.render_ctx, state: ctx.state, z_ops: Vec::new(), region: ctx.region.clone(), widget_state: &mut self.state, depth: ctx.depth, }; self.inner.paint(&mut inner_ctx, data, env); ctx.z_ops.append(&mut inner_ctx.z_ops); let debug_ids = inner_ctx.is_hot() && env.get(Env::DEBUG_WIDGET_ID); if debug_ids { // this also draws layout bounds self.debug_paint_widget_ids(ctx, env); } if !debug_ids && env.get(Env::DEBUG_PAINT) { self.debug_paint_layout_bounds(ctx, env); } } /// Paint the widget, translating it by the origin of its layout rectangle. /// /// This will recursively paint widgets, stopping if a widget's layout /// rect is outside of the currently visible region. pub fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.paint_impl(ctx, data, env, false) } /// Paint the widget, even if its layout rect is outside of the currently /// visible region. pub fn paint_always(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.paint_impl(ctx, data, env, true) } /// Shared implementation that can skip drawing non-visible content. fn paint_impl(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env, paint_if_not_visible: bool) { if !paint_if_not_visible && !ctx.region().intersects(self.state.paint_rect()) { return; } if !self.is_initialized() { debug_panic!( "{:?} with widget id {:?}: paint method called before receiving WidgetAdded.", self.inner.type_name(), ctx.widget_id() ); return; } ctx.with_save(|ctx| { let layout_origin = self.layout_rect().origin().to_vec2(); ctx.transform(Affine::translate(layout_origin)); let mut visible = ctx.region().clone(); visible.intersect_with(self.state.paint_rect()); visible -= layout_origin; ctx.with_child_ctx(visible, |ctx| self.paint_raw(ctx, data, env)); }); } fn make_widget_id_layout_if_needed(&mut self, id: WidgetId, ctx: &mut PaintCtx, env: &Env) { if self.debug_widget_text.needs_rebuild() { // switch text color based on background, this is meh and that's okay let border_color = env.get_debug_color(id.to_raw()); let (r, g, b, _) = border_color.as_rgba8(); let avg = (r as u32 + g as u32 + b as u32) / 3; let text_color = if avg < 128 { Color::WHITE } else { Color::BLACK }; let id_string = id.to_raw().to_string(); self.debug_widget_text.set_text(id_string.into()); self.debug_widget_text.set_text_size(10.0); self.debug_widget_text.set_text_color(text_color); self.debug_widget_text.rebuild_if_needed(ctx.text(), env); } } fn debug_paint_widget_ids(&self, ctx: &mut PaintCtx, env: &Env) { // we clone because we need to move it for paint_with_z_index let text = self.debug_widget_text.clone(); let text_size = text.size(); let origin = ctx.size().to_vec2() - text_size.to_vec2(); let border_color = env.get_debug_color(ctx.widget_id().to_raw()); self.debug_paint_layout_bounds(ctx, env); ctx.paint_with_z_index(ctx.depth(), move |ctx| { let origin = Point::new(origin.x.max(0.0), origin.y.max(0.0)); let text_rect = Rect::from_origin_size(origin, text_size); ctx.fill(text_rect, &border_color); text.draw(ctx, origin); }) } fn debug_paint_layout_bounds(&self, ctx: &mut PaintCtx, env: &Env) { const BORDER_WIDTH: f64 = 1.0; let rect = ctx.size().to_rect().inset(BORDER_WIDTH / -2.0); let id = self.id().to_raw(); let color = env.get_debug_color(id); ctx.stroke(rect, &color, BORDER_WIDTH); } /// Compute layout of a widget. /// /// Generally called by container widgets as part of their [`layout`] /// method. /// /// [`layout`]: Widget::layout pub fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> Size { if !self.is_initialized() { debug_panic!( "{:?} with widget id {:?}: layout method called before receiving WidgetAdded.", self.inner.type_name(), ctx.widget_id() ); return Size::ZERO; } self.state.needs_layout = false; self.state.is_expecting_set_origin_call = true; let prev_size = self.state.size; let mut child_ctx = LayoutCtx { widget_state: &mut self.state, state: ctx.state, }; let new_size = self.inner.layout(&mut child_ctx, bc, data, env); if new_size != prev_size { let mut child_ctx = LifeCycleCtx { widget_state: child_ctx.widget_state, state: child_ctx.state, }; let size_event = LifeCycle::Size(new_size); // We add a span so that inner logs are marked as being in a lifecycle pass let _span = trace_span!("lifecycle"); let _span = _span.enter(); self.inner.lifecycle(&mut child_ctx, &size_event, data, env); } ctx.widget_state.merge_up(child_ctx.widget_state); self.state.size = new_size; self.log_layout_issues(new_size); new_size } fn log_layout_issues(&self, size: Size) { if size.width.is_infinite() { let name = self.widget().type_name(); warn!("Widget `{}` has an infinite width.", name); } if size.height.is_infinite() { let name = self.widget().type_name(); warn!("Widget `{}` has an infinite height.", name); } } /// Propagate an event. /// /// Generally the [`event`] method of a container widget will call this /// method on all its children. Here is where a great deal of the event /// flow logic resides, particularly whether to continue propagating /// the event. /// /// [`event`]: Widget::event pub fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if !self.is_initialized() { debug_panic!( "{:?} with widget id {:?}: event method called before receiving WidgetAdded.", self.inner.type_name(), ctx.widget_id() ); return; } // log if we seem not to be laid out when we should be if self.state.is_expecting_set_origin_call && !event.should_propagate_to_hidden() { warn!( "{:?} with widget id {:?} received an event ({:?}) without having been laid out. \ This likely indicates a missed call to set_origin.", self.inner.type_name(), ctx.widget_id(), event, ); } // TODO: factor as much logic as possible into monomorphic functions. // a follow_up event should reach the widget which handled the first event. // in this case we dont discard events when ctx.is_handled is set but just dont set our hot // state to true let follow_up_event = event.is_pointer_event() && self.state.has_active; if ctx.is_handled && !follow_up_event { // This function is called by containers to propagate an event from // containers to children. Non-recurse events will be invoked directly // from other points in the library. return; } let had_active = self.state.has_active; let rect = self.layout_rect(); // If we need to replace either the event or its data. let mut modified_event = None; let recurse = match event { Event::Internal(internal) => match internal { InternalEvent::MouseLeave => { let hot_changed = self.set_hot_state(ctx.state, None, data, env); had_active || hot_changed } InternalEvent::TargetedCommand(cmd) => { match cmd.target() { Target::Widget(id) if id == self.id() => { modified_event = Some(Event::Command(cmd.clone())); true } Target::Widget(id) => { // Recurse when the target widget could be our descendant. // The bloom filter we're checking can return false positives. self.state.children.may_contain(&id) } Target::Global | Target::Window(_) => { modified_event = Some(Event::Command(cmd.clone())); true } _ => false, } } InternalEvent::RouteTimer(token, widget_id) => { if *widget_id == self.id() { modified_event = Some(Event::Timer(*token)); true } else { self.state.children.may_contain(widget_id) } } InternalEvent::RouteImeStateChange(widget_id) => { if *widget_id == self.id() { modified_event = Some(Event::ImeStateChange); true } else { self.state.children.may_contain(widget_id) } } }, Event::WindowConnected | Event::WindowCloseRequested => true, Event::WindowDisconnected => { for (window_id, _) in &self.state.sub_window_hosts { ctx.submit_command(CLOSE_WINDOW.to(*window_id)) } true } Event::WindowScale(_) => { self.state.needs_layout = true; true } Event::WindowSize(_) => { self.state.needs_layout = true; ctx.is_root } Event::MouseDown(mouse_event) => { self.set_hot_state( ctx.state, if !ctx.is_handled { Some(mouse_event.pos) } else { None }, data, env, ); if had_active || self.state.is_hot { let mut mouse_event = mouse_event.clone(); mouse_event.pos -= rect.origin().to_vec2(); modified_event = Some(Event::MouseDown(mouse_event)); true } else { false } } Event::MouseUp(mouse_event) => { self.set_hot_state( ctx.state, if !ctx.is_handled { Some(mouse_event.pos) } else { None }, data, env, ); if had_active || self.state.is_hot { let mut mouse_event = mouse_event.clone(); mouse_event.pos -= rect.origin().to_vec2(); modified_event = Some(Event::MouseUp(mouse_event)); true } else { false } } Event::MouseMove(mouse_event) => { let hot_changed = self.set_hot_state( ctx.state, if !ctx.is_handled { Some(mouse_event.pos) } else { None }, data, env, ); // MouseMove is recursed even if the widget is not active and not hot, // but was hot previously. This is to allow the widget to respond to the movement, // e.g. drag functionality where the widget wants to follow the mouse. if had_active || self.state.is_hot || hot_changed { let mut mouse_event = mouse_event.clone(); mouse_event.pos -= rect.origin().to_vec2(); modified_event = Some(Event::MouseMove(mouse_event)); true } else { false } } Event::Wheel(mouse_event) => { self.set_hot_state( ctx.state, if !ctx.is_handled { Some(mouse_event.pos) } else { None }, data, env, ); if had_active || self.state.is_hot { let mut mouse_event = mouse_event.clone(); mouse_event.pos -= rect.origin().to_vec2(); modified_event = Some(Event::Wheel(mouse_event)); true } else { false } } Event::AnimFrame(_) => { let r = self.state.request_anim; self.state.request_anim = false; r } Event::KeyDown(_) => self.state.has_focus, Event::KeyUp(_) => self.state.has_focus, Event::Paste(_) => self.state.has_focus, Event::Zoom(_) => had_active || self.state.is_hot, Event::Timer(_) => false, // This event was targeted only to our parent Event::ImeStateChange => true, // once delivered to the focus widget, recurse to the component? Event::Command(_) => true, Event::Notification(_) => false, }; if recurse { let mut notifications = VecDeque::new(); let mut inner_ctx = EventCtx { state: ctx.state, widget_state: &mut self.state, notifications: &mut notifications, is_handled: false, is_root: false, }; let inner_event = modified_event.as_ref().unwrap_or(event); inner_ctx.widget_state.has_active = false; match inner_event { Event::Command(cmd) if cmd.is(SUB_WINDOW_HOST_TO_PARENT) => { if let Some(update) = cmd .get_unchecked(SUB_WINDOW_HOST_TO_PARENT) .downcast_ref::<T>() { *data = (*update).clone(); } ctx.is_handled = true } Event::Command(cmd) if cmd.is(SCROLL_TO_VIEW) => { // Submit the SCROLL_TO notification if it was used from a update or lifecycle // call. let rect = cmd.get_unchecked(SCROLL_TO_VIEW); inner_ctx.submit_notification_without_warning(SCROLL_TO_VIEW.with(*rect)); ctx.is_handled = true; } _ => { self.inner.event(&mut inner_ctx, inner_event, data, env); inner_ctx.widget_state.has_active |= inner_ctx.widget_state.is_active; ctx.is_handled |= inner_ctx.is_handled; } } // we try to handle the notifications that occurred below us in the tree self.send_notifications(ctx, &mut notifications, data, env); } // Always merge even if not needed, because merging is idempotent and gives us simpler code. // Doing this conditionally only makes sense when there's a measurable performance boost. ctx.widget_state.merge_up(&mut self.state); } /// Send notifications originating from this widget's children to this /// widget. ///
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/env.rs
druid/src/env.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! An environment which is passed downward into the widget tree. // TODO: Figure out if Env really needs to stay Arc, or if it can be switched to Rc #![allow(clippy::arc_with_non_send_sync)] use std::any::{self, Any}; use std::borrow::Borrow; use std::collections::{hash_map::Entry, HashMap}; use std::fmt::{Debug, Formatter}; use std::marker::PhantomData; use std::ops::Deref; use std::sync::Arc; use crate::kurbo::RoundedRectRadii; use crate::localization::L10nManager; use crate::text::FontDescriptor; use crate::{ArcStr, Color, Data, Insets, Point, Rect, Size}; /// An environment passed down through all widget traversals. /// /// All widget methods have access to an environment, and it is passed /// downwards during traversals. /// /// A widget can retrieve theme parameters (colors, dimensions, etc.). In /// addition, it can pass custom data down to all descendants. An important /// example of the latter is setting a value for enabled/disabled status /// so that an entire subtree can be disabled ("grayed out") with one /// setting. /// /// [`EnvScope`] can be used to override parts of `Env` for its descendants. /// /// # Important /// It is the programmer's responsibility to ensure that the environment /// is used correctly. See [`Key`] for an example. /// - [`Key`]s should be `const`s with unique names /// - [`Key`]s must always be set before they are used. /// - Values can only be overwritten by values of the same type. /// /// [`EnvScope`]: crate::widget::EnvScope #[derive(Clone)] pub struct Env(Arc<EnvImpl>); #[derive(Debug, Clone)] struct EnvImpl { map: HashMap<ArcStr, Value>, l10n: Option<Arc<L10nManager>>, } /// A typed [`Env`] key. /// /// This lets you retrieve values of a given type. The parameter /// implements [`ValueType`]. For "expensive" types, this is a reference, /// so the type for a string is `Key<&str>`. /// /// # Examples /// /// ``` ///# use druid::{Key, Color, WindowDesc, AppLauncher, widget::Label}; /// const IMPORTANT_LABEL_COLOR: Key<Color> = Key::new("org.linebender.example.important-label-color"); /// /// fn important_label() -> Label<()> { /// Label::new("Warning!").with_text_color(IMPORTANT_LABEL_COLOR) /// } /// /// fn main() { /// let main_window = WindowDesc::new(important_label()); /// /// AppLauncher::with_window(main_window) /// .configure_env(|env, _state| { /// // The `Key` must be set before it is used. /// env.set(IMPORTANT_LABEL_COLOR, Color::rgb(1.0, 0.0, 0.0)); /// }); /// } /// ``` #[derive(Clone, Debug, PartialEq, Eq, Data)] pub struct Key<T> { key: &'static str, value_type: PhantomData<T>, } /// A dynamic type representing all values that can be stored in an environment. #[derive(Clone, Data)] #[allow(missing_docs)] // ANCHOR: value_type pub enum Value { Point(Point), Size(Size), Rect(Rect), Insets(Insets), Color(Color), Float(f64), Bool(bool), UnsignedInt(u64), String(ArcStr), Font(FontDescriptor), RoundedRectRadii(RoundedRectRadii), Other(Arc<dyn Any + Send + Sync>), } // ANCHOR_END: value_type /// Either a concrete `T` or a [`Key<T>`] that can be resolved in the [`Env`]. /// /// This is a way to allow widgets to interchangeably use either a specific /// value or a value from the environment for some purpose. #[derive(Clone, PartialEq, Eq, Debug)] pub enum KeyOrValue<T> { /// A concrete [`Value`] of type `T`. Concrete(T), /// A [`Key<T>`] that can be resolved to a value in the [`Env`]. Key(Key<T>), } impl<T: Data> Data for KeyOrValue<T> { fn same(&self, other: &Self) -> bool { match (self, other) { (Self::Concrete(a), Self::Concrete(b)) => a.same(b), (Self::Key(a), Self::Key(b)) => a.same(b), _ => false, } } } /// A trait for anything that can resolve a value of some type from the [`Env`]. /// /// This is a generalization of the idea of [`KeyOrValue`], mostly motivated /// by wanting to improve the API used for checking if items in the [`Env`] have changed. /// /// [`Env`]: struct.Env.html /// [`KeyOrValue`]: enum.KeyOrValue.html pub trait KeyLike<T> { /// Returns `true` if this item has changed between the old and new [`Env`]. fn changed(&self, old: &Env, new: &Env) -> bool; } impl<T: ValueType> KeyLike<T> for Key<T> { fn changed(&self, old: &Env, new: &Env) -> bool { !old.get_untyped(self).same(new.get_untyped(self)) } } impl<T> KeyLike<T> for KeyOrValue<T> { fn changed(&self, old: &Env, new: &Env) -> bool { match self { KeyOrValue::Concrete(_) => false, KeyOrValue::Key(key) => !old.get_untyped(key).same(new.get_untyped(key)), } } } /// Values which can be stored in an environment. pub trait ValueType: Sized + Clone + Into<Value> { /// Attempt to convert the generic `Value` into this type. fn try_from_value(v: &Value) -> Result<Self, ValueTypeError>; } /// The error type for environment access. /// /// This error is expected to happen rarely, if ever, as it only /// happens when the string part of keys collide but the types /// mismatch. #[derive(Debug, Clone)] pub struct ValueTypeError { expected: &'static str, found: Value, } /// An error type for when a key is missing from the [`Env`]. #[derive(Debug, Clone)] #[non_exhaustive] pub struct MissingKeyError { /// The raw key. key: Arc<str>, } impl Env { /// State for whether or not to paint colorful rectangles for layout /// debugging. /// /// Set by the [`WidgetExt::debug_paint_layout`] method. /// /// [`WidgetExt::debug_paint_layout`]: crate::WidgetExt::debug_paint_layout pub(crate) const DEBUG_PAINT: Key<bool> = Key::new("org.linebender.druid.built-in.debug-paint"); /// State for whether or not to paint `WidgetId`s, for event debugging. /// /// Set by the [`WidgetExt::debug_widget_id`] method. /// /// [`WidgetExt::debug_widget_id`]: crate::WidgetExt::debug_widget_id pub(crate) const DEBUG_WIDGET_ID: Key<bool> = Key::new("org.linebender.druid.built-in.debug-widget-id"); /// A key used to tell widgets to print additional debug information. /// /// This does nothing by default; however you can check this key while /// debugging a widget to limit println spam. /// /// For convenience, this key can be set with the [`WidgetExt::debug_widget`] /// method. /// /// # Examples /// /// ```no_run /// # use druid::Env; /// # let env = Env::empty(); /// # let widget_id = 0; /// # let my_rect = druid::Rect::ZERO; /// if env.get(Env::DEBUG_WIDGET) { /// eprintln!("widget {:?} bounds: {:?}", widget_id, my_rect); /// } /// ``` /// /// [`WidgetExt::debug_widget`]: crate::WidgetExt::debug_widget pub const DEBUG_WIDGET: Key<bool> = Key::new("org.linebender.druid.built-in.debug-widget"); /// Gets a value from the environment, expecting it to be present. /// /// Note that the return value is a reference for "expensive" types such /// as strings, but an ordinary value for "cheap" types such as numbers /// and colors. /// /// # Panics /// /// Panics if the key is not found, or if it is present with the wrong type. pub fn get<V: ValueType>(&self, key: impl Borrow<Key<V>>) -> V { match self.try_get(key) { Ok(value) => value, Err(err) => panic!("{}", err), } } /// Tries to get a value from the environment. /// /// If the value is not found, the raw key is returned as the error. /// /// # Panics /// /// Panics if the value for the key is found, but has the wrong type. pub fn try_get<V: ValueType>(&self, key: impl Borrow<Key<V>>) -> Result<V, MissingKeyError> { self.0 .map .get(key.borrow().key) .map(|value| value.to_inner_unchecked()) .ok_or(MissingKeyError { key: key.borrow().key.into(), }) } /// Gets a value from the environment, in its encapsulated [`Value`] form, /// expecting the key to be present. /// /// *WARNING:* This is not intended for general use, but only for inspecting an `Env` e.g. /// for debugging, theme editing, and theme loading. /// /// # Panics /// /// Panics if the key is not found. pub fn get_untyped<V>(&self, key: impl Borrow<Key<V>>) -> &Value { match self.try_get_untyped(key) { Ok(val) => val, Err(err) => panic!("{}", err), } } /// Gets a value from the environment, in its encapsulated [`Value`] form, /// returning `None` if a value isn't found. /// /// # Note /// This is not intended for general use, but only for inspecting an `Env` /// e.g. for debugging, theme editing, and theme loading. pub fn try_get_untyped<V>(&self, key: impl Borrow<Key<V>>) -> Result<&Value, MissingKeyError> { self.0.map.get(key.borrow().key).ok_or(MissingKeyError { key: key.borrow().key.into(), }) } /// Gets the entire contents of the `Env`, in key-value pairs. /// /// *WARNING:* This is not intended for general use, but only for inspecting an `Env` e.g. /// for debugging, theme editing, and theme loading. pub fn get_all(&self) -> impl ExactSizeIterator<Item = (&ArcStr, &Value)> { self.0.map.iter() } /// Adds a key/value, acting like a builder. pub fn adding<V: ValueType>(mut self, key: Key<V>, value: impl Into<V>) -> Env { let env = Arc::make_mut(&mut self.0); env.map.insert(key.into(), value.into().into()); self } /// Sets a value in an environment. /// /// # Panics /// /// Panics if the environment already has a value for the key, but it is /// of a different type. pub fn set<V: ValueType>(&mut self, key: Key<V>, value: impl Into<V>) { let value = value.into().into(); self.try_set_raw(key, value).unwrap(); } /// Try to set a resolved `Value` for this key. /// /// This will return a [`ValueTypeError`] if the value's inner type differs /// from the type of the key. pub fn try_set_raw<V: ValueType>( &mut self, key: Key<V>, raw: Value, ) -> Result<(), ValueTypeError> { let env = Arc::make_mut(&mut self.0); let key = key.into(); match env.map.entry(key) { Entry::Occupied(mut e) => { let existing = e.get_mut(); if !existing.is_same_type(&raw) { return Err(ValueTypeError::new(any::type_name::<V>(), raw)); } *existing = raw; } Entry::Vacant(e) => { e.insert(raw); } } Ok(()) } /// Returns a reference to the [`L10nManager`], which handles localization /// resources. /// /// This always exists on the base `Env` configured by Druid. pub(crate) fn localization_manager(&self) -> Option<&L10nManager> { self.0.l10n.as_deref() } /// Given an id, returns one of 18 distinct colors #[doc(hidden)] pub fn get_debug_color(&self, id: u64) -> Color { let color_num = id as usize % DEBUG_COLOR.len(); DEBUG_COLOR[color_num] } } impl std::fmt::Debug for Env { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("Env") .field("l10n", &self.0.l10n) .field("map", &self.0.map) .finish() } } impl<T> Key<T> { /// Create a new strongly typed `Key` with the given string value. /// The type of the key will be inferred. /// /// # Examples /// /// ``` /// use druid::Key; /// use druid::piet::Color; /// /// let float_key: Key<f64> = Key::new("org.linebender.example.a.very.good.float"); /// let color_key: Key<Color> = Key::new("org.linebender.example.a.very.nice.color"); /// ``` pub const fn new(key: &'static str) -> Self { Key { key, value_type: PhantomData, } } } impl Key<()> { /// Create an untyped `Key` with the given string value. /// /// *WARNING:* This is not for general usage - it's only useful /// for inspecting the contents of an [`Env`] - this is expected to be /// used for debugging, loading, and manipulating themes. /// /// [`Env`]: struct.Env.html pub const fn untyped(key: &'static str) -> Self { Key { key, value_type: PhantomData, } } /// Return this key's raw string value. /// /// This should only be needed for things like debugging or for building /// other tooling that needs to inspect keys. pub const fn raw(&self) -> &'static str { self.key } } impl Value { /// Get a reference to the inner object. /// /// # Panics /// /// Panics when the value variant doesn't match the provided type. pub fn to_inner_unchecked<V: ValueType>(&self) -> V { match ValueType::try_from_value(self) { Ok(v) => v, Err(s) => panic!("{}", s), } } fn is_same_type(&self, other: &Value) -> bool { use Value::*; matches!( (self, other), (Point(_), Point(_)) | (Size(_), Size(_)) | (Rect(_), Rect(_)) | (Insets(_), Insets(_)) | (Color(_), Color(_)) | (Float(_), Float(_)) | (Bool(_), Bool(_)) | (UnsignedInt(_), UnsignedInt(_)) | (String(_), String(_)) | (Font(_), Font(_)) | (RoundedRectRadii(_), RoundedRectRadii(_)) ) } } impl Debug for Value { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { match self { Value::Point(p) => write!(f, "Point {p:?}"), Value::Size(s) => write!(f, "Size {s:?}"), Value::Rect(r) => write!(f, "Rect {r:?}"), Value::Insets(i) => write!(f, "Insets {i:?}"), Value::Color(c) => write!(f, "Color {c:?}"), Value::Float(x) => write!(f, "Float {x}"), Value::Bool(b) => write!(f, "Bool {b}"), Value::UnsignedInt(x) => write!(f, "UnsignedInt {x}"), Value::String(s) => write!(f, "String {s:?}"), Value::Font(font) => write!(f, "Font {font:?}"), Value::RoundedRectRadii(radius) => write!(f, "RoundedRectRadii {radius:?}"), Value::Other(other) => write!(f, "{other:?}"), } } } impl Data for Env { fn same(&self, other: &Env) -> bool { Arc::ptr_eq(&self.0, &other.0) || self.0.deref().same(other.0.deref()) } } impl Data for EnvImpl { fn same(&self, other: &EnvImpl) -> bool { self.map.len() == other.map.len() && self .map .iter() .all(|(k, v1)| other.map.get(k).map(|v2| v1.same(v2)).unwrap_or(false)) } } // Colors are from https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/ // They're picked for visual distinction and accessbility (99 percent) static DEBUG_COLOR: &[Color] = &[ Color::rgb8(230, 25, 75), Color::rgb8(60, 180, 75), Color::rgb8(255, 225, 25), Color::rgb8(0, 130, 200), Color::rgb8(245, 130, 48), Color::rgb8(70, 240, 240), Color::rgb8(240, 50, 230), Color::rgb8(250, 190, 190), Color::rgb8(0, 128, 128), Color::rgb8(230, 190, 255), Color::rgb8(170, 110, 40), Color::rgb8(255, 250, 200), Color::rgb8(128, 0, 0), Color::rgb8(170, 255, 195), Color::rgb8(0, 0, 128), Color::rgb8(128, 128, 128), Color::rgb8(255, 255, 255), Color::rgb8(0, 0, 0), ]; impl Env { /// Returns an empty `Env`. /// /// This is useful for creating a set of overrides. pub fn empty() -> Self { Env(Arc::new(EnvImpl { l10n: None, map: HashMap::new(), })) } pub(crate) fn with_default_i10n() -> Self { Env::with_i10n(vec!["builtin.ftl".into()], "./resources/i18n/") } pub(crate) fn with_i10n(resources: Vec<String>, base_dir: &str) -> Self { let l10n = L10nManager::new(resources, base_dir); let inner = EnvImpl { l10n: Some(Arc::new(l10n)), map: HashMap::new(), }; let env = Env(Arc::new(inner)) .adding(Env::DEBUG_PAINT, false) .adding(Env::DEBUG_WIDGET_ID, false) .adding(Env::DEBUG_WIDGET, false); crate::theme::add_to_env(env) } } impl<T> From<Key<T>> for ArcStr { fn from(src: Key<T>) -> ArcStr { ArcStr::from(src.key) } } impl ValueTypeError { fn new(expected: &'static str, found: Value) -> ValueTypeError { ValueTypeError { expected, found } } } impl std::fmt::Display for ValueTypeError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Incorrect value type: expected {} found {:?}", self.expected, self.found ) } } impl MissingKeyError { /// The raw key that was missing. pub fn raw_key(&self) -> &str { &self.key } } impl std::fmt::Display for MissingKeyError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Missing key: '{}'", self.key) } } impl std::error::Error for ValueTypeError {} impl std::error::Error for MissingKeyError {} /// Use this macro for types which are cheap to clone (ie all `Copy` types). macro_rules! impl_value_type { ($ty:ty, $var:ident) => { impl ValueType for $ty { fn try_from_value(value: &Value) -> Result<Self, ValueTypeError> { match value { Value::$var(f) => Ok(f.to_owned()), other => Err(ValueTypeError::new(any::type_name::<$ty>(), other.clone())), } } } impl From<$ty> for Value { fn from(val: $ty) -> Value { Value::$var(val) } } }; } impl_value_type!(f64, Float); impl_value_type!(bool, Bool); impl_value_type!(u64, UnsignedInt); impl_value_type!(Color, Color); impl_value_type!(Rect, Rect); impl_value_type!(Point, Point); impl_value_type!(Size, Size); impl_value_type!(Insets, Insets); impl_value_type!(ArcStr, String); impl_value_type!(FontDescriptor, Font); impl_value_type!(RoundedRectRadii, RoundedRectRadii); impl<T: 'static + Send + Sync> From<Arc<T>> for Value { fn from(this: Arc<T>) -> Value { Value::Other(this) } } impl<T: 'static + Send + Sync> ValueType for Arc<T> { fn try_from_value(v: &Value) -> Result<Self, ValueTypeError> { let err = ValueTypeError { expected: any::type_name::<T>(), found: v.clone(), }; match v { Value::Other(o) => o.clone().downcast::<T>().map_err(|_| err), _ => Err(err), } } } impl<T: ValueType> KeyOrValue<T> { /// Resolve the concrete type `T` from this `KeyOrValue`, using the provided /// [`Env`] if required. /// /// [`Env`]: struct.Env.html pub fn resolve(&self, env: &Env) -> T { match self { KeyOrValue::Concrete(ref value) => value.to_owned(), KeyOrValue::Key(key) => env.get(key), } } } impl<T: Into<Value>> From<T> for KeyOrValue<T> { fn from(value: T) -> KeyOrValue<T> { KeyOrValue::Concrete(value) } } impl<T: ValueType> From<Key<T>> for KeyOrValue<T> { fn from(key: Key<T>) -> KeyOrValue<T> { KeyOrValue::Key(key) } } macro_rules! key_or_value_from_concrete { ($from:ty => $to:ty) => { impl From<$from> for KeyOrValue<$to> { fn from(f: $from) -> KeyOrValue<$to> { KeyOrValue::Concrete(f.into()) } } }; } key_or_value_from_concrete!(f64 => Insets); key_or_value_from_concrete!((f64, f64) => Insets); key_or_value_from_concrete!((f64, f64, f64, f64) => Insets); key_or_value_from_concrete!(f64 => RoundedRectRadii); key_or_value_from_concrete!((f64, f64, f64, f64) => RoundedRectRadii); #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn string_key_or_value() { const MY_KEY: Key<ArcStr> = Key::new("org.linebender.test.my-string-key"); let env = Env::empty().adding(MY_KEY, "Owned"); assert_eq!(env.get(MY_KEY).as_ref(), "Owned"); let key: KeyOrValue<ArcStr> = MY_KEY.into(); let value: KeyOrValue<ArcStr> = ArcStr::from("Owned").into(); assert_eq!(key.resolve(&env), value.resolve(&env)); } #[test] fn key_is_send_and_sync() { fn assert_send_sync<T: Send + Sync>() {} assert_send_sync::<Key<()>>(); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/contexts.rs
druid/src/contexts.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The context types that are passed into various widget methods. use std::{ any::{Any, TypeId}, collections::{HashMap, VecDeque}, ops::{Deref, DerefMut}, rc::Rc, time::Duration, }; use tracing::{error, trace, warn}; use crate::commands::SCROLL_TO_VIEW; use crate::core::{CommandQueue, CursorChange, FocusChange, WidgetState}; use crate::env::KeyLike; use crate::menu::ContextMenu; use crate::piet::{Piet, PietText, RenderContext}; use crate::shell::text::Event as ImeInvalidation; use crate::shell::Region; use crate::text::{ImeHandlerRef, TextFieldRegistration}; use crate::{ commands, sub_window::SubWindowDesc, widget::Widget, Affine, Command, Cursor, Data, Env, ExtEventSink, Insets, Menu, Notification, Point, Rect, Scale, SingleUse, Size, Target, TimerToken, Vec2, WidgetId, WindowConfig, WindowDesc, WindowHandle, WindowId, }; /// A macro for implementing methods on multiple contexts. /// /// There are a lot of methods defined on multiple contexts; this lets us only /// have to write them out once. macro_rules! impl_context_method { ($ty:ty, { $($method:item)+ } ) => { impl $ty { $($method)+ } }; ( $ty:ty, $($more:ty),+, { $($method:item)+ } ) => { impl_context_method!($ty, { $($method)+ }); impl_context_method!($($more),+, { $($method)+ }); }; } /// A macro for implementing context traits for multiple contexts. macro_rules! impl_context_trait { ($tr:ty => $ty:ty, { $($method:item)+ } ) => { impl $tr for $ty { $($method)+ } }; ($tr:ty => $ty:ty, $($more:ty),+, { $($method:item)+ } ) => { impl_context_trait!($tr => $ty, { $($method)+ }); impl_context_trait!($tr => $($more),+, { $($method)+ }); }; } /// Static state that is shared between most contexts. pub(crate) struct ContextState<'a> { pub(crate) command_queue: &'a mut CommandQueue, pub(crate) ext_handle: &'a ExtEventSink, pub(crate) window_id: WindowId, pub(crate) window: &'a WindowHandle, pub(crate) text: PietText, /// The id of the widget that currently has focus. pub(crate) focus_widget: Option<WidgetId>, pub(crate) root_app_data_type: TypeId, pub(crate) timers: &'a mut HashMap<TimerToken, WidgetId>, pub(crate) text_registrations: &'a mut Vec<TextFieldRegistration>, } /// A mutable context provided to event handling methods of widgets. /// /// Widgets should call [`request_paint`] whenever an event causes a change /// in the widget's appearance, to schedule a repaint. /// /// [`request_paint`]: #method.request_paint pub struct EventCtx<'a, 'b> { pub(crate) state: &'a mut ContextState<'b>, pub(crate) widget_state: &'a mut WidgetState, pub(crate) notifications: &'a mut VecDeque<Notification>, pub(crate) is_handled: bool, pub(crate) is_root: bool, } /// A mutable context provided to the [`lifecycle`] method on widgets. /// /// Certain methods on this context are only meaningful during the handling of /// specific lifecycle events; for instance [`register_child`] /// should only be called while handling [`LifeCycle::WidgetAdded`]. /// /// [`lifecycle`]: Widget::lifecycle /// [`register_child`]: #method.register_child /// [`LifeCycle::WidgetAdded`]: crate::LifeCycle::WidgetAdded pub struct LifeCycleCtx<'a, 'b> { pub(crate) state: &'a mut ContextState<'b>, pub(crate) widget_state: &'a mut WidgetState, } /// A mutable context provided to data update methods of widgets. /// /// Widgets should call [`request_paint`] whenever a data change causes a change /// in the widget's appearance, to schedule a repaint. /// /// [`request_paint`]: #method.request_paint pub struct UpdateCtx<'a, 'b> { pub(crate) state: &'a mut ContextState<'b>, pub(crate) widget_state: &'a mut WidgetState, pub(crate) prev_env: Option<&'a Env>, pub(crate) env: &'a Env, } /// A context provided to layout-handling methods of widgets. /// /// As of now, the main service provided is access to a factory for /// creating text layout objects, which are likely to be useful /// during widget layout. pub struct LayoutCtx<'a, 'b> { pub(crate) state: &'a mut ContextState<'b>, pub(crate) widget_state: &'a mut WidgetState, } /// Z-order paint operations with transformations. pub(crate) struct ZOrderPaintOp { pub z_index: u32, pub paint_func: Box<dyn FnOnce(&mut PaintCtx) + 'static>, pub transform: Affine, } /// A context passed to paint methods of widgets. /// /// In addition to the API below, [`PaintCtx`] derefs to an implementation of /// the [`RenderContext`] trait, which defines the basic available drawing /// commands. pub struct PaintCtx<'a, 'b, 'c> { pub(crate) state: &'a mut ContextState<'b>, pub(crate) widget_state: &'a WidgetState, /// The render context for actually painting. pub render_ctx: &'a mut Piet<'c>, /// The z-order paint operations. pub(crate) z_ops: Vec<ZOrderPaintOp>, /// The currently visible region. pub(crate) region: Region, /// The approximate depth in the tree at the time of painting. pub(crate) depth: u32, } /// The state of a widget and its global context. pub struct State<'a> { // currently the only method using the State struct is set_origin. // the context state could be included into this struct to allow changes to context state // changes from Context traits // pub(crate) state: &'a mut ContextState<'b>, pub(crate) widget_state: &'a mut WidgetState, } /// Convenience trait for code generic over contexts. /// /// Methods that deal with commands and timers. /// Available to all contexts but [`PaintCtx`]. pub trait ChangeCtx { /// Submit a [`Command`] to be run after this event is handled. See [`submit_command`]. /// /// [`submit_command`]: EventCtx::submit_command fn submit_command(&mut self, cmd: impl Into<Command>); /// Returns an [`ExtEventSink`] for submitting commands from other threads. See ['get_external_handle']. /// /// [`get_external_handle`]: EventCtx::get_external_handle fn get_external_handle(&self) -> ExtEventSink; /// Request a timer event. See [`request_timer`] /// /// [`request_timer`]: EventCtx::request_timer fn request_timer(&mut self, deadline: Duration) -> TimerToken; /// Returns the state of the widget. /// /// This method should only be used by the framework to do mergeups. fn state(&mut self) -> State<'_>; } /// Convenience trait for invalidation and request methods available on multiple contexts. /// /// These methods are available on [`EventCtx`], [`LifeCycleCtx`], and [`UpdateCtx`]. #[allow(dead_code)] pub trait RequestCtx: ChangeCtx { /// Request a [`paint`] pass. See ['request_paint'] /// /// ['request_paint']: EventCtx::request_paint /// [`paint`]: Widget::paint fn request_paint(&mut self); /// Request a [`paint`] pass for redrawing a rectangle. See [`request_paint_rect`]. /// /// [`request_paint_rect`]: EventCtx::request_paint_rect /// [`paint`]: Widget::paint fn request_paint_rect(&mut self, rect: Rect); /// Request a layout pass. See [`request_layout`]. /// /// [`request_layout`]: EventCtx::request_layout fn request_layout(&mut self); /// Request an animation frame. See [`request_anim_frame`]. /// /// [`request_anim_frame`]: EventCtx::request_anim_frame fn request_anim_frame(&mut self); /// Indicate that your children have changed. See [`children_changed`]. /// /// [`children_changed`]: EventCtx::children_changed fn children_changed(&mut self); /// Create a new sub-window. See [`new_sub_window`]. /// /// [`new_sub_window`]: EventCtx::new_sub_window fn new_sub_window<W: Widget<U> + 'static, U: Data>( &mut self, window_config: WindowConfig, widget: W, data: U, env: Env, ) -> WindowId; /// Change the disabled state of this widget. See [`set_disabled`]. /// /// [`set_disabled`]: EventCtx::set_disabled fn set_disabled(&mut self, disabled: bool); /// Indicate that text input state has changed. See [`invalidate_text_input`]. /// /// [`invalidate_text_input`]: EventCtx::invalidate_text_input fn invalidate_text_input(&mut self, event: ImeInvalidation); /// Scrolls this widget into view. /// /// [`scroll_to_view`]: EventCtx::scroll_to_view fn scroll_to_view(&mut self); /// Scrolls the area into view. See [`scroll_area_to_view`]. /// /// [`scroll_area_to_view`]: EventCtx::scroll_area_to_view fn scroll_area_to_view(&mut self, area: Rect); } impl_context_trait!( ChangeCtx => EventCtx<'_, '_>, UpdateCtx<'_, '_>, LifeCycleCtx<'_, '_>, LayoutCtx<'_, '_>, { fn submit_command(&mut self, cmd: impl Into<Command>) { Self::submit_command(self, cmd) } fn get_external_handle(&self) -> ExtEventSink { Self::get_external_handle(self) } fn request_timer(&mut self, deadline: Duration) -> TimerToken { Self::request_timer(self, deadline) } fn state(&mut self) -> State<'_> { State { //state: &mut *self.state, widget_state: &mut *self.widget_state, } } } ); impl_context_trait!( RequestCtx => EventCtx<'_, '_>, UpdateCtx<'_, '_>, LifeCycleCtx<'_, '_>, { fn request_paint(&mut self) { Self::request_paint(self) } fn request_paint_rect(&mut self, rect: Rect) { Self::request_paint_rect(self, rect) } fn request_layout(&mut self) { Self::request_layout(self) } fn request_anim_frame(&mut self) { Self::request_anim_frame(self) } fn children_changed(&mut self) { Self::children_changed(self) } fn new_sub_window<W: Widget<U> + 'static, U: Data>( &mut self, window_config: WindowConfig, widget: W, data: U, env: Env, ) -> WindowId { Self::new_sub_window(self, window_config, widget, data, env) } fn set_disabled(&mut self, disabled: bool) { Self::set_disabled(self, disabled) } fn invalidate_text_input(&mut self, event: ImeInvalidation) { Self::invalidate_text_input(self, event) } fn scroll_to_view(&mut self) { Self::scroll_to_view(self) } fn scroll_area_to_view(&mut self, area: Rect) { Self::scroll_area_to_view(self, area) } } ); // methods on everyone impl_context_method!( EventCtx<'_, '_>, UpdateCtx<'_, '_>, LifeCycleCtx<'_, '_>, PaintCtx<'_, '_, '_>, LayoutCtx<'_, '_>, { /// get the `WidgetId` of the current widget. pub fn widget_id(&self) -> WidgetId { self.widget_state.id } /// Returns a reference to the current `WindowHandle`. pub fn window(&self) -> &WindowHandle { self.state.window } /// Get the `WindowId` of the current window. pub fn window_id(&self) -> WindowId { self.state.window_id } /// Get an object which can create text layouts. pub fn text(&mut self) -> &mut PietText { &mut self.state.text } /// The current window's [`Scale`]. /// /// The returned [`Scale`] is a copy and thus its information will be stale after /// the platform changes the window's scale. This means you can only rely on it /// until the next [`Event::WindowScale`] event happens. /// /// [`Scale`]: crate::Scale /// [`Event::WindowScale`]: crate::Event::WindowScale pub fn scale(&self) -> Scale { self.state.window.get_scale().unwrap_or_default() } } ); // methods on everyone but layoutctx impl_context_method!( EventCtx<'_, '_>, UpdateCtx<'_, '_>, LifeCycleCtx<'_, '_>, PaintCtx<'_, '_, '_>, { /// The layout size. /// /// This is the layout size as ultimately determined by the parent /// container, on the previous layout pass. /// /// Generally it will be the same as the size returned by the child widget's /// [`layout`] method. /// /// [`layout`]: Widget::layout pub fn size(&self) -> Size { self.widget_state.size() } /// The origin of the widget in window coordinates, relative to the top left corner of the /// content area. pub fn window_origin(&self) -> Point { self.widget_state.window_origin() } /// Convert a point from the widget's coordinate space to the window's. /// /// The returned point is relative to the content area; it excludes window chrome. pub fn to_window(&self, widget_point: Point) -> Point { self.window_origin() + widget_point.to_vec2() } /// Convert a point from the widget's coordinate space to the screen's. /// See the [`Screen`] module /// /// [`Screen`]: crate::shell::Screen pub fn to_screen(&self, widget_point: Point) -> Point { let insets = self.window().content_insets(); let content_origin = self.window().get_position() + Vec2::new(insets.x0, insets.y0); content_origin + self.to_window(widget_point).to_vec2() } /// Query the "hot" state of the widget. /// /// See [`WidgetPod::is_hot`] for additional information. /// /// [`WidgetPod::is_hot`]: crate::WidgetPod::is_hot pub fn is_hot(&self) -> bool { self.widget_state.is_hot } /// Query the "active" state of the widget. /// /// See [`WidgetPod::is_active`] for additional information. /// /// [`WidgetPod::is_active`]: crate::WidgetPod::is_active pub fn is_active(&self) -> bool { self.widget_state.is_active } /// The focus status of a widget. /// /// Returns `true` if this specific widget is focused. /// To check if any descendants are focused use [`has_focus`]. /// /// Focus means that the widget receives keyboard events. /// /// A widget can request focus using the [`request_focus`] method. /// It's also possible to register for automatic focus via [`register_for_focus`]. /// /// If a widget gains or loses focus it will get a [`LifeCycle::FocusChanged`] event. /// /// Only one widget at a time is focused. However due to the way events are routed, /// all ancestors of that widget will also receive keyboard events. /// /// [`request_focus`]: EventCtx::request_focus /// [`register_for_focus`]: LifeCycleCtx::register_for_focus /// [`LifeCycle::FocusChanged`]: crate::LifeCycle::FocusChanged /// [`has_focus`]: #method.has_focus pub fn is_focused(&self) -> bool { self.state.focus_widget == Some(self.widget_id()) } /// The (tree) focus status of a widget. /// /// Returns `true` if either this specific widget or any one of its descendants is focused. /// To check if only this specific widget is focused use [`is_focused`], /// /// [`is_focused`]: crate::EventCtx::is_focused pub fn has_focus(&self) -> bool { self.widget_state.has_focus } /// The disabled state of a widget. /// /// Returns `true` if this widget or any of its ancestors is explicitly disabled. /// To make this widget explicitly disabled use [`set_disabled`]. /// /// Disabled means that this widget should not change the state of the application. What /// that means is not entirely clear but in any it should not change its data. Therefore /// others can use this as a safety mechanism to prevent the application from entering an /// illegal state. /// For an example the decrease button of a counter of type `usize` should be disabled if the /// value is `0`. /// /// [`set_disabled`]: crate::EventCtx::set_disabled pub fn is_disabled(&self) -> bool { self.widget_state.is_disabled() } } ); impl_context_method!(EventCtx<'_, '_>, UpdateCtx<'_, '_>, { /// Set the cursor icon. /// /// This setting will be retained until [`clear_cursor`] is called, but it will only take /// effect when this widget is either [`hot`] or [`active`]. If a child widget also sets a /// cursor, the child widget's cursor will take precedence. (If that isn't what you want, use /// [`override_cursor`] instead.) /// /// [`clear_cursor`]: crate::EventCtx::clear_cursor /// [`override_cursor`]: crate::EventCtx::override_cursor /// [`hot`]: crate::EventCtx::is_hot /// [`active`]: crate::EventCtx::is_active pub fn set_cursor(&mut self, cursor: &Cursor) { trace!("set_cursor {:?}", cursor); self.widget_state.cursor_change = CursorChange::Set(cursor.clone()); } /// Override the cursor icon. /// /// This setting will be retained until [`clear_cursor`] is called, but it will only take /// effect when this widget is either [`hot`] or [`active`]. This will override the cursor /// preferences of a child widget. (If that isn't what you want, use [`set_cursor`] instead.) /// /// [`clear_cursor`]: crate::EventCtx::clear_cursor /// [`set_cursor`]: crate::EventCtx::set_cursor /// [`hot`]: crate::EventCtx::is_hot /// [`active`]: crate::EventCtx::is_active pub fn override_cursor(&mut self, cursor: &Cursor) { trace!("override_cursor {:?}", cursor); self.widget_state.cursor_change = CursorChange::Override(cursor.clone()); } /// Clear the cursor icon. /// /// This undoes the effect of [`set_cursor`] and [`override_cursor`]. /// /// [`override_cursor`]: crate::EventCtx::override_cursor /// [`set_cursor`]: crate::EventCtx::set_cursor pub fn clear_cursor(&mut self) { trace!("clear_cursor"); self.widget_state.cursor_change = CursorChange::Default; } }); // methods on event, update and layout. impl_context_method!(EventCtx<'_, '_>, UpdateCtx<'_, '_>, LayoutCtx<'_, '_>, { /// Indicate that your [`ViewContext`] has changed. /// /// This event is sent after layout is done and before paint is called. Note that you can still /// receive this event even if there was no prior call to layout. /// /// Widgets must call this method after changing the clip region of their children. /// Changes to the other parts of [`ViewContext`] (cursor position and global origin) are tracked /// internally. /// /// [`ViewContext`]: crate::ViewContext pub fn view_context_changed(&mut self) { self.widget_state.view_context_changed = true; } }); // methods on event, update, and lifecycle impl_context_method!(EventCtx<'_, '_>, UpdateCtx<'_, '_>, LifeCycleCtx<'_, '_>, { /// Request a [`paint`] pass. This is equivalent to calling /// [`request_paint_rect`] for the widget's [`paint_rect`]. /// /// [`paint`]: Widget::paint /// [`request_paint_rect`]: #method.request_paint_rect /// [`paint_rect`]: crate::WidgetPod::paint_rect pub fn request_paint(&mut self) { trace!("request_paint"); self.widget_state.invalid.set_rect( self.widget_state.paint_rect() - self.widget_state.layout_rect().origin().to_vec2(), ); } /// Request a [`paint`] pass for redrawing a rectangle, which is given /// relative to our layout rectangle. /// /// [`paint`]: Widget::paint pub fn request_paint_rect(&mut self, rect: Rect) { trace!("request_paint_rect {}", rect); self.widget_state.invalid.add_rect(rect); } /// Request a layout pass. /// /// A Widget's [`layout`] method is always called when the widget tree /// changes, or the window is resized. /// /// If your widget would like to have layout called at any other time, /// (such as if it would like to change the layout of children in /// response to some event) it must call this method. /// /// [`layout`]: Widget::layout pub fn request_layout(&mut self) { trace!("request_layout"); self.widget_state.needs_layout = true; } /// Request an [`AnimFrame`] event. /// /// Receiving [`AnimFrame`] does not inherently mean a `paint` invocation will follow. /// If you want something actually painted you need to explicitly call [`request_paint`] /// or [`request_paint_rect`] when handling the [`AnimFrame`] event. /// /// Note that not requesting paint when handling the [`AnimFrame`] event and then /// recursively requesting another [`AnimFrame`] can lead to rapid event fire, /// which is probably not what you want and would most likely be wasted compute cycles. /// /// [`AnimFrame`]: crate::Event::AnimFrame /// [`request_paint`]: #method.request_paint /// [`request_paint_rect`]: #method.request_paint_rect pub fn request_anim_frame(&mut self) { trace!("request_anim_frame"); self.widget_state.request_anim = true; } /// Indicate that your children have changed. /// /// Widgets must call this method after adding a new child, removing a child or changing which /// children are hidden (see [`should_propagate_to_hidden`]). /// /// [`should_propagate_to_hidden`]: crate::Event::should_propagate_to_hidden pub fn children_changed(&mut self) { trace!("children_changed"); self.widget_state.children_changed = true; self.widget_state.update_focus_chain = true; self.request_layout(); } /// Set the disabled state for this widget. /// /// Setting this to `false` does not mean a widget is not still disabled; for instance it may /// still be disabled by an ancestor. See [`is_disabled`] for more information. /// /// Calling this method during [`LifeCycle::DisabledChanged`] has no effect. /// /// [`LifeCycle::DisabledChanged`]: crate::LifeCycle::DisabledChanged /// [`is_disabled`]: EventCtx::is_disabled pub fn set_disabled(&mut self, disabled: bool) { // widget_state.children_disabled_changed is not set because we want to be able to delete // changes that happened during DisabledChanged. self.widget_state.is_explicitly_disabled_new = disabled; } /// Indicate that text input state has changed. /// /// A widget that accepts text input should call this anytime input state /// (such as the text or the selection) changes as a result of a non text-input /// event. pub fn invalidate_text_input(&mut self, event: ImeInvalidation) { let payload = commands::ImeInvalidation { widget: self.widget_id(), event, }; let cmd = commands::INVALIDATE_IME .with(payload) .to(Target::Window(self.window_id())); self.submit_command(cmd); } /// Create a new sub-window. /// /// The sub-window will have its app data synchronised with caller's nearest ancestor [`WidgetPod`]. /// 'U' must be the type of the nearest surrounding [`WidgetPod`]. The 'data' argument should be /// the current value of data for that widget. /// /// [`WidgetPod`]: crate::WidgetPod // TODO - dynamically check that the type of the pod we are registering this on is the same as the type of the // requirement. Needs type ids recorded. This goes wrong if you don't have a pod between you and a lens. pub fn new_sub_window<W: Widget<U> + 'static, U: Data>( &mut self, window_config: WindowConfig, widget: W, data: U, env: Env, ) -> WindowId { trace!("new_sub_window"); let req = SubWindowDesc::new(self.widget_id(), window_config, widget, data, env); let window_id = req.window_id; self.widget_state .add_sub_window_host(window_id, req.host_id); self.submit_command(commands::NEW_SUB_WINDOW.with(SingleUse::new(req))); window_id } /// Scrolls this widget into view. /// /// If this widget is only partially visible or not visible at all because of [`Scroll`]s /// it is wrapped in, they will do the minimum amount of scrolling necessary to bring this /// widget fully into view. /// /// If the widget is [`hidden`], this method has no effect. /// /// This functionality is achieved by sending a [`SCROLL_TO_VIEW`] notification. /// /// [`Scroll`]: crate::widget::Scroll /// [`hidden`]: crate::Event::should_propagate_to_hidden /// [`SCROLL_TO_VIEW`]: crate::commands::SCROLL_TO_VIEW pub fn scroll_to_view(&mut self) { self.scroll_area_to_view(self.size().to_rect()) } }); // methods on everyone but paintctx impl_context_method!( EventCtx<'_, '_>, UpdateCtx<'_, '_>, LifeCycleCtx<'_, '_>, LayoutCtx<'_, '_>, { /// Submit a [`Command`] to be run after this event is handled. /// /// Commands are run in the order they are submitted; all commands /// submitted during the handling of an event are executed before /// the [`update`] method is called; events submitted during [`update`] /// are handled after painting. /// /// [`Target::Auto`] commands will be sent to the window containing the widget. /// /// [`update`]: Widget::update pub fn submit_command(&mut self, cmd: impl Into<Command>) { trace!("submit_command"); self.state.submit_command(cmd.into()) } /// Returns an [`ExtEventSink`] that can be moved between threads, /// and can be used to submit commands back to the application. pub fn get_external_handle(&self) -> ExtEventSink { trace!("get_external_handle"); self.state.ext_handle.clone() } /// Request a timer event. /// /// The return value is a token, which can be used to associate the /// request with the event. pub fn request_timer(&mut self, deadline: Duration) -> TimerToken { trace!("request_timer deadline={:?}", deadline); self.state.request_timer(self.widget_state.id, deadline) } } ); impl EventCtx<'_, '_> { /// Submit a [`Notification`]. /// /// The provided argument can be a [`Selector`] or a [`Command`]; this lets /// us work with the existing API for adding a payload to a [`Selector`]. /// /// If the argument is a `Command`, the command's target will be ignored. /// /// # Examples /// /// ``` /// # use druid::{Event, EventCtx, Selector}; /// const IMPORTANT_EVENT: Selector<String> = Selector::new("druid-example.important-event"); /// /// fn check_event(ctx: &mut EventCtx, event: &Event) { /// if is_this_the_event_we_were_looking_for(event) { /// ctx.submit_notification(IMPORTANT_EVENT.with("That's the one".to_string())) /// } /// } /// /// # fn is_this_the_event_we_were_looking_for(event: &Event) -> bool { true } /// ``` /// /// [`Selector`]: crate::Selector pub fn submit_notification(&mut self, note: impl Into<Command>) { trace!("submit_notification"); let note = note.into().into_notification(self.widget_state.id); self.notifications.push_back(note); } /// Submit a [`Notification`] without warning. /// /// In contrast to [`submit_notification`], calling this method will not result in an /// "unhandled notification" warning. /// /// [`submit_notification`]: crate::EventCtx::submit_notification pub fn submit_notification_without_warning(&mut self, note: impl Into<Command>) { trace!("submit_notification"); let note = note .into() .into_notification(self.widget_state.id) .warn_if_unused(false); self.notifications.push_back(note); } /// Set the "active" state of the widget. /// /// See [`EventCtx::is_active`](struct.EventCtx.html#method.is_active). pub fn set_active(&mut self, active: bool) { trace!("set_active({})", active); self.widget_state.is_active = active; // TODO: plumb mouse grab through to platform (through druid-shell) } /// Create a new window. /// `T` must be the application's root `Data` type (the type provided to [`AppLauncher::launch`]). /// /// [`AppLauncher::launch`]: crate::AppLauncher::launch pub fn new_window<T: Any>(&mut self, desc: WindowDesc<T>) { trace!("new_window"); if self.state.root_app_data_type == TypeId::of::<T>() { self.submit_command( commands::NEW_WINDOW .with(SingleUse::new(Box::new(desc))) .to(Target::Global), ); } else { debug_panic!("EventCtx::new_window<T> - T must match the application data type."); } } /// Show the context menu in the window containing the current widget. /// `T` must be the application's root `Data` type (the type provided to [`AppLauncher::launch`]). /// /// [`AppLauncher::launch`]: crate::AppLauncher::launch pub fn show_context_menu<T: Any>(&mut self, menu: Menu<T>, location: Point) { trace!("show_context_menu"); if self.state.root_app_data_type == TypeId::of::<T>() { let menu = ContextMenu { menu, location }; self.submit_command( commands::SHOW_CONTEXT_MENU .with(SingleUse::new(Box::new(menu))) .to(Target::Window(self.state.window_id)), ); } else { debug_panic!( "EventCtx::show_context_menu<T> - T must match the application data type." ); } } /// Set the event as "handled", which stops its propagation to other /// widgets. pub fn set_handled(&mut self) { trace!("set_handled"); self.is_handled = true; } /// Determine whether the event has been handled by some other widget. pub fn is_handled(&self) -> bool { self.is_handled } /// Request keyboard focus. /// /// Because only one widget can be focused at a time, multiple focus requests /// from different widgets during a single event cycle means that the last /// widget that requests focus will override the previous requests. /// /// See [`is_focused`] for more information about focus. /// /// [`is_focused`]: struct.EventCtx.html#method.is_focused pub fn request_focus(&mut self) { trace!("request_focus"); // We need to send the request even if we're currently focused, // because we may have a sibling widget that already requested focus // and we have no way of knowing that yet. We need to override that // to deliver on the "last focus request wins" promise. let id = self.widget_id(); self.widget_state.request_focus = Some(FocusChange::Focus(id)); } /// Transfer focus to the widget with the given `WidgetId`. /// /// See [`is_focused`] for more information about focus. /// /// [`is_focused`]: struct.EventCtx.html#method.is_focused pub fn set_focus(&mut self, target: WidgetId) { trace!("set_focus target={:?}", target); self.widget_state.request_focus = Some(FocusChange::Focus(target)); } /// Transfer focus to the next focusable widget. /// /// This should only be called by a widget that currently has focus. /// /// See [`is_focused`] for more information about focus. /// /// [`is_focused`]: struct.EventCtx.html#method.is_focused pub fn focus_next(&mut self) { trace!("focus_next"); if self.has_focus() { self.widget_state.request_focus = Some(FocusChange::Next); } else { warn!( "focus_next can only be called by the currently \ focused widget or one of its ancestors." ); } } /// Transfer focus to the previous focusable widget. ///
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/bloom.rs
druid/src/bloom.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A simple Bloom filter, used to track child widgets. use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use fnv::FnvHasher; const NUM_BITS: u64 = 64; // the 'offset_basis' for the fnv-1a hash algorithm. // see http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param // // The first of these is the one described in the algorithm, the second is random. const OFFSET_ONE: u64 = 0xcbf2_9ce4_8422_2325; const OFFSET_TWO: u64 = 0xe10_3ad8_2dad_8028; /// A very simple Bloom filter optimized for small values. #[derive(Clone, Copy)] pub(crate) struct Bloom<T: ?Sized> { bits: u64, data: PhantomData<T>, entry_count: usize, } impl<T: ?Sized + Hash> Bloom<T> { /// Create a new filter. pub fn new() -> Self { Self::default() } /// Returns the number of items that have been added to the filter. /// /// Does not count unique entries; this is just the number of times /// `add()` was called since the filter was created or last `clear()`ed. // it feels wrong to call this 'len'? #[cfg(test)] pub fn entry_count(&self) -> usize { self.entry_count } /// Return the raw bits of this filter. #[allow(dead_code)] pub fn to_raw(&self) -> u64 { self.bits } /// Remove all entries from the filter. pub fn clear(&mut self) { self.bits = 0; self.entry_count = 0; } /// Add an item to the filter. pub fn add(&mut self, item: &T) { let mask = self.make_bit_mask(item); self.bits |= mask; self.entry_count += 1; } /// Returns `true` if the item may have been added to the filter. /// /// This can return false positives, but never false negatives. /// Thus `true` means that the item may have been added - or not, /// while `false` means that the item has definitely not been added. pub fn may_contain(&self, item: &T) -> bool { let mask = self.make_bit_mask(item); self.bits & mask == mask } /// Create a new `Bloom` with the items from both filters. pub fn union(&self, other: Bloom<T>) -> Bloom<T> { Bloom { bits: self.bits | other.bits, data: PhantomData, entry_count: self.entry_count + other.entry_count, } } #[inline] fn make_bit_mask(&self, item: &T) -> u64 { //NOTE: we use two hash functions, which performs better than a single hash // with smaller numbers of items, but poorer with more items. Threshold // (given 64 bits) is ~30 items. // The reasoning is that with large numbers of items we're already in bad shape; // optimize for fewer false positives as we get closer to the leaves. // This can be tweaked after profiling. let hash1 = self.make_hash(item, OFFSET_ONE); let hash2 = self.make_hash(item, OFFSET_TWO); (1 << (hash1 % NUM_BITS)) | (1 << (hash2 % NUM_BITS)) } #[inline] fn make_hash(&self, item: &T, seed: u64) -> u64 { let mut hasher = FnvHasher::with_key(seed); item.hash(&mut hasher); hasher.finish() } } impl<T: ?Sized> std::fmt::Debug for Bloom<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Bloom: {:064b}: ({})", self.bits, self.entry_count) } } impl<T: ?Sized> Default for Bloom<T> { fn default() -> Self { Bloom { bits: 0, data: PhantomData, entry_count: 0, } } } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn very_good_test() { let mut bloom = Bloom::default(); for i in 0..100 { bloom.add(&i); assert!(bloom.may_contain(&i)); } bloom.clear(); for i in 0..100 { assert!(!bloom.may_contain(&i)); } } #[test] fn union() { let mut bloom1 = Bloom::default(); bloom1.add(&0); bloom1.add(&1); assert!(!bloom1.may_contain(&2)); assert!(!bloom1.may_contain(&3)); let mut bloom2 = Bloom::default(); bloom2.add(&2); bloom2.add(&3); assert!(!bloom2.may_contain(&0)); assert!(!bloom2.may_contain(&1)); let bloom3 = bloom1.union(bloom2); assert!(bloom3.may_contain(&0)); assert!(bloom3.may_contain(&1)); assert!(bloom3.may_contain(&2)); assert!(bloom3.may_contain(&3)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/util.rs
druid/src/util.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Miscellaneous utility functions. use std::collections::HashMap; use std::hash::Hash; use std::mem; /// Panic in debug and tracing::error in release mode. /// /// This macro is in some way a combination of `panic` and `debug_assert`, /// but it will log the provided message instead of ignoring it in release builds. /// /// It's useful when a backtrace would aid debugging but a crash can be avoided in release. macro_rules! debug_panic { () => { ... }; ($msg:expr) => { if cfg!(debug_assertions) { panic!($msg); } else { tracing::error!($msg); } }; ($msg:expr,) => { debug_panic!($msg) }; ($fmt:expr, $($arg:tt)+) => { if cfg!(debug_assertions) { panic!($fmt, $($arg)*); } else { tracing::error!($fmt, $($arg)*); } }; } /// Fast path for equal type extend + drain. pub trait ExtendDrain { /// Extend the collection by draining the entries from `source`. /// /// This function may swap the underlying memory locations, /// so keep that in mind if one of the collections has a large allocation /// and it should keep that allocation. #[allow(dead_code)] fn extend_drain(&mut self, source: &mut Self); } impl<K, V> ExtendDrain for HashMap<K, V> where K: Eq + Hash + Copy, V: Copy, { // Benchmarking this vs just extend+drain with a 10k entry map. // // running 2 tests // test bench_extend ... bench: 1,971 ns/iter (+/- 566) // test bench_extend_drain ... bench: 0 ns/iter (+/- 0) fn extend_drain(&mut self, source: &mut Self) { if !source.is_empty() { if self.is_empty() { // If the target is empty we can just swap the pointers. mem::swap(self, source); } else { // Otherwise we need to fall back to regular extend-drain. self.extend(source.drain()); } } } } /// An enum for specifying whether an event was handled. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Handled { /// An event was already handled, and shouldn't be propagated to other event handlers. Yes, /// An event has not yet been handled. No, } impl Handled { /// Has the event been handled yet? pub fn is_handled(self) -> bool { self == Handled::Yes } } impl From<bool> for Handled { /// Returns `Handled::Yes` if `handled` is true, and `Handled::No` otherwise. fn from(handled: bool) -> Handled { if handled { Handled::Yes } else { Handled::No } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/debug_state.rs
druid/src/debug_state.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A data structure for representing widget trees. use std::collections::HashMap; /// A description widget and its children, clonable and comparable, meant /// for testing and debugging. This is extremely not optimized. #[derive(Default, Clone, PartialEq, Eq)] pub struct DebugState { /// The widget's type as a human-readable string. pub display_name: String, /// If a widget has a "central" value (for instance, a textbox's contents), /// it is stored here. pub main_value: String, /// Untyped values that reveal useful information about the widget. pub other_values: HashMap<String, String>, /// Debug info of child widgets. pub children: Vec<DebugState>, } impl std::fmt::Debug for DebugState { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { if self.other_values.is_empty() && self.children.is_empty() && self.main_value.is_empty() { f.write_str(&self.display_name) } else if self.other_values.is_empty() && self.children.is_empty() { f.debug_tuple(&self.display_name) .field(&self.main_value) .finish() } else if self.other_values.is_empty() && self.main_value.is_empty() { let mut f_tuple = f.debug_tuple(&self.display_name); for child in &self.children { f_tuple.field(child); } f_tuple.finish() } else { let mut f_struct = f.debug_struct(&self.display_name); if !self.main_value.is_empty() { f_struct.field("_main_value_", &self.main_value); } for (key, value) in self.other_values.iter() { f_struct.field(key, &value); } if !self.children.is_empty() { f_struct.field("children", &self.children); } f_struct.finish() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/box_constraints.rs
druid/src/box_constraints.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The fundamental Druid types. use crate::kurbo::Size; use crate::widget::Axis; /// Constraints for layout. /// /// The layout strategy for Druid is strongly inspired by Flutter, /// and this struct is similar to the [Flutter BoxConstraints] class. /// /// At the moment, it represents simply a minimum and maximum size. /// A widget's [`layout`] method should choose an appropriate size that /// meets these constraints. /// /// Further, a container widget should compute appropriate constraints /// for each of its child widgets, and pass those down when recursing. /// /// The constraints are always [rounded away from zero] to integers /// to enable pixel perfect layout. /// /// [`layout`]: crate::Widget::layout /// [Flutter BoxConstraints]: https://api.flutter.dev/flutter/rendering/BoxConstraints-class.html /// [rounded away from zero]: Size::expand #[derive(Clone, Copy, Debug, PartialEq)] pub struct BoxConstraints { min: Size, max: Size, } impl BoxConstraints { /// An unbounded box constraints object. /// /// Can be satisfied by any nonnegative size. pub const UNBOUNDED: BoxConstraints = BoxConstraints { min: Size::ZERO, max: Size::new(f64::INFINITY, f64::INFINITY), }; /// Create a new box constraints object. /// /// Create constraints based on minimum and maximum size. /// /// The given sizes are also [rounded away from zero], /// so that the layout is aligned to integers. /// /// [rounded away from zero]: Size::expand pub fn new(min: Size, max: Size) -> BoxConstraints { BoxConstraints { min: min.expand(), max: max.expand(), } } /// Create a "tight" box constraints object. /// /// A "tight" constraint can only be satisfied by a single size. /// /// The given size is also [rounded away from zero], /// so that the layout is aligned to integers. /// /// [rounded away from zero]: Size::expand pub fn tight(size: Size) -> BoxConstraints { let size = size.expand(); BoxConstraints { min: size, max: size, } } /// Create a "loose" version of the constraints. /// /// Make a version with zero minimum size, but the same maximum size. pub fn loosen(&self) -> BoxConstraints { BoxConstraints { min: Size::ZERO, max: self.max, } } /// Clamp a given size so that it fits within the constraints. /// /// The given size is also [rounded away from zero], /// so that the layout is aligned to integers. /// /// [rounded away from zero]: Size::expand pub fn constrain(&self, size: impl Into<Size>) -> Size { size.into().expand().clamp(self.min, self.max) } /// Returns the max size of these constraints. pub fn max(&self) -> Size { self.max } /// Returns the min size of these constraints. pub fn min(&self) -> Size { self.min } /// Whether there is an upper bound on the width. pub fn is_width_bounded(&self) -> bool { self.max.width.is_finite() } /// Whether there is an upper bound on the height. pub fn is_height_bounded(&self) -> bool { self.max.height.is_finite() } /// Check to see if these constraints are legit. /// /// Logs a warning if BoxConstraints are invalid. pub fn debug_check(&self, name: &str) { if !(0.0 <= self.min.width && self.min.width <= self.max.width && 0.0 <= self.min.height && self.min.height <= self.max.height && self.min.expand() == self.min && self.max.expand() == self.max) { tracing::warn!("Bad BoxConstraints passed to {}:", name); tracing::warn!("{:?}", self); } if self.min.width.is_infinite() { tracing::warn!("Infinite minimum width constraint passed to {}:", name); } if self.min.height.is_infinite() { tracing::warn!("Infinite minimum height constraint passed to {}:", name); } } /// Shrink min and max constraints by size /// /// The given size is also [rounded away from zero], /// so that the layout is aligned to integers. /// /// [rounded away from zero]: Size::expand pub fn shrink(&self, diff: impl Into<Size>) -> BoxConstraints { let diff = diff.into().expand(); let min = Size::new( (self.min().width - diff.width).max(0.), (self.min().height - diff.height).max(0.), ); let max = Size::new( (self.max().width - diff.width).max(0.), (self.max().height - diff.height).max(0.), ); BoxConstraints::new(min, max) } /// Test whether these constraints contain the given `Size`. pub fn contains(&self, size: impl Into<Size>) -> bool { let size = size.into(); (self.min.width <= size.width && size.width <= self.max.width) && (self.min.height <= size.height && size.height <= self.max.height) } /// Find the `Size` within these `BoxConstraint`s that minimises the difference between the /// returned `Size`'s aspect ratio and `aspect_ratio`, where *aspect ratio* is defined as /// `height / width`. /// /// If multiple `Size`s give the optimal `aspect_ratio`, then the one with the `width` nearest /// the supplied width will be used. Specifically, if `width == 0.0` then the smallest possible /// `Size` will be chosen, and likewise if `width == f64::INFINITY`, then the largest `Size` /// will be chosen. /// /// Use this function when maintaining an aspect ratio is more important than minimizing the /// distance between input and output size width and height. pub fn constrain_aspect_ratio(&self, aspect_ratio: f64, width: f64) -> Size { // Minimizing/maximizing based on aspect ratio seems complicated, but in reality everything // is linear, so the amount of work to do is low. let ideal_size = Size { width, height: width * aspect_ratio, }; // It may be possible to remove these in the future if the invariant is checked elsewhere. let aspect_ratio = aspect_ratio.abs(); let width = width.abs(); // Firstly check if we can simply return the exact requested if self.contains(ideal_size) { return ideal_size; } // Then we check if any `Size`s with our desired aspect ratio are inside the constraints. // TODO this currently outputs garbage when things are < 0. let min_w_min_h = self.min.height / self.min.width; let max_w_min_h = self.min.height / self.max.width; let min_w_max_h = self.max.height / self.min.width; let max_w_max_h = self.max.height / self.max.width; // When the aspect ratio line crosses the constraints, the closest point must be one of the // two points where the aspect ratio enters/exits. // When the aspect ratio line doesn't intersect the box of possible sizes, the closest // point must be either (max width, min height) or (max height, min width). So all we have // to do is check which one of these has the closest aspect ratio. // Check each possible intersection (or not) of the aspect ratio line with the constraints if aspect_ratio > min_w_max_h { // outside max height min width Size { width: self.min.width, height: self.max.height, } } else if aspect_ratio < max_w_min_h { // outside min height max width Size { width: self.max.width, height: self.min.height, } } else if aspect_ratio > min_w_min_h { // hits the constraints on the min width line if width < self.min.width { // we take the point on the min width Size { width: self.min.width, height: self.min.width * aspect_ratio, } } else if aspect_ratio < max_w_max_h { // exits through max.width Size { width: self.max.width, height: self.max.width * aspect_ratio, } } else { // exits through max.height Size { width: self.max.height * aspect_ratio.recip(), height: self.max.height, } } } else { // final case is where we hit constraints on the min height line if width < self.min.width { // take the point on the min height Size { width: self.min.height * aspect_ratio.recip(), height: self.min.height, } } else if aspect_ratio > max_w_max_h { // exit thru max height Size { width: self.max.height * aspect_ratio.recip(), height: self.max.height, } } else { // exit thru max width Size { width: self.max.width, height: self.max.width * aspect_ratio, } } } } /// Sets the max on a given axis to infinity. pub fn unbound_max(&self, axis: Axis) -> Self { match axis { Axis::Horizontal => self.unbound_max_width(), Axis::Vertical => self.unbound_max_height(), } } /// Sets max width to infinity. pub fn unbound_max_width(&self) -> Self { let mut max = self.max(); max.width = f64::INFINITY; BoxConstraints::new(self.min(), max) } /// Sets max height to infinity. pub fn unbound_max_height(&self) -> Self { let mut max = self.max(); max.height = f64::INFINITY; BoxConstraints::new(self.min(), max) } /// Shrinks the max dimension on the given axis. /// Does NOT shrink beyond min. pub fn shrink_max_to(&self, axis: Axis, dim: f64) -> Self { match axis { Axis::Horizontal => self.shrink_max_width_to(dim), Axis::Vertical => self.shrink_max_height_to(dim), } } /// Shrinks the max width to dim. /// Does NOT shrink beyond min width. pub fn shrink_max_width_to(&self, dim: f64) -> Self { let mut max = self.max(); max.width = f64::max(dim, self.min().width); BoxConstraints::new(self.min(), max) } /// Shrinks the max height to dim. /// Does NOT shrink beyond min height. pub fn shrink_max_height_to(&self, dim: f64) -> Self { let mut max = self.max(); max.height = f64::max(dim, self.min().height); BoxConstraints::new(self.min(), max) } } #[cfg(test)] mod tests { use super::*; use test_log::test; fn bc(min_width: f64, min_height: f64, max_width: f64, max_height: f64) -> BoxConstraints { BoxConstraints::new( Size::new(min_width, min_height), Size::new(max_width, max_height), ) } #[test] fn constrain_aspect_ratio() { for (bc, aspect_ratio, width, output) in [ // The ideal size lies within the constraints (bc(0.0, 0.0, 100.0, 100.0), 1.0, 50.0, Size::new(50.0, 50.0)), (bc(0.0, 10.0, 90.0, 100.0), 1.0, 50.0, Size::new(50.0, 50.0)), // The correct aspect ratio is available (but not width) // min height ( bc(10.0, 10.0, 100.0, 100.0), 1.0, 5.0, Size::new(10.0, 10.0), ), ( bc(40.0, 90.0, 60.0, 100.0), 2.0, 30.0, Size::new(45.0, 90.0), ), ( bc(10.0, 10.0, 100.0, 100.0), 0.5, 5.0, Size::new(20.0, 10.0), ), // min width ( bc(10.0, 10.0, 100.0, 100.0), 2.0, 5.0, Size::new(10.0, 20.0), ), ( bc(90.0, 40.0, 100.0, 60.0), 0.5, 60.0, Size::new(90.0, 45.0), ), ( bc(50.0, 0.0, 50.0, 100.0), 1.0, 100.0, Size::new(50.0, 50.0), ), // max height ( bc(10.0, 10.0, 100.0, 100.0), 2.0, 105.0, Size::new(50.0, 100.0), ), ( bc(10.0, 10.0, 100.0, 100.0), 0.5, 105.0, Size::new(100.0, 50.0), ), // The correct aspet ratio is not available ( bc(20.0, 20.0, 40.0, 40.0), 10.0, 30.0, Size::new(20.0, 40.0), ), (bc(20.0, 20.0, 40.0, 40.0), 0.1, 30.0, Size::new(40.0, 20.0)), // non-finite ( bc(50.0, 0.0, 50.0, f64::INFINITY), 1.0, 100.0, Size::new(50.0, 50.0), ), ] .iter() { assert_eq!( bc.constrain_aspect_ratio(*aspect_ratio, *width), *output, "bc:{bc:?}, ar:{aspect_ratio}, w:{width}" ); } } #[test] fn unbounded() { assert!(!BoxConstraints::UNBOUNDED.is_width_bounded()); assert!(!BoxConstraints::UNBOUNDED.is_height_bounded()); assert_eq!(BoxConstraints::UNBOUNDED.min(), Size::ZERO); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/window.rs
druid/src/window.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Management of multiple windows. use std::collections::{HashMap, VecDeque}; use std::mem; use tracing::{error, info, trace_span}; // Automatically defaults to std::time::Instant on non Wasm platforms use instant::Instant; use crate::piet::{Color, Piet, RenderContext}; use crate::shell::{text::InputHandler, Counter, Cursor, Region, TextFieldToken, WindowHandle}; use crate::app::{PendingWindow, WindowSizePolicy}; use crate::contexts::ContextState; use crate::core::{CommandQueue, FocusChange, WidgetState}; use crate::debug_state::DebugState; use crate::menu::{MenuItemId, MenuManager}; use crate::text::TextFieldRegistration; use crate::widget::LabelText; use crate::win_handler::RUN_COMMANDS_TOKEN; use crate::{ BoxConstraints, Data, Env, Event, EventCtx, ExtEventSink, Handled, InternalEvent, InternalLifeCycle, LayoutCtx, LifeCycle, LifeCycleCtx, Menu, PaintCtx, Point, Size, TimerToken, UpdateCtx, ViewContext, Widget, WidgetId, WidgetPod, }; pub type ImeUpdateFn = dyn FnOnce(crate::shell::text::Event); /// A unique identifier for a window. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct WindowId(u64); /// Per-window state not owned by user code. pub struct Window<T> { pub(crate) id: WindowId, pub(crate) root: WidgetPod<T, Box<dyn Widget<T>>>, pub(crate) title: LabelText<T>, size_policy: WindowSizePolicy, size: Size, invalid: Region, pub(crate) menu: Option<MenuManager<T>>, pub(crate) context_menu: Option<(MenuManager<T>, Point)>, // This will be `Some` whenever the most recently displayed frame was an animation frame. pub(crate) last_anim: Option<Instant>, pub(crate) last_mouse_pos: Option<Point>, pub(crate) focus: Option<WidgetId>, pub(crate) handle: WindowHandle, pub(crate) timers: HashMap<TimerToken, WidgetId>, pub(crate) pending_text_registrations: Vec<TextFieldRegistration>, pub(crate) transparent: bool, pub(crate) ime_handlers: Vec<(TextFieldToken, TextFieldRegistration)>, ext_handle: ExtEventSink, pub(crate) ime_focus_change: Option<Option<TextFieldToken>>, } impl<T> Window<T> { pub(crate) fn new( id: WindowId, handle: WindowHandle, pending: PendingWindow<T>, ext_handle: ExtEventSink, ) -> Window<T> { Window { id, root: WidgetPod::new(pending.root), size_policy: pending.size_policy, size: Size::ZERO, invalid: Region::EMPTY, title: pending.title, transparent: pending.transparent, menu: pending.menu, context_menu: None, last_anim: None, last_mouse_pos: None, focus: None, handle, timers: HashMap::new(), ext_handle, ime_handlers: Vec::new(), ime_focus_change: None, pending_text_registrations: Vec::new(), } } } impl<T: Data> Window<T> { /// `true` iff any child requested an animation frame since the last `AnimFrame` event. pub(crate) fn wants_animation_frame(&self) -> bool { self.root.state().request_anim } pub(crate) fn focus_chain(&self) -> &[WidgetId] { &self.root.state().focus_chain } /// Returns `true` if the provided widget may be in this window, /// but it may also be a false positive. /// However when this returns `false` the widget is definitely not in this window. pub(crate) fn may_contain_widget(&self, widget_id: WidgetId) -> bool { // The bloom filter we're checking can return false positives. widget_id == self.root.id() || self.root.state().children.may_contain(&widget_id) } pub(crate) fn menu_cmd( &mut self, queue: &mut CommandQueue, cmd_id: MenuItemId, data: &mut T, env: &Env, ) { if let Some(menu) = &mut self.menu { menu.event(queue, Some(self.id), cmd_id, data, env); } if let Some((menu, _)) = &mut self.context_menu { menu.event(queue, Some(self.id), cmd_id, data, env); } } pub(crate) fn show_context_menu(&mut self, menu: Menu<T>, point: Point, data: &T, env: &Env) { let mut manager = MenuManager::new_for_popup(menu); self.handle .show_context_menu(manager.initialize(Some(self.id), data, env), point); self.context_menu = Some((manager, point)); } /// On macos we need to update the global application menu to be the menu /// for the current window. #[cfg(target_os = "macos")] pub(crate) fn macos_update_app_menu(&mut self, data: &T, env: &Env) { if let Some(menu) = self.menu.as_mut() { self.handle.set_menu(menu.refresh(data, env)); } } fn post_event_processing( &mut self, widget_state: &mut WidgetState, queue: &mut CommandQueue, data: &T, env: &Env, process_commands: bool, ) { // If children are changed during the handling of an event, // we need to send RouteWidgetAdded now, so that they are ready for update/layout. if widget_state.children_changed { // Anytime widgets are removed we check and see if any of those // widgets had IME sessions and unregister them if so. let Window { ime_handlers, handle, .. } = self; ime_handlers.retain(|(token, v)| { let will_retain = v.is_alive(); if !will_retain { tracing::debug!("{:?} removed", token); handle.remove_text_field(*token); } will_retain }); self.lifecycle( queue, &LifeCycle::Internal(InternalLifeCycle::RouteWidgetAdded), data, env, false, ); } if widget_state.children_view_context_changed && !widget_state.needs_layout { let event = LifeCycle::Internal(InternalLifeCycle::RouteViewContextChanged(ViewContext { window_origin: Point::ORIGIN, // not the same as the root widget's origin last_mouse_position: self.last_mouse_pos, clip: self.size.to_rect(), })); self.lifecycle(queue, &event, data, env, false); } // Update the disabled state if necessary // Always do this before updating the focus-chain if widget_state.tree_disabled_changed() { let event = LifeCycle::Internal(InternalLifeCycle::RouteDisabledChanged); self.lifecycle(queue, &event, data, env, false); } // Update the focus-chain if necessary // Always do this before sending focus change, since this event updates the focus chain. if widget_state.update_focus_chain { let event = LifeCycle::BuildFocusChain; self.lifecycle(queue, &event, data, env, false); } self.update_focus(widget_state, queue, data, env); // If we need a new paint pass, make sure druid-shell knows it. if self.wants_animation_frame() { self.handle.request_anim_frame(); } self.invalid.union_with(&widget_state.invalid); for ime_field in self.pending_text_registrations.drain(..) { let token = self.handle.add_text_field(); tracing::debug!("{:?} added", token); self.ime_handlers.push((token, ime_field)); } // If there are any commands and they should be processed if process_commands && !queue.is_empty() { // Ask the handler to call us back on idle // so we can process them in a new event/update pass. if let Some(mut handle) = self.handle.get_idle_handle() { handle.schedule_idle(RUN_COMMANDS_TOKEN); } else { error!("failed to get idle handle"); } } } pub(crate) fn event( &mut self, queue: &mut CommandQueue, event: Event, data: &mut T, env: &Env, ) -> Handled { match &event { Event::WindowSize(size) => self.size = *size, Event::MouseDown(e) | Event::MouseUp(e) | Event::MouseMove(e) | Event::Wheel(e) => { self.last_mouse_pos = Some(e.pos) } Event::Internal(InternalEvent::MouseLeave) => self.last_mouse_pos = None, _ => (), } let event = match event { Event::Timer(token) => { if let Some(widget_id) = self.timers.remove(&token) { Event::Internal(InternalEvent::RouteTimer(token, widget_id)) } else { error!("No widget found for timer {:?}", token); return Handled::No; } } other => other, }; if let Event::WindowConnected = event { self.lifecycle( queue, &LifeCycle::Internal(InternalLifeCycle::RouteWidgetAdded), data, env, false, ); } let mut widget_state = WidgetState::new(self.root.id(), Some(self.size)); let is_handled = { let mut state = ContextState::new::<T>( queue, &self.ext_handle, &self.handle, self.id, self.focus, &mut self.timers, &mut self.pending_text_registrations, ); let mut notifications = VecDeque::new(); let mut ctx = EventCtx { state: &mut state, notifications: &mut notifications, widget_state: &mut widget_state, is_handled: false, is_root: true, }; { let _span = trace_span!("event"); let _span = _span.enter(); self.root.event(&mut ctx, &event, data, env); } ctx.notifications.retain(|n| n.warn_if_unused_set()); if !ctx.notifications.is_empty() { info!("{} unhandled notifications:", ctx.notifications.len()); for (i, n) in ctx.notifications.iter().enumerate() { info!("{}: {:?}", i, n); } info!( "if this was intended use EventCtx::submit_notification_without_warning instead" ); } Handled::from(ctx.is_handled) }; if let Some(cursor) = &widget_state.cursor { self.handle.set_cursor(cursor); } else if matches!( event, Event::MouseMove(..) | Event::Internal(InternalEvent::MouseLeave) ) { self.handle.set_cursor(&Cursor::Arrow); } if matches!( (event, self.size_policy), (Event::WindowSize(_), WindowSizePolicy::Content) ) { // Because our initial size can be zero, the window system won't ask us to paint. // So layout ourselves and hopefully we resize self.layout(queue, data, env); } self.post_event_processing(&mut widget_state, queue, data, env, false); is_handled } pub(crate) fn lifecycle( &mut self, queue: &mut CommandQueue, event: &LifeCycle, data: &T, env: &Env, process_commands: bool, ) { let mut widget_state = WidgetState::new(self.root.id(), Some(self.size)); let mut state = ContextState::new::<T>( queue, &self.ext_handle, &self.handle, self.id, self.focus, &mut self.timers, &mut self.pending_text_registrations, ); let mut ctx = LifeCycleCtx { state: &mut state, widget_state: &mut widget_state, }; { let _span = trace_span!("lifecycle"); let _span = _span.enter(); self.root.lifecycle(&mut ctx, event, data, env); } self.post_event_processing(&mut widget_state, queue, data, env, process_commands); } pub(crate) fn update(&mut self, queue: &mut CommandQueue, data: &T, env: &Env) { self.update_title(data, env); let mut widget_state = WidgetState::new(self.root.id(), Some(self.size)); let mut state = ContextState::new::<T>( queue, &self.ext_handle, &self.handle, self.id, self.focus, &mut self.timers, &mut self.pending_text_registrations, ); let mut update_ctx = UpdateCtx { widget_state: &mut widget_state, state: &mut state, prev_env: None, env, }; { let _span = trace_span!("update"); let _span = _span.enter(); self.root.update(&mut update_ctx, data, env); } if let Some(cursor) = &widget_state.cursor { self.handle.set_cursor(cursor); } self.post_event_processing(&mut widget_state, queue, data, env, false); } pub(crate) fn invalidate_and_finalize(&mut self) { if self.root.state().needs_layout { self.handle.invalidate(); } else { for rect in self.invalid.rects() { self.handle.invalidate_rect(*rect); } } self.invalid.clear(); } #[allow(dead_code)] pub(crate) fn invalid(&self) -> &Region { &self.invalid } #[allow(dead_code)] pub(crate) fn invalid_mut(&mut self) -> &mut Region { &mut self.invalid } /// Get ready for painting, by doing layout and sending an `AnimFrame` event. pub(crate) fn prepare_paint(&mut self, queue: &mut CommandQueue, data: &mut T, env: &Env) { let now = Instant::now(); // TODO: this calculation uses wall-clock time of the paint call, which // potentially has jitter. // // See https://github.com/linebender/druid/issues/85 for discussion. let last = self.last_anim.take(); let elapsed_ns = last.map(|t| now.duration_since(t).as_nanos()).unwrap_or(0) as u64; if self.wants_animation_frame() { self.event(queue, Event::AnimFrame(elapsed_ns), data, env); self.last_anim = Some(now); } } pub(crate) fn do_paint( &mut self, piet: &mut Piet, invalid: &Region, queue: &mut CommandQueue, data: &T, env: &Env, ) { if self.root.state().needs_layout { self.layout(queue, data, env); } for &r in invalid.rects() { piet.clear( Some(r), if self.transparent { Color::TRANSPARENT } else { env.get(crate::theme::WINDOW_BACKGROUND_COLOR) }, ); } self.paint(piet, invalid, queue, data, env); } fn layout(&mut self, queue: &mut CommandQueue, data: &T, env: &Env) { let mut widget_state = WidgetState::new(self.root.id(), Some(self.size)); let mut state = ContextState::new::<T>( queue, &self.ext_handle, &self.handle, self.id, self.focus, &mut self.timers, &mut self.pending_text_registrations, ); let mut layout_ctx = LayoutCtx { state: &mut state, widget_state: &mut widget_state, }; let bc = match self.size_policy { WindowSizePolicy::User => BoxConstraints::tight(self.size), WindowSizePolicy::Content => BoxConstraints::UNBOUNDED, }; let content_size = { let _span = trace_span!("layout"); let _span = _span.enter(); self.root.layout(&mut layout_ctx, &bc, data, env) }; if let WindowSizePolicy::Content = self.size_policy { let insets = self.handle.content_insets(); let full_size = (content_size.to_rect() + insets).size(); if self.size != full_size { self.size = full_size; self.handle.set_size(full_size) } } self.root.set_origin(&mut layout_ctx, Point::ORIGIN); self.post_event_processing(&mut widget_state, queue, data, env, true); } /// only expose `layout` for testing; normally it is called as part of `do_paint` #[cfg(not(target_arch = "wasm32"))] pub(crate) fn just_layout(&mut self, queue: &mut CommandQueue, data: &T, env: &Env) { self.layout(queue, data, env) } fn paint( &mut self, piet: &mut Piet, invalid: &Region, queue: &mut CommandQueue, data: &T, env: &Env, ) { let widget_state = WidgetState::new(self.root.id(), Some(self.size)); let mut state = ContextState::new::<T>( queue, &self.ext_handle, &self.handle, self.id, self.focus, &mut self.timers, &mut self.pending_text_registrations, ); let mut ctx = PaintCtx { render_ctx: piet, state: &mut state, widget_state: &widget_state, z_ops: Vec::new(), region: invalid.clone(), depth: 0, }; let root = &mut self.root; trace_span!("paint").in_scope(|| { ctx.with_child_ctx(invalid.clone(), |ctx| root.paint_raw(ctx, data, env)); }); let mut z_ops = mem::take(&mut ctx.z_ops); z_ops.sort_by_key(|k| k.z_index); for z_op in z_ops.into_iter() { ctx.with_child_ctx(invalid.clone(), |ctx| { ctx.with_save(|ctx| { ctx.render_ctx.transform(z_op.transform); (z_op.paint_func)(ctx); }); }); } if self.wants_animation_frame() { self.handle.request_anim_frame(); } } /// Get a best-effort representation of the entire widget tree for debug purposes. pub fn root_debug_state(&self, data: &T) -> DebugState { self.root.widget().debug_state(data) } pub(crate) fn update_title(&mut self, data: &T, env: &Env) { if self.title.resolve(data, env) { self.handle.set_title(&self.title.display_text()); } } pub(crate) fn update_menu(&mut self, data: &T, env: &Env) { if let Some(menu) = &mut self.menu { if let Some(new_menu) = menu.update(Some(self.id), data, env) { self.handle.set_menu(new_menu); } } if let Some((menu, point)) = &mut self.context_menu { if let Some(new_menu) = menu.update(Some(self.id), data, env) { self.handle.show_context_menu(new_menu, *point); } } } pub(crate) fn get_ime_handler( &mut self, req_token: TextFieldToken, mutable: bool, ) -> Box<dyn InputHandler> { self.ime_handlers .iter() .find(|(token, _)| req_token == *token) .and_then(|(_, reg)| reg.document.acquire(mutable)) .unwrap() } fn update_focus( &mut self, widget_state: &mut WidgetState, queue: &mut CommandQueue, data: &T, env: &Env, ) { if let Some(focus_req) = widget_state.request_focus.take() { let old = self.focus; let new = self.widget_for_focus_request(focus_req); // Only send RouteFocusChanged in case there's actual change if old != new { let event = LifeCycle::Internal(InternalLifeCycle::RouteFocusChanged { old, new }); self.lifecycle(queue, &event, data, env, false); self.focus = new; // check if the newly focused widget has an IME session, and // notify the system if so. // // If you're here because a profiler sent you: I guess I should've // used a hashmap? let old_was_ime = old .map(|old| { self.ime_handlers .iter() .any(|(_, sesh)| sesh.widget_id == old) }) .unwrap_or(false); let maybe_active_text_field = self .ime_handlers .iter() .find(|(_, sesh)| Some(sesh.widget_id) == self.focus) .map(|(token, _)| *token); // we call this on every focus change; we could call it less but does it matter? self.ime_focus_change = if maybe_active_text_field.is_some() { Some(maybe_active_text_field) } else if old_was_ime { Some(None) } else { None }; } } } /// Create a function that can invalidate the provided widget's text state. /// /// This will be called from outside the main app state in order to avoid /// reentrancy problems. pub(crate) fn ime_invalidation_fn(&self, widget: WidgetId) -> Option<Box<ImeUpdateFn>> { let token = self .ime_handlers .iter() .find(|(_, reg)| reg.widget_id == widget) .map(|(t, _)| *t)?; let window_handle = self.handle.clone(); Some(Box::new(move |event| { window_handle.update_text_field(token, event) })) } /// Release a lock on an IME session, returning a `WidgetId` if the lock was mutable. /// /// After a mutable lock is released, the widget needs to be notified so that /// it can update any internal state. pub(crate) fn release_ime_lock(&mut self, req_token: TextFieldToken) -> Option<WidgetId> { self.ime_handlers .iter() .find(|(token, _)| req_token == *token) .and_then(|(_, reg)| reg.document.release().then_some(reg.widget_id)) } fn widget_for_focus_request(&self, focus: FocusChange) -> Option<WidgetId> { match focus { FocusChange::Resign => None, FocusChange::Focus(id) => Some(id), FocusChange::Next => self.widget_from_focus_chain(true), FocusChange::Previous => self.widget_from_focus_chain(false), } } fn widget_from_focus_chain(&self, forward: bool) -> Option<WidgetId> { self.focus.and_then(|focus| { self.focus_chain() .iter() // Find where the focused widget is in the focus chain .position(|id| id == &focus) .map(|idx| { // Return the id that's next to it in the focus chain let len = self.focus_chain().len(); let new_idx = if forward { (idx + 1) % len } else { (idx + len - 1) % len }; self.focus_chain()[new_idx] }) .or_else(|| { // If the currently focused widget isn't in the focus chain, // then we'll just return the first/last entry of the chain, if any. if forward { self.focus_chain().first().copied() } else { self.focus_chain().last().copied() } }) }) } } impl WindowId { /// Allocate a new, unique window id. pub fn next() -> WindowId { static WINDOW_COUNTER: Counter = Counter::new(); WindowId(WINDOW_COUNTER.next()) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/data.rs
druid/src/data.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Traits for handling value types. use std::ptr; use std::rc::Rc; use std::sync::Arc; use crate::kurbo::{self, ParamCurve}; use crate::piet; use crate::shell::Scale; pub use druid_derive::Data; use piet::ImageBuf; /// A trait used to represent value types. /// /// These should be cheap to compare and cheap to clone. /// /// See <https://sinusoid.es/lager/model.html#id2> for a well-written /// explanation of value types (albeit within a C++ context). /// /// ## Derive macro /// /// In general, you can use `derive` to generate a `Data` impl for your types. /// /// ``` /// # use std::sync::Arc; /// # use druid::Data; /// #[derive(Clone, Data)] /// enum Foo { /// Case1(i32, f32), /// Case2 { a: String, b: Arc<i32> } /// } /// ``` /// /// ### Derive macro attributes /// /// There are a number of field attributes available for use with `derive(Data)`. /// /// - **`#[data(ignore)]`** /// /// Skip this field when computing `same`ness. /// /// If the type you are implementing `Data` on contains some fields that are /// not relevant to the `Data` impl, you can ignore them with this attribute. /// /// - **`#[data(same_fn = "path")]`** /// /// Use a specific function to compute `same`ness. /// /// By default, derived implementations of `Data` just call [`Data::same`] /// recursively on each field. With this attribute, you can specify a /// custom function that will be used instead. /// /// This function must have a signature in the form, `fn<T>(&T, &T) -> bool`, /// where `T` is the type of the field. /// /// ## Collection types /// /// `Data` is not implemented for `std` collection types, because comparing them /// can be expensive. To use collection types with Druid, there are two easy options: /// either wrap the collection in an `Arc`, or build `druid` with the `im` feature, /// which adds `Data` implementations to the collections from the [`im` crate], /// a set of immutable data structures that fit nicely with Druid. /// /// If the `im` feature is used, the `im` crate is reexported from the root /// of the `druid` crate. /// /// ### Example: /// /// ``` /// # use std::path::PathBuf; /// # use std::time::Instant; /// # use druid::Data; /// #[derive(Clone, Data)] /// struct PathEntry { /// // There's no Data impl for PathBuf, but no problem /// #[data(eq)] /// path: PathBuf, /// priority: usize, /// // This field is not part of our data model. /// #[data(ignore)] /// last_read: Instant, /// } /// ``` /// /// ## C-style enums /// /// In the case of a "c-style" enum (one that only contains unit variants, /// that is where no variant has fields), the implementation that is generated /// checks for equality. Therefore, such types must also implement `PartialEq`. /// /// [`im` crate]: https://crates.io/crates/im pub trait Data: Clone + 'static { //// ANCHOR: same_fn /// Determine whether two values are the same. /// /// This is intended to always be a fast operation. If it returns /// `true`, the two values *must* be equal, but two equal values /// need not be considered the same here, as will often be the /// case when two copies are separately allocated. /// /// Note that "equal" above has a slightly different meaning than /// `PartialEq`, for example two floating point NaN values should /// be considered equal when they have the same bit representation. fn same(&self, other: &Self) -> bool; //// ANCHOR_END: same_fn } /// An impl of `Data` suitable for simple types. /// /// The `same` method is implemented with equality, so the type should /// implement `Eq` at least. macro_rules! impl_data_simple { ($t:ty) => { impl Data for $t { fn same(&self, other: &Self) -> bool { self == other } } }; } // Standard library impls impl_data_simple!(i8); impl_data_simple!(i16); impl_data_simple!(i32); impl_data_simple!(i64); impl_data_simple!(i128); impl_data_simple!(isize); impl_data_simple!(u8); impl_data_simple!(u16); impl_data_simple!(u32); impl_data_simple!(u64); impl_data_simple!(u128); impl_data_simple!(usize); impl_data_simple!(char); impl_data_simple!(bool); impl_data_simple!(std::num::NonZeroI8); impl_data_simple!(std::num::NonZeroI16); impl_data_simple!(std::num::NonZeroI32); impl_data_simple!(std::num::NonZeroI64); impl_data_simple!(std::num::NonZeroI128); impl_data_simple!(std::num::NonZeroIsize); impl_data_simple!(std::num::NonZeroU8); impl_data_simple!(std::num::NonZeroU16); impl_data_simple!(std::num::NonZeroU32); impl_data_simple!(std::num::NonZeroU64); impl_data_simple!(std::num::NonZeroU128); impl_data_simple!(std::num::NonZeroUsize); impl_data_simple!(std::time::SystemTime); impl_data_simple!(std::time::Instant); impl_data_simple!(std::time::Duration); impl_data_simple!(std::io::ErrorKind); impl_data_simple!(std::net::Ipv4Addr); impl_data_simple!(std::net::Ipv6Addr); impl_data_simple!(std::net::SocketAddrV4); impl_data_simple!(std::net::SocketAddrV6); impl_data_simple!(std::net::IpAddr); impl_data_simple!(std::net::SocketAddr); impl_data_simple!(std::ops::RangeFull); impl_data_simple!(druid::piet::InterpolationMode); #[cfg(feature = "chrono")] impl_data_simple!(chrono::Duration); #[cfg(feature = "chrono")] impl_data_simple!(chrono::naive::IsoWeek); #[cfg(feature = "chrono")] impl_data_simple!(chrono::naive::NaiveDate); #[cfg(feature = "chrono")] impl_data_simple!(chrono::naive::NaiveDateTime); #[cfg(feature = "chrono")] impl_data_simple!(chrono::naive::NaiveTime); //TODO: remove me!? impl_data_simple!(String); impl Data for &'static str { fn same(&self, other: &Self) -> bool { ptr::eq(*self, *other) } } impl Data for f32 { fn same(&self, other: &Self) -> bool { self.to_bits() == other.to_bits() } } impl Data for f64 { fn same(&self, other: &Self) -> bool { self.to_bits() == other.to_bits() } } /// Checks pointer equality. The internal value is not checked. impl<T: ?Sized + 'static> Data for Arc<T> { fn same(&self, other: &Self) -> bool { Arc::ptr_eq(self, other) } } impl<T: ?Sized + 'static> Data for std::sync::Weak<T> { fn same(&self, other: &Self) -> bool { std::sync::Weak::ptr_eq(self, other) } } impl<T: ?Sized + 'static> Data for Rc<T> { fn same(&self, other: &Self) -> bool { Rc::ptr_eq(self, other) } } impl<T: ?Sized + 'static> Data for std::rc::Weak<T> { fn same(&self, other: &Self) -> bool { std::rc::Weak::ptr_eq(self, other) } } impl<T: Data> Data for Option<T> { fn same(&self, other: &Self) -> bool { match (self, other) { (Some(a), Some(b)) => a.same(b), (None, None) => true, _ => false, } } } impl<T: Data, U: Data> Data for Result<T, U> { fn same(&self, other: &Self) -> bool { match (self, other) { (Ok(a), Ok(b)) => a.same(b), (Err(a), Err(b)) => a.same(b), _ => false, } } } impl Data for () { fn same(&self, _other: &Self) -> bool { true } } impl<T0: Data> Data for (T0,) { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) } } impl<T0: Data, T1: Data> Data for (T0, T1) { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) && self.1.same(&other.1) } } impl<T0: Data, T1: Data, T2: Data> Data for (T0, T1, T2) { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) && self.1.same(&other.1) && self.2.same(&other.2) } } impl<T0: Data, T1: Data, T2: Data, T3: Data> Data for (T0, T1, T2, T3) { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) && self.1.same(&other.1) && self.2.same(&other.2) && self.3.same(&other.3) } } impl<T0: Data, T1: Data, T2: Data, T3: Data, T4: Data> Data for (T0, T1, T2, T3, T4) { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) && self.1.same(&other.1) && self.2.same(&other.2) && self.3.same(&other.3) && self.4.same(&other.4) } } impl<T0: Data, T1: Data, T2: Data, T3: Data, T4: Data, T5: Data> Data for (T0, T1, T2, T3, T4, T5) { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) && self.1.same(&other.1) && self.2.same(&other.2) && self.3.same(&other.3) && self.4.same(&other.4) && self.5.same(&other.5) } } impl<T: 'static + ?Sized> Data for std::marker::PhantomData<T> { fn same(&self, _other: &Self) -> bool { // zero-sized types true } } impl<T: 'static> Data for std::mem::Discriminant<T> { fn same(&self, other: &Self) -> bool { *self == *other } } impl<T: 'static + Data> Data for std::mem::ManuallyDrop<T> { fn same(&self, other: &Self) -> bool { (**self).same(&**other) } } impl<T: Data> Data for std::num::Wrapping<T> { fn same(&self, other: &Self) -> bool { self.0.same(&other.0) } } impl<T: Data> Data for std::ops::Range<T> { fn same(&self, other: &Self) -> bool { self.start.same(&other.start) && self.end.same(&other.end) } } impl<T: Data> Data for std::ops::RangeFrom<T> { fn same(&self, other: &Self) -> bool { self.start.same(&other.start) } } impl<T: Data> Data for std::ops::RangeInclusive<T> { fn same(&self, other: &Self) -> bool { self.start().same(other.start()) && self.end().same(other.end()) } } impl<T: Data> Data for std::ops::RangeTo<T> { fn same(&self, other: &Self) -> bool { self.end.same(&other.end) } } impl<T: Data> Data for std::ops::RangeToInclusive<T> { fn same(&self, other: &Self) -> bool { self.end.same(&other.end) } } impl<T: Data> Data for std::ops::Bound<T> { fn same(&self, other: &Self) -> bool { use std::ops::Bound::*; match (self, other) { (Included(t1), Included(t2)) if t1.same(t2) => true, (Excluded(t1), Excluded(t2)) if t1.same(t2) => true, (Unbounded, Unbounded) => true, _ => false, } } } // druid & deps impls impl Data for Scale { fn same(&self, other: &Self) -> bool { self == other } } impl Data for kurbo::Point { fn same(&self, other: &Self) -> bool { self.x.same(&other.x) && self.y.same(&other.y) } } impl Data for kurbo::Vec2 { fn same(&self, other: &Self) -> bool { self.x.same(&other.x) && self.y.same(&other.y) } } impl Data for kurbo::Size { fn same(&self, other: &Self) -> bool { self.width.same(&other.width) && self.height.same(&other.height) } } impl Data for kurbo::Affine { fn same(&self, other: &Self) -> bool { let rhs = self.as_coeffs(); let lhs = other.as_coeffs(); rhs.iter().zip(lhs.iter()).all(|(r, l)| r.same(l)) } } impl Data for kurbo::Insets { fn same(&self, other: &Self) -> bool { self.x0.same(&other.x0) && self.y0.same(&other.y0) && self.x1.same(&other.x1) && self.y1.same(&other.y1) } } impl Data for kurbo::Rect { fn same(&self, other: &Self) -> bool { self.x0.same(&other.x0) && self.y0.same(&other.y0) && self.x1.same(&other.x1) && self.y1.same(&other.y1) } } impl Data for kurbo::RoundedRectRadii { fn same(&self, other: &Self) -> bool { self.top_left.same(&other.top_left) && self.top_right.same(&other.top_right) && self.bottom_left.same(&other.bottom_left) && self.bottom_right.same(&other.bottom_right) } } impl Data for kurbo::RoundedRect { fn same(&self, other: &Self) -> bool { self.rect().same(&other.rect()) && self.radii().same(&other.radii()) } } impl Data for kurbo::Arc { fn same(&self, other: &Self) -> bool { self.center.same(&other.center) && self.radii.same(&other.radii) && self.start_angle.same(&other.start_angle) && self.sweep_angle.same(&other.sweep_angle) && self.x_rotation.same(&other.x_rotation) } } impl Data for kurbo::PathEl { fn same(&self, other: &Self) -> bool { use kurbo::PathEl::*; match (self, other) { (MoveTo(p1), MoveTo(p2)) => p1.same(p2), (LineTo(p1), LineTo(p2)) => p1.same(p2), (QuadTo(x1, y1), QuadTo(x2, y2)) => x1.same(x2) && y1.same(y2), (CurveTo(x1, y1, z1), CurveTo(x2, y2, z2)) => x1.same(x2) && y1.same(y2) && z1.same(z2), (ClosePath, ClosePath) => true, _ => false, } } } impl Data for kurbo::PathSeg { fn same(&self, other: &Self) -> bool { use kurbo::PathSeg; match (self, other) { (PathSeg::Line(l1), PathSeg::Line(l2)) => l1.same(l2), (PathSeg::Quad(q1), PathSeg::Quad(q2)) => q1.same(q2), (PathSeg::Cubic(c1), PathSeg::Cubic(c2)) => c1.same(c2), _ => false, } } } impl Data for kurbo::BezPath { fn same(&self, other: &Self) -> bool { let rhs = self.elements(); let lhs = other.elements(); if rhs.len() == lhs.len() { rhs.iter().zip(lhs.iter()).all(|(x, y)| x.same(y)) } else { false } } } impl Data for kurbo::Circle { fn same(&self, other: &Self) -> bool { self.center.same(&other.center) && self.radius.same(&other.radius) } } impl Data for kurbo::CubicBez { fn same(&self, other: &Self) -> bool { self.p0.same(&other.p0) && self.p1.same(&other.p1) && self.p2.same(&other.p2) && self.p3.same(&other.p3) } } impl Data for kurbo::Line { fn same(&self, other: &Self) -> bool { self.p0.same(&other.p0) && self.p1.same(&other.p1) } } impl Data for kurbo::ConstPoint { fn same(&self, other: &Self) -> bool { self.eval(0.).same(&other.eval(0.)) } } impl Data for kurbo::QuadBez { fn same(&self, other: &Self) -> bool { self.p0.same(&other.p0) && self.p1.same(&other.p1) && self.p2.same(&other.p2) } } impl Data for piet::Color { fn same(&self, other: &Self) -> bool { self.as_rgba_u32().same(&other.as_rgba_u32()) } } impl Data for piet::FontFamily { fn same(&self, other: &Self) -> bool { self == other } } impl Data for piet::FontWeight { fn same(&self, other: &Self) -> bool { self == other } } impl Data for piet::FontStyle { fn same(&self, other: &Self) -> bool { self == other } } impl Data for piet::TextAlignment { fn same(&self, other: &Self) -> bool { self == other } } impl Data for ImageBuf { fn same(&self, other: &Self) -> bool { self.raw_pixels_shared().same(&other.raw_pixels_shared()) } } #[cfg(feature = "chrono")] impl<Tz: chrono::offset::TimeZone + 'static> Data for chrono::Date<Tz> { fn same(&self, other: &Self) -> bool { self == other } } #[cfg(feature = "chrono")] impl<Tz: chrono::offset::TimeZone + 'static> Data for chrono::DateTime<Tz> { fn same(&self, other: &Self) -> bool { self == other } } #[cfg(feature = "im")] impl<T: Data> Data for im::Vector<T> { fn same(&self, other: &Self) -> bool { // if a vec is small enough that it doesn't require an allocation // it is 'inline'; in this case a pointer comparison is meaningless. if self.is_inline() { self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a.same(b)) } else { self.ptr_eq(other) } } } #[cfg(feature = "im")] impl<K: Clone + 'static, V: Data> Data for im::HashMap<K, V> { fn same(&self, other: &Self) -> bool { self.ptr_eq(other) } } #[cfg(feature = "im")] impl<T: Data> Data for im::HashSet<T> { fn same(&self, other: &Self) -> bool { self.ptr_eq(other) } } #[cfg(feature = "im")] impl<K: Clone + 'static, V: Data> Data for im::OrdMap<K, V> { fn same(&self, other: &Self) -> bool { self.ptr_eq(other) } } #[cfg(feature = "im")] impl<T: Data> Data for im::OrdSet<T> { fn same(&self, other: &Self) -> bool { self.ptr_eq(other) } } impl<T: Data, const N: usize> Data for [T; N] { fn same(&self, other: &Self) -> bool { self.iter().zip(other.iter()).all(|(a, b)| a.same(b)) } } #[cfg(test)] mod test { use super::Data; use test_log::test; #[test] fn array_data() { let input = [1u8, 0, 0, 1, 0]; assert!(input.same(&[1u8, 0, 0, 1, 0])); assert!(!input.same(&[1u8, 1, 0, 1, 0])); } #[test] #[cfg(feature = "im")] fn im_data() { for len in 8..256 { let input = std::iter::repeat_n(0_u8, len).collect::<im::Vector<_>>(); let mut inp2 = input.clone(); assert!(input.same(&inp2)); inp2.set(len - 1, 98); assert!(!input.same(&inp2)); } } #[test] #[cfg(feature = "im")] fn im_vec_different_length() { let one = std::iter::repeat_n(0_u8, 9).collect::<im::Vector<_>>(); let two = std::iter::repeat_n(0_u8, 10).collect::<im::Vector<_>>(); assert!(!one.same(&two)); } #[test] fn static_strings() { let first = "test"; let same = "test"; let second = "test2"; assert!(!Data::same(&first, &second)); assert!(Data::same(&first, &first)); // although these are different, the compiler will notice that the string "test" is common, // intern it, and reuse it for all "text" `&'static str`s. assert!(Data::same(&first, &same)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/win_handler.rs
druid/src/win_handler.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! The implementation of the `WinHandler` trait (`druid-shell` integration). use std::any::{Any, TypeId}; use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use crate::kurbo::Size; use crate::piet::Piet; use crate::shell::{ text::InputHandler, Application, FileDialogToken, FileInfo, IdleToken, MouseEvent, Region, Scale, TextFieldToken, WinHandler, WindowHandle, }; use crate::app_delegate::{AppDelegate, DelegateCtx}; use crate::core::CommandQueue; use crate::ext_event::{ExtEventHost, ExtEventSink}; use crate::menu::{ContextMenu, MenuItemId, MenuManager}; use crate::window::{ImeUpdateFn, Window}; use crate::{ Command, Data, Env, Event, Handled, InternalEvent, KeyEvent, PlatformError, Selector, Target, TimerToken, WidgetId, WindowDesc, WindowId, }; use crate::app::{PendingWindow, WindowConfig}; use crate::command::sys as sys_cmd; use druid_shell::WindowBuilder; pub(crate) const RUN_COMMANDS_TOKEN: IdleToken = IdleToken::new(1); /// A token we are called back with if an external event was submitted. pub(crate) const EXT_EVENT_IDLE_TOKEN: IdleToken = IdleToken::new(2); /// The struct implements the `druid-shell` `WinHandler` trait. /// /// One `DruidHandler` exists per window. /// /// This is something of an internal detail and possibly we don't want to surface /// it publicly. pub struct DruidHandler<T> { /// The shared app state. pub(crate) app_state: AppState<T>, /// The id for the current window. window_id: WindowId, } /// The top level event handler. /// /// This corresponds to the `AppHandler` trait in `druid-shell`, which is only /// used to handle events that are not associated with a window. /// /// Currently, this means only menu items on macOS when no window is open. pub(crate) struct AppHandler<T> { app_state: AppState<T>, } /// State shared by all windows in the UI. #[derive(Clone)] pub(crate) struct AppState<T> { inner: Rc<RefCell<InnerAppState<T>>>, } /// The information for forwarding `druid-shell`'s file dialog reply to the right place. struct DialogInfo { /// The window to send the command to. id: WindowId, /// The command to send if the dialog is accepted. accept_cmd: Selector<FileInfo>, /// The command to send if the dialog is accepted with multiple files. accept_multiple_cmd: Selector<Vec<FileInfo>>, /// The command to send if the dialog is cancelled. cancel_cmd: Selector<()>, } struct InnerAppState<T> { app: Application, delegate: Option<Box<dyn AppDelegate<T>>>, command_queue: CommandQueue, file_dialogs: HashMap<FileDialogToken, DialogInfo>, ext_event_host: ExtEventHost, windows: Windows<T>, /// the application-level menu, only set on macos and only if there /// are no open windows. root_menu: Option<MenuManager<T>>, /// The id of the most-recently-focused window that has a menu. On macOS, this /// is the window that's currently in charge of the app menu. #[allow(unused)] menu_window: Option<WindowId>, pub(crate) env: Env, pub(crate) data: T, ime_focus_change: Option<Box<dyn Fn()>>, } /// All active windows. struct Windows<T> { pending: HashMap<WindowId, PendingWindow<T>>, windows: HashMap<WindowId, Window<T>>, } impl<T> Windows<T> { fn connect(&mut self, id: WindowId, handle: WindowHandle, ext_handle: ExtEventSink) { if let Some(pending) = self.pending.remove(&id) { let win = Window::new(id, handle, pending, ext_handle); assert!(self.windows.insert(id, win).is_none(), "duplicate window"); } else { tracing::error!("no window for connecting handle {:?}", id); } } fn add(&mut self, id: WindowId, win: PendingWindow<T>) { assert!(self.pending.insert(id, win).is_none(), "duplicate pending"); } fn remove(&mut self, id: WindowId) -> Option<Window<T>> { self.windows.remove(&id) } fn iter_mut(&mut self) -> impl Iterator<Item = &'_ mut Window<T>> { self.windows.values_mut() } fn get(&self, id: WindowId) -> Option<&Window<T>> { self.windows.get(&id) } fn get_mut(&mut self, id: WindowId) -> Option<&mut Window<T>> { self.windows.get_mut(&id) } fn count(&self) -> usize { self.windows.len() + self.pending.len() } } impl<T> AppHandler<T> { pub(crate) fn new(app_state: AppState<T>) -> Self { Self { app_state } } } impl<T> AppState<T> { pub(crate) fn new( app: Application, data: T, env: Env, delegate: Option<Box<dyn AppDelegate<T>>>, ext_event_host: ExtEventHost, ) -> Self { let inner = Rc::new(RefCell::new(InnerAppState { app, delegate, command_queue: VecDeque::new(), file_dialogs: HashMap::new(), root_menu: None, menu_window: None, ext_event_host, data, env, windows: Windows::default(), ime_focus_change: None, })); AppState { inner } } pub(crate) fn app(&self) -> Application { self.inner.borrow().app.clone() } } impl<T: Data> InnerAppState<T> { fn handle_menu_cmd(&mut self, cmd_id: MenuItemId, window_id: Option<WindowId>) { let queue = &mut self.command_queue; let data = &mut self.data; let env = &self.env; match window_id { Some(id) => self .windows .get_mut(id) .map(|w| w.menu_cmd(queue, cmd_id, data, env)), None => self .root_menu .as_mut() .map(|m| m.event(queue, None, cmd_id, data, env)), }; } fn append_command(&mut self, cmd: Command) { self.command_queue.push_back(cmd); } /// A helper fn for setting up the `DelegateCtx`. Takes a closure with /// an arbitrary return type `R`, and returns `Some(R)` if an `AppDelegate` /// is configured. fn with_delegate<R, F>(&mut self, f: F) -> Option<R> where F: FnOnce(&mut dyn AppDelegate<T>, &mut T, &Env, &mut DelegateCtx) -> R, { let InnerAppState { ref mut delegate, ref mut command_queue, ref mut data, ref ext_event_host, ref env, .. } = self; let mut ctx = DelegateCtx { command_queue, app_data_type: TypeId::of::<T>(), ext_event_host, }; delegate .as_deref_mut() .map(|delegate| f(delegate, data, env, &mut ctx)) } fn delegate_event(&mut self, id: WindowId, event: Event) -> Option<Event> { if self.delegate.is_some() { self.with_delegate(|del, data, env, ctx| del.event(ctx, id, event, data, env)) .unwrap() } else { Some(event) } } fn delegate_cmd(&mut self, cmd: &Command) -> Handled { self.with_delegate(|del, data, env, ctx| del.command(ctx, cmd.target(), cmd, data, env)) .unwrap_or(Handled::No) } fn connect(&mut self, id: WindowId, handle: WindowHandle) { self.windows .connect(id, handle.clone(), self.ext_event_host.make_sink()); // If the external event host has no handle, it cannot wake us // when an event arrives. if self.ext_event_host.handle_window_id.is_none() { self.set_ext_event_idle_handler(id); } self.with_delegate(|del, data, env, ctx| del.window_added(id, handle, data, env, ctx)); } /// Called after this window has been closed by the platform. /// /// We clean up resources and notify the delegate, if necessary. fn remove_window(&mut self, window_id: WindowId) { self.with_delegate(|del, data, env, ctx| del.window_removed(window_id, data, env, ctx)); // when closing the last window: if let Some(mut win) = self.windows.remove(window_id) { if self.windows.windows.is_empty() { // on mac we need to keep the menu around self.root_menu = win.menu.take(); // If there are even no pending windows, we quit the run loop. if self.windows.count() == 0 { #[cfg(any(target_os = "windows", feature = "x11"))] self.app.quit(); } } } // if we are closing the window that is currently responsible for // waking us when external events arrive, we want to pass that responsibility // to another window. if self.ext_event_host.handle_window_id == Some(window_id) { self.ext_event_host.handle_window_id = None; // find any other live window let win_id = self.windows.windows.keys().find(|k| *k != &window_id); if let Some(any_other_window) = win_id.cloned() { self.set_ext_event_idle_handler(any_other_window); } } } /// Set the idle handle that will be used to wake us when external events arrive. fn set_ext_event_idle_handler(&mut self, id: WindowId) { if let Some(mut idle) = self .windows .get_mut(id) .and_then(|win| win.handle.get_idle_handle()) { if self.ext_event_host.has_pending_items() { idle.schedule_idle(EXT_EVENT_IDLE_TOKEN); } self.ext_event_host.set_idle(idle, id); } } /// triggered by a menu item or other command. /// /// This doesn't close the window; it calls the close method on the platform /// window handle; the platform should close the window, and then call /// our handlers `destroy()` method, at which point we can do our cleanup. fn request_close_window(&mut self, window_id: WindowId) { if let Some(win) = self.windows.get_mut(window_id) { win.handle.close(); } } /// Requests the platform to close all windows. fn request_close_all_windows(&mut self) { for win in self.windows.iter_mut() { win.handle.close(); } } fn show_window(&mut self, id: WindowId) { if let Some(win) = self.windows.get_mut(id) { win.handle.bring_to_front_and_focus(); } } fn hide_window(&mut self, id: WindowId) { if let Some(win) = self.windows.get_mut(id) { win.handle.hide(); } } fn configure_window(&mut self, config: &WindowConfig, id: WindowId) { if let Some(win) = self.windows.get_mut(id) { config.apply_to_handle(&mut win.handle); } } fn prepare_paint(&mut self, window_id: WindowId) { if let Some(win) = self.windows.get_mut(window_id) { win.prepare_paint(&mut self.command_queue, &mut self.data, &self.env); } self.do_update(); } fn paint(&mut self, window_id: WindowId, piet: &mut Piet, invalid: &Region) { if let Some(win) = self.windows.get_mut(window_id) { win.do_paint( piet, invalid, &mut self.command_queue, &self.data, &self.env, ); } } fn dispatch_cmd(&mut self, cmd: Command) -> Handled { let handled = self.delegate_cmd(&cmd); self.do_update(); if handled.is_handled() { return handled; } match cmd.target() { Target::Window(id) => { if cmd.is(sys_cmd::SHOW_CONTEXT_MENU) { self.show_context_menu(id, &cmd); return Handled::Yes; } if let Some(w) = self.windows.get_mut(id) { return if cmd.is(sys_cmd::CLOSE_WINDOW) { let handled = w.event( &mut self.command_queue, Event::WindowCloseRequested, &mut self.data, &self.env, ); if !handled.is_handled() { w.event( &mut self.command_queue, Event::WindowDisconnected, &mut self.data, &self.env, ); } handled } else { w.event( &mut self.command_queue, Event::Command(cmd), &mut self.data, &self.env, ) }; } } // in this case we send it to every window that might contain // this widget, breaking if the event is handled. Target::Widget(id) => { for w in self.windows.iter_mut().filter(|w| w.may_contain_widget(id)) { let event = Event::Internal(InternalEvent::TargetedCommand(cmd.clone())); if w.event(&mut self.command_queue, event, &mut self.data, &self.env) .is_handled() { return Handled::Yes; } } } Target::Global => { for w in self.windows.iter_mut() { let event = Event::Command(cmd.clone()); if w.event(&mut self.command_queue, event, &mut self.data, &self.env) .is_handled() { return Handled::Yes; } } } Target::Auto => { tracing::error!("{:?} reached window handler with `Target::Auto`", cmd); } } Handled::No } fn do_window_event(&mut self, source_id: WindowId, event: Event) -> Handled { match event { Event::Command(..) | Event::Internal(InternalEvent::TargetedCommand(..)) => { panic!("commands should be dispatched via dispatch_cmd"); } _ => (), } // if the event was swallowed by the delegate we consider it handled? let event = match self.delegate_event(source_id, event) { Some(event) => event, None => return Handled::Yes, }; if let Some(win) = self.windows.get_mut(source_id) { win.event(&mut self.command_queue, event, &mut self.data, &self.env) } else { Handled::No } } fn show_context_menu(&mut self, window_id: WindowId, cmd: &Command) { if let Some(win) = self.windows.get_mut(window_id) { match cmd .get_unchecked(sys_cmd::SHOW_CONTEXT_MENU) .take() .and_then(|b| b.downcast::<ContextMenu<T>>().ok()) { Some(menu) => { win.show_context_menu(menu.menu, menu.location, &self.data, &self.env) } None => panic!( "{} command must carry a ContextMenu<application state>.", sys_cmd::SHOW_CONTEXT_MENU ), } } } fn do_update(&mut self) { // we send `update` to all windows, not just the active one: for window in self.windows.iter_mut() { window.update(&mut self.command_queue, &self.data, &self.env); if let Some(focus_change) = window.ime_focus_change.take() { // we need to call this outside of the borrow, so we create a // closure that takes the correct window handle. yes, it feels // weird. let handle = window.handle.clone(); let f = Box::new(move || handle.set_focused_text_field(focus_change)); self.ime_focus_change = Some(f); } #[cfg(not(target_os = "macos"))] window.update_menu(&self.data, &self.env); } #[cfg(target_os = "macos")] { use druid_shell::platform::mac::ApplicationExt as _; let windows = &mut self.windows; let window = self.menu_window.and_then(|w| windows.get_mut(w)); if let Some(window) = window { window.update_menu(&self.data, &self.env); } else if let Some(root_menu) = &mut self.root_menu { if let Some(new_menu) = root_menu.update(None, &self.data, &self.env) { self.app.set_menu(new_menu); } } } self.invalidate_and_finalize(); } /// invalidate any window handles that need it. /// /// This should always be called at the end of an event update cycle, /// including for lifecycle events. fn invalidate_and_finalize(&mut self) { for win in self.windows.iter_mut() { win.invalidate_and_finalize(); } } fn ime_update_fn(&self, window_id: WindowId, widget_id: WidgetId) -> Option<Box<ImeUpdateFn>> { self.windows .get(window_id) .and_then(|window| window.ime_invalidation_fn(widget_id)) } fn get_ime_lock( &mut self, window_id: WindowId, token: TextFieldToken, mutable: bool, ) -> Box<dyn InputHandler> { self.windows .get_mut(window_id) .unwrap() .get_ime_handler(token, mutable) } /// Returns a `WidgetId` if the lock was mutable; the widget should be updated. fn release_ime_lock(&mut self, window_id: WindowId, token: TextFieldToken) -> Option<WidgetId> { self.windows .get_mut(window_id) .unwrap() .release_ime_lock(token) } fn window_got_focus(&mut self, window_id: WindowId) { if let Some(win) = self.windows.get_mut(window_id) { if win.menu.is_some() { self.menu_window = Some(window_id); } #[cfg(target_os = "macos")] win.macos_update_app_menu(&self.data, &self.env) } } } impl<T: Data> DruidHandler<T> { /// Note: the root widget doesn't go in here, because it gets added to the /// app state. pub(crate) fn new_shared(app_state: AppState<T>, window_id: WindowId) -> DruidHandler<T> { DruidHandler { app_state, window_id, } } } impl<T: Data> AppState<T> { pub(crate) fn data(&self) -> T { self.inner.borrow().data.clone() } pub(crate) fn env(&self) -> Env { self.inner.borrow().env.clone() } pub(crate) fn add_window(&self, id: WindowId, window: PendingWindow<T>) { self.inner.borrow_mut().windows.add(id, window); } fn connect_window(&mut self, window_id: WindowId, handle: WindowHandle) { self.inner.borrow_mut().connect(window_id, handle) } fn remove_window(&mut self, window_id: WindowId) { self.inner.borrow_mut().remove_window(window_id) } fn window_got_focus(&mut self, window_id: WindowId) { self.inner.borrow_mut().window_got_focus(window_id) } /// Send an event to the widget hierarchy. /// /// Returns `true` if the event produced an action. /// /// This is principally because in certain cases (such as keydown on Windows) /// the OS needs to know if an event was handled. fn do_window_event(&mut self, event: Event, window_id: WindowId) -> Handled { let result = self.inner.borrow_mut().do_window_event(window_id, event); self.process_commands(); self.inner.borrow_mut().do_update(); let ime_change = self.inner.borrow_mut().ime_focus_change.take(); if let Some(ime_change) = ime_change { (ime_change)() } result } fn prepare_paint_window(&mut self, window_id: WindowId) { self.inner.borrow_mut().prepare_paint(window_id); } fn paint_window(&mut self, window_id: WindowId, piet: &mut Piet, invalid: &Region) { self.inner.borrow_mut().paint(window_id, piet, invalid); } fn idle(&mut self, token: IdleToken) { match token { RUN_COMMANDS_TOKEN => { self.process_commands(); self.inner.borrow_mut().do_update(); } EXT_EVENT_IDLE_TOKEN => { self.process_ext_events(); self.process_commands(); self.inner.borrow_mut().do_update(); } other => tracing::warn!("unexpected idle token {:?}", other), } } pub(crate) fn handle_idle_callback(&mut self, cb: impl FnOnce(&mut T)) { let mut inner = self.inner.borrow_mut(); cb(&mut inner.data); inner.do_update(); } fn process_commands(&mut self) { loop { let next_cmd = self.inner.borrow_mut().command_queue.pop_front(); match next_cmd { Some(cmd) => self.handle_cmd(cmd), None => break, } } } fn process_ext_events(&mut self) { loop { let ext_cmd = self.inner.borrow_mut().ext_event_host.recv(); match ext_cmd { Some(cmd) => self.handle_cmd(cmd), None => break, } } } /// Handle a 'command' message from `druid-shell`. These map to an item /// in an application, window, or context (right-click) menu. /// /// If the menu is associated with a window (the general case) then /// the `window_id` will be `Some(_)`, otherwise (such as if no window /// is open but a menu exists, as on macOS) it will be `None`. fn handle_system_cmd(&mut self, cmd_id: u32, window_id: Option<WindowId>) { self.inner .borrow_mut() .handle_menu_cmd(MenuItemId::new(cmd_id), window_id); self.process_commands(); self.inner.borrow_mut().do_update(); } /// Handle a command. Top level commands (e.g. for creating and destroying /// windows) have their logic here; other commands are passed to the window. fn handle_cmd(&mut self, cmd: Command) { use Target as T; match cmd.target() { // these are handled the same no matter where they come from _ if cmd.is(sys_cmd::QUIT_APP) => self.quit(), #[cfg(target_os = "macos")] _ if cmd.is(sys_cmd::HIDE_APPLICATION) => self.hide_app(), #[cfg(target_os = "macos")] _ if cmd.is(sys_cmd::HIDE_OTHERS) => self.hide_others(), _ if cmd.is(sys_cmd::NEW_WINDOW) => { if let Err(e) = self.new_window(cmd) { tracing::error!("failed to create window: '{}'", e); } } _ if cmd.is(sys_cmd::NEW_SUB_WINDOW) => { if let Err(e) = self.new_sub_window(cmd) { tracing::error!("failed to create sub window: '{}'", e); } } _ if cmd.is(sys_cmd::CLOSE_ALL_WINDOWS) => self.request_close_all_windows(), T::Window(id) if cmd.is(sys_cmd::INVALIDATE_IME) => self.invalidate_ime(cmd, id), // these should come from a window // FIXME: we need to be able to open a file without a window handle T::Window(id) if cmd.is(sys_cmd::SHOW_OPEN_PANEL) => self.show_open_panel(cmd, id), T::Window(id) if cmd.is(sys_cmd::SHOW_SAVE_PANEL) => self.show_save_panel(cmd, id), T::Window(id) if cmd.is(sys_cmd::CONFIGURE_WINDOW) => self.configure_window(cmd, id), T::Window(id) if cmd.is(sys_cmd::CLOSE_WINDOW) => { if !self.inner.borrow_mut().dispatch_cmd(cmd).is_handled() { self.request_close_window(id); } } T::Window(id) if cmd.is(sys_cmd::SHOW_WINDOW) => self.show_window(id), T::Window(id) if cmd.is(sys_cmd::HIDE_WINDOW) => self.hide_window(id), T::Window(id) if cmd.is(sys_cmd::PASTE) => self.do_paste(id), _ if cmd.is(sys_cmd::CLOSE_WINDOW) => { tracing::warn!("CLOSE_WINDOW command must target a window.") } _ if cmd.is(sys_cmd::SHOW_WINDOW) => { tracing::warn!("SHOW_WINDOW command must target a window.") } _ if cmd.is(sys_cmd::HIDE_WINDOW) => { tracing::warn!("HIDE_WINDOW command must target a window.") } _ if cmd.is(sys_cmd::SHOW_OPEN_PANEL) => { tracing::warn!("SHOW_OPEN_PANEL command must target a window.") } _ => { self.inner.borrow_mut().dispatch_cmd(cmd); } } } fn show_open_panel(&mut self, cmd: Command, window_id: WindowId) { let options = cmd.get_unchecked(sys_cmd::SHOW_OPEN_PANEL).to_owned(); let handle = self .inner .borrow_mut() .windows .get_mut(window_id) .map(|w| w.handle.clone()); let accept_cmd = options.accept_cmd.unwrap_or(crate::commands::OPEN_FILE); let accept_multiple_cmd = options .accept_multiple_cmd .unwrap_or(crate::commands::OPEN_FILES); let cancel_cmd = options .cancel_cmd .unwrap_or(crate::commands::OPEN_PANEL_CANCELLED); let token = handle.and_then(|mut handle| handle.open_file(options.opt)); if let Some(token) = token { self.inner.borrow_mut().file_dialogs.insert( token, DialogInfo { id: window_id, accept_cmd, accept_multiple_cmd, cancel_cmd, }, ); } } fn show_save_panel(&mut self, cmd: Command, window_id: WindowId) { let options = cmd.get_unchecked(sys_cmd::SHOW_SAVE_PANEL).to_owned(); let handle = self .inner .borrow_mut() .windows .get_mut(window_id) .map(|w| w.handle.clone()); let accept_cmd = options.accept_cmd.unwrap_or(crate::commands::SAVE_FILE_AS); let accept_multiple_cmd = options .accept_multiple_cmd .unwrap_or(crate::commands::OPEN_FILES); let cancel_cmd = options .cancel_cmd .unwrap_or(crate::commands::SAVE_PANEL_CANCELLED); let token = handle.and_then(|mut handle| handle.save_as(options.opt)); if let Some(token) = token { self.inner.borrow_mut().file_dialogs.insert( token, DialogInfo { id: window_id, accept_cmd, accept_multiple_cmd, cancel_cmd, }, ); } } fn handle_dialog_multiple_response( &mut self, token: FileDialogToken, file_info: Vec<FileInfo>, ) { let mut inner = self.inner.borrow_mut(); if let Some(dialog_info) = inner.file_dialogs.remove(&token) { let cmd = if !file_info.is_empty() { dialog_info .accept_multiple_cmd .with(file_info) .to(dialog_info.id) } else { dialog_info.cancel_cmd.to(dialog_info.id) }; inner.append_command(cmd); } else { tracing::error!("unknown dialog token"); } std::mem::drop(inner); self.process_commands(); self.inner.borrow_mut().do_update(); } fn handle_dialog_response(&mut self, token: FileDialogToken, file_info: Option<FileInfo>) { let mut inner = self.inner.borrow_mut(); if let Some(dialog_info) = inner.file_dialogs.remove(&token) { let cmd = if let Some(info) = file_info { dialog_info.accept_cmd.with(info).to(dialog_info.id) } else { dialog_info.cancel_cmd.to(dialog_info.id) }; inner.append_command(cmd); } else { tracing::error!("unknown dialog token"); } std::mem::drop(inner); self.process_commands(); self.inner.borrow_mut().do_update(); } fn new_window(&mut self, cmd: Command) -> Result<(), Box<dyn std::error::Error>> { let desc = cmd.get_unchecked(sys_cmd::NEW_WINDOW); // The NEW_WINDOW command is private and only druid can receive it by normal means, // thus unwrapping can be considered safe and deserves a panic. let desc = desc.take().unwrap().downcast::<WindowDesc<T>>().unwrap(); let window = desc.build_native(self)?; window.show(); Ok(()) } fn new_sub_window(&mut self, cmd: Command) -> Result<(), Box<dyn std::error::Error>> { if let Some(transfer) = cmd.get(sys_cmd::NEW_SUB_WINDOW) { if let Some(sub_window_desc) = transfer.take() { let window = sub_window_desc.make_sub_window(self)?; window.show(); Ok(()) } else { panic!( "{} command must carry a SubWindowDesc internally", sys_cmd::NEW_SUB_WINDOW ) } } else { panic!( "{} command must carry a SingleUse<SubWindowDesc>", sys_cmd::NEW_SUB_WINDOW ) } } fn request_close_window(&mut self, id: WindowId) { self.inner.borrow_mut().request_close_window(id); } fn request_close_all_windows(&mut self) { self.inner.borrow_mut().request_close_all_windows(); } fn show_window(&mut self, id: WindowId) { self.inner.borrow_mut().show_window(id); } fn hide_window(&mut self, id: WindowId) { self.inner.borrow_mut().hide_window(id); } fn configure_window(&mut self, cmd: Command, id: WindowId) { if let Some(config) = cmd.get(sys_cmd::CONFIGURE_WINDOW) { self.inner.borrow_mut().configure_window(config, id); } } fn do_paste(&mut self, window_id: WindowId) { let event = Event::Paste(self.inner.borrow().app.clipboard()); self.inner.borrow_mut().do_window_event(window_id, event); } fn invalidate_ime(&mut self, cmd: Command, id: WindowId) { let params = cmd.get_unchecked(sys_cmd::INVALIDATE_IME); let update_fn = self.inner.borrow().ime_update_fn(id, params.widget); if let Some(func) = update_fn { func(params.event); } } fn release_ime_lock(&mut self, window_id: WindowId, token: TextFieldToken) { let needs_update = self.inner.borrow_mut().release_ime_lock(window_id, token); if let Some(widget) = needs_update { let event = Event::Internal(InternalEvent::RouteImeStateChange(widget)); self.do_window_event(event, window_id); } } fn quit(&self) { self.inner.borrow().app.quit() } #[cfg(target_os = "macos")] fn hide_app(&self) { use druid_shell::platform::mac::ApplicationExt as _; self.inner.borrow().app.hide() } #[cfg(target_os = "macos")] fn hide_others(&mut self) { use druid_shell::platform::mac::ApplicationExt as _; self.inner.borrow().app.hide_others(); } pub(crate) fn build_native_window( &mut self, id: WindowId, mut pending: PendingWindow<T>, config: WindowConfig, ) -> Result<WindowHandle, PlatformError> { let mut builder = WindowBuilder::new(self.app()); config.apply_to_builder(&mut builder); let data = self.data(); let env = self.env(); pending.size_policy = config.size_policy; pending.title.resolve(&data, &env); builder.set_title(pending.title.display_text().to_string()); let platform_menu = pending .menu .as_mut() .map(|m| m.initialize(Some(id), &data, &env)); if let Some(menu) = platform_menu { builder.set_menu(menu); } let handler = DruidHandler::new_shared((*self).clone(), id); builder.set_handler(Box::new(handler)); self.add_window(id, pending); builder.build() } } impl<T: Data> crate::shell::AppHandler for AppHandler<T> {
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/lens/mod.rs
druid/src/lens/mod.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Implementations of [`Lens`], a way of focusing on subfields of data. //! //! Lenses are useful whenever a widget only needs access to a subfield of a larger struct or //! generally access to part of a larger value. //! //! For example: If one wants to embed a [`TextBox`](crate::widget::TextBox) in a widget with //! a `Data` type that is not `String`, they need to specify how to access a `String` from //! within the `Data`. //! //! ``` //! use druid::{Data, Lens, Widget, WidgetExt, widget::{TextBox, Flex}}; //! //! #[derive(Clone, Debug, Data, Lens)] //! struct MyState { //! search_term: String, //! scale: f64, //! // ... //! } //! //! //! fn my_sidebar() -> impl Widget<MyState> { //! // `TextBox` is of type `Widget<String>` //! // via `.lens` we get it to be of type `Widget<MyState>`. //! // `MyState::search_term` is a lens generated by the `derive(Lens)` macro, //! // that provides access to the search_term field. //! let searchbar = TextBox::new().lens(MyState::search_term); //! //! // ... //! //! // We can now use `searchbar` just like any other `Widget<MyState>` //! Flex::column().with_child(searchbar) //! } //! ``` //! //! Most of the time, if you want to create your own lenses, you need to use //! [`#[derive(Lens)]`](druid_derive::Lens). #[allow(clippy::module_inception)] #[macro_use] mod lens; pub use lens::{ Constant, Deref, Field, Identity, InArc, Index, Lens, LensExt, Map, Ref, Then, Unit, };
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/lens/lens.rs
druid/src/lens/lens.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::marker::PhantomData; use std::ops; use std::sync::Arc; use crate::Data; /// A lens is a datatype that gives access to a part of a larger /// data structure. /// /// A simple example of a lens is a field of a struct; in this case, /// the lens itself is zero-sized. Another case is accessing an array /// element, in which case the lens contains the array index. /// /// The most common way to create `Lens` implementations is to /// use [`#[derive(Lens)]`](druid_derive::Lens) to access a struct's /// fields, but custom implementations are practical as well. /// /// The name "lens" is inspired by the [Haskell lens] package, which /// has generally similar goals. It's likely we'll develop more /// sophistication, for example combinators to combine lenses. /// /// [Haskell lens]: http://hackage.haskell.org/package/lens pub trait Lens<T: ?Sized, U: ?Sized> { /// Get non-mut access to the field. /// /// Runs the supplied closure with a reference to the data. It's /// structured this way, as opposed to simply returning a reference, /// so that the data might be synthesized on-the-fly by the lens. fn with<V, F: FnOnce(&U) -> V>(&self, data: &T, f: F) -> V; /// Get mutable access to the field. /// /// This method is defined in terms of a closure, rather than simply /// yielding a mutable reference, because it is intended to be used /// with value-type data (also known as immutable data structures). /// For example, a lens for an immutable list might be implemented by /// cloning the list, giving the closure mutable access to the clone, /// then updating the reference after the closure returns. fn with_mut<V, F: FnOnce(&mut U) -> V>(&self, data: &mut T, f: F) -> V; } /// Helpers for manipulating `Lens`es pub trait LensExt<A: ?Sized, B: ?Sized>: Lens<A, B> { /// Copy the targeted value out of `data` fn get(&self, data: &A) -> B where B: Clone, { self.with(data, |x| x.clone()) } /// Set the targeted value in `data` to `value` fn put(&self, data: &mut A, value: B) where B: Sized, { self.with_mut(data, |x| *x = value); } /// Compose a `Lens<A, B>` with a `Lens<B, C>` to produce a `Lens<A, C>` /// /// ``` /// # use druid::*; /// struct Foo { x: (u32, bool) } /// let lens = lens!(Foo, x).then(lens!((u32, bool), 1)); /// assert_eq!(lens.get(&Foo { x: (0, true) }), true); /// ``` fn then<Other, C>(self, other: Other) -> Then<Self, Other, B> where Other: Lens<B, C> + Sized, C: ?Sized, Self: Sized, { Then::new(self, other) } /// Combine a `Lens<A, B>` with a function that can transform a `B` and its inverse. /// /// Useful for cases where the desired value doesn't physically exist in `A`, but can be /// computed. For example, a lens like the following might be used to adapt a value with the /// range 0-2 for use with a `Widget<f64>` like `Slider` that has a range of 0-1: /// /// ``` /// # use druid::*; /// let lens = lens!((bool, f64), 1); /// assert_eq!(lens.map(|x| x / 2.0, |x, y| *x = y * 2.0).get(&(true, 2.0)), 1.0); /// ``` /// /// The computed `C` may represent a whole or only part of the original `B`. fn map<Get, Put, C>(self, get: Get, put: Put) -> Then<Self, Map<Get, Put>, B> where Get: Fn(&B) -> C, Put: Fn(&mut B, C), Self: Sized, { self.then(Map::new(get, put)) } /// Invoke a type's `Deref` impl /// /// ``` /// # use druid::*; /// assert_eq!(lens::Identity.deref().get(&Box::new(42)), 42); /// ``` fn deref(self) -> Then<Self, Deref, B> where B: ops::Deref + ops::DerefMut, Self: Sized, { self.then(Deref) } /// Invoke a type's `AsRef` and `AsMut` impl. /// /// It also allows indexing arrays with the [`index`] lens as shown in the example. /// This is necessary, because the `Index` trait in Rust is only implemented /// for slices (`[T]`), but not for arrays (`[T; N]`). /// /// # Examples /// /// Using `ref` this works: /// /// ``` /// use druid::{widget::TextBox, Data, Lens, LensExt, Widget, WidgetExt}; /// /// #[derive(Clone, Default, Data, Lens)] /// struct State { /// data: [String; 2], /// } /// /// fn with_ref() -> impl Widget<State> { /// TextBox::new().lens(State::data.as_ref().index(1)) /// } /// ``` /// /// While this fails: /// /// ```compile_fail /// # use druid::*; /// # #[derive(Clone, Default, Data, Lens)] /// # struct State { /// # data: [String; 2], /// # } /// fn without_ref() -> impl Widget<State> { /// // results in: `[std::string::String; 2]` cannot be mutably indexed by `usize` /// TextBox::new().lens(State::data.index(1)) /// } /// ``` /// /// [`Lens`]: ./trait.Lens.html /// [`index`]: #method.index #[allow(clippy::wrong_self_convention)] fn as_ref<T: ?Sized>(self) -> Then<Self, Ref, B> where B: AsRef<T> + AsMut<T>, Self: Sized, { self.then(Ref) } /// Access an index in a container /// /// ``` /// # use druid::*; /// assert_eq!(lens::Identity.index(2).get(&vec![0u32, 1, 2, 3]), 2); /// ``` fn index<I>(self, index: I) -> Then<Self, Index<I>, B> where I: Clone, B: ops::Index<I> + ops::IndexMut<I>, Self: Sized, { self.then(Index::new(index)) } /// Adapt to operate on the contents of an `Arc` with efficient copy-on-write semantics /// /// ``` /// # use druid::*; use std::sync::Arc; /// let lens = lens::Identity.index(2).in_arc(); /// let mut x = Arc::new(vec![0, 1, 2, 3]); /// let original = x.clone(); /// assert_eq!(lens.get(&x), 2); /// lens.put(&mut x, 2); /// assert!(Arc::ptr_eq(&original, &x), "no-op writes don't cause a deep copy"); /// lens.put(&mut x, 42); /// assert_eq!(&*x, &[0, 1, 42, 3]); /// ``` fn in_arc(self) -> InArc<Self> where A: Clone, B: Data, Self: Sized, { InArc::new(self) } /// A lens that reverses a boolean value /// /// # Examples /// /// ``` /// # use druid::*; /// use druid::LensExt; /// /// #[derive(Lens)] /// struct MyThing { /// first: bool /// } /// /// let lens = MyThing::first.not(); /// let mut val = MyThing { first: false }; /// assert_eq!(lens.with(&val, |v| *v), true); /// lens.with_mut(&mut val, |v| *v = false); /// assert_eq!(val.first, true); /// ``` fn not(self) -> Then<Self, Not, B> where Self: Sized, B: Sized + Into<bool> + Copy, bool: Into<B>, { self.then(Not) } } impl<A: ?Sized, B: ?Sized, T: Lens<A, B>> LensExt<A, B> for T {} /// Lens accessing a member of some type using accessor functions /// /// See also the `lens` macro. /// /// ``` /// let lens = druid::lens::Field::new(|x: &Vec<u32>| &x[42], |x| &mut x[42]); /// ``` pub struct Field<Get, GetMut> { get: Get, get_mut: GetMut, } impl<Get, GetMut> Field<Get, GetMut> { /// Construct a lens from a pair of getter functions pub fn new<T: ?Sized, U: ?Sized>(get: Get, get_mut: GetMut) -> Self where Get: Fn(&T) -> &U, GetMut: Fn(&mut T) -> &mut U, { Self { get, get_mut } } } impl<T, U, Get, GetMut> Lens<T, U> for Field<Get, GetMut> where T: ?Sized, U: ?Sized, Get: Fn(&T) -> &U, GetMut: Fn(&mut T) -> &mut U, { fn with<V, F: FnOnce(&U) -> V>(&self, data: &T, f: F) -> V { f((self.get)(data)) } fn with_mut<V, F: FnOnce(&mut U) -> V>(&self, data: &mut T, f: F) -> V { f((self.get_mut)(data)) } } /// Construct a lens accessing a type's field /// /// This is a convenience macro for constructing `Field` lenses for fields or indexable elements. /// /// ``` /// struct Foo { x: Bar } /// struct Bar { y: [i32; 10] } /// let lens = druid::lens!(Foo, x); /// let lens = druid::lens!((u32, bool), 1); /// let lens = druid::lens!([u8], [4]); /// let lens = druid::lens!(Foo, x.y[5]); /// ``` #[macro_export] macro_rules! lens { ($ty:ty, [$index:expr]) => { $crate::lens::Field::new::<$ty, _>(move |x| &x[$index], move |x| &mut x[$index]) }; ($ty:ty, $($field:tt)*) => { $crate::lens::Field::new::<$ty, _>(move |x| &x.$($field)*, move |x| &mut x.$($field)*) }; } /// `Lens` composed of two lenses joined together #[derive(Debug, Copy)] pub struct Then<T, U, B: ?Sized> { left: T, right: U, _marker: PhantomData<B>, } impl<T, U, B: ?Sized> Then<T, U, B> { /// Compose two lenses /// /// See also `LensExt::then`. pub fn new<A: ?Sized, C: ?Sized>(left: T, right: U) -> Self where T: Lens<A, B>, U: Lens<B, C>, { Self { left, right, _marker: PhantomData, } } } impl<T, U, A, B, C> Lens<A, C> for Then<T, U, B> where A: ?Sized, B: ?Sized, C: ?Sized, T: Lens<A, B>, U: Lens<B, C>, { fn with<V, F: FnOnce(&C) -> V>(&self, data: &A, f: F) -> V { self.left.with(data, |b| self.right.with(b, f)) } fn with_mut<V, F: FnOnce(&mut C) -> V>(&self, data: &mut A, f: F) -> V { self.left.with_mut(data, |b| self.right.with_mut(b, f)) } } impl<T: Clone, U: Clone, B> Clone for Then<T, U, B> { fn clone(&self) -> Self { Self { left: self.left.clone(), right: self.right.clone(), _marker: PhantomData, } } } /// `Lens` built from a getter and a setter #[derive(Debug, Copy, Clone)] pub struct Map<Get, Put> { get: Get, put: Put, } impl<Get, Put> Map<Get, Put> { /// Construct a mapping /// /// See also `LensExt::map` pub fn new<A: ?Sized, B>(get: Get, put: Put) -> Self where Get: Fn(&A) -> B, Put: Fn(&mut A, B), { Self { get, put } } } impl<A: ?Sized, B, Get, Put> Lens<A, B> for Map<Get, Put> where Get: Fn(&A) -> B, Put: Fn(&mut A, B), { fn with<V, F: FnOnce(&B) -> V>(&self, data: &A, f: F) -> V { f(&(self.get)(data)) } fn with_mut<V, F: FnOnce(&mut B) -> V>(&self, data: &mut A, f: F) -> V { let mut temp = (self.get)(data); let x = f(&mut temp); (self.put)(data, temp); x } } /// `Lens` for invoking `Deref` and `DerefMut` on a type. /// /// See also [`LensExt::deref`]. #[derive(Debug, Copy, Clone)] pub struct Deref; impl<T: ?Sized> Lens<T, T::Target> for Deref where T: ops::Deref + ops::DerefMut, { fn with<V, F: FnOnce(&T::Target) -> V>(&self, data: &T, f: F) -> V { f(data.deref()) } fn with_mut<V, F: FnOnce(&mut T::Target) -> V>(&self, data: &mut T, f: F) -> V { f(data.deref_mut()) } } /// [`Lens`] for invoking `AsRef` and `AsMut` on a type. /// /// [`LensExt::as_ref`] offers an easy way to apply this, /// as well as more information and examples. #[derive(Debug, Copy, Clone)] pub struct Ref; impl<T: ?Sized, U: ?Sized> Lens<T, U> for Ref where T: AsRef<U> + AsMut<U>, { fn with<V, F: FnOnce(&U) -> V>(&self, data: &T, f: F) -> V { f(data.as_ref()) } fn with_mut<V, F: FnOnce(&mut U) -> V>(&self, data: &mut T, f: F) -> V { f(data.as_mut()) } } /// `Lens` for indexing containers #[derive(Debug, Copy, Clone)] pub struct Index<I> { index: I, } impl<I> Index<I> { /// Construct a lens that accesses a particular index /// /// See also `LensExt::index`. pub fn new(index: I) -> Self { Self { index } } } impl<T, I> Lens<T, T::Output> for Index<I> where T: ?Sized + ops::Index<I> + ops::IndexMut<I>, I: Clone, { fn with<V, F: FnOnce(&T::Output) -> V>(&self, data: &T, f: F) -> V { f(&data[self.index.clone()]) } fn with_mut<V, F: FnOnce(&mut T::Output) -> V>(&self, data: &mut T, f: F) -> V { f(&mut data[self.index.clone()]) } } /// The identity lens: the lens which does nothing, i.e. exposes exactly /// the original value. /// /// Useful for starting a lens combinator chain, or passing to lens-based /// interfaces. #[derive(Debug, Copy, Clone)] pub struct Identity; impl<A: ?Sized> Lens<A, A> for Identity { fn with<V, F: FnOnce(&A) -> V>(&self, data: &A, f: F) -> V { f(data) } fn with_mut<V, F: FnOnce(&mut A) -> V>(&self, data: &mut A, f: F) -> V { f(data) } } /// A `Lens` that exposes data within an `Arc` with copy-on-write semantics /// /// A copy is only made in the event that a different value is written. #[derive(Debug, Copy, Clone)] pub struct InArc<L> { inner: L, } impl<L> InArc<L> { /// Adapt a lens to operate on an `Arc` /// /// See also `LensExt::in_arc` pub fn new<A, B>(inner: L) -> Self where A: Clone, B: Data, L: Lens<A, B>, { Self { inner } } } impl<A, B, L> Lens<Arc<A>, B> for InArc<L> where A: Clone, B: Data, L: Lens<A, B>, { fn with<V, F: FnOnce(&B) -> V>(&self, data: &Arc<A>, f: F) -> V { self.inner.with(data, f) } fn with_mut<V, F: FnOnce(&mut B) -> V>(&self, data: &mut Arc<A>, f: F) -> V { let mut temp = self.inner.with(data, |x| x.clone()); let v = f(&mut temp); if self.inner.with(data, |x| !x.same(&temp)) { self.inner.with_mut(Arc::make_mut(data), |x| *x = temp); } v } } /// A `Lens` that always yields (). /// /// This is useful when you wish to have a display only widget, require a type-erased widget, or /// obtain app data out of band and ignore your input. (E.g sub-windows) #[derive(Debug, Default, Copy, Clone)] pub struct Unit; impl<T> Lens<T, ()> for Unit { fn with<V, F: FnOnce(&()) -> V>(&self, _data: &T, f: F) -> V { f(&()) } fn with_mut<V, F: FnOnce(&mut ()) -> V>(&self, _data: &mut T, f: F) -> V { f(&mut ()) } } /// A lens that negates a boolean. /// /// It should usually be created using the `LensExt::not` method. #[derive(Debug, Copy, Clone)] pub struct Not; impl<T> Lens<T, bool> for Not where T: Into<bool> + Copy, bool: Into<T>, { fn with<V, F: FnOnce(&bool) -> V>(&self, data: &T, f: F) -> V { let tmp = !<T as Into<bool>>::into(*data); f(&tmp) } fn with_mut<V, F: FnOnce(&mut bool) -> V>(&self, data: &mut T, f: F) -> V { let mut tmp = !<T as Into<bool>>::into(*data); let out = f(&mut tmp); *data = (!tmp).into(); out } } /// A lens that always gives the same value and discards changes. #[derive(Debug, Copy, Clone)] pub struct Constant<T>(pub T); impl<A, B: Clone> Lens<A, B> for Constant<B> { fn with<V, F: FnOnce(&B) -> V>(&self, _: &A, f: F) -> V { f(&self.0) } fn with_mut<V, F: FnOnce(&mut B) -> V>(&self, _: &mut A, f: F) -> V { let mut tmp = self.0.clone(); f(&mut tmp) } } macro_rules! impl_lens_for_tuple { ($(($Lens:ident, $B:ident, $i:tt)),*) => { #[allow(non_snake_case)] impl<A, $($Lens,)* $($B,)*> Lens<A, ($($B,)*)> for ($($Lens,)*) where $($B: Clone,)* $($Lens: Lens<A, $B>,)* { fn with<V, F: FnOnce(&($($B,)*)) -> V>(&self, data: &A, f: F) -> V { $(let $B = self.$i.with(data, |v| v.clone());)* let tuple = ($($B,)*); f(&tuple) } fn with_mut<V, F: FnOnce(&mut ($($B,)*)) -> V>(&self, data: &mut A, f: F) -> V { $(let $B = self.$i.with(data, |v| v.clone());)* let mut tuple = ($($B,)*); let out = f(&mut tuple); let ($($B,)*) = tuple; $(self.$i.with_mut(data, |v| *v = $B);)* out } } }; } impl_lens_for_tuple!((L0, L0B, 0), (L1, L1B, 1)); impl_lens_for_tuple!((L0, L0B, 0), (L1, L1B, 1), (L2, L2B, 2)); impl_lens_for_tuple!((L0, L0B, 0), (L1, L1B, 1), (L2, L2B, 2), (L3, L3B, 3)); impl_lens_for_tuple!( (L0, L0B, 0), (L1, L1B, 1), (L2, L2B, 2), (L3, L3B, 3), (L4, L4B, 4) ); impl_lens_for_tuple!( (L0, L0B, 0), (L1, L1B, 1), (L2, L2B, 2), (L3, L3B, 3), (L4, L4B, 4), (L5, L5B, 5) ); impl_lens_for_tuple!( (L0, L0B, 0), (L1, L1B, 1), (L2, L2B, 2), (L3, L3B, 3), (L4, L4B, 4), (L5, L5B, 5), (L6, L6B, 6) ); impl_lens_for_tuple!( (L0, L0B, 0), (L1, L1B, 1), (L2, L2B, 2), (L3, L3B, 3), (L4, L4B, 4), (L5, L5B, 5), (L6, L6B, 6), (L7, L7B, 7) );
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/tests/helpers.rs
druid/src/tests/helpers.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Helper types for test writing. //! //! This includes tools for making throwaway widgets more easily. //! //! Note: Some of these types are undocumented. They're meant to help maintainers of Druid and //! people trying to build a framework on top of Druid (like crochet), not to be user-facing. #![allow(missing_docs)] use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use crate::*; pub type EventFn<S, T> = dyn FnMut(&mut S, &mut EventCtx, &Event, &mut T, &Env); pub type LifeCycleFn<S, T> = dyn FnMut(&mut S, &mut LifeCycleCtx, &LifeCycle, &T, &Env); pub type UpdateFn<S, T> = dyn FnMut(&mut S, &mut UpdateCtx, &T, &T, &Env); pub type LayoutFn<S, T> = dyn FnMut(&mut S, &mut LayoutCtx, &BoxConstraints, &T, &Env) -> Size; pub type PaintFn<S, T> = dyn FnMut(&mut S, &mut PaintCtx, &T, &Env); pub const REPLACE_CHILD: Selector = Selector::new("druid-test.replace-child"); /// A widget that can be constructed from individual functions, builder-style. /// /// This widget is generic over its state, which is passed in at construction time. pub struct ModularWidget<S, T> { state: S, event: Option<Box<EventFn<S, T>>>, lifecycle: Option<Box<LifeCycleFn<S, T>>>, update: Option<Box<UpdateFn<S, T>>>, layout: Option<Box<LayoutFn<S, T>>>, paint: Option<Box<PaintFn<S, T>>>, } /// A widget that can replace its child on command pub struct ReplaceChild<T> { child: WidgetPod<T, Box<dyn Widget<T>>>, replacer: Box<dyn Fn() -> Box<dyn Widget<T>>>, } /// A widget that records each time one of its methods is called. /// /// Make one like this: /// /// ``` /// # use druid::widget::Label; /// # use druid::{WidgetExt, LifeCycle}; /// use druid::tests::helpers::{Recording, Record, TestWidgetExt}; /// use druid::tests::harness::Harness; /// let recording = Recording::default(); /// let widget = Label::new("Hello").padding(4.0).record(&recording); /// /// Harness::create_simple((), widget, |harness| { /// harness.send_initial_events(); /// assert!(matches!(recording.next(), Record::L(LifeCycle::WidgetAdded))); /// }) /// ``` pub struct Recorder<W> { recording: Recording, child: W, } /// A recording of widget method calls. #[derive(Debug, Clone, Default)] pub struct Recording(Rc<RefCell<VecDeque<Record>>>); /// A recording of a method call on a widget. /// /// Each member of the enum corresponds to one of the methods on `Widget`. #[derive(Debug, Clone)] pub enum Record { /// An `Event`. E(Event), /// A `LifeCycle` event. L(LifeCycle), Layout(Size), Update(Region), Paint, // instead of always returning an Option<Record>, we have a none variant; // this would be code smell elsewhere but here I think it makes the tests // easier to read. None, } /// like WidgetExt but just for this one thing pub trait TestWidgetExt<T: Data>: Widget<T> + Sized + 'static { fn record(self, recording: &Recording) -> Recorder<Self> { Recorder { child: self, recording: recording.clone(), } } } impl<T: Data, W: Widget<T> + 'static> TestWidgetExt<T> for W {} #[allow(dead_code)] impl<S, T> ModularWidget<S, T> { pub fn new(state: S) -> Self { ModularWidget { state, event: None, lifecycle: None, update: None, layout: None, paint: None, } } pub fn event_fn( mut self, f: impl FnMut(&mut S, &mut EventCtx, &Event, &mut T, &Env) + 'static, ) -> Self { self.event = Some(Box::new(f)); self } pub fn lifecycle_fn( mut self, f: impl FnMut(&mut S, &mut LifeCycleCtx, &LifeCycle, &T, &Env) + 'static, ) -> Self { self.lifecycle = Some(Box::new(f)); self } pub fn update_fn( mut self, f: impl FnMut(&mut S, &mut UpdateCtx, &T, &T, &Env) + 'static, ) -> Self { self.update = Some(Box::new(f)); self } pub fn layout_fn( mut self, f: impl FnMut(&mut S, &mut LayoutCtx, &BoxConstraints, &T, &Env) -> Size + 'static, ) -> Self { self.layout = Some(Box::new(f)); self } pub fn paint_fn(mut self, f: impl FnMut(&mut S, &mut PaintCtx, &T, &Env) + 'static) -> Self { self.paint = Some(Box::new(f)); self } } impl<S, T: Data> Widget<T> for ModularWidget<S, T> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if let Some(f) = self.event.as_mut() { f(&mut self.state, ctx, event, data, env) } } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { if let Some(f) = self.lifecycle.as_mut() { f(&mut self.state, ctx, event, data, env) } } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { if let Some(f) = self.update.as_mut() { f(&mut self.state, ctx, old_data, data, env) } } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { let ModularWidget { ref mut state, ref mut layout, .. } = self; layout .as_mut() .map(|f| f(state, ctx, bc, data, env)) .unwrap_or_else(|| Size::new(100., 100.)) } fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { if let Some(f) = self.paint.as_mut() { f(&mut self.state, ctx, data, env) } } } impl<T: Data> ReplaceChild<T> { pub fn new<W: Widget<T> + 'static>( child: impl Widget<T> + 'static, f: impl Fn() -> W + 'static, ) -> Self { let child = WidgetPod::new(child.boxed()); let replacer = Box::new(move || f().boxed()); ReplaceChild { child, replacer } } } impl<T: Data> Widget<T> for ReplaceChild<T> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if let Event::Command(cmd) = event { if cmd.is(REPLACE_CHILD) { self.child = WidgetPod::new((self.replacer)()); ctx.children_changed(); return; } } self.child.event(ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.child.lifecycle(ctx, event, data, env) } fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) { self.child.update(ctx, data, env) } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.child.paint_raw(ctx, data, env) } } #[allow(dead_code)] impl Recording { pub fn is_empty(&self) -> bool { self.0.borrow().is_empty() } #[allow(dead_code)] pub fn len(&self) -> usize { self.0.borrow().len() } pub fn clear(&self) { self.0.borrow_mut().clear() } /// Returns the next event in the recording, if one exists. /// /// This consumes the event. pub fn next(&self) -> Record { self.0.borrow_mut().pop_front().unwrap_or(Record::None) } /// Returns an iterator of events drained from the recording. pub fn drain(&self) -> impl Iterator<Item = Record> { self.0 .borrow_mut() .drain(..) .collect::<Vec<_>>() .into_iter() } fn push(&self, event: Record) { self.0.borrow_mut().push_back(event) } } impl<T: Data, W: Widget<T>> Widget<T> for Recorder<W> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.recording.push(Record::E(event.clone())); self.child.event(ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { let should_record = !matches!( event, LifeCycle::Internal(InternalLifeCycle::DebugRequestState { .. }) | LifeCycle::Internal(InternalLifeCycle::DebugInspectState(_)) ); if should_record { self.recording.push(Record::L(event.clone())); } self.child.lifecycle(ctx, event, data, env) } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.child.update(ctx, old_data, data, env); self.recording .push(Record::Update(ctx.widget_state.invalid.clone())); } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { let size = self.child.layout(ctx, bc, data, env); self.recording.push(Record::Layout(size)); size } fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.child.paint(ctx, data, env); self.recording.push(Record::Paint) } } pub fn widget_ids<const N: usize>() -> [WidgetId; N] { let mut ids = [WidgetId::reserved(0); N]; for id in &mut ids { *id = WidgetId::next() } ids }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/tests/invalidation_tests.rs
druid/src/tests/invalidation_tests.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Tests related to propagation of invalid rects. use float_cmp::assert_approx_eq; use test_log::test; use super::*; #[test] fn invalidate_union() { let id_child1 = WidgetId::next(); let id_child2 = WidgetId::next(); let id_parent = WidgetId::next(); let widget = Split::columns( Button::new("hi").with_id(id_child1), Button::new("there").with_id(id_child2), ) .with_id(id_parent); Harness::create_simple(true, widget, |harness| { harness.send_initial_events(); harness.just_layout(); let child1_rect = harness.get_state(id_child1).layout_rect(); let child2_rect = harness.get_state(id_child2).layout_rect(); harness.event(Event::MouseMove(move_mouse((10., 10.)))); assert_eq!(harness.window().invalid().rects(), &[child1_rect]); // This resets the invalid region. harness.paint_invalid(); assert!(harness.window().invalid().is_empty()); harness.event(Event::MouseMove(move_mouse((210., 10.)))); assert_eq!( harness.window().invalid().rects(), // TODO: this is probably too fragile, because is there any guarantee on the order? &[child1_rect, child2_rect] ); }); } #[test] fn invalidate_scroll() { const RECT: Rect = Rect { x0: 30., y0: 40., x1: 40., y1: 50., }; struct Invalidator; impl<T: Data> Widget<T> for Invalidator { fn event(&mut self, ctx: &mut EventCtx, _: &Event, _: &mut T, _: &Env) { ctx.request_paint_rect(RECT); } fn lifecycle(&mut self, _: &mut LifeCycleCtx, _: &LifeCycle, _: &T, _: &Env) {} fn update(&mut self, _: &mut UpdateCtx, _: &T, _: &T, _: &Env) {} fn layout(&mut self, _: &mut LayoutCtx, _: &BoxConstraints, _: &T, _: &Env) -> Size { Size::new(1000., 1000.) } fn paint(&mut self, ctx: &mut PaintCtx, _: &T, _: &Env) { assert_eq!(ctx.region().rects().len(), 1); let rect = ctx.region().rects().first().unwrap(); assert_approx_eq!(f64, rect.x0, 30.); assert_approx_eq!(f64, rect.y0, 40.); assert_approx_eq!(f64, rect.x1, 40.); assert_approx_eq!(f64, rect.y1, 50.); } } let id = WidgetId::next(); let scroll_id = WidgetId::next(); let invalidator = IdentityWrapper::wrap(Invalidator, id); let scroll = Scroll::new(invalidator).with_id(scroll_id); Harness::create_simple(true, scroll, |harness| { harness.send_initial_events(); harness.just_layout(); // Sending an event should cause RECT to get invalidated. harness.event(Event::MouseMove(move_mouse((10., 10.)))); assert_eq!(harness.window().invalid().rects(), &[RECT]); // This resets the invalid region, and our widget checks to make sure it sees the right // invalid region in the paint function. harness.paint_invalid(); assert!(harness.window().invalid().is_empty()); harness.event(Event::Wheel(scroll_mouse((10., 10.), (7.0, 9.0)))); // Scrolling invalidates the whole window. assert_eq!( harness.window().invalid().rects(), &[Size::new(400., 400.).to_rect()] ); harness.window_mut().invalid_mut().clear(); // After the scroll, the window should see the translated invalid regions... harness.event(Event::MouseMove(move_mouse((10., 10.)))); assert_eq!( harness.window().invalid().rects(), &[RECT - Vec2::new(7.0, 9.0)] ); // ...but in its paint callback, the widget will see the invalid region relative to itself. harness.paint_invalid(); }); } // TODO: one with scroll
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/tests/mod.rs
druid/src/tests/mod.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Additional unit tests that cross file or module boundaries. #![allow(unused_imports)] pub mod harness; pub mod helpers; #[cfg(test)] mod invalidation_tests; #[cfg(test)] mod layout_tests; use std::cell::Cell; use std::collections::HashMap; use std::env; use std::fs; use std::rc::Rc; use crate::widget::*; use crate::*; use harness::*; use helpers::*; use kurbo::Vec2; /// Helper function to construct a "move to this position" mouse event. pub fn move_mouse(p: impl Into<Point>) -> MouseEvent { let pos = p.into(); MouseEvent { pos, window_pos: pos, buttons: MouseButtons::default(), mods: Modifiers::default(), count: 0, focus: false, button: MouseButton::None, wheel_delta: Vec2::ZERO, } } /// Helper function to construct a "scroll by n ticks" mouse event. pub fn scroll_mouse(p: impl Into<Point>, delta: impl Into<Vec2>) -> MouseEvent { let pos = p.into(); MouseEvent { pos, window_pos: pos, buttons: MouseButtons::default(), mods: Modifiers::default(), count: 0, focus: false, button: MouseButton::None, wheel_delta: delta.into(), } } /// This function creates a temporary directory and returns a PathBuf to it. /// /// This directory will be created relative to the executable and will therefore /// be created in the target directory for tests when running with cargo. The /// directory will be cleaned up at the end of the PathBufs lifetime. This /// uses the `tempfile` crate. #[allow(dead_code)] #[cfg(test)] pub fn temp_dir_for_test() -> std::path::PathBuf { let current_exe_path = env::current_exe().unwrap(); let mut exe_dir = current_exe_path.parent().unwrap(); if exe_dir.ends_with("deps") { exe_dir = exe_dir.parent().unwrap(); } let test_dir = exe_dir.parent().unwrap().join("tests"); fs::create_dir_all(&test_dir).unwrap(); tempfile::Builder::new() .prefix("TempDir") .tempdir_in(test_dir) .unwrap() .keep() } /// test that the first widget to request focus during an event gets it. #[test] fn propagate_hot() { let [button, pad, root, empty] = widget_ids(); let root_rec = Recording::default(); let padding_rec = Recording::default(); let button_rec = Recording::default(); let widget = Split::columns( SizedBox::empty().with_id(empty), Button::new("hot") .record(&button_rec) .with_id(button) .padding(50.) .record(&padding_rec) .with_id(pad), ) .record(&root_rec) .with_id(root); #[allow(clippy::cognitive_complexity)] Harness::create_simple((), widget, |harness| { harness.send_initial_events(); harness.just_layout(); // we don't care about setup events, so discard them now. root_rec.clear(); padding_rec.clear(); button_rec.clear(); harness.inspect_state(|state| assert!(!state.is_hot)); // What we are doing here is moving the mouse to different widgets, // and verifying both the widget's `is_hot` status and also that // each widget received the expected HotChanged messages. harness.event(Event::MouseMove(move_mouse((10., 10.)))); assert!(harness.get_state(root).is_hot); assert!(harness.get_state(empty).is_hot); assert!(!harness.get_state(pad).is_hot); assert!(matches!( root_rec.next(), Record::L(LifeCycle::HotChanged(true)) )); assert!(matches!(root_rec.next(), Record::E(Event::MouseMove(_)))); assert!(root_rec.is_empty() && padding_rec.is_empty() && button_rec.is_empty()); harness.event(Event::MouseMove(move_mouse((210., 10.)))); assert!(harness.get_state(root).is_hot); assert!(!harness.get_state(empty).is_hot); assert!(!harness.get_state(button).is_hot); assert!(harness.get_state(pad).is_hot); assert!(matches!(root_rec.next(), Record::E(Event::MouseMove(_)))); assert!(matches!( padding_rec.next(), Record::L(LifeCycle::HotChanged(true)) )); assert!(matches!(padding_rec.next(), Record::E(Event::MouseMove(_)))); assert!(root_rec.is_empty() && padding_rec.is_empty() && button_rec.is_empty()); harness.event(Event::MouseMove(move_mouse((260., 60.)))); assert!(harness.get_state(root).is_hot); assert!(!harness.get_state(empty).is_hot); assert!(harness.get_state(button).is_hot); assert!(harness.get_state(pad).is_hot); assert!(matches!(root_rec.next(), Record::E(Event::MouseMove(_)))); assert!(matches!(padding_rec.next(), Record::E(Event::MouseMove(_)))); assert!(matches!( button_rec.next(), Record::L(LifeCycle::HotChanged(true)) )); assert!(matches!(button_rec.next(), Record::E(Event::MouseMove(_)))); assert!(root_rec.is_empty() && padding_rec.is_empty() && button_rec.is_empty()); harness.event(Event::MouseMove(move_mouse((10., 10.)))); assert!(harness.get_state(root).is_hot); assert!(harness.get_state(empty).is_hot); assert!(!harness.get_state(button).is_hot); assert!(!harness.get_state(pad).is_hot); assert!(matches!(root_rec.next(), Record::E(Event::MouseMove(_)))); assert!(matches!( padding_rec.next(), Record::L(LifeCycle::HotChanged(false)) )); assert!(matches!(padding_rec.next(), Record::E(Event::MouseMove(_)))); assert!(matches!( button_rec.next(), Record::L(LifeCycle::HotChanged(false)) )); assert!(matches!(button_rec.next(), Record::E(Event::MouseMove(_)))); assert!(root_rec.is_empty() && padding_rec.is_empty() && button_rec.is_empty()); }); } #[test] fn take_focus() { const TAKE_FOCUS: Selector = Selector::new("druid-tests.take-focus"); /// A widget that takes focus when sent a particular command. /// The widget records focus change events into the inner cell. fn make_focus_taker(inner: Rc<Cell<Option<bool>>>) -> impl Widget<bool> { ModularWidget::new(inner) .event_fn(|_, ctx, event, _data, _env| { if let Event::Command(cmd) = event { if cmd.is(TAKE_FOCUS) { ctx.request_focus(); } } }) .lifecycle_fn(|is_focused, _, event, _data, _env| { if let LifeCycle::FocusChanged(focus) = event { is_focused.set(Some(*focus)); } }) } let [id_1, id_2, _id_3] = widget_ids(); // we use these so that we can check the widget's internal state let left_focus: Rc<Cell<Option<bool>>> = Default::default(); let right_focus: Rc<Cell<Option<bool>>> = Default::default(); assert!(left_focus.get().is_none()); let left = make_focus_taker(left_focus.clone()).with_id(id_1); let right = make_focus_taker(right_focus.clone()).with_id(id_2); let app = Split::columns(left, right).padding(5.0); let data = true; Harness::create_simple(data, app, |harness| { harness.send_initial_events(); // nobody should have focus assert!(left_focus.get().is_none()); assert!(right_focus.get().is_none()); // this is sent to all widgets; the last widget to request focus should get it harness.submit_command(TAKE_FOCUS); assert_eq!(harness.window().focus, Some(id_2)); assert_eq!(left_focus.get(), None); assert_eq!(right_focus.get(), Some(true)); // this is sent to all widgets; the last widget to request focus should still get it // NOTE: This tests siblings in particular, so careful when moving away from Split. harness.submit_command(TAKE_FOCUS); assert_eq!(harness.window().focus, Some(id_2)); assert_eq!(left_focus.get(), None); assert_eq!(right_focus.get(), Some(true)); // this is sent to a specific widget; it should get focus harness.submit_command(TAKE_FOCUS.to(id_1)); assert_eq!(harness.window().focus, Some(id_1)); assert_eq!(left_focus.get(), Some(true)); assert_eq!(right_focus.get(), Some(false)); // this is sent to a specific widget; it should get focus harness.submit_command(TAKE_FOCUS.to(id_2)); assert_eq!(harness.window().focus, Some(id_2)); assert_eq!(left_focus.get(), Some(false)); assert_eq!(right_focus.get(), Some(true)); }) } #[test] fn focus_changed() { const TAKE_FOCUS: Selector = Selector::new("druid-tests.take-focus"); const ALL_TAKE_FOCUS_BEFORE: Selector = Selector::new("druid-tests.take-focus-before"); const ALL_TAKE_FOCUS_AFTER: Selector = Selector::new("druid-tests.take-focus-after"); fn make_focus_container(children: Vec<WidgetPod<(), Box<dyn Widget<()>>>>) -> impl Widget<()> { ModularWidget::new(children) .event_fn(|children, ctx, event, data, env| { if let Event::Command(cmd) = event { if cmd.is(TAKE_FOCUS) { ctx.request_focus(); // Stop propagating this command so children // aren't requesting focus too. ctx.set_handled(); } else if cmd.is(ALL_TAKE_FOCUS_BEFORE) { ctx.request_focus(); } } children .iter_mut() .for_each(|a| a.event(ctx, event, data, env)); if let Event::Command(cmd) = event { if cmd.is(ALL_TAKE_FOCUS_AFTER) { ctx.request_focus(); } } }) .lifecycle_fn(|children, ctx, event, data, env| { children .iter_mut() .for_each(|a| a.lifecycle(ctx, event, data, env)); }) } let a_rec = Recording::default(); let b_rec = Recording::default(); let c_rec = Recording::default(); let [id_a, id_b, id_c] = widget_ids(); // a contains b which contains c let c = make_focus_container(vec![]).record(&c_rec).with_id(id_c); let b = make_focus_container(vec![WidgetPod::new(c).boxed()]) .record(&b_rec) .with_id(id_b); let a = make_focus_container(vec![WidgetPod::new(b).boxed()]) .record(&a_rec) .with_id(id_a); let f = |a| match a { Record::L(LifeCycle::FocusChanged(c)) => Some(c), _ => None, }; let no_change = |a: &Recording| a.drain().filter_map(f).count() == 0; let changed = |a: &Recording, b| a.drain().filter_map(f).eq(std::iter::once(b)); Harness::create_simple((), a, |harness| { harness.send_initial_events(); // focus none -> a harness.submit_command(TAKE_FOCUS.to(id_a)); assert_eq!(harness.window().focus, Some(id_a)); assert!(changed(&a_rec, true)); assert!(no_change(&b_rec)); assert!(no_change(&c_rec)); // focus a -> b harness.submit_command(TAKE_FOCUS.to(id_b)); assert_eq!(harness.window().focus, Some(id_b)); assert!(changed(&a_rec, false)); assert!(changed(&b_rec, true)); assert!(no_change(&c_rec)); // focus b -> c harness.submit_command(TAKE_FOCUS.to(id_c)); assert_eq!(harness.window().focus, Some(id_c)); assert!(no_change(&a_rec)); assert!(changed(&b_rec, false)); assert!(changed(&c_rec, true)); // focus c -> a harness.submit_command(TAKE_FOCUS.to(id_a)); assert_eq!(harness.window().focus, Some(id_a)); assert!(changed(&a_rec, true)); assert!(no_change(&b_rec)); assert!(changed(&c_rec, false)); // all focus before passing down the event harness.submit_command(ALL_TAKE_FOCUS_BEFORE); assert_eq!(harness.window().focus, Some(id_c)); assert!(changed(&a_rec, false)); assert!(no_change(&b_rec)); assert!(changed(&c_rec, true)); // all focus after passing down the event harness.submit_command(ALL_TAKE_FOCUS_AFTER); assert_eq!(harness.window().focus, Some(id_a)); assert!(changed(&a_rec, true)); assert!(no_change(&b_rec)); assert!(changed(&c_rec, false)); }) } #[test] fn simple_disable() { const CHANGE_DISABLED: Selector<bool> = Selector::new("druid-tests.change-disabled"); let test_widget_factory = |auto_focus: bool, id: WidgetId, state: Rc<Cell<Option<bool>>>| { ModularWidget::new(state) .lifecycle_fn(move |state, ctx, event, _, _| match event { LifeCycle::BuildFocusChain => { if auto_focus { ctx.register_for_focus(); } } LifeCycle::DisabledChanged(disabled) => { state.set(Some(*disabled)); } _ => {} }) .event_fn(|_, ctx, event, _, _| { if let Event::Command(cmd) = event { if let Some(disabled) = cmd.get(CHANGE_DISABLED) { ctx.set_disabled(*disabled); } } }) .with_id(id) }; let disabled_0: Rc<Cell<Option<bool>>> = Default::default(); let disabled_1: Rc<Cell<Option<bool>>> = Default::default(); let disabled_2: Rc<Cell<Option<bool>>> = Default::default(); let disabled_3: Rc<Cell<Option<bool>>> = Default::default(); let check_states = |name: &str, desired: [Option<bool>; 4]| { if desired[0] != disabled_0.get() || desired[1] != disabled_1.get() || desired[2] != disabled_2.get() || desired[3] != disabled_3.get() { eprintln!( "test \"{}\":\nexpected: {:?}\n got: {:?}", name, desired, [ disabled_0.get(), disabled_1.get(), disabled_2.get(), disabled_3.get() ] ); panic!(); } }; let id_0 = WidgetId::next(); let id_1 = WidgetId::next(); let id_2 = WidgetId::next(); let id_3 = WidgetId::next(); let root = Flex::row() .with_child(test_widget_factory(true, id_0, disabled_0.clone())) .with_child(test_widget_factory(true, id_1, disabled_1.clone())) .with_child(test_widget_factory(true, id_2, disabled_2.clone())) .with_child(test_widget_factory(true, id_3, disabled_3.clone())); Harness::create_simple((), root, |harness| { harness.send_initial_events(); check_states("send_initial_events", [None, None, None, None]); assert_eq!(harness.window().focus_chain(), &[id_0, id_1, id_2, id_3]); harness.submit_command(CHANGE_DISABLED.with(true).to(id_0)); check_states("Change 1", [Some(true), None, None, None]); assert_eq!(harness.window().focus_chain(), &[id_1, id_2, id_3]); harness.submit_command(CHANGE_DISABLED.with(true).to(id_2)); check_states("Change 2", [Some(true), None, Some(true), None]); assert_eq!(harness.window().focus_chain(), &[id_1, id_3]); harness.submit_command(CHANGE_DISABLED.with(true).to(id_3)); check_states("Change 3", [Some(true), None, Some(true), Some(true)]); assert_eq!(harness.window().focus_chain(), &[id_1]); harness.submit_command(CHANGE_DISABLED.with(false).to(id_2)); check_states("Change 4", [Some(true), None, Some(false), Some(true)]); assert_eq!(harness.window().focus_chain(), &[id_1, id_2]); harness.submit_command(CHANGE_DISABLED.with(true).to(id_2)); check_states("Change 5", [Some(true), None, Some(true), Some(true)]); assert_eq!(harness.window().focus_chain(), &[id_1]); //This is intended the widget should not receive an event! harness.submit_command(CHANGE_DISABLED.with(false).to(id_1)); check_states("Change 6", [Some(true), None, Some(true), Some(true)]); assert_eq!(harness.window().focus_chain(), &[id_1]); }) } #[test] fn resign_focus_on_disable() { const CHANGE_DISABLED: Selector<bool> = Selector::new("druid-tests.change-disabled-disable"); const REQUEST_FOCUS: Selector<()> = Selector::new("druid-tests.change-disabled-focus"); let test_widget_factory = |auto_focus: bool, id: WidgetId, inner: Option<Box<dyn Widget<()>>>| { ModularWidget::new(inner.map(WidgetPod::new)) .lifecycle_fn(move |state, ctx, event, data, env| { if let LifeCycle::BuildFocusChain = event { if auto_focus { ctx.register_for_focus(); } } if let Some(inner) = state { inner.lifecycle(ctx, event, data, env); } }) .event_fn(|state, ctx, event, data, env| { if let Event::Command(cmd) = event { if let Some(disabled) = cmd.get(CHANGE_DISABLED) { ctx.set_disabled(*disabled); return; } if cmd.is(REQUEST_FOCUS) { ctx.request_focus(); return; } } if let Some(inner) = state { inner.event(ctx, event, data, env); } }) .with_id(id) }; let id_0 = WidgetId::next(); let id_1 = WidgetId::next(); let id_2 = WidgetId::next(); let root = Flex::row() .with_child(test_widget_factory( true, id_0, Some(test_widget_factory(true, id_1, None).boxed()), )) .with_child(test_widget_factory(true, id_2, None)); Harness::create_simple((), root, |harness| { harness.send_initial_events(); assert_eq!(harness.window().focus_chain(), &[id_0, id_1, id_2]); assert_eq!(harness.window().focus, None); harness.submit_command(REQUEST_FOCUS.to(id_2)); assert_eq!(harness.window().focus_chain(), &[id_0, id_1, id_2]); assert_eq!(harness.window().focus, Some(id_2)); harness.submit_command(CHANGE_DISABLED.with(true).to(id_0)); assert_eq!(harness.window().focus_chain(), &[id_2]); assert_eq!(harness.window().focus, Some(id_2)); harness.submit_command(CHANGE_DISABLED.with(true).to(id_2)); assert_eq!(harness.window().focus_chain(), &[]); assert_eq!(harness.window().focus, None); harness.submit_command(CHANGE_DISABLED.with(false).to(id_0)); assert_eq!(harness.window().focus_chain(), &[id_0, id_1]); assert_eq!(harness.window().focus, None); harness.submit_command(REQUEST_FOCUS.to(id_1)); assert_eq!(harness.window().focus_chain(), &[id_0, id_1]); assert_eq!(harness.window().focus, Some(id_1)); harness.submit_command(CHANGE_DISABLED.with(false).to(id_2)); assert_eq!(harness.window().focus_chain(), &[id_0, id_1, id_2]); assert_eq!(harness.window().focus, Some(id_1)); harness.submit_command(CHANGE_DISABLED.with(true).to(id_0)); assert_eq!(harness.window().focus_chain(), &[id_2]); assert_eq!(harness.window().focus, None); }) } #[test] fn disable_tree() { const MULTI_CHANGE_DISABLED: Selector<HashMap<WidgetId, bool>> = Selector::new("druid-tests.multi-change-disabled"); let leaf_factory = |state: Rc<Cell<Option<bool>>>| { ModularWidget::new(state).lifecycle_fn(move |state, ctx, event, _, _| match event { LifeCycle::BuildFocusChain => { ctx.register_for_focus(); } LifeCycle::DisabledChanged(disabled) => { state.set(Some(*disabled)); } _ => {} }) }; let wrapper = |id: WidgetId, widget: Box<dyn Widget<()>>| { ModularWidget::new(WidgetPod::new(widget)) .lifecycle_fn(|inner, ctx, event, data, env| { inner.lifecycle(ctx, event, data, env); }) .event_fn(|inner, ctx, event, data, env| { if let Event::Command(cmd) = event { if let Some(map) = cmd.get(MULTI_CHANGE_DISABLED) { if let Some(disabled) = map.get(&ctx.widget_id()) { ctx.set_disabled(*disabled); return; } } } inner.event(ctx, event, data, env); }) .with_id(id) }; fn multi_update(states: &[(WidgetId, bool)]) -> Command { let payload = states.iter().cloned().collect::<HashMap<_, _>>(); MULTI_CHANGE_DISABLED.with(payload).to(Target::Global) } let disabled_0: Rc<Cell<Option<bool>>> = Default::default(); let disabled_1: Rc<Cell<Option<bool>>> = Default::default(); let disabled_2: Rc<Cell<Option<bool>>> = Default::default(); let disabled_3: Rc<Cell<Option<bool>>> = Default::default(); let disabled_4: Rc<Cell<Option<bool>>> = Default::default(); let disabled_5: Rc<Cell<Option<bool>>> = Default::default(); let check_states = |name: &str, desired: [Option<bool>; 6]| { if desired[0] != disabled_0.get() || desired[1] != disabled_1.get() || desired[2] != disabled_2.get() || desired[3] != disabled_3.get() || desired[4] != disabled_4.get() || desired[5] != disabled_5.get() { eprintln!( "test \"{}\":\nexpected: {:?}\n got: {:?}", name, desired, [ disabled_0.get(), disabled_1.get(), disabled_2.get(), disabled_3.get(), disabled_4.get(), disabled_5.get() ] ); panic!(); } }; let outer_id = WidgetId::next(); let inner_id = WidgetId::next(); let single_id = WidgetId::next(); let root_id = WidgetId::next(); let node0 = Flex::row() .with_child(leaf_factory(disabled_0.clone())) .with_child(leaf_factory(disabled_1.clone())) .boxed(); let node1 = leaf_factory(disabled_2.clone()).boxed(); let node2 = Flex::row() .with_child(wrapper(outer_id, wrapper(inner_id, node0).boxed())) .with_child(wrapper(single_id, node1)) .with_child(leaf_factory(disabled_3.clone())) .with_child(leaf_factory(disabled_4.clone())) .with_child(leaf_factory(disabled_5.clone())) .boxed(); let root = wrapper(root_id, node2); Harness::create_simple((), root, |harness| { harness.send_initial_events(); check_states("Send initial events", [None, None, None, None, None, None]); assert_eq!(harness.window().focus_chain().len(), 6); harness.submit_command(multi_update(&[(root_id, true)])); check_states( "disable root (0)", [ Some(true), Some(true), Some(true), Some(true), Some(true), Some(true), ], ); assert_eq!(harness.window().focus_chain().len(), 0); harness.submit_command(multi_update(&[(inner_id, true)])); check_states( "disable inner (1)", [ Some(true), Some(true), Some(true), Some(true), Some(true), Some(true), ], ); assert_eq!(harness.window().focus_chain().len(), 0); // Node 0 should not be affected harness.submit_command(multi_update(&[(root_id, false)])); check_states( "enable root (2)", [ Some(true), Some(true), Some(false), Some(false), Some(false), Some(false), ], ); assert_eq!(harness.window().focus_chain().len(), 4); // Changing inner and outer in different directions should not affect the leaves harness.submit_command(multi_update(&[(inner_id, false), (outer_id, true)])); check_states( "change inner outer (3)", [ Some(true), Some(true), Some(false), Some(false), Some(false), Some(false), ], ); assert_eq!(harness.window().focus_chain().len(), 4); // Changing inner and outer in different directions should not affect the leaves harness.submit_command(multi_update(&[(inner_id, true), (outer_id, false)])); check_states( "change inner outer (4)", [ Some(true), Some(true), Some(false), Some(false), Some(false), Some(false), ], ); assert_eq!(harness.window().focus_chain().len(), 4); // Changing two widgets on the same level harness.submit_command(multi_update(&[(single_id, true), (inner_id, false)])); check_states( "change horizontal (5)", [ Some(false), Some(false), Some(true), Some(false), Some(false), Some(false), ], ); assert_eq!(harness.window().focus_chain().len(), 5); // Disabling the root should disable all widgets harness.submit_command(multi_update(&[(root_id, true)])); check_states( "disable root (6)", [ Some(true), Some(true), Some(true), Some(true), Some(true), Some(true), ], ); assert_eq!(harness.window().focus_chain().len(), 0); // Enabling a widget in a disabled tree should not affect the enclosed widgets harness.submit_command(multi_update(&[(single_id, false)])); check_states( "enable single (7)", [ Some(true), Some(true), Some(true), Some(true), Some(true), Some(true), ], ); assert_eq!(harness.window().focus_chain().len(), 0); }) } #[test] fn simple_lifecyle() { let record = Recording::default(); let widget = SizedBox::empty().record(&record); Harness::create_simple(true, widget, |harness| { harness.send_initial_events(); assert!(matches!(record.next(), Record::L(LifeCycle::WidgetAdded))); assert!(matches!( record.next(), Record::L(LifeCycle::BuildFocusChain) )); assert!(matches!(record.next(), Record::E(Event::WindowConnected))); assert!(matches!(record.next(), Record::E(Event::WindowSize(_)))); assert!(record.is_empty()); }) } #[test] /// Test that lifecycle events are sent correctly to a child added during event /// handling fn adding_child_lifecycle() { let record = Recording::default(); let record_new_child = Recording::default(); let record_new_child2 = record_new_child.clone(); let replacer = ReplaceChild::new(TextBox::new(), move || { Split::columns(TextBox::new(), TextBox::new().record(&record_new_child2)) }); let widget = Split::columns(Label::new("hi").record(&record), replacer); Harness::create_simple(String::new(), widget, |harness| { harness.send_initial_events(); assert!(matches!(record.next(), Record::L(LifeCycle::WidgetAdded))); assert!(matches!( record.next(), Record::L(LifeCycle::BuildFocusChain) )); assert!(matches!(record.next(), Record::E(Event::WindowConnected))); assert!(record.is_empty()); assert!(record_new_child.is_empty()); harness.submit_command(REPLACE_CHILD); assert!(matches!(record.next(), Record::E(Event::Command(_)))); assert!(matches!( record_new_child.next(), Record::L(LifeCycle::WidgetAdded) )); assert!(matches!( record_new_child.next(), Record::L(LifeCycle::BuildFocusChain) )); assert!(record_new_child.is_empty()); }) } #[test] fn participate_in_autofocus() { let [id_1, id_2, id_3, id_4, id_5, id_6] = widget_ids(); // this widget starts with a single child, and will replace them with a split // when we send it a command. let replacer = ReplaceChild::new(TextBox::new().with_id(id_4), move || { Split::columns(TextBox::new().with_id(id_5), TextBox::new().with_id(id_6)) }); let widget = Split::columns( Flex::row() .with_flex_child(TextBox::new().with_id(id_1), 1.0) .with_flex_child(TextBox::new().with_id(id_2), 1.0) .with_flex_child(TextBox::new().with_id(id_3), 1.0), replacer, ); Harness::create_simple("my test text".to_string(), widget, |harness| { // verify that all widgets are marked as having children_changed // (this should always be true for a new widget) harness.inspect_state(|state| assert!(state.children_changed)); harness.send_initial_events(); // verify that we start out with four widgets registered for focus assert_eq!(harness.window().focus_chain(), &[id_1, id_2, id_3, id_4]); // tell the replacer widget to swap its children harness.submit_command(REPLACE_CHILD); // verify that the two new children are registered for focus. assert_eq!( harness.window().focus_chain(), &[id_1, id_2, id_3, id_5, id_6] ); // verify that no widgets still report that their children changed: harness.inspect_state(|state| assert!(!state.children_changed)) }) } #[test] fn child_tracking() { let [id_1, id_2, id_3, id_4] = widget_ids(); let widget = Split::columns( SizedBox::empty().with_id(id_1), SizedBox::empty().with_id(id_2), ) .with_id(id_3) .padding(5.0) .with_id(id_4); Harness::create_simple(true, widget, |harness| { harness.send_initial_events(); let root = harness.get_state(id_4); assert_eq!(root.children.entry_count(), 3); assert!(root.children.may_contain(&id_1)); assert!(root.children.may_contain(&id_2)); assert!(root.children.may_contain(&id_3)); let split = harness.get_state(id_3); assert!(split.children.may_contain(&id_1)); assert!(split.children.may_contain(&id_2)); assert_eq!(split.children.entry_count(), 2); }); } #[test] /// Test that all children are registered correctly after a child is replaced. fn register_after_adding_child() { let [id_1, id_2, id_3, id_4, id_5, id_6, id_7] = widget_ids(); let replacer = ReplaceChild::new(Slider::new().with_id(id_1), move || { Split::columns(Slider::new().with_id(id_2), Slider::new().with_id(id_3)).with_id(id_7) }) .with_id(id_6); let widget = Split::columns(Label::new("hi").with_id(id_4), replacer).with_id(id_5); Harness::create_simple(0.0, widget, |harness| { harness.send_initial_events(); assert!(harness.get_state(id_5).children.may_contain(&id_6)); assert!(harness.get_state(id_5).children.may_contain(&id_1)); assert!(harness.get_state(id_5).children.may_contain(&id_4)); assert_eq!(harness.get_state(id_5).children.entry_count(), 3); harness.submit_command(REPLACE_CHILD); assert!(harness.get_state(id_5).children.may_contain(&id_6)); assert!(harness.get_state(id_5).children.may_contain(&id_4)); assert!(harness.get_state(id_5).children.may_contain(&id_7));
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/tests/layout_tests.rs
druid/src/tests/layout_tests.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Tests related to layout. use float_cmp::assert_approx_eq; use test_log::test; use super::*; #[test] fn simple_layout() { const BOX_WIDTH: f64 = 200.; const PADDING: f64 = 10.; let id_1 = WidgetId::next(); let widget = Split::columns(Label::new("hi"), Label::new("there")) .fix_size(BOX_WIDTH, BOX_WIDTH) .padding(10.0) .with_id(id_1) .center(); Harness::create_simple(true, widget, |harness| { harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id_1); assert_approx_eq!( f64, state.layout_rect().x0, ((DEFAULT_SIZE.width - BOX_WIDTH) / 2.) - PADDING ); }) } #[test] fn row_column() { let [id1, id2, id3, id4, id5, id6] = widget_ids(); let widget = Flex::row() .must_fill_main_axis(true) .with_flex_child( Flex::column() .with_flex_child(SizedBox::empty().expand().with_id(id1), 1.0) .with_flex_child(SizedBox::empty().expand().with_id(id2), 1.0), 1.0, ) .with_flex_child( Flex::column() .with_flex_child(SizedBox::empty().expand().with_id(id3), 1.0) .with_flex_child(SizedBox::empty().expand().with_id(id4), 1.0) .with_flex_child(SizedBox::empty().expand().with_id(id5), 1.0) .with_flex_child(SizedBox::empty().expand().with_id(id6), 1.0) .expand_width(), 1.0, ); Harness::create_simple((), widget, |harness| { harness.send_initial_events(); harness.just_layout(); let state1 = harness.get_state(id1); assert_eq!(state1.layout_rect().origin(), Point::ZERO); let state2 = harness.get_state(id2); assert_eq!(state2.layout_rect().origin(), Point::new(0., 200.)); let state3 = harness.get_state(id3); assert_eq!(state3.layout_rect().origin(), Point::ZERO); let state5 = harness.get_state(id5); assert_eq!(state5.layout_rect().origin(), Point::new(0., 200.)); }) } #[test] fn simple_paint_rect() { let [id1, id2] = widget_ids(); let widget = ModularWidget::<(), ()>::new(()) .layout_fn(|_, ctx, bc, _, _| { // this widget paints twenty points above below its layout bounds ctx.set_paint_insets(Insets::uniform_xy(0., 20.)); bc.max() }) .with_id(id1) .fix_size(100., 100.) .padding(10.0) .with_id(id2) .background(Color::BLACK) .center(); Harness::create_simple((), widget, |harness| { harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id1); // offset by padding assert_eq!(state.layout_rect().origin(), Point::new(10., 10.,)); // offset by padding, but then inset by paint insets assert_eq!(state.paint_rect().origin(), Point::new(10., -10.,)); // layout size is fixed assert_eq!(state.layout_rect().size(), Size::new(100., 100.,)); // paint size is modified by insets assert_eq!(state.paint_rect().size(), Size::new(100., 140.,)); // now does the container widget correctly propagate the child's paint rect? let state = harness.get_state(id2); assert_eq!(state.layout_rect().origin(), Point::ZERO); // offset by padding, but then inset by paint insets assert_eq!(state.paint_rect().origin(), Point::new(0., -10.,)); // 100 + 10 on each side assert_eq!(state.layout_rect().size(), Size::new(120., 120.,)); // paint size is modified by insets assert_eq!(state.paint_rect().size(), Size::new(120., 140.,)); }) } #[test] /// Does a Flex correctly compute the union of multiple children's paint rects? fn flex_paint_rect_overflow() { let id = WidgetId::next(); let widget = Flex::row() .with_flex_child( ModularWidget::new(()) .layout_fn(|_, ctx, bc, _, _| { ctx.set_paint_insets(Insets::new(20., 0., 0., 0.)); bc.constrain(Size::new(10., 10.)) }) .expand(), 1.0, ) .with_flex_child( ModularWidget::new(()) .layout_fn(|_, ctx, bc, _, _| { ctx.set_paint_insets(Insets::new(0., 20., 0., 0.)); bc.constrain(Size::new(10., 10.)) }) .expand(), 1.0, ) .with_flex_child( ModularWidget::new(()) .layout_fn(|_, ctx, bc, _, _| { ctx.set_paint_insets(Insets::new(0., 0., 0., 20.)); bc.constrain(Size::new(10., 10.)) }) .expand(), 1.0, ) .with_flex_child( ModularWidget::new(()) .layout_fn(|_, ctx, bc, _, _| { ctx.set_paint_insets(Insets::new(0., 0., 20., 0.)); bc.constrain(Size::new(10., 10.)) }) .expand(), 1.0, ) .with_id(id) .fix_height(200.) .padding(10.) .center(); Harness::create_simple((), widget, |harness| { harness.set_initial_size(Size::new(300., 300.)); harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id); assert_eq!(state.layout_rect().origin(), Point::new(10., 10.,)); assert_eq!(state.paint_rect().origin(), Point::new(-10., -10.,)); // each of our children insets 20. on a different side; their union // is a uniform 20. inset. let expected_paint_rect = state.layout_rect() + Insets::uniform(20.); assert_eq!(state.paint_rect().size(), expected_paint_rect.size()); }) } use crate::tests::harness::*; use crate::widget::AspectRatioBox; use crate::widget::Label; use crate::WidgetExt; #[test] fn aspect_ratio_tight_constraints() { let id = WidgetId::next(); let (width, height) = (400., 400.); let aspect = AspectRatioBox::<()>::new(Label::new("hello!"), 1.0) .with_id(id) .fix_width(width) .fix_height(height) .center(); let (window_width, window_height) = (600., 600.); Harness::create_simple((), aspect, |harness| { harness.set_initial_size(Size::new(window_width, window_height)); harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id); assert_eq!(state.layout_rect().size(), Size::new(width, height)); }); } #[test] fn aspect_ratio_infinite_constraints() { let id = WidgetId::next(); let (width, height) = (100., 100.); let label = Label::new("hello!").fix_width(width).height(height); let aspect = AspectRatioBox::<()>::new(label, 1.0) .with_id(id) .scroll() .center(); let (window_width, window_height) = (600., 600.); Harness::create_simple((), aspect, |harness| { harness.set_initial_size(Size::new(window_width, window_height)); harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id); assert_eq!(state.layout_rect().size(), Size::new(width, height)); }); } #[test] fn aspect_ratio_tight_constraint_on_width() { let id = WidgetId::next(); let label = Label::new("hello!"); let aspect = AspectRatioBox::<()>::new(label, 2.0) .with_id(id) .fix_width(300.) .center(); let (window_width, window_height) = (600., 50.); Harness::create_simple((), aspect, |harness| { harness.set_initial_size(Size::new(window_width, window_height)); harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id); assert_eq!(state.layout_rect().size(), Size::new(300., 50.)); }); } #[test] fn aspect_ratio() { let id = WidgetId::next(); let label = Label::new("hello!"); let aspect = AspectRatioBox::<()>::new(label, 2.0) .with_id(id) .center() .center(); let (window_width, window_height) = (1000., 1000.); Harness::create_simple((), aspect, |harness| { harness.set_initial_size(Size::new(window_width, window_height)); harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id); assert_eq!(state.layout_rect().size(), Size::new(1000., 500.)); }); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/tests/harness.rs
druid/src/tests/harness.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Tools and infrastructure for testing widgets. use std::path::Path; use std::sync::Arc; use crate::app::PendingWindow; use crate::core::{CommandQueue, WidgetState}; use crate::ext_event::ExtEventHost; use crate::piet::{BitmapTarget, Device, Error, ImageFormat, Piet}; use crate::*; use crate::debug_state::DebugState; pub(crate) const DEFAULT_SIZE: Size = Size::new(400., 400.); /// A type that tries very hard to provide a comforting and safe environment /// for widgets who are trying to find their way. /// /// You create a `Harness` with some widget and its initial data; then you /// can send events to that widget and verify that expected conditions are met. /// /// Harness tries to act like the normal Druid environment; for instance, it will /// attempt to dispatch any `Command`s that are sent during event handling, and /// it will call `update` automatically after an event. /// /// That said, it _is_ missing a bunch of logic that would normally be handled /// in `AppState`: for instance it does not clear the `needs_inval` and /// `children_changed` flags on the window after an update. /// /// In addition, layout and paint **are not called automatically**. This is /// because paint is triggered by `druid-shell`, and there is no `druid-shell` here; /// /// if you want those functions run you will need to call them yourself. /// /// Also, timers don't work. ¯\_(ツ)_/¯ pub struct Harness<'a, T> { piet: Piet<'a>, mock_app: MockAppState<T>, window_size: Size, } /// All of the state except for the `Piet` (render context). We need to pass /// that in to get around some lifetime issues. struct MockAppState<T> { data: T, env: Env, window: Window<T>, cmds: CommandQueue, } /// A way to clean up resources when our target goes out of scope. // the inner type is an option so that we can take ownership in `drop` even // though self is `& mut`. pub struct TargetGuard<'a>(Option<BitmapTarget<'a>>); impl<'a> TargetGuard<'a> { /// Turns the TargetGuard into a array of pixels #[allow(dead_code)] pub fn into_raw(mut self) -> Arc<[u8]> { let mut raw_target = self.0.take().unwrap(); raw_target .to_image_buf(ImageFormat::RgbaPremul) .unwrap() .raw_pixels_shared() } /// Saves the TargetGuard into a png #[allow(dead_code)] pub fn into_png<P: AsRef<Path>>(mut self, path: P) -> Result<(), Error> { let raw_target = self.0.take().unwrap(); raw_target.save_to_file(path) } } #[allow(missing_docs)] impl<T: Data> Harness<'_, T> { /// Create a new `Harness` with the given data and a root widget, /// and provide that harness to the passed in function. /// /// For lifetime reasons™, we cannot just make a harness. It's complicated. /// I tried my best. /// /// This function is a subset of [create_with_render](Harness::create_with_render) pub fn create_simple( data: T, root: impl Widget<T> + 'static, harness_closure: impl FnMut(&mut Harness<T>), ) { Self::create_with_render(data, root, DEFAULT_SIZE, harness_closure, |_target| {}) } /// Create a new `Harness` with the given data and a root widget, /// and provide that harness to the `harness_closure` callback and then the /// render_context to the `render_context_closure` callback. /// /// For lifetime reasons™, we cannot just make a harness. It's complicated. /// I tried my best. /// /// The with_render version of `create` also has a callback that can be used /// to save or inspect the painted widget /// /// # Usage /// /// The create functions are used to test a widget. The function takes a `root` widget /// and a data structure and uses them to create a `Harness`. The Harness can then be interacted /// with via the `harness_closure` callback. The final render of /// the widget can be inspected with the `render_context_closure` callback. /// /// # Arguments /// /// * `data` - A structure that matches the type of the widget and that will be /// passed to the `harness_closure` callback via the `Harness` structure. /// /// * `root` - The widget under test /// /// * `shape` - The shape of the render_context in the `Harness` structure /// /// * `harness_closure` - A closure used to interact with the widget under test through the /// `Harness` structure. /// /// * `render_context_closure` - A closure used to inspect the final render_context via the `TargetGuard` structure. /// pub fn create_with_render( data: T, root: impl Widget<T> + 'static, window_size: Size, mut harness_closure: impl FnMut(&mut Harness<T>), mut render_context_closure: impl FnMut(TargetGuard), ) { let ext_host = ExtEventHost::default(); let ext_handle = ext_host.make_sink(); let mut device = Device::new().expect("harness failed to get device"); let target = device .bitmap_target(window_size.width as usize, window_size.height as usize, 1.0) .expect("bitmap_target"); let mut target = TargetGuard(Some(target)); { let piet = target.0.as_mut().unwrap().render_context(); let pending = PendingWindow::new(root); let window = Window::new(WindowId::next(), Default::default(), pending, ext_handle); let mock_app = MockAppState { data, env: Env::with_default_i10n(), window, cmds: Default::default(), }; let mut harness = Harness { piet, mock_app, window_size, }; druid_shell::init_harness(); harness_closure(&mut harness); } render_context_closure(target) } /// Set the size without sending a resize event; intended to be used /// before calling `send_initial_events` pub fn set_initial_size(&mut self, size: Size) { self.window_size = size; } pub fn window(&self) -> &Window<T> { &self.mock_app.window } #[allow(dead_code)] pub fn window_mut(&mut self) -> &mut Window<T> { &mut self.mock_app.window } #[allow(dead_code)] pub fn data(&self) -> &T { &self.mock_app.data } /// Retrieve a copy of this widget's `WidgetState`, or die trying. pub fn get_state(&mut self, widget: WidgetId) -> WidgetState { match self.try_get_state(widget) { Some(thing) => thing, None => panic!("get_state failed for widget {widget:?}"), } } /// Attempt to retrieve a copy of this widget's `WidgetState`. pub fn try_get_state(&mut self, widget: WidgetId) -> Option<WidgetState> { let cell = StateCell::default(); let state_cell = cell.clone(); self.lifecycle(LifeCycle::Internal(InternalLifeCycle::DebugRequestState { widget, state_cell, })); cell.take() } /// Retrieve a copy of the root widget's `DebugState` (and by recursion, all others) pub fn get_root_debug_state(&self) -> DebugState { self.mock_app.root_debug_state() } /// Retrieve a copy of this widget's `DebugState`, or die trying. pub fn get_debug_state(&mut self, widget_id: WidgetId) -> DebugState { match self.try_get_debug_state(widget_id) { Some(thing) => thing, None => panic!("get_debug_state failed for widget {widget_id:?}"), } } /// Attempt to retrieve a copy of this widget's `DebugState`. pub fn try_get_debug_state(&mut self, widget_id: WidgetId) -> Option<DebugState> { let cell = DebugStateCell::default(); let state_cell = cell.clone(); self.lifecycle(LifeCycle::Internal( InternalLifeCycle::DebugRequestDebugState { widget: widget_id, state_cell, }, )); cell.take() } /// Inspect the `WidgetState` of each widget in the tree. /// /// The provided closure will be called on each widget. pub fn inspect_state(&mut self, f: impl Fn(&WidgetState) + 'static) { let checkfn = StateCheckFn::new(f); self.lifecycle(LifeCycle::Internal(InternalLifeCycle::DebugInspectState( checkfn, ))) } /// Send a command to a target. pub fn submit_command(&mut self, cmd: impl Into<Command>) { let command = cmd.into().default_to(self.mock_app.window.id.into()); let event = Event::Internal(InternalEvent::TargetedCommand(command)); self.event(event); } /// Send the events that would normally be sent when the app starts. // should we do this automatically? Also these will change regularly? pub fn send_initial_events(&mut self) { self.event(Event::WindowConnected); self.event(Event::WindowSize(self.window_size)); } /// Send an event to the widget. /// /// If this event triggers lifecycle events, they will also be dispatched, /// as will any resulting commands. This will also trigger `update`. /// /// Commands dispatched during `update` will not be sent? pub fn event(&mut self, event: Event) { self.mock_app.event(event); self.process_commands(); self.update(); } fn process_commands(&mut self) { loop { let cmd = self.mock_app.cmds.pop_front(); match cmd { Some(cmd) => self.event(Event::Internal(InternalEvent::TargetedCommand(cmd))), None => break, } } } pub(crate) fn lifecycle(&mut self, event: LifeCycle) { self.mock_app.lifecycle(event) } //TODO: should we expose this? I don't think so? fn update(&mut self) { self.mock_app.update() } /// Only do a layout pass, without painting pub fn just_layout(&mut self) { self.mock_app.layout() } /// Paints just the part of the window that was invalidated by calls to `request_paint` or /// `request_paint_rect`. /// /// Also resets the invalid region. #[allow(dead_code)] pub fn paint_invalid(&mut self) { let invalid = std::mem::replace(self.window_mut().invalid_mut(), Region::EMPTY); self.mock_app.paint_region(&mut self.piet, &invalid); } /// Paints the entire window and resets the invalid region. #[allow(dead_code)] pub fn paint(&mut self) { self.window_mut().invalid_mut().clear(); self.mock_app .paint_region(&mut self.piet, &self.window_size.to_rect().into()); } pub fn root_debug_state(&self) -> DebugState { self.mock_app.root_debug_state() } } impl<T: Data> MockAppState<T> { fn event(&mut self, event: Event) { self.window .event(&mut self.cmds, event, &mut self.data, &self.env); } fn lifecycle(&mut self, event: LifeCycle) { self.window .lifecycle(&mut self.cmds, &event, &self.data, &self.env, false); } fn update(&mut self) { self.window.update(&mut self.cmds, &self.data, &self.env); } fn layout(&mut self) { self.window .just_layout(&mut self.cmds, &self.data, &self.env); } #[allow(dead_code)] fn paint_region(&mut self, piet: &mut Piet, invalid: &Region) { self.window .do_paint(piet, invalid, &mut self.cmds, &self.data, &self.env); } pub fn root_debug_state(&self) -> DebugState { self.window.root_debug_state(&self.data) } } impl<T> Drop for Harness<'_, T> { fn drop(&mut self) { // We need to call finish even if a test assert failed if let Err(err) = self.piet.finish() { // We can't panic, because we might already be panicking tracing::error!("piet finish failed: {}", err); } } } impl Drop for TargetGuard<'_> { fn drop(&mut self) { // we need to call this to clean up the context let _ = self .0 .take() .map(|mut t| t.to_image_buf(piet::ImageFormat::RgbaPremul)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/menu/mod.rs
druid/src/menu/mod.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! ## Window, application, and context menus //! //! Menus in Druid follow a data-driven design similar to that of the main widget tree. The main //! types are [`Menu`] (representing a tree of menus and submenus) and [`MenuItem`] (representing a //! single "leaf" element). //! //! ## Menu actions //! //! Menu items can be associated with callbacks, which are triggered when a user selects that menu //! item. Each callback has access to the application data, and also gets access to a //! [`MenuEventCtx`], which allows for submitting [`Command`]s. //! //! ## Refreshing and rebuilding //! //! Menus, like widgets, update themselves based on changes in the data. There are two different //! ways that the menus update themselves: //! //! - a "refresh" is when the menu items update their text or their status (e.g. disabled, //! selected) based on changes to the data. Menu refreshes are handled for you automatically. For //! example, if you create a menu item whose title is a [`LabelText::Dynamic`] then that title //! will be kept up-to-date for you. //! //! The limitation of a "refresh" is that it cannot change the structure of the menus (e.g. by //! adding new items or moving things around). //! //! - a "rebuild" is when the menu is rebuilt from scratch. When you first set a menu (e.g. using //! [`WindowDesc::menu`]), you provide a callback for building the menu from data; a rebuild is //! when the menu decides to rebuild itself by invoking that callback again. //! //! Rebuilds have none of the limitations of refreshes, but Druid does not automatically decide //! when to do them. You need to use [`Menu::rebuild_on`] to decide when rebuild should //! occur. //! //! ## The macOS app menu //! //! On macOS, the main menu belongs to the application, not to the window. //! //! In Druid, whichever window is frontmost will have its menu displayed as the application menu. //! //! ## Examples //! //! Creating the default app menu for macOS: //! //! ``` //! use druid::commands; //! use druid::{Data, LocalizedString, Menu, MenuItem, SysMods}; //! //! fn macos_application_menu<T: Data>() -> Menu<T> { //! Menu::new(LocalizedString::new("macos-menu-application-menu")) //! .entry( //! MenuItem::new(LocalizedString::new("macos-menu-about-app")) //! // You need to handle the SHOW_ABOUT command yourself (or else do something //! // directly to the data here instead of using a command). //! .command(commands::SHOW_ABOUT), //! ) //! .separator() //! .entry( //! MenuItem::new(LocalizedString::new("macos-menu-preferences")) //! // You need to handle the SHOW_PREFERENCES command yourself (or else do something //! // directly to the data here instead of using a command). //! .command(commands::SHOW_PREFERENCES) //! .hotkey(SysMods::Cmd, ","), //! ) //! .separator() //! .entry(MenuItem::new(LocalizedString::new("macos-menu-services"))) //! .entry( //! MenuItem::new(LocalizedString::new("macos-menu-hide-app")) //! // Druid handles the HIDE_APPLICATION command automatically //! .command(commands::HIDE_APPLICATION) //! .hotkey(SysMods::Cmd, "h"), //! ) //! .entry( //! MenuItem::new(LocalizedString::new("macos-menu-hide-others")) //! // Druid handles the HIDE_OTHERS command automatically //! .command(commands::HIDE_OTHERS) //! .hotkey(SysMods::AltCmd, "h"), //! ) //! .entry( //! MenuItem::new(LocalizedString::new("macos-menu-show-all")) //! // You need to handle the SHOW_ALL command yourself (or else do something //! // directly to the data here instead of using a command). //! .command(commands::SHOW_ALL) //! ) //! .separator() //! .entry( //! MenuItem::new(LocalizedString::new("macos-menu-quit-app")) //! // Druid handles the QUIT_APP command automatically //! .command(commands::QUIT_APP) //! .hotkey(SysMods::Cmd, "q"), //! ) //! } //! ``` //! //! [`LabelText::Dynamic`]: crate::widget::LabelText::Dynamic //! [`WindowDesc::menu`]: crate::WindowDesc::menu //! [`Command`]: crate::Command use std::num::NonZeroU32; use crate::core::CommandQueue; use crate::kurbo::Point; use crate::shell::{Counter, HotKey, IntoKey, Menu as PlatformMenu}; use crate::widget::LabelText; use crate::{ArcStr, Command, Data, Env, Lens, RawMods, Target, WindowId}; static COUNTER: Counter = Counter::new(); pub mod sys; type MenuBuild<T> = Box<dyn FnMut(Option<WindowId>, &T, &Env) -> Menu<T>>; /// This is for completely recreating the menus (for when you want to change the actual menu /// structure, rather than just, say, enabling or disabling entries). pub(crate) struct MenuManager<T> { // The function for rebuilding the menu. If this is `None` (which is the case for context // menus), `menu` will always be `Some(..)`. build: Option<MenuBuild<T>>, popup: bool, old_data: Option<T>, menu: Option<Menu<T>>, } /// A menu displayed as a pop-over. pub(crate) struct ContextMenu<T> { pub(crate) menu: Menu<T>, pub(crate) location: Point, } impl<T: Data> MenuManager<T> { /// Create a new [`MenuManager`] for a title-bar menu. pub fn new( build: impl FnMut(Option<WindowId>, &T, &Env) -> Menu<T> + 'static, ) -> MenuManager<T> { MenuManager { build: Some(Box::new(build)), popup: false, old_data: None, menu: None, } } /// Create a new [`MenuManager`] for a context menu. pub fn new_for_popup(menu: Menu<T>) -> MenuManager<T> { MenuManager { build: None, popup: true, old_data: None, menu: Some(menu), } } /// If this platform always expects windows to have a menu by default, returns a menu. /// Otherwise, returns `None`. #[allow(unreachable_code)] pub fn platform_default() -> Option<MenuManager<T>> { #[cfg(target_os = "macos")] return Some(MenuManager::new(|_, _, _| sys::mac::menu_bar())); #[cfg(any( target_os = "windows", target_os = "freebsd", target_os = "linux", target_os = "openbsd" ))] return None; // we want to explicitly handle all platforms; log if a platform is missing. tracing::warn!("MenuManager::platform_default is not implemented for this platform."); None } /// Called when a menu event is received from the system. pub fn event( &mut self, queue: &mut CommandQueue, window: Option<WindowId>, id: MenuItemId, data: &mut T, env: &Env, ) { if let Some(m) = &mut self.menu { let mut ctx = MenuEventCtx { window, queue }; m.activate(&mut ctx, id, data, env); } } /// Build an initial menu from the application data. pub fn initialize(&mut self, window: Option<WindowId>, data: &T, env: &Env) -> PlatformMenu { if let Some(build) = &mut self.build { self.menu = Some((build)(window, data, env)); } self.old_data = Some(data.clone()); self.refresh(data, env) } /// Update the menu based on a change to the data. /// /// Returns a new `PlatformMenu` if the menu has changed; returns `None` if it hasn't. pub fn update( &mut self, window: Option<WindowId>, data: &T, env: &Env, ) -> Option<PlatformMenu> { if let (Some(menu), Some(old_data)) = (self.menu.as_mut(), self.old_data.as_ref()) { let ret = match menu.update(old_data, data, env) { MenuUpdate::NeedsRebuild => { if let Some(build) = &mut self.build { self.menu = Some((build)(window, data, env)); } else { tracing::warn!("tried to rebuild a context menu"); } Some(self.refresh(data, env)) } MenuUpdate::NeedsRefresh => Some(self.refresh(data, env)), MenuUpdate::UpToDate => None, }; self.old_data = Some(data.clone()); ret } else { tracing::error!("tried to update uninitialized menus"); None } } /// Builds a new menu for displaying the given data. /// /// Mostly you should probably use `update` instead, because that actually checks whether a /// refresh is necessary. pub fn refresh(&mut self, data: &T, env: &Env) -> PlatformMenu { if let Some(menu) = self.menu.as_mut() { let mut ctx = MenuBuildCtx::new(self.popup); menu.refresh_children(&mut ctx, data, env); ctx.current } else { tracing::error!("tried to refresh uninitialized menus"); PlatformMenu::new() } } } /// This context is available to the callback that is called when a menu item is activated. /// /// Currently, it only allows for submission of [`Command`]s. /// /// [`Command`]: crate::Command pub struct MenuEventCtx<'a> { window: Option<WindowId>, queue: &'a mut CommandQueue, } /// This context helps menu items to build the platform menu. struct MenuBuildCtx { current: PlatformMenu, } impl MenuBuildCtx { fn new(popup: bool) -> MenuBuildCtx { MenuBuildCtx { current: if popup { PlatformMenu::new_for_popup() } else { PlatformMenu::new() }, } } fn with_submenu(&mut self, text: &str, enabled: bool, f: impl FnOnce(&mut MenuBuildCtx)) { let mut child = MenuBuildCtx::new(false); f(&mut child); self.current.add_dropdown(child.current, text, enabled); } fn add_item( &mut self, id: u32, text: &str, key: Option<&HotKey>, selected: Option<bool>, enabled: bool, ) { self.current.add_item(id, text, key, selected, enabled); } fn add_separator(&mut self) { self.current.add_separator(); } } impl<'a> MenuEventCtx<'a> { /// Submit a [`Command`] to be handled by the main widget tree. /// /// If the command's target is [`Target::Auto`], it will be sent to the menu's window if the /// menu is associated with a window, or to [`Target::Global`] if the menu is not associated /// with a window. /// /// See [`EventCtx::submit_command`] for more information. /// /// [`Command`]: crate::Command /// [`EventCtx::submit_command`]: crate::EventCtx::submit_command /// [`Target::Auto`]: crate::Target::Auto /// [`Target::Global`]: crate::Target::Global pub fn submit_command(&mut self, cmd: impl Into<Command>) { self.queue.push_back( cmd.into() .default_to(self.window.map(Target::Window).unwrap_or(Target::Global)), ); } } #[derive(Clone, Copy, Debug)] enum MenuUpdate { /// The structure of the current menu is ok, but some elements need to be refreshed (e.g. /// changing their text, whether they are enabled, etc.) NeedsRefresh, /// The structure of the menu has changed; we need to rebuilt from scratch. NeedsRebuild, /// No need to rebuild anything. UpToDate, } impl MenuUpdate { fn combine(self, other: MenuUpdate) -> MenuUpdate { use MenuUpdate::*; match (self, other) { (NeedsRebuild, _) | (_, NeedsRebuild) => NeedsRebuild, (NeedsRefresh, _) | (_, NeedsRefresh) => NeedsRefresh, _ => UpToDate, } } } /// This is the trait that enables recursive visiting of all menu entries. It isn't publicly /// visible (the publicly visible analogue of this is `Into<MenuEntry<T>>`). trait MenuVisitor<T> { /// Called when a menu item is activated. /// /// `id` is the id of the entry that got activated. If this is different from your id, you are /// responsible for routing the activation to your child items. fn activate(&mut self, ctx: &mut MenuEventCtx, id: MenuItemId, data: &mut T, env: &Env); /// Called when the data is changed. fn update(&mut self, old_data: &T, data: &T, env: &Env) -> MenuUpdate; /// Called to refresh the menu. fn refresh(&mut self, ctx: &mut MenuBuildCtx, data: &T, env: &Env); } /// A wrapper for a menu item (or submenu) to give it access to a part of its parent data. /// /// This is the menu analogue of [`LensWrap`]. You will usually create it with [`Menu::lens`] or /// [`MenuItem::lens`] instead of using this struct directly. /// /// [`LensWrap`]: crate::widget::LensWrap pub struct MenuLensWrap<L, U> { lens: L, inner: Box<dyn MenuVisitor<U>>, old_data: Option<U>, old_env: Option<Env>, } impl<T: Data, U: Data, L: Lens<T, U>> MenuVisitor<T> for MenuLensWrap<L, U> { fn activate(&mut self, ctx: &mut MenuEventCtx, id: MenuItemId, data: &mut T, env: &Env) { let inner = &mut self.inner; self.lens .with_mut(data, |u| inner.activate(ctx, id, u, env)); } fn update(&mut self, old_data: &T, data: &T, env: &Env) -> MenuUpdate { let inner = &mut self.inner; let lens = &self.lens; let cached_old_data = &mut self.old_data; let cached_old_env = &mut self.old_env; lens.with(old_data, |old| { lens.with(data, |new| { let ret = if cached_old_data.as_ref().map(|x| x.same(old)) == Some(true) && cached_old_env.as_ref().map(|x| x.same(env)) == Some(true) { MenuUpdate::UpToDate } else { inner.update(old, new, env) }; *cached_old_data = Some(new.clone()); *cached_old_env = Some(env.clone()); ret }) }) } fn refresh(&mut self, ctx: &mut MenuBuildCtx, data: &T, env: &Env) { let inner = &mut self.inner; self.lens.with(data, |u| inner.refresh(ctx, u, env)) } } impl<T: Data, U: Data, L: Lens<T, U> + 'static> From<MenuLensWrap<L, U>> for MenuEntry<T> { fn from(m: MenuLensWrap<L, U>) -> MenuEntry<T> { MenuEntry { inner: Box::new(m) } } } /// An entry in a menu. /// /// An entry is either a [`MenuItem`], a submenu (i.e. [`Menu`]), or one of a few other /// possibilities (such as one of the two options above, wrapped in a [`MenuLensWrap`]). pub struct MenuEntry<T> { inner: Box<dyn MenuVisitor<T>>, } type MenuPredicate<T> = Box<dyn FnMut(&T, &T, &Env) -> bool>; /// A menu. /// /// Menus can be nested arbitrarily, so this could also be a submenu. /// See the [module level documentation](crate::menu) for more on how to use menus. pub struct Menu<T> { rebuild_on: Option<MenuPredicate<T>>, refresh_on: Option<MenuPredicate<T>>, item: MenuItem<T>, children: Vec<MenuEntry<T>>, // bloom? } #[doc(hidden)] #[deprecated(since = "0.8.0", note = "Renamed to Menu")] pub type MenuDesc<T> = Menu<T>; impl<T: Data> From<Menu<T>> for MenuEntry<T> { fn from(menu: Menu<T>) -> MenuEntry<T> { MenuEntry { inner: Box::new(menu), } } } type MenuCallback<T> = Box<dyn FnMut(&mut MenuEventCtx, &mut T, &Env)>; type HotKeyCallback<T> = Box<dyn FnMut(&T, &Env) -> Option<HotKey>>; /// An item in a menu. /// /// See the [module level documentation](crate::menu) for more on how to use menus. pub struct MenuItem<T> { id: MenuItemId, title: LabelText<T>, callback: Option<MenuCallback<T>>, hotkey: Option<HotKeyCallback<T>>, selected: Option<Box<dyn FnMut(&T, &Env) -> bool>>, enabled: Option<Box<dyn FnMut(&T, &Env) -> bool>>, // The last resolved state of this menu item. This is basically consists of all the properties // above, but "static" versions of them not depending on the data. old_state: Option<MenuItemState>, } impl<T: Data> From<MenuItem<T>> for MenuEntry<T> { fn from(i: MenuItem<T>) -> MenuEntry<T> { MenuEntry { inner: Box::new(i) } } } struct Separator; impl<T: Data> From<Separator> for MenuEntry<T> { fn from(s: Separator) -> MenuEntry<T> { MenuEntry { inner: Box::new(s) } } } impl<T: Data> Menu<T> { /// Create an empty menu. pub fn empty() -> Menu<T> { Menu { rebuild_on: None, refresh_on: None, item: MenuItem::new(""), children: Vec::new(), } } /// Create a menu with the given name. pub fn new(title: impl Into<LabelText<T>>) -> Menu<T> { Menu { rebuild_on: None, refresh_on: None, item: MenuItem::new(title), children: Vec::new(), } } /// Provide a callback for determining whether this item should be enabled. /// /// Whenever the callback returns `true`, the menu will be enabled. pub fn enabled_if(mut self, enabled: impl FnMut(&T, &Env) -> bool + 'static) -> Self { self.item = self.item.enabled_if(enabled); self } /// Enable or disable this menu. pub fn enabled(self, enabled: bool) -> Self { self.enabled_if(move |_data, _env| enabled) } #[doc(hidden)] #[deprecated(since = "0.8.0", note = "use entry instead")] pub fn append_entry(self, entry: impl Into<MenuEntry<T>>) -> Self { self.entry(entry) } #[doc(hidden)] #[deprecated(since = "0.8.0", note = "use separator instead")] pub fn append_separator(self) -> Self { self.separator() } /// Append a menu entry to this menu, returning the modified menu. pub fn entry(mut self, entry: impl Into<MenuEntry<T>>) -> Self { self.children.push(entry.into()); self } /// Append a separator to this menu, returning the modified menu. pub fn separator(self) -> Self { self.entry(Separator) } /// Supply a function to check when this menu needs to refresh itself. /// /// The arguments to the callback are (in order): /// - the previous value of the data, /// - the current value of the data, and /// - the current value of the environment. /// /// The callback should return true if the menu needs to refresh itself. /// /// This callback is intended to be purely an optimization. If you do create a menu without /// supplying a refresh callback, the menu will recursively check whether any children have /// changed and refresh itself if any have. By supplying a callback here, you can short-circuit /// those recursive calls. pub fn refresh_on(mut self, refresh: impl FnMut(&T, &T, &Env) -> bool + 'static) -> Self { self.refresh_on = Some(Box::new(refresh)); self } /// Supply a function to check when this menu needs to be rebuild from scratch. /// /// The arguments to the callback are (in order): /// - the previous value of the data, /// - the current value of the data, and /// - the current value of the environment. /// /// The callback should return true if the menu needs to be rebuilt. /// /// The difference between rebuilding and refreshing (as in [`refresh_on`]) is /// that rebuilding creates the menu from scratch using the original menu-building callback, /// whereas refreshing involves tweaking the existing menu entries (e.g. enabling or disabling /// items). /// /// If you do not provide a callback using this method, the menu will never get rebuilt. Also, /// only window and application menus get rebuilt; context menus never do. /// /// [`refresh_on`]: self::Menu<T>::refresh_on pub fn rebuild_on(mut self, rebuild: impl FnMut(&T, &T, &Env) -> bool + 'static) -> Self { self.rebuild_on = Some(Box::new(rebuild)); self } /// Wraps this menu in a lens, so that it can be added to a `Menu<S>`. pub fn lens<S: Data>(self, lens: impl Lens<S, T> + 'static) -> MenuEntry<S> { MenuLensWrap { lens, inner: Box::new(self), old_data: None, old_env: None, } .into() } // This is like MenuVisitor::refresh, but it doesn't add a submenu for the current level. // (This is the behavior we need for the top-level (unnamed) menu, which contains (e.g.) File, // Edit, etc. as submenus.) fn refresh_children(&mut self, ctx: &mut MenuBuildCtx, data: &T, env: &Env) { self.item.resolve(data, env); for child in &mut self.children { child.refresh(ctx, data, env); } } } impl<T: Data> MenuItem<T> { /// Create a new menu item with a given name. pub fn new(title: impl Into<LabelText<T>>) -> MenuItem<T> { let mut id = COUNTER.next() as u32; if id == 0 { id = COUNTER.next() as u32; } MenuItem { id: MenuItemId(std::num::NonZeroU32::new(id)), title: title.into(), callback: None, hotkey: None, selected: None, enabled: None, old_state: None, } } /// Provide a callback that will be invoked when this menu item is chosen. pub fn on_activate( mut self, on_activate: impl FnMut(&mut MenuEventCtx, &mut T, &Env) + 'static, ) -> Self { self.callback = Some(Box::new(on_activate)); self } /// Provide a [`Command`] that will be sent when this menu item is chosen. /// /// This is equivalent to `self.on_activate(move |ctx, _data, _env| ctx.submit_command(cmd))`. /// If the command's target is [`Target::Auto`], it will be sent to the menu's window if the /// menu is associated with a window, or to [`Target::Global`] if the menu is not associated /// with a window. /// /// [`Command`]: crate::Command /// [`Target::Auto`]: crate::Target::Auto /// [`Target::Global`]: crate::Target::Global pub fn command(self, cmd: impl Into<Command>) -> Self { let cmd = cmd.into(); self.on_activate(move |ctx, _data, _env| ctx.submit_command(cmd.clone())) } /// Provide a hotkey for activating this menu item. /// /// This is equivalent to /// `self.dynamic_hotkey(move |_, _| Some(HotKey::new(mods, key))` pub fn hotkey(self, mods: impl Into<Option<RawMods>>, key: impl IntoKey) -> Self { let hotkey = HotKey::new(mods, key); self.dynamic_hotkey(move |_, _| Some(hotkey.clone())) } /// Provide a dynamic hotkey for activating this menu item. /// /// The hotkey can change depending on the data. pub fn dynamic_hotkey( mut self, hotkey: impl FnMut(&T, &Env) -> Option<HotKey> + 'static, ) -> Self { self.hotkey = Some(Box::new(hotkey)); self } /// Provide a callback for determining whether this menu item should be enabled. /// /// Whenever the callback returns `true`, the item will be enabled. pub fn enabled_if(mut self, enabled: impl FnMut(&T, &Env) -> bool + 'static) -> Self { self.enabled = Some(Box::new(enabled)); self } /// Enable or disable this menu item. pub fn enabled(self, enabled: bool) -> Self { self.enabled_if(move |_data, _env| enabled) } /// Provide a callback for determining whether this menu item should be selected. /// /// Whenever the callback returns `true`, the item will be selected. pub fn selected_if(mut self, selected: impl FnMut(&T, &Env) -> bool + 'static) -> Self { self.selected = Some(Box::new(selected)); self } /// Select or deselect this menu item. pub fn selected(self, selected: bool) -> Self { self.selected_if(move |_data, _env| selected) } /// Wraps this menu item in a lens, so that it can be added to a `Menu<S>`. pub fn lens<S: Data>(self, lens: impl Lens<S, T> + 'static) -> MenuEntry<S> { MenuLensWrap { lens, inner: Box::new(self), old_data: None, old_env: None, } .into() } fn resolve(&mut self, data: &T, env: &Env) -> bool { self.title.resolve(data, env); let new_state = MenuItemState { title: self.title.display_text(), hotkey: self.hotkey.as_mut().and_then(|h| h(data, env)), selected: self.selected.as_mut().map(|s| s(data, env)), enabled: self.enabled.as_mut().map(|e| e(data, env)).unwrap_or(true), }; let ret = self.old_state.as_ref() != Some(&new_state); self.old_state = Some(new_state); ret } // Panics if we haven't been resolved. fn text(&self) -> &str { &self.old_state.as_ref().unwrap().title } // Panics if we haven't been resolved. fn is_enabled(&self) -> bool { self.old_state.as_ref().unwrap().enabled } } impl<T: Data> MenuVisitor<T> for Menu<T> { fn activate(&mut self, ctx: &mut MenuEventCtx, id: MenuItemId, data: &mut T, env: &Env) { for child in &mut self.children { child.activate(ctx, id, data, env); } } fn update(&mut self, old_data: &T, data: &T, env: &Env) -> MenuUpdate { if let Some(rebuild_on) = &mut self.rebuild_on { if rebuild_on(old_data, data, env) { return MenuUpdate::NeedsRebuild; } } if let Some(refresh_on) = &mut self.refresh_on { if refresh_on(old_data, data, env) { return MenuUpdate::NeedsRefresh; } } let mut ret = self.item.update(old_data, data, env); for child in &mut self.children { ret = ret.combine(child.update(old_data, data, env)); } ret } fn refresh(&mut self, ctx: &mut MenuBuildCtx, data: &T, env: &Env) { self.item.resolve(data, env); let children = &mut self.children; ctx.with_submenu(self.item.text(), self.item.is_enabled(), |ctx| { for child in children { child.refresh(ctx, data, env); } }); } } impl<T: Data> MenuVisitor<T> for MenuEntry<T> { fn activate(&mut self, ctx: &mut MenuEventCtx, id: MenuItemId, data: &mut T, env: &Env) { self.inner.activate(ctx, id, data, env); } fn update(&mut self, old_data: &T, data: &T, env: &Env) -> MenuUpdate { self.inner.update(old_data, data, env) } fn refresh(&mut self, ctx: &mut MenuBuildCtx, data: &T, env: &Env) { self.inner.refresh(ctx, data, env); } } impl<T: Data> MenuVisitor<T> for MenuItem<T> { fn activate(&mut self, ctx: &mut MenuEventCtx, id: MenuItemId, data: &mut T, env: &Env) { if id == self.id { if let Some(callback) = &mut self.callback { callback(ctx, data, env); } } } fn update(&mut self, _old_data: &T, data: &T, env: &Env) -> MenuUpdate { if self.resolve(data, env) { MenuUpdate::NeedsRefresh } else { MenuUpdate::UpToDate } } fn refresh(&mut self, ctx: &mut MenuBuildCtx, data: &T, env: &Env) { self.resolve(data, env); let state = self.old_state.as_ref().unwrap(); ctx.add_item( self.id.0.map(|x| x.get()).unwrap_or(0), &state.title, state.hotkey.as_ref(), state.selected, state.enabled, ); } } impl<T: Data> MenuVisitor<T> for Separator { fn activate(&mut self, _ctx: &mut MenuEventCtx, _id: MenuItemId, _data: &mut T, _env: &Env) {} fn update(&mut self, _old_data: &T, _data: &T, _env: &Env) -> MenuUpdate { MenuUpdate::UpToDate } fn refresh(&mut self, ctx: &mut MenuBuildCtx, _data: &T, _env: &Env) { ctx.add_separator(); } } // The resolved state of a menu item. #[derive(PartialEq)] struct MenuItemState { title: ArcStr, hotkey: Option<HotKey>, selected: Option<bool>, enabled: bool, } /// Uniquely identifies a menu item. /// /// On the `druid-shell` side, the id is represented as a u32. /// We reserve '0' as a placeholder value; on the Rust side /// we represent this as an `Option<NonZerou32>`, which better /// represents the semantics of our program. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct MenuItemId(Option<NonZeroU32>); impl MenuItemId { pub(crate) fn new(id: u32) -> MenuItemId { MenuItemId(NonZeroU32::new(id)) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/menu/sys.rs
druid/src/menu/sys.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Pre-configured, platform appropriate menus and menu items. use crate::{commands, LocalizedString, SysMods}; use super::*; /// Menu items that exist on all platforms. pub mod common { use super::*; /// 'Cut'. pub fn cut<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-cut")) .command(commands::CUT) .hotkey(SysMods::Cmd, "x") } /// The 'Copy' menu item. pub fn copy<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-copy")) .command(commands::COPY) .hotkey(SysMods::Cmd, "c") } /// The 'Paste' menu item. pub fn paste<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-paste")) .command(commands::PASTE) .hotkey(SysMods::Cmd, "v") } /// The 'Undo' menu item. pub fn undo<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-undo")) .command(commands::UNDO) .hotkey(SysMods::Cmd, "z") } /// The 'Redo' menu item. pub fn redo<T: Data>() -> MenuItem<T> { let item = MenuItem::new(LocalizedString::new("common-menu-redo")).command(commands::REDO); #[cfg(target_os = "windows")] { item.hotkey(SysMods::Cmd, "y") } #[cfg(not(target_os = "windows"))] { item.hotkey(SysMods::CmdShift, "Z") } } } /// Windows. pub mod win { use super::*; /// The 'File' menu. /// /// These items are taken from [the win32 documentation][]. /// /// [the win32 documentation]: https://docs.microsoft.com/en-us/windows/win32/uxguide/cmd-menus#standard-menus pub mod file { use super::*; use crate::FileDialogOptions; /// A default file menu. /// /// This will not be suitable for many applications; you should /// build the menu you need manually, using the items defined here /// where appropriate. pub fn default<T: Data>() -> Menu<T> { Menu::new(LocalizedString::new("common-menu-file-menu")) .entry(new()) .entry(open()) .entry(close()) .entry(save_ellipsis()) .entry(save_as()) // revert to saved? .entry(print()) .entry(page_setup()) .separator() .entry(exit()) } /// The 'New' menu item. pub fn new<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-new")) .command(commands::NEW_FILE) .hotkey(SysMods::Cmd, "n") } /// The 'Open...' menu item. pub fn open<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-open")) .command(commands::SHOW_OPEN_PANEL.with(FileDialogOptions::default())) .hotkey(SysMods::Cmd, "o") } /// The 'Close' menu item. pub fn close<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-close")) .command(commands::CLOSE_WINDOW) } /// The 'Save' menu item. pub fn save<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-save")) .command(commands::SAVE_FILE) .hotkey(SysMods::Cmd, "s") } /// The 'Save...' menu item. /// /// This is used if we need to show a dialog to select save location. pub fn save_ellipsis<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-save-ellipsis")) .command(commands::SHOW_SAVE_PANEL.with(FileDialogOptions::default())) .hotkey(SysMods::Cmd, "s") } /// The 'Save as...' menu item. pub fn save_as<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-save-as")) .command(commands::SHOW_SAVE_PANEL.with(FileDialogOptions::default())) .hotkey(SysMods::CmdShift, "S") } /// The 'Print...' menu item. pub fn print<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-print")) .command(commands::PRINT) .hotkey(SysMods::Cmd, "p") } /// The 'Print Preview' menu item. pub fn print_preview<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-print-preview")) .command(commands::PRINT_PREVIEW) } /// The 'Page Setup...' menu item. pub fn page_setup<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-page-setup")) .command(commands::PRINT_SETUP) } /// The 'Exit' menu item. pub fn exit<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("win-menu-file-exit")).command(commands::QUIT_APP) } } } /// macOS. pub mod mac { use super::*; /// A basic macOS menu bar. pub fn menu_bar<T: Data>() -> Menu<T> { Menu::new(LocalizedString::new("")) .entry(application::default()) .entry(file::default()) } /// The application menu pub mod application { use super::*; /// The default Application menu. pub fn default<T: Data>() -> Menu<T> { #[allow(deprecated)] Menu::new(LocalizedString::new("macos-menu-application-menu")) .entry(about()) .separator() .entry(preferences().enabled(false)) .separator() //.entry(MenuDesc::new(LocalizedString::new("macos-menu-services"))) .entry(hide()) .entry(hide_others()) .entry(show_all().enabled(false)) .separator() .entry(quit()) } /// The 'About App' menu item. pub fn about<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("macos-menu-about-app")) .command(commands::SHOW_ABOUT) } /// The preferences menu item. pub fn preferences<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("macos-menu-preferences")) .command(commands::SHOW_PREFERENCES) .hotkey(SysMods::Cmd, ",") } /// The 'Hide' builtin menu item. #[cfg_attr( not(target_os = "macos"), deprecated = "hide does nothing on platforms other than macOS" )] pub fn hide<T: Data>() -> MenuItem<T> { #[allow(deprecated)] MenuItem::new(LocalizedString::new("macos-menu-hide-app")) .command(commands::HIDE_APPLICATION) .hotkey(SysMods::Cmd, "h") } /// The 'Hide Others' builtin menu item. #[cfg_attr( not(target_os = "macos"), deprecated = "hide_others does nothing on platforms other than macOS" )] pub fn hide_others<T: Data>() -> MenuItem<T> { #[allow(deprecated)] MenuItem::new(LocalizedString::new("macos-menu-hide-others")) .command(commands::HIDE_OTHERS) .hotkey(SysMods::AltCmd, "h") } /// The 'show all' builtin menu item //FIXME: this doesn't work pub fn show_all<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("macos-menu-show-all")).command(commands::SHOW_ALL) } /// The 'Quit' menu item. pub fn quit<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("macos-menu-quit-app")) .command(commands::QUIT_APP) .hotkey(SysMods::Cmd, "q") } } /// The file menu. pub mod file { use super::*; use crate::FileDialogOptions; /// A default file menu. /// /// This will not be suitable for many applications; you should /// build the menu you need manually, using the items defined here /// where appropriate. pub fn default<T: Data>() -> Menu<T> { Menu::new(LocalizedString::new("common-menu-file-menu")) .entry(new_file()) .entry(open_file()) // open recent? .separator() .entry(close()) .entry(save().enabled(false)) .entry(save_as().enabled(false)) // revert to saved? .separator() .entry(page_setup().enabled(false)) .entry(print().enabled(false)) } /// The 'New Window' item. /// /// Note: depending on context, apps might show 'New', 'New Window', /// 'New File', or 'New...' (where the last indicates that the menu /// item will open a prompt). You may want to create a custom /// item to capture the intent of your menu, instead of using this one. pub fn new_file<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-new")) .command(commands::NEW_FILE) .hotkey(SysMods::Cmd, "n") } /// The 'Open...' menu item. Will display the system file-chooser. pub fn open_file<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-open")) .command(commands::SHOW_OPEN_PANEL.with(FileDialogOptions::default())) .hotkey(SysMods::Cmd, "o") } /// The 'Close' menu item. pub fn close<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-close")) .command(commands::CLOSE_WINDOW) .hotkey(SysMods::Cmd, "w") } /// The 'Save' menu item. pub fn save<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-save")) .command(commands::SAVE_FILE) .hotkey(SysMods::Cmd, "s") } /// The 'Save...' menu item. /// /// This is used if we need to show a dialog to select save location. pub fn save_ellipsis<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-save-ellipsis")) .command(commands::SHOW_SAVE_PANEL.with(FileDialogOptions::default())) .hotkey(SysMods::Cmd, "s") } /// The 'Save as...' pub fn save_as<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-save-as")) .command(commands::SHOW_SAVE_PANEL.with(FileDialogOptions::default())) .hotkey(SysMods::CmdShift, "S") } /// The 'Page Setup...' menu item. pub fn page_setup<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-page-setup")) .command(commands::PRINT_SETUP) .hotkey(SysMods::CmdShift, "P") } /// The 'Print...' menu item. pub fn print<T: Data>() -> MenuItem<T> { MenuItem::new(LocalizedString::new("common-menu-file-print")) .command(commands::PRINT) .hotkey(SysMods::Cmd, "p") } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/attribute.rs
druid/src/text/attribute.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Text attributes and spans. use std::ops::Range; use crate::piet::{Color, FontFamily, FontStyle, FontWeight, TextAttribute as PietAttr}; use crate::{Command, Env, FontDescriptor, KeyOrValue}; use super::EnvUpdateCtx; /// A clickable range of text with an associated [`Command`]. #[derive(Debug, Clone)] pub struct Link { /// The range of text for the link. pub range: Range<usize>, /// A [`Command`] representing the link's payload. pub command: Command, } /// A collection of spans of attributes of various kinds. #[derive(Debug, Clone, Default)] pub struct AttributeSpans { family: SpanSet<FontFamily>, size: SpanSet<KeyOrValue<f64>>, weight: SpanSet<FontWeight>, fg_color: SpanSet<KeyOrValue<Color>>, style: SpanSet<FontStyle>, underline: SpanSet<bool>, strikethrough: SpanSet<bool>, font_descriptor: SpanSet<KeyOrValue<FontDescriptor>>, } /// A set of spans for a given attribute. /// /// Invariant: the spans are sorted and non-overlapping. #[derive(Debug, Clone)] struct SpanSet<T> { spans: Vec<Span<T>>, } /// An attribute and a range. /// /// This is used to represent text attributes of various kinds, /// with the range representing a region of some text buffer. #[derive(Debug, Clone, PartialEq)] struct Span<T> { range: Range<usize>, attr: T, } /// Attributes that can be applied to text. /// /// Where possible, attributes are [`KeyOrValue`] types; this means you /// can use items defined in the [`theme`] *or* concrete types, where appropriate. /// /// The easiest way to construct these attributes is via the various constructor /// methods, such as [`Attribute::size`] or [`Attribute::text_color`]. /// /// # Examples /// /// ``` /// use druid::text::Attribute; /// use druid::{theme, Color}; /// /// let font = Attribute::font_descriptor(theme::UI_FONT); /// let font_size = Attribute::size(32.0); /// let explicit_color = Attribute::text_color(Color::BLACK); /// let theme_color = Attribute::text_color(theme::SELECTION_COLOR); /// ``` /// /// [`theme`]: crate::theme #[derive(Debug, Clone)] pub enum Attribute { /// The font family. FontFamily(FontFamily), /// The font size, in points. FontSize(KeyOrValue<f64>), /// The [`FontWeight`]. Weight(FontWeight), /// The foreground color of the text. TextColor(KeyOrValue<Color>), /// The [`FontStyle`]; either regular or italic. Style(FontStyle), /// Underline. Underline(bool), /// Strikethrough Strikethrough(bool), /// A [`FontDescriptor`]. Descriptor(KeyOrValue<FontDescriptor>), } impl Link { /// Create a new `Link`. pub fn new(range: Range<usize>, command: Command) -> Self { Self { range, command } } /// Get this `Link`'s range. pub fn range(&self) -> Range<usize> { self.range.clone() } } impl AttributeSpans { /// Create a new, empty `AttributeSpans`. pub fn new() -> Self { Default::default() } /// Add a new [`Attribute`] over the provided [`Range`]. pub fn add(&mut self, range: Range<usize>, attr: Attribute) { match attr { Attribute::FontFamily(attr) => self.family.add(Span::new(range, attr)), Attribute::FontSize(attr) => self.size.add(Span::new(range, attr)), Attribute::Weight(attr) => self.weight.add(Span::new(range, attr)), Attribute::TextColor(attr) => self.fg_color.add(Span::new(range, attr)), Attribute::Style(attr) => self.style.add(Span::new(range, attr)), Attribute::Underline(attr) => self.underline.add(Span::new(range, attr)), Attribute::Strikethrough(attr) => self.strikethrough.add(Span::new(range, attr)), Attribute::Descriptor(attr) => self.font_descriptor.add(Span::new(range, attr)), } } pub(crate) fn to_piet_attrs(&self, env: &Env) -> Vec<(Range<usize>, PietAttr)> { let mut items = Vec::new(); for Span { range, attr } in self.font_descriptor.iter() { let font = attr.resolve(env); items.push((range.clone(), PietAttr::FontFamily(font.family))); items.push((range.clone(), PietAttr::FontSize(font.size))); items.push((range.clone(), PietAttr::Weight(font.weight))); items.push((range.clone(), PietAttr::Style(font.style))); } items.extend( self.family .iter() .map(|s| (s.range.clone(), PietAttr::FontFamily(s.attr.clone()))), ); items.extend( self.size .iter() .map(|s| (s.range.clone(), PietAttr::FontSize(s.attr.resolve(env)))), ); items.extend( self.weight .iter() .map(|s| (s.range.clone(), PietAttr::Weight(s.attr))), ); items.extend( self.fg_color .iter() .map(|s| (s.range.clone(), PietAttr::TextColor(s.attr.resolve(env)))), ); items.extend( self.style .iter() .map(|s| (s.range.clone(), PietAttr::Style(s.attr))), ); items.extend( self.underline .iter() .map(|s| (s.range.clone(), PietAttr::Underline(s.attr))), ); items.extend( self.strikethrough .iter() .map(|s| (s.range.clone(), PietAttr::Strikethrough(s.attr))), ); // sort by ascending start order; this is a stable sort // so items that come from FontDescriptor will stay at the front items.sort_by(|a, b| a.0.start.cmp(&b.0.start)); items } pub(crate) fn env_update(&self, ctx: &EnvUpdateCtx) -> bool { self.size .iter() .any(|span_attr| ctx.env_key_changed(&span_attr.attr)) || self .fg_color .iter() .any(|span_attr| ctx.env_key_changed(&span_attr.attr)) || self .font_descriptor .iter() .any(|span_attr| ctx.env_key_changed(&span_attr.attr)) } } impl<T: Clone> SpanSet<T> { fn iter(&self) -> impl Iterator<Item = &Span<T>> { self.spans.iter() } /// Add a `Span` to this `SpanSet`. /// /// Spans can be added in any order. existing spans will be updated /// as required. fn add(&mut self, span: Span<T>) { let span_start = span.range.start; let span_end = span.range.end; let insert_idx = self .spans .iter() .position(|x| x.range.start >= span.range.start) .unwrap_or(self.spans.len()); // if we are inserting into the middle of an existing span we need // to add the trailing portion back afterwards. let mut prev_remainder = None; if insert_idx > 0 { // truncate the preceding item, if necessary let before = self.spans.get_mut(insert_idx - 1).unwrap(); if before.range.end > span_end { let mut remainder = before.clone(); remainder.range.start = span_end; prev_remainder = Some(remainder); } before.range.end = before.range.end.min(span_start); } self.spans.insert(insert_idx, span); if let Some(remainder) = prev_remainder.take() { self.spans.insert(insert_idx + 1, remainder); } // clip any existing spans as needed for after in self.spans.iter_mut().skip(insert_idx + 1) { after.range.start = after.range.start.max(span_end); after.range.end = after.range.end.max(span_end); } // remove any spans that have been overwritten self.spans.retain(|span| !span.is_empty()); } /// Edit the spans, inserting empty space into the changed region if needed. /// /// This is used to keep the spans up to date as edits occur in the buffer. /// /// `changed` is the range of the string that has been replaced; this can /// be an empty range (eg, 10..10) for the insertion case. /// /// `new_len` is the length of the inserted text. //TODO: we could be smarter here about just extending the existing spans //as required for insertions in the interior of a span. //TODO: this isn't currently used; it should be used if we use spans with //some editable type. // the branches are much more readable without sharing code #[allow(dead_code, clippy::branches_sharing_code)] fn edit(&mut self, changed: Range<usize>, new_len: usize) { let old_len = changed.len(); let mut to_insert = None; for (idx, Span { range, attr }) in self.spans.iter_mut().enumerate() { if range.end <= changed.start { continue; } else if range.start < changed.start { // we start before but end inside; truncate end if range.end <= changed.end { range.end = changed.start; // we start before and end after; this is a special case, // we'll need to add a new span } else { let new_start = changed.start + new_len; let new_end = range.end - old_len + new_len; let new_span = Span::new(new_start..new_end, attr.clone()); to_insert = Some((idx + 1, new_span)); range.end = changed.start; } // start inside } else if range.start < changed.end { range.start = changed.start + new_len; // end inside; collapse if range.end <= changed.end { range.end = changed.start + new_len; // end outside: adjust by length delta } else { range.end -= old_len; range.end += new_len; } // whole range is after: } else { range.start -= old_len; range.start += new_len; range.end -= old_len; range.end += new_len; } } if let Some((idx, span)) = to_insert.take() { self.spans.insert(idx, span); } self.spans.retain(|span| !span.is_empty()); } } impl<T> Span<T> { fn new(range: Range<usize>, attr: T) -> Self { Span { range, attr } } fn is_empty(&self) -> bool { self.range.end <= self.range.start } } impl Attribute { /// Create a new font size attribute. pub fn size(size: impl Into<KeyOrValue<f64>>) -> Self { Attribute::FontSize(size.into()) } /// Create a new foreground color attribute. pub fn text_color(color: impl Into<KeyOrValue<Color>>) -> Self { Attribute::TextColor(color.into()) } /// Create a new font family attribute. pub fn font_family(family: FontFamily) -> Self { Attribute::FontFamily(family) } /// Create a new `FontWeight` attribute. pub fn weight(weight: FontWeight) -> Self { Attribute::Weight(weight) } /// Create a new `FontStyle` attribute. pub fn style(style: FontStyle) -> Self { Attribute::Style(style) } /// Create a new underline attribute. pub fn underline(underline: bool) -> Self { Attribute::Underline(underline) } /// Create a new strikethrough attribute. pub fn strikethrough(strikethrough: bool) -> Self { Attribute::Strikethrough(strikethrough) } /// Create a new `FontDescriptor` attribute. pub fn font_descriptor(font: impl Into<KeyOrValue<FontDescriptor>>) -> Self { Attribute::Descriptor(font.into()) } } impl<T> Default for SpanSet<T> { fn default() -> Self { SpanSet { spans: Vec::new() } } } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn smoke_test_spans() { let mut spans = SpanSet::<u32>::default(); spans.add(Span::new(2..10, 1)); spans.add(Span::new(3..6, 2)); assert_eq!( &spans.spans, &vec![Span::new(2..3, 1), Span::new(3..6, 2), Span::new(6..10, 1)] ); spans.add(Span::new(0..12, 3)); assert_eq!(&spans.spans, &vec![Span::new(0..12, 3)]); spans.add(Span::new(5..20, 4)); assert_eq!(&spans.spans, &vec![Span::new(0..5, 3), Span::new(5..20, 4)]); } #[test] fn edit_spans() { let mut spans = SpanSet::<u32>::default(); spans.add(Span::new(0..2, 1)); spans.add(Span::new(8..12, 2)); spans.add(Span::new(13..16, 3)); spans.add(Span::new(20..22, 4)); let mut deletion = spans.clone(); deletion.edit(6..14, 0); assert_eq!( &deletion.spans, &vec![Span::new(0..2, 1), Span::new(6..8, 3), Span::new(12..14, 4)] ); spans.edit(10..10, 2); assert_eq!( &spans.spans, &vec![ Span::new(0..2, 1), Span::new(8..10, 2), Span::new(12..14, 2), Span::new(15..18, 3), Span::new(22..24, 4), ] ); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/rich_text.rs
druid/src/text/rich_text.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Rich text with style spans. use std::ops::{Range, RangeBounds}; use std::sync::Arc; use super::attribute::Link; use super::{Attribute, AttributeSpans, EnvUpdateCtx, TextStorage}; use crate::piet::{ util, Color, FontFamily, FontStyle, FontWeight, PietTextLayoutBuilder, TextLayoutBuilder, TextStorage as PietTextStorage, }; use crate::{ArcStr, Command, Data, Env, FontDescriptor, KeyOrValue}; /// Text with optional style spans. #[derive(Clone, Debug, Data)] pub struct RichText { buffer: ArcStr, attrs: Arc<AttributeSpans>, links: Arc<[Link]>, } impl RichText { /// Create a new `RichText` object with the provided text. pub fn new(buffer: ArcStr) -> Self { RichText::new_with_attributes(buffer, Default::default()) } /// Create a new `RichText`, providing explicit attributes. pub fn new_with_attributes(buffer: ArcStr, attributes: AttributeSpans) -> Self { RichText { buffer, attrs: Arc::new(attributes), // TODO: Figure out if this needs to stay Arc, or if it can be switched to Rc #[allow(clippy::arc_with_non_send_sync)] links: Arc::new([]), } } /// Builder-style method for adding an [`Attribute`] to a range of text. pub fn with_attribute(mut self, range: impl RangeBounds<usize>, attr: Attribute) -> Self { self.add_attribute(range, attr); self } /// The length of the buffer, in utf8 code units. pub fn len(&self) -> usize { self.buffer.len() } /// Returns `true` if the underlying buffer is empty. pub fn is_empty(&self) -> bool { self.buffer.is_empty() } /// Add an [`Attribute`] to the provided range of text. pub fn add_attribute(&mut self, range: impl RangeBounds<usize>, attr: Attribute) { let range = util::resolve_range(range, self.buffer.len()); Arc::make_mut(&mut self.attrs).add(range, attr); } } impl PietTextStorage for RichText { fn as_str(&self) -> &str { self.buffer.as_str() } } impl TextStorage for RichText { fn add_attributes( &self, mut builder: PietTextLayoutBuilder, env: &Env, ) -> PietTextLayoutBuilder { for (range, attr) in self.attrs.to_piet_attrs(env) { builder = builder.range_attribute(range, attr); } builder } fn env_update(&self, ctx: &EnvUpdateCtx) -> bool { self.attrs.env_update(ctx) } fn links(&self) -> &[Link] { &self.links } } /// A builder for creating [`RichText`] objects. /// /// This builder allows you to construct a [`RichText`] object by building up a sequence /// of styled sub-strings; first you [`push`](RichTextBuilder::push) a `&str` onto the string, /// and then you can optionally add styles to that text via the returned [`AttributesAdder`] /// object. /// /// # Example /// ``` /// # use druid::text::{Attribute, RichTextBuilder}; /// # use druid::{FontWeight, Color}; /// let mut builder = RichTextBuilder::new(); /// builder.push("Hello "); /// builder.push("World!").weight(FontWeight::BOLD); /// /// // Can also use write! /// write!(builder, "Here is your number: {}", 1).underline(true).text_color(Color::RED); /// /// let rich_text = builder.build(); /// ``` #[derive(Default)] pub struct RichTextBuilder { buffer: String, attrs: AttributeSpans, links: Vec<Link>, } impl RichTextBuilder { /// Create a new `RichTextBuilder`. pub fn new() -> Self { Self::default() } /// Append a `&str` to the end of the text. /// /// This method returns a [`AttributesAdder`] that can be used to style the newly /// added string slice. pub fn push(&mut self, string: &str) -> AttributesAdder<'_> { let range = self.buffer.len()..(self.buffer.len() + string.len()); self.buffer.push_str(string); self.add_attributes_for_range(range) } /// Glue for usage of the write! macro. /// /// This method should generally not be invoked manually, but rather through the write! macro itself. #[doc(hidden)] pub fn write_fmt(&mut self, fmt: std::fmt::Arguments<'_>) -> AttributesAdder<'_> { use std::fmt::Write; let start = self.buffer.len(); self.buffer .write_fmt(fmt) .expect("a formatting trait implementation returned an error"); self.add_attributes_for_range(start..self.buffer.len()) } /// Get an [`AttributesAdder`] for the given range. /// /// This can be used to modify styles for a given range after it has been added. pub fn add_attributes_for_range( &mut self, range: impl RangeBounds<usize>, ) -> AttributesAdder<'_> { let range = util::resolve_range(range, self.buffer.len()); AttributesAdder { rich_text_builder: self, range, } } /// Build the `RichText`. pub fn build(self) -> RichText { RichText { buffer: self.buffer.into(), attrs: self.attrs.into(), links: self.links.into(), } } } /// Adds Attributes to the text. /// /// See also: [`RichTextBuilder`] pub struct AttributesAdder<'a> { rich_text_builder: &'a mut RichTextBuilder, range: Range<usize>, } impl AttributesAdder<'_> { /// Add the given attribute. pub fn add_attr(&mut self, attr: Attribute) -> &mut Self { self.rich_text_builder.attrs.add(self.range.clone(), attr); self } /// Add a font size attribute. pub fn size(&mut self, size: impl Into<KeyOrValue<f64>>) -> &mut Self { self.add_attr(Attribute::size(size)); self } /// Add a foreground color attribute. pub fn text_color(&mut self, color: impl Into<KeyOrValue<Color>>) -> &mut Self { self.add_attr(Attribute::text_color(color)); self } /// Add a font family attribute. pub fn font_family(&mut self, family: FontFamily) -> &mut Self { self.add_attr(Attribute::font_family(family)); self } /// Add a `FontWeight` attribute. pub fn weight(&mut self, weight: FontWeight) -> &mut Self { self.add_attr(Attribute::weight(weight)); self } /// Add a `FontStyle` attribute. pub fn style(&mut self, style: FontStyle) -> &mut Self { self.add_attr(Attribute::style(style)); self } /// Add a underline attribute. pub fn underline(&mut self, underline: bool) -> &mut Self { self.add_attr(Attribute::underline(underline)); self } /// Add a strikethrough attribute. pub fn strikethrough(&mut self, strikethrough: bool) -> &mut Self { self.add_attr(Attribute::Strikethrough(strikethrough)); self } /// Add a `FontDescriptor` attribute. pub fn font_descriptor(&mut self, font: impl Into<KeyOrValue<FontDescriptor>>) -> &mut Self { self.add_attr(Attribute::font_descriptor(font)); self } /// Add a [`Link`] attribute. /// /// [`Link`]: super::attribute::Link pub fn link(&mut self, command: impl Into<Command>) -> &mut Self { self.rich_text_builder .links .push(Link::new(self.range.clone(), command.into())); self } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/input_component.rs
druid/src/text/input_component.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget component that integrates with the platform text system. use std::cell::{Cell, Ref, RefCell, RefMut}; use std::ops::Range; use std::sync::{Arc, Weak}; use tracing::instrument; use super::{ EditableText, ImeHandlerRef, ImeInvalidation, InputHandler, Movement, Selection, TextAction, TextLayout, TextStorage, }; use crate::kurbo::{Line, Point, Rect, Vec2}; use crate::piet::TextLayout as _; use crate::widget::prelude::*; use crate::{text, theme, Cursor, Env, Modifiers, Selector, TextAlignment, UpdateCtx}; /// A widget that accepts text input. /// /// This is intended to be used as a component of other widgets. /// /// Text input is more complicated than you think, probably. For a good /// overview, see [`druid_shell::text`]. /// /// This type manages an inner [`EditSession`] that is shared with the platform. /// Unlike other aspects of Druid, the platform interacts with this session, not /// through discrete events. /// /// This is managed through a simple 'locking' mechanism; the platform asks for /// a lock on a particular text session that it wishes to interact with, calls /// methods on the locked session, and then later releases the lock. /// /// Importantly, *other events may be received while the lock is held*. /// /// It is the responsibility of the user of this widget to ensure that the /// session is not locked before it is accessed. This can be done by checking /// [`TextComponent::can_read`] and [`TextComponent::can_write`]; /// after checking these methods the inner session can be accessed via /// [`TextComponent::borrow`] and [`TextComponent::borrow_mut`]. /// /// Sementically, this functions like a `RefCell`; attempting to borrow while /// a lock is held will result in a panic. #[derive(Debug, Clone)] pub struct TextComponent<T> { edit_session: Arc<RefCell<EditSession<T>>>, lock: Arc<Cell<ImeLock>>, // HACK: because of the way focus works (it is managed higher up, in // whatever widget is controlling this) we can't rely on `is_focused` in // the PaintCtx. /// A manual flag set by the parent to control drawing behaviour. /// /// The parent should update this when handling [`LifeCycle::FocusChanged`]. pub has_focus: bool, } /// Editable text state. /// /// This is the inner state of a [`TextComponent`]. It should only be accessed /// through its containing [`TextComponent`], or by the platform through an /// [`ImeHandlerRef`] created by [`TextComponent::input_handler`]. #[derive(Debug, Clone)] pub struct EditSession<T> { /// The inner [`TextLayout`] object. /// /// This is exposed so that users can do things like set text properties; /// you should avoid doing things like rebuilding this layout manually, or /// setting the text directly. pub layout: TextLayout<T>, /// If the platform modifies the text, this contains the new text; /// we update the app `Data` with this text on the next update pass. external_text_change: Option<T>, external_selection_change: Option<Selection>, external_scroll_to: Option<bool>, external_action: Option<TextAction>, /// A flag set in `update` if the text has changed from a non-IME source. pending_ime_invalidation: Option<ImeInvalidation>, /// If `true`, the component will send the [`TextComponent::RETURN`] /// notification when the user enters a newline. pub send_notification_on_return: bool, /// If `true`, the component will send the [`TextComponent::CANCEL`] /// notification when the user cancels editing. pub send_notification_on_cancel: bool, selection: Selection, accepts_newlines: bool, accepts_tabs: bool, alignment: TextAlignment, /// The y-position of the text when it does not fill our width. alignment_offset: f64, /// The portion of the text that is currently marked by the IME. composition_range: Option<Range<usize>>, drag_granularity: DragGranularity, /// The origin of the textbox, relative to the origin of the window. pub origin: Point, } /// An object that can be used to acquire an `ImeHandler`. /// /// This does not own the session; when the widget that owns the session /// is dropped, this will become invalid. #[derive(Debug, Clone)] struct EditSessionRef<T> { inner: Weak<RefCell<EditSession<T>>>, lock: Arc<Cell<ImeLock>>, } /// A locked handle to an [`EditSession`]. /// /// This type implements [`InputHandler`]; it is the type that we pass to the /// platform. struct EditSessionHandle<T> { text: T, inner: Arc<RefCell<EditSession<T>>>, } /// When a drag follows a double- or triple-click, the behaviour of /// drag changes to only select whole words or whole paragraphs. #[derive(Debug, Clone, Copy, PartialEq)] enum DragGranularity { Grapheme, /// Start and end are the start/end bounds of the initial selection. Word { start: usize, end: usize, }, /// Start and end are the start/end bounds of the initial selection. Paragraph { start: usize, end: usize, }, } /// An informal lock. #[derive(Debug, Clone, Copy, PartialEq)] enum ImeLock { None, ReadWrite, Read, } impl<T: TextStorage + EditableText> ImeHandlerRef for EditSessionRef<T> { fn is_alive(&self) -> bool { Weak::strong_count(&self.inner) > 0 } fn acquire(&self, mutable: bool) -> Option<Box<dyn InputHandler + 'static>> { let lock = if mutable { ImeLock::ReadWrite } else { ImeLock::Read }; assert_eq!( self.lock.replace(lock), ImeLock::None, "Ime session is already locked" ); Weak::upgrade(&self.inner) .map(EditSessionHandle::new) .map(|doc| Box::new(doc) as Box<dyn InputHandler>) } fn release(&self) -> bool { self.lock.replace(ImeLock::None) == ImeLock::ReadWrite } } impl TextComponent<()> { /// A notification sent by the component when the cursor has moved. /// /// If the payload is true, this follows an edit, and the view will need /// layout before scrolling. pub const SCROLL_TO: Selector<bool> = Selector::new("druid-builtin.textbox-scroll-to"); /// A notification sent by the component when the user hits return. /// /// This is only sent when `send_notification_on_return` is `true`. pub const RETURN: Selector = Selector::new("druid-builtin.textbox-return"); /// A notification sent when the user cancels editing. /// /// This is only sent when `send_notification_on_cancel` is `true`. pub const CANCEL: Selector = Selector::new("druid-builtin.textbox-cancel"); /// A notification sent by the component when the user presses the tab key. /// /// This is not sent if `accepts_tabs` is true. /// /// An ancestor can handle this event in order to do things like request /// a focus change. pub const TAB: Selector = Selector::new("druid-builtin.textbox-tab"); /// A notification sent by the component when the user inserts a backtab. /// /// This is not sent if `accepts_tabs` is true. /// /// An ancestor can handle this event in order to do things like request /// a focus change. pub const BACKTAB: Selector = Selector::new("druid-builtin.textbox-backtab"); } impl<T> TextComponent<T> { /// Returns `true` if the inner [`EditSession`] can be read. pub fn can_read(&self) -> bool { self.lock.get() != ImeLock::ReadWrite } /// Returns `true` if the inner [`EditSession`] can be mutated. pub fn can_write(&self) -> bool { self.lock.get() == ImeLock::None } /// Returns `true` if the IME is actively composing (or the text is locked.) /// /// When text is composing, you should avoid doing things like modifying the /// selection or copy/pasting text. pub fn is_composing(&self) -> bool { self.can_read() && self.borrow().composition_range.is_some() } /// Attempt to mutably borrow the inner [`EditSession`]. /// /// # Panics /// /// This method panics if there is an outstanding lock on the session. pub fn borrow_mut(&self) -> RefMut<'_, EditSession<T>> { assert!(self.can_write()); self.edit_session.borrow_mut() } /// Attempt to borrow the inner [`EditSession`]. /// /// # Panics /// /// This method panics if there is an outstanding write lock on the session. pub fn borrow(&self) -> Ref<'_, EditSession<T>> { assert!(self.can_read()); self.edit_session.borrow() } } impl<T: EditableText + TextStorage> TextComponent<T> { /// Returns an [`ImeHandlerRef`] that can accept platform text input. /// /// The widget managing this component should call [`LifeCycleCtx::register_text_input`] /// during [`LifeCycle::WidgetAdded`], and pass it this object. pub fn input_handler(&self) -> impl ImeHandlerRef { EditSessionRef { inner: Arc::downgrade(&self.edit_session), lock: self.lock.clone(), } } } impl<T: TextStorage + EditableText> Widget<T> for TextComponent<T> { #[instrument( name = "InputComponent", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { match event { Event::MouseDown(mouse) if self.can_write() && !ctx.is_disabled() => { ctx.set_active(true); // ensure data is up to date before a click let needs_rebuild = self .borrow() .layout .text() .map(|old| !old.same(data)) .unwrap_or(true); if needs_rebuild { self.borrow_mut().layout.set_text(data.clone()); self.borrow_mut().layout.rebuild_if_needed(ctx.text(), env); self.borrow_mut() .update_pending_invalidation(ImeInvalidation::Reset); } self.borrow_mut() .do_mouse_down(mouse.pos, mouse.mods, mouse.count); self.borrow_mut() .update_pending_invalidation(ImeInvalidation::SelectionChanged); ctx.request_update(); ctx.request_paint(); } Event::MouseMove(mouse) if self.can_write() => { if !ctx.is_disabled() { ctx.set_cursor(&Cursor::IBeam); if ctx.is_active() { let pre_sel = self.borrow().selection(); self.borrow_mut().do_drag(mouse.pos); if self.borrow().selection() != pre_sel { self.borrow_mut() .update_pending_invalidation(ImeInvalidation::SelectionChanged); ctx.request_update(); ctx.request_paint(); } } } else { ctx.set_disabled(false); ctx.clear_cursor(); } } Event::MouseUp(_) if ctx.is_active() => { ctx.set_active(false); ctx.request_paint(); } Event::ImeStateChange => { assert!( self.can_write(), "lock release should be cause of ImeStateChange event" ); let scroll_to = self.borrow_mut().take_scroll_to(); let action = self.borrow_mut().take_external_action(); if let Some(scroll_to) = scroll_to { ctx.submit_notification(TextComponent::SCROLL_TO.with(scroll_to)); } if let Some(action) = action { match action { TextAction::Cancel => ctx.submit_notification(TextComponent::CANCEL), TextAction::InsertNewLine { .. } => { ctx.submit_notification(TextComponent::RETURN) } TextAction::InsertTab { .. } => ctx.submit_notification(TextComponent::TAB), TextAction::InsertBacktab => { ctx.submit_notification(TextComponent::BACKTAB) } _ => tracing::warn!("unexpected external action '{:?}'", action), }; } let text = self.borrow_mut().take_external_text_change(); let selection = self.borrow_mut().take_external_selection_change(); if let Some(text) = text { self.borrow_mut().layout.set_text(text.clone()); *data = text; } if let Some(selection) = selection { self.borrow_mut().selection = selection; ctx.request_paint(); } ctx.request_update(); } _ => (), } } #[instrument( name = "InputComponent", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::WidgetAdded => { assert!( self.can_write(), "ime should never be locked at WidgetAdded" ); self.borrow_mut().layout.set_text(data.to_owned()); self.borrow_mut().layout.rebuild_if_needed(ctx.text(), env); } //FIXME: this should happen in the parent too? LifeCycle::ViewContextChanged(_) if self.can_write() => { if self.can_write() { let prev_origin = self.borrow().origin; let new_origin = ctx.window_origin(); if prev_origin != new_origin { self.borrow_mut().origin = ctx.window_origin(); ctx.invalidate_text_input(ImeInvalidation::LayoutChanged); } } } LifeCycle::DisabledChanged(disabled) => { if self.can_write() { let color = if *disabled { env.get(theme::DISABLED_TEXT_COLOR) } else { env.get(theme::TEXT_COLOR) }; self.borrow_mut().layout.set_text_color(color); } ctx.request_layout(); } _ => (), } } #[instrument( name = "InputComponent", level = "trace", skip(self, ctx, _old, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, _old: &T, data: &T, env: &Env) { if self.can_write() { self.borrow_mut().update(ctx, data, env); } } #[instrument( name = "InputComponent", level = "trace", skip(self, ctx, bc, _data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size { if !self.can_write() { tracing::warn!("Text layout called with IME lock held."); return Size::ZERO; } self.borrow_mut().layout.set_wrap_width(bc.max().width); self.borrow_mut().layout.rebuild_if_needed(ctx.text(), env); let metrics = self.borrow().layout.layout_metrics(); let width = if bc.max().width.is_infinite() || bc.max().width < f64::MAX { metrics.trailing_whitespace_width } else { metrics.size.width }; let size = bc.constrain((width, metrics.size.height)); let extra_width = if self.borrow().accepts_newlines { 0.0 } else { (size.width - width).max(0.0) }; self.borrow_mut().update_alignment_offset(extra_width); let baseline_off = metrics.size.height - metrics.first_baseline; ctx.set_baseline_offset(baseline_off); size } #[instrument(name = "InputComponent", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { if !self.can_read() { tracing::warn!("Text paint called with IME lock held."); } let selection_color = if self.has_focus { env.get(theme::SELECTED_TEXT_BACKGROUND_COLOR) } else { env.get(theme::SELECTED_TEXT_INACTIVE_BACKGROUND_COLOR) }; let cursor_color = env.get(theme::CURSOR_COLOR); let text_offset = Vec2::new(self.borrow().alignment_offset, 0.0); let selection = self.borrow().selection(); let composition = self.borrow().composition_range(); let sel_rects = self.borrow().layout.rects_for_range(selection.range()); if let Some(composition) = composition { // I believe selection should always be contained in composition range while composing? assert!(composition.start <= selection.anchor && composition.end >= selection.active); let comp_rects = self.borrow().layout.rects_for_range(composition); for region in comp_rects { let y = region.max_y().floor(); let line = Line::new((region.min_x(), y), (region.max_x(), y)) + text_offset; ctx.stroke(line, &cursor_color, 1.0); } for region in sel_rects { let y = region.max_y().floor(); let line = Line::new((region.min_x(), y), (region.max_x(), y)) + text_offset; ctx.stroke(line, &cursor_color, 2.0); } } else { for region in sel_rects { let rounded = (region + text_offset).to_rounded_rect(1.0); ctx.fill(rounded, &selection_color); } } self.borrow().layout.draw(ctx, text_offset.to_point()); } } impl<T> EditSession<T> { /// The current [`Selection`]. pub fn selection(&self) -> Selection { self.selection } /// Manually set the selection. /// /// If the new selection is different from the current selection, this /// will return an ime event that the controlling widget should use to /// invalidte the platform's IME state, by passing it to /// [`EventCtx::invalidate_text_input`]. #[must_use] pub fn set_selection(&mut self, selection: Selection) -> Option<ImeInvalidation> { if selection != self.selection { self.selection = selection; self.update_pending_invalidation(ImeInvalidation::SelectionChanged); Some(ImeInvalidation::SelectionChanged) } else { None } } /// The range of text currently being modified by an IME. pub fn composition_range(&self) -> Option<Range<usize>> { self.composition_range.clone() } /// Sets whether or not this session will allow the insertion of newlines. pub fn set_accepts_newlines(&mut self, accepts_newlines: bool) { self.accepts_newlines = accepts_newlines; } /// Set the text alignment. /// /// This is only meaningful for single-line text that does not fill /// the minimum layout size. pub fn set_text_alignment(&mut self, alignment: TextAlignment) { self.alignment = alignment; } /// The text alignment. pub fn text_alignment(&self) -> TextAlignment { self.alignment } /// Returns any invalidation action that should be passed to the platform. /// /// The user of this component *must* check this after calling `update`. pub fn pending_ime_invalidation(&mut self) -> Option<ImeInvalidation> { self.pending_ime_invalidation.take() } fn take_external_text_change(&mut self) -> Option<T> { self.external_text_change.take() } fn take_external_selection_change(&mut self) -> Option<Selection> { self.external_selection_change.take() } fn take_scroll_to(&mut self) -> Option<bool> { self.external_scroll_to.take() } fn take_external_action(&mut self) -> Option<TextAction> { self.external_action.take() } // we don't want to replace a more aggressive invalidation with a less aggressive one. fn update_pending_invalidation(&mut self, new_invalidation: ImeInvalidation) { self.pending_ime_invalidation = match self.pending_ime_invalidation.take() { None => Some(new_invalidation), Some(prev) => match (prev, new_invalidation) { (ImeInvalidation::SelectionChanged, ImeInvalidation::SelectionChanged) => { ImeInvalidation::SelectionChanged } (ImeInvalidation::LayoutChanged, ImeInvalidation::LayoutChanged) => { ImeInvalidation::LayoutChanged } _ => ImeInvalidation::Reset, } .into(), } } fn update_alignment_offset(&mut self, extra_width: f64) { self.alignment_offset = match self.alignment { TextAlignment::Start | TextAlignment::Justified => 0.0, TextAlignment::End => extra_width, TextAlignment::Center => extra_width / 2.0, }; } } impl<T: TextStorage + EditableText> EditSession<T> { /// Insert text *not* from the IME, replacing the current selection. /// /// The caller is responsible for notifying the platform of the change in /// text state, by calling [`EventCtx::invalidate_text_input`]. #[must_use] pub fn insert_text(&mut self, data: &mut T, new_text: &str) -> ImeInvalidation { let new_cursor_pos = self.selection.min() + new_text.len(); data.edit(self.selection.range(), new_text); self.selection = Selection::caret(new_cursor_pos); self.scroll_to_selection_end(true); ImeInvalidation::Reset } /// Sets the clipboard to the contents of the current selection. /// /// Returns `true` if the clipboard was set, and `false` if not (indicating) /// that the selection was empty.) pub fn set_clipboard(&self) -> bool { if let Some(text) = self .layout .text() .and_then(|txt| txt.slice(self.selection.range())) { if !text.is_empty() { crate::Application::global().clipboard().put_string(text); return true; } } false } fn scroll_to_selection_end(&mut self, after_edit: bool) { self.external_scroll_to = Some(after_edit); } fn do_action(&mut self, buffer: &mut T, action: TextAction) { match action { TextAction::Move(movement) => { let sel = text::movement(movement, self.selection, &self.layout, false); self.external_selection_change = Some(sel); self.scroll_to_selection_end(false); } TextAction::MoveSelecting(movement) => { let sel = text::movement(movement, self.selection, &self.layout, true); self.external_selection_change = Some(sel); self.scroll_to_selection_end(false); } TextAction::SelectAll => { let len = buffer.len(); self.external_selection_change = Some(Selection::new(0, len)); } TextAction::SelectWord => { if self.selection.is_caret() { let range = text::movement::word_range_for_pos(buffer.as_str(), self.selection.active); self.external_selection_change = Some(Selection::new(range.start, range.end)); } // it is unclear what the behaviour should be if the selection // is not a caret (and may span multiple words) } // This requires us to have access to the layout, which might be stale? TextAction::SelectLine => (), // this assumes our internal selection is consistent with the buffer? TextAction::SelectParagraph => { if !self.selection.is_caret() || buffer.len() < self.selection.active { return; } let prev = buffer.preceding_line_break(self.selection.active); let next = buffer.next_line_break(self.selection.active); self.external_selection_change = Some(Selection::new(prev, next)); } TextAction::Delete(movement) if self.selection.is_caret() => { if movement == Movement::Grapheme(druid_shell::text::Direction::Upstream) { self.backspace(buffer); } else { let to_delete = text::movement(movement, self.selection, &self.layout, true); self.selection = to_delete; self.ime_insert_text(buffer, "") } } TextAction::Delete(_) => self.ime_insert_text(buffer, ""), TextAction::DecomposingBackspace => { tracing::warn!("Decomposing Backspace is not implemented"); self.backspace(buffer); } //TextAction::UppercaseSelection //| TextAction::LowercaseSelection //| TextAction::TitlecaseSelection => { //tracing::warn!("IME transformations are not implemented"); //} TextAction::InsertNewLine { newline_type, ignore_hotkey, } => { if self.send_notification_on_return && !ignore_hotkey { self.external_action = Some(action); } else if self.accepts_newlines { self.ime_insert_text(buffer, &newline_type.to_string()); } } TextAction::InsertTab { ignore_hotkey } => { if ignore_hotkey || self.accepts_tabs { self.ime_insert_text(buffer, "\t"); } else if !ignore_hotkey { self.external_action = Some(action); } } TextAction::InsertBacktab => { if !self.accepts_tabs { self.external_action = Some(action); } } TextAction::InsertSingleQuoteIgnoringSmartQuotes => self.ime_insert_text(buffer, "'"), TextAction::InsertDoubleQuoteIgnoringSmartQuotes => self.ime_insert_text(buffer, "\""), TextAction::Cancel if self.send_notification_on_cancel => { self.external_action = Some(action) } other => tracing::warn!("unhandled IME action {:?}", other), } } /// Replace the current selection with `text`, and advance the cursor. /// /// This should only be called from the IME. fn ime_insert_text(&mut self, buffer: &mut T, text: &str) { let new_cursor_pos = self.selection.min() + text.len(); buffer.edit(self.selection.range(), text); self.external_selection_change = Some(Selection::caret(new_cursor_pos)); self.scroll_to_selection_end(true); } fn backspace(&mut self, buffer: &mut T) { let to_del = if self.selection.is_caret() { let del_start = text::offset_for_delete_backwards(&self.selection, buffer); del_start..self.selection.anchor } else { self.selection.range() }; self.external_selection_change = Some(Selection::caret(to_del.start)); buffer.edit(to_del, ""); self.scroll_to_selection_end(true); } fn do_mouse_down(&mut self, point: Point, mods: Modifiers, count: u8) { let point = point - Vec2::new(self.alignment_offset, 0.0); let pos = self.layout.text_position_for_point(point); if mods.shift() { self.selection.active = pos; } else { let Range { start, end } = self.sel_region_for_pos(pos, count); self.selection = Selection::new(start, end); self.drag_granularity = match count { 2 => DragGranularity::Word { start, end }, 3 => DragGranularity::Paragraph { start, end }, _ => DragGranularity::Grapheme, }; } } fn do_drag(&mut self, point: Point) { let point = point - Vec2::new(self.alignment_offset, 0.0); //FIXME: this should behave differently if we were double or triple clicked let pos = self.layout.text_position_for_point(point); let text = match self.layout.text() { Some(text) => text, None => return, }; let (start, end) = match self.drag_granularity { DragGranularity::Grapheme => (self.selection.anchor, pos), DragGranularity::Word { start, end } => { let word_range = self.word_for_pos(pos); if pos <= start { (end, word_range.start) } else { (start, word_range.end) } } DragGranularity::Paragraph { start, end } => { let par_start = text.preceding_line_break(pos); let par_end = text.next_line_break(pos); if pos <= start { (end, par_start) } else { (start, par_end) } } }; self.selection = Selection::new(start, end); self.scroll_to_selection_end(false); } /// Returns a line suitable for drawing a standard cursor. pub fn cursor_line_for_text_position(&self, pos: usize) -> Line { let line = self.layout.cursor_line_for_text_position(pos); line + Vec2::new(self.alignment_offset, 0.0) } fn sel_region_for_pos(&mut self, pos: usize, click_count: u8) -> Range<usize> { match click_count { 1 => pos..pos, 2 => self.word_for_pos(pos), _ => { let text = match self.layout.text() { Some(text) => text, None => return pos..pos, }; let line_min = text.preceding_line_break(pos); let line_max = text.next_line_break(pos); line_min..line_max } } } fn word_for_pos(&self, pos: usize) -> Range<usize> { let layout = match self.layout.layout() { Some(layout) => layout, None => return pos..pos, }; let line_n = layout.hit_test_text_position(pos).line; let lm = layout.line_metric(line_n).unwrap(); let text = layout.line_text(line_n).unwrap(); let rel_pos = pos - lm.start_offset; let mut range = text::movement::word_range_for_pos(text, rel_pos); range.start += lm.start_offset; range.end += lm.start_offset; range } fn update(&mut self, ctx: &mut UpdateCtx, new_data: &T, env: &Env) { if self .layout .text() .as_ref() .map(|t| !t.same(new_data)) .unwrap_or(true) { self.update_pending_invalidation(ImeInvalidation::Reset); self.layout.set_text(new_data.clone()); } if self.layout.needs_rebuild_after_update(ctx) { ctx.request_layout(); } let new_sel = self.selection.constrained(new_data.as_str()); if new_sel != self.selection { self.selection = new_sel; self.update_pending_invalidation(ImeInvalidation::SelectionChanged); } self.layout.rebuild_if_needed(ctx.text(), env); } } impl<T: TextStorage> EditSessionHandle<T> { fn new(inner: Arc<RefCell<EditSession<T>>>) -> Self { let text = inner.borrow().layout.text().cloned().unwrap(); EditSessionHandle { text, inner } } } impl<T: TextStorage + EditableText> InputHandler for EditSessionHandle<T> { fn selection(&self) -> Selection { self.inner.borrow().selection } fn set_selection(&mut self, selection: Selection) { self.inner.borrow_mut().external_selection_change = Some(selection); self.inner.borrow_mut().external_scroll_to = Some(true); } fn composition_range(&self) -> Option<Range<usize>> {
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/backspace.rs
druid/src/text/backspace.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Calc start of a backspace delete interval use crate::text::{EditableText, EditableTextCursor, Selection}; use xi_unicode::*; #[allow(clippy::cognitive_complexity)] fn backspace_offset(text: &impl EditableText, start: usize) -> usize { #[derive(PartialEq)] enum State { Start, Lf, BeforeKeycap, BeforeVsAndKeycap, BeforeEmojiModifier, BeforeVsAndEmojiModifier, BeforeVs, BeforeEmoji, BeforeZwj, BeforeVsAndZwj, OddNumberedRis, EvenNumberedRis, InTagSequence, Finished, } let mut state = State::Start; let mut delete_code_point_count = 0; let mut last_seen_vs_code_point_count = 0; let mut cursor = text .cursor(start) .expect("Backspace must begin at a valid codepoint boundary."); while state != State::Finished && cursor.pos() > 0 { let code_point = cursor.prev_codepoint().unwrap_or('0'); match state { State::Start => { delete_code_point_count = 1; if code_point == '\n' { state = State::Lf; } else if is_variation_selector(code_point) { state = State::BeforeVs; } else if code_point.is_regional_indicator_symbol() { state = State::OddNumberedRis; } else if code_point.is_emoji_modifier() { state = State::BeforeEmojiModifier; } else if code_point.is_emoji_combining_enclosing_keycap() { state = State::BeforeKeycap; } else if code_point.is_emoji() { state = State::BeforeEmoji; } else if code_point.is_emoji_cancel_tag() { state = State::InTagSequence; } else { state = State::Finished; } } State::Lf => { if code_point == '\r' { delete_code_point_count += 1; } state = State::Finished; } State::OddNumberedRis => { if code_point.is_regional_indicator_symbol() { delete_code_point_count += 1; state = State::EvenNumberedRis } else { state = State::Finished } } State::EvenNumberedRis => { if code_point.is_regional_indicator_symbol() { delete_code_point_count -= 1; state = State::OddNumberedRis; } else { state = State::Finished; } } State::BeforeKeycap => { if is_variation_selector(code_point) { last_seen_vs_code_point_count = 1; state = State::BeforeVsAndKeycap; } else { if is_keycap_base(code_point) { delete_code_point_count += 1; } state = State::Finished; } } State::BeforeVsAndKeycap => { if is_keycap_base(code_point) { delete_code_point_count += last_seen_vs_code_point_count + 1; } state = State::Finished; } State::BeforeEmojiModifier => { if is_variation_selector(code_point) { last_seen_vs_code_point_count = 1; state = State::BeforeVsAndEmojiModifier; } else { if code_point.is_emoji_modifier_base() { delete_code_point_count += 1; } state = State::Finished; } } State::BeforeVsAndEmojiModifier => { if code_point.is_emoji_modifier_base() { delete_code_point_count += last_seen_vs_code_point_count + 1; } state = State::Finished; } State::BeforeVs => { if code_point.is_emoji() { delete_code_point_count += 1; state = State::BeforeEmoji; } else { if !is_variation_selector(code_point) { //TODO: UCharacter.getCombiningClass(codePoint) == 0 delete_code_point_count += 1; } state = State::Finished; } } State::BeforeEmoji => { if code_point.is_zwj() { state = State::BeforeZwj; } else { state = State::Finished; } } State::BeforeZwj => { if code_point.is_emoji() { delete_code_point_count += 2; state = if code_point.is_emoji_modifier() { State::BeforeEmojiModifier } else { State::BeforeEmoji }; } else if is_variation_selector(code_point) { last_seen_vs_code_point_count = 1; state = State::BeforeVsAndZwj; } else { state = State::Finished; } } State::BeforeVsAndZwj => { if code_point.is_emoji() { delete_code_point_count += last_seen_vs_code_point_count + 2; last_seen_vs_code_point_count = 0; state = State::BeforeEmoji; } else { state = State::Finished; } } State::InTagSequence => { if code_point.is_tag_spec_char() { delete_code_point_count += 1; } else if code_point.is_emoji() { delete_code_point_count += 1; state = State::Finished; } else { delete_code_point_count = 1; state = State::Finished; } } State::Finished => { break; } } } cursor.set(start); for _ in 0..delete_code_point_count { let _ = cursor.prev_codepoint(); } cursor.pos() } /// Calculate resulting offset for a backwards delete. /// /// This involves complicated logic to handle various special cases that /// are unique to backspace. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn offset_for_delete_backwards(region: &Selection, text: &impl EditableText) -> usize { if !region.is_caret() { region.min() } else { backspace_offset(text, region.active) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/storage.rs
druid/src/text/storage.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Storing text. use std::sync::Arc; use crate::env::KeyLike; use crate::piet::{PietTextLayoutBuilder, TextStorage as PietTextStorage}; use crate::{Data, Env}; use super::attribute::Link; use crate::UpdateCtx; /// A type that represents text that can be displayed. pub trait TextStorage: PietTextStorage + Data { /// If this TextStorage object manages style spans, it should implement /// this method and update the provided builder with its spans, as required. #[allow(unused_variables)] fn add_attributes(&self, builder: PietTextLayoutBuilder, env: &Env) -> PietTextLayoutBuilder { builder } /// This is called whenever the Env changes and should return true /// if the layout should be rebuilt. #[allow(unused_variables)] fn env_update(&self, ctx: &EnvUpdateCtx) -> bool { false } /// Any additional [`Link`] attributes on this text. /// /// If this `TextStorage` object manages link attributes, it should implement this /// method and return any attached [`Link`]s. /// /// Unlike other attributes, links are managed in Druid, not in [`piet`]; as such they /// require a separate API. /// /// [`Link`]: super::attribute::Link /// [`piet`]: crate::piet fn links(&self) -> &[Link] { &[] } } /// Provides information about keys change for more fine grained invalidation pub struct EnvUpdateCtx<'a, 'b>(&'a UpdateCtx<'a, 'b>); impl<'a, 'b> EnvUpdateCtx<'a, 'b> { /// Create an [`EnvUpdateCtx`] for [`Widget::update`]. /// /// [`Widget::update`]: crate::Widget::update pub(crate) fn for_update(ctx: &'a UpdateCtx<'a, 'b>) -> Self { Self(ctx) } /// Returns `true` if the given key has changed since the last [`env_update`] /// call. /// /// See [`UpdateCtx::env_key_changed`] for more details. /// /// [`env_update`]: TextStorage::env_update pub fn env_key_changed<T>(&self, key: &impl KeyLike<T>) -> bool { self.0.env_key_changed(key) } } /// A reference counted string slice. /// /// This is a data-friendly way to represent strings in Druid. Unlike `String` /// it cannot be mutated, but unlike `String` it can be cheaply cloned. pub type ArcStr = Arc<str>; impl TextStorage for ArcStr {} impl TextStorage for String {} impl TextStorage for Arc<String> {}
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/input_methods.rs
druid/src/text/input_methods.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Types related to input method editing. //! //! Most IME-related code is in `druid-shell`; these are helper types used //! exclusively in `druid`. use std::rc::Rc; use crate::shell::text::InputHandler; use crate::WidgetId; /// A trait for input handlers registered by widgets. /// /// A widget registers itself as accepting text input by calling /// [`LifeCycleCtx::register_text_input`] while handling the /// [`LifeCycle::WidgetAdded`] event. /// /// The widget does not explicitly *deregister* afterwards; rather anytime /// the widget tree changes, `druid` will call [`is_alive`] on each registered /// `ImeHandlerRef`, and deregister those that return `false`. /// /// [`LifeCycle::WidgetAdded`]: crate::LifeCycle::WidgetAdded /// [`LifeCycleCtx::register_text_input`]: crate::LifeCycleCtx::register_text_input /// [`is_alive`]: ImeHandlerRef::is_alive pub trait ImeHandlerRef { /// Returns `true` if this handler is still active. fn is_alive(&self) -> bool; /// Mark the session as locked, and return a handle. /// /// The lock can be read-write or read-only, indicated by the `mutable` flag. /// /// if [`is_alive`] is `true`, this should always return `Some(_)`. /// /// [`is_alive`]: ImeHandlerRef::is_alive fn acquire(&self, mutable: bool) -> Option<Box<dyn InputHandler + 'static>>; /// Mark the session as released. fn release(&self) -> bool; } /// A type we use to keep track of which widgets are responsible for which /// ime sessions. #[derive(Clone)] pub(crate) struct TextFieldRegistration { pub widget_id: WidgetId, pub document: Rc<dyn ImeHandlerRef>, } impl TextFieldRegistration { pub fn is_alive(&self) -> bool { self.document.is_alive() } } impl std::fmt::Debug for TextFieldRegistration { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("TextFieldRegistration") .field("widget_id", &self.widget_id) .field("is_alive", &self.document.is_alive()) .finish() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/editable_text.rs
druid/src/text/editable_text.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Traits for text editing and a basic String implementation. use std::borrow::Cow; use std::ops::{Deref, Range}; use std::sync::Arc; use unicode_segmentation::{GraphemeCursor, UnicodeSegmentation}; /// An EditableText trait. pub trait EditableText: Sized { // TODO: would be nice to have something like // type Cursor: EditableTextCursor<Self>; /// Create a cursor with a reference to the text and a offset position. /// /// Returns None if the position isn't a codepoint boundary. fn cursor(&self, position: usize) -> Option<StringCursor<'_>>; /// Replace range with new text. /// Can panic if supplied an invalid range. // TODO: make this generic over Self fn edit(&mut self, range: Range<usize>, new: impl Into<String>); /// Get slice of text at range. fn slice(&self, range: Range<usize>) -> Option<Cow<'_, str>>; /// Get length of text (in bytes). fn len(&self) -> usize; /// Get the previous word offset from the given offset, if it exists. fn prev_word_offset(&self, offset: usize) -> Option<usize>; /// Get the next word offset from the given offset, if it exists. fn next_word_offset(&self, offset: usize) -> Option<usize>; /// Get the next grapheme offset from the given offset, if it exists. fn prev_grapheme_offset(&self, offset: usize) -> Option<usize>; /// Get the next grapheme offset from the given offset, if it exists. fn next_grapheme_offset(&self, offset: usize) -> Option<usize>; /// Get the previous codepoint offset from the given offset, if it exists. fn prev_codepoint_offset(&self, offset: usize) -> Option<usize>; /// Get the next codepoint offset from the given offset, if it exists. fn next_codepoint_offset(&self, offset: usize) -> Option<usize>; /// Get the preceding line break offset from the given offset fn preceding_line_break(&self, offset: usize) -> usize; /// Get the next line break offset from the given offset fn next_line_break(&self, offset: usize) -> usize; /// Returns `true` if this text has 0 length. fn is_empty(&self) -> bool; /// Construct an instance of this type from a `&str`. fn from_str(s: &str) -> Self; } impl EditableText for String { fn cursor<'a>(&self, position: usize) -> Option<StringCursor<'_>> { let new_cursor = StringCursor { text: self, position, }; if new_cursor.is_boundary() { Some(new_cursor) } else { None } } fn edit(&mut self, range: Range<usize>, new: impl Into<String>) { self.replace_range(range, &new.into()); } fn slice(&self, range: Range<usize>) -> Option<Cow<'_, str>> { self.get(range).map(Cow::from) } fn len(&self) -> usize { self.len() } fn prev_grapheme_offset(&self, from: usize) -> Option<usize> { let mut c = GraphemeCursor::new(from, self.len(), true); c.prev_boundary(self, 0).unwrap() } fn next_grapheme_offset(&self, from: usize) -> Option<usize> { let mut c = GraphemeCursor::new(from, self.len(), true); c.next_boundary(self, 0).unwrap() } fn prev_codepoint_offset(&self, from: usize) -> Option<usize> { let mut c = self.cursor(from).unwrap(); c.prev() } fn next_codepoint_offset(&self, from: usize) -> Option<usize> { let mut c = self.cursor(from).unwrap(); if c.next().is_some() { Some(c.pos()) } else { None } } fn prev_word_offset(&self, from: usize) -> Option<usize> { let mut offset = from; let mut passed_alphanumeric = false; for prev_grapheme in self.get(0..from)?.graphemes(true).rev() { let is_alphanumeric = prev_grapheme.chars().next()?.is_alphanumeric(); if is_alphanumeric { passed_alphanumeric = true; } else if passed_alphanumeric { return Some(offset); } offset -= prev_grapheme.len(); } None } fn next_word_offset(&self, from: usize) -> Option<usize> { let mut offset = from; let mut passed_alphanumeric = false; for next_grapheme in self.get(from..)?.graphemes(true) { let is_alphanumeric = next_grapheme.chars().next()?.is_alphanumeric(); if is_alphanumeric { passed_alphanumeric = true; } else if passed_alphanumeric { return Some(offset); } offset += next_grapheme.len(); } Some(self.len()) } fn is_empty(&self) -> bool { self.is_empty() } fn from_str(s: &str) -> Self { s.to_string() } fn preceding_line_break(&self, from: usize) -> usize { let mut offset = from; for byte in self.get(0..from).unwrap_or("").bytes().rev() { if byte == 0x0a { return offset; } offset -= 1; } 0 } fn next_line_break(&self, from: usize) -> usize { let mut offset = from; for char in self.get(from..).unwrap_or("").bytes() { if char == 0x0a { return offset; } offset += 1; } self.len() } } impl EditableText for Arc<String> { fn cursor(&self, position: usize) -> Option<StringCursor<'_>> { <String as EditableText>::cursor(self, position) } fn edit(&mut self, range: Range<usize>, new: impl Into<String>) { let new = new.into(); if !range.is_empty() || !new.is_empty() { Arc::make_mut(self).edit(range, new) } } fn slice(&self, range: Range<usize>) -> Option<Cow<'_, str>> { Some(Cow::Borrowed(&self[range])) } fn len(&self) -> usize { self.deref().len() } fn prev_word_offset(&self, offset: usize) -> Option<usize> { self.deref().prev_word_offset(offset) } fn next_word_offset(&self, offset: usize) -> Option<usize> { self.deref().next_word_offset(offset) } fn prev_grapheme_offset(&self, offset: usize) -> Option<usize> { self.deref().prev_grapheme_offset(offset) } fn next_grapheme_offset(&self, offset: usize) -> Option<usize> { self.deref().next_grapheme_offset(offset) } fn prev_codepoint_offset(&self, offset: usize) -> Option<usize> { self.deref().prev_codepoint_offset(offset) } fn next_codepoint_offset(&self, offset: usize) -> Option<usize> { self.deref().next_codepoint_offset(offset) } fn preceding_line_break(&self, offset: usize) -> usize { self.deref().preceding_line_break(offset) } fn next_line_break(&self, offset: usize) -> usize { self.deref().next_line_break(offset) } fn is_empty(&self) -> bool { self.deref().is_empty() } fn from_str(s: &str) -> Self { Arc::new(s.to_owned()) } } /// A cursor with convenience functions for moving through EditableText. pub trait EditableTextCursor<EditableText> { /// Set cursor position. fn set(&mut self, position: usize); /// Get cursor position. fn pos(&self) -> usize; /// Check if cursor position is at a codepoint boundary. fn is_boundary(&self) -> bool; /// Move cursor to previous codepoint boundary, if it exists. /// Returns previous codepoint as usize offset. fn prev(&mut self) -> Option<usize>; /// Move cursor to next codepoint boundary, if it exists. /// Returns current codepoint as usize offset. fn next(&mut self) -> Option<usize>; /// Get the next codepoint after the cursor position, without advancing /// the cursor. fn peek_next_codepoint(&self) -> Option<char>; /// Return codepoint preceding cursor offset and move cursor backward. fn prev_codepoint(&mut self) -> Option<char>; /// Return codepoint at cursor offset and move cursor forward. fn next_codepoint(&mut self) -> Option<char>; /// Return current offset if it's a boundary, else next. fn at_or_next(&mut self) -> Option<usize>; /// Return current offset if it's a boundary, else previous. fn at_or_prev(&mut self) -> Option<usize>; } /// A cursor type that implements EditableTextCursor for String #[derive(Debug)] pub struct StringCursor<'a> { text: &'a str, position: usize, } impl<'a> StringCursor<'a> { /// Create a new cursor. pub fn new(text: &'a str) -> Self { Self { text, position: 0 } } } impl<'a> EditableTextCursor<&'a String> for StringCursor<'a> { fn set(&mut self, position: usize) { self.position = position; } fn pos(&self) -> usize { self.position } fn is_boundary(&self) -> bool { self.text.is_char_boundary(self.position) } fn prev(&mut self) -> Option<usize> { let current_pos = self.pos(); if current_pos == 0 { None } else { let mut len = 1; while !self.text.is_char_boundary(current_pos - len) { len += 1; } self.set(self.pos() - len); Some(self.pos()) } } fn next(&mut self) -> Option<usize> { let current_pos = self.pos(); if current_pos == self.text.len() { None } else { let b = self.text.as_bytes()[current_pos]; self.set(current_pos + len_utf8_from_first_byte(b)); Some(current_pos) } } fn peek_next_codepoint(&self) -> Option<char> { self.text[self.pos()..].chars().next() } fn prev_codepoint(&mut self) -> Option<char> { if let Some(prev) = self.prev() { self.text[prev..].chars().next() } else { None } } fn next_codepoint(&mut self) -> Option<char> { let current_index = self.pos(); if self.next().is_some() { self.text[current_index..].chars().next() } else { None } } fn at_or_next(&mut self) -> Option<usize> { if self.is_boundary() { Some(self.pos()) } else { self.next() } } fn at_or_prev(&mut self) -> Option<usize> { if self.is_boundary() { Some(self.pos()) } else { self.prev() } } } pub fn len_utf8_from_first_byte(b: u8) -> usize { match b { b if b < 0x80 => 1, b if b < 0xe0 => 2, b if b < 0xf0 => 3, _ => 4, } } #[cfg(test)] mod tests { use super::*; use crate::Data; use test_log::test; #[test] fn replace() { let mut a = String::from("hello world"); a.edit(1..9, "era"); assert_eq!("herald", a); } #[test] fn prev_codepoint_offset() { let a = String::from("a\u{00A1}\u{4E00}\u{1F4A9}"); assert_eq!(Some(6), a.prev_codepoint_offset(10)); assert_eq!(Some(3), a.prev_codepoint_offset(6)); assert_eq!(Some(1), a.prev_codepoint_offset(3)); assert_eq!(Some(0), a.prev_codepoint_offset(1)); assert_eq!(None, a.prev_codepoint_offset(0)); let b = a.slice(1..10).unwrap().to_string(); assert_eq!(Some(5), b.prev_codepoint_offset(9)); assert_eq!(Some(2), b.prev_codepoint_offset(5)); assert_eq!(Some(0), b.prev_codepoint_offset(2)); assert_eq!(None, b.prev_codepoint_offset(0)); } #[test] fn next_codepoint_offset() { let a = String::from("a\u{00A1}\u{4E00}\u{1F4A9}"); assert_eq!(Some(10), a.next_codepoint_offset(6)); assert_eq!(Some(6), a.next_codepoint_offset(3)); assert_eq!(Some(3), a.next_codepoint_offset(1)); assert_eq!(Some(1), a.next_codepoint_offset(0)); assert_eq!(None, a.next_codepoint_offset(10)); let b = a.slice(1..10).unwrap().to_string(); assert_eq!(Some(9), b.next_codepoint_offset(5)); assert_eq!(Some(5), b.next_codepoint_offset(2)); assert_eq!(Some(2), b.next_codepoint_offset(0)); assert_eq!(None, b.next_codepoint_offset(9)); } #[test] fn prev_next() { let input = String::from("abc"); let mut cursor = input.cursor(0).unwrap(); assert_eq!(cursor.next(), Some(0)); assert_eq!(cursor.next(), Some(1)); assert_eq!(cursor.prev(), Some(1)); assert_eq!(cursor.next(), Some(1)); assert_eq!(cursor.next(), Some(2)); } #[test] fn peek_next_codepoint() { let inp = String::from("$¢€£💶"); let mut cursor = inp.cursor(0).unwrap(); assert_eq!(cursor.peek_next_codepoint(), Some('$')); assert_eq!(cursor.peek_next_codepoint(), Some('$')); assert_eq!(cursor.next_codepoint(), Some('$')); assert_eq!(cursor.peek_next_codepoint(), Some('¢')); assert_eq!(cursor.prev_codepoint(), Some('$')); assert_eq!(cursor.peek_next_codepoint(), Some('$')); assert_eq!(cursor.next_codepoint(), Some('$')); assert_eq!(cursor.next_codepoint(), Some('¢')); assert_eq!(cursor.peek_next_codepoint(), Some('€')); assert_eq!(cursor.next_codepoint(), Some('€')); assert_eq!(cursor.peek_next_codepoint(), Some('£')); assert_eq!(cursor.next_codepoint(), Some('£')); assert_eq!(cursor.peek_next_codepoint(), Some('💶')); assert_eq!(cursor.next_codepoint(), Some('💶')); assert_eq!(cursor.peek_next_codepoint(), None); assert_eq!(cursor.next_codepoint(), None); assert_eq!(cursor.peek_next_codepoint(), None); } #[test] fn prev_grapheme_offset() { // A with ring, hangul, regional indicator "US" let a = String::from("A\u{030a}\u{110b}\u{1161}\u{1f1fa}\u{1f1f8}"); assert_eq!(Some(9), a.prev_grapheme_offset(17)); assert_eq!(Some(3), a.prev_grapheme_offset(9)); assert_eq!(Some(0), a.prev_grapheme_offset(3)); assert_eq!(None, a.prev_grapheme_offset(0)); } #[test] fn next_grapheme_offset() { // A with ring, hangul, regional indicator "US" let a = String::from("A\u{030a}\u{110b}\u{1161}\u{1f1fa}\u{1f1f8}"); assert_eq!(Some(3), a.next_grapheme_offset(0)); assert_eq!(Some(9), a.next_grapheme_offset(3)); assert_eq!(Some(17), a.next_grapheme_offset(9)); assert_eq!(None, a.next_grapheme_offset(17)); } #[test] fn prev_word_offset() { let a = String::from("Technically a word: ৬藏A\u{030a}\u{110b}\u{1161}"); assert_eq!(Some(20), a.prev_word_offset(35)); assert_eq!(Some(20), a.prev_word_offset(27)); assert_eq!(Some(20), a.prev_word_offset(23)); assert_eq!(Some(14), a.prev_word_offset(20)); assert_eq!(Some(14), a.prev_word_offset(19)); assert_eq!(Some(12), a.prev_word_offset(13)); assert_eq!(None, a.prev_word_offset(12)); assert_eq!(None, a.prev_word_offset(11)); assert_eq!(None, a.prev_word_offset(0)); } #[test] fn next_word_offset() { let a = String::from("Technically a word: ৬藏A\u{030a}\u{110b}\u{1161}"); assert_eq!(Some(11), a.next_word_offset(0)); assert_eq!(Some(11), a.next_word_offset(7)); assert_eq!(Some(13), a.next_word_offset(11)); assert_eq!(Some(18), a.next_word_offset(14)); assert_eq!(Some(35), a.next_word_offset(18)); assert_eq!(Some(35), a.next_word_offset(19)); assert_eq!(Some(35), a.next_word_offset(20)); assert_eq!(Some(35), a.next_word_offset(26)); assert_eq!(Some(35), a.next_word_offset(35)); } #[test] fn preceding_line_break() { let a = String::from("Technically\na word:\n ৬藏A\u{030a}\n\u{110b}\u{1161}"); assert_eq!(0, a.preceding_line_break(0)); assert_eq!(0, a.preceding_line_break(11)); assert_eq!(12, a.preceding_line_break(12)); assert_eq!(12, a.preceding_line_break(13)); assert_eq!(20, a.preceding_line_break(21)); assert_eq!(31, a.preceding_line_break(31)); assert_eq!(31, a.preceding_line_break(34)); let b = String::from("Technically a word: ৬藏A\u{030a}\u{110b}\u{1161}"); assert_eq!(0, b.preceding_line_break(0)); assert_eq!(0, b.preceding_line_break(11)); assert_eq!(0, b.preceding_line_break(13)); assert_eq!(0, b.preceding_line_break(21)); } #[test] fn next_line_break() { let a = String::from("Technically\na word:\n ৬藏A\u{030a}\n\u{110b}\u{1161}"); assert_eq!(11, a.next_line_break(0)); assert_eq!(11, a.next_line_break(11)); assert_eq!(19, a.next_line_break(13)); assert_eq!(30, a.next_line_break(21)); assert_eq!(a.len(), a.next_line_break(31)); let b = String::from("Technically a word: ৬藏A\u{030a}\u{110b}\u{1161}"); assert_eq!(b.len(), b.next_line_break(0)); assert_eq!(b.len(), b.next_line_break(11)); assert_eq!(b.len(), b.next_line_break(13)); assert_eq!(b.len(), b.next_line_break(19)); } #[test] fn arcstring_empty_edit() { let a = Arc::new("hello".to_owned()); let mut b = a.clone(); b.edit(5..5, ""); assert!(a.same(&b)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/mod.rs
druid/src/text/mod.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Editing and displaying text. mod attribute; mod backspace; mod editable_text; mod font_descriptor; mod format; mod input_component; mod input_methods; mod layout; mod movement; mod rich_text; mod storage; pub use crate::piet::{FontFamily, FontStyle, FontWeight, TextAlignment}; pub use druid_shell::text::{ Action as TextAction, Affinity, Direction, Event as ImeInvalidation, InputHandler, Movement, Selection, VerticalMovement, WritingDirection, }; pub use self::attribute::{Attribute, AttributeSpans, Link}; pub use self::backspace::offset_for_delete_backwards; pub use self::editable_text::{EditableText, EditableTextCursor, StringCursor}; pub use self::font_descriptor::FontDescriptor; pub use self::format::{Formatter, ParseFormatter, Validation, ValidationError}; pub use self::layout::{LayoutMetrics, TextLayout}; pub use self::movement::movement; pub use input_component::{EditSession, TextComponent}; pub use input_methods::ImeHandlerRef; pub use rich_text::{AttributesAdder, RichText, RichTextBuilder}; pub use storage::{ArcStr, EnvUpdateCtx, TextStorage}; pub(crate) use input_methods::TextFieldRegistration;
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/layout.rs
druid/src/text/layout.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A type for laying out, drawing, and interacting with text. use std::ops::Range; use std::rc::Rc; use super::{EnvUpdateCtx, Link, TextStorage}; use crate::kurbo::{Line, Point, Rect, Size}; use crate::piet::{ Color, PietText, PietTextLayout, Text as _, TextAlignment, TextAttribute, TextLayout as _, TextLayoutBuilder as _, }; use crate::{Env, FontDescriptor, KeyOrValue, PaintCtx, RenderContext, UpdateCtx}; /// A component for displaying text on screen. /// /// This is a type intended to be used by other widgets that display text. /// It allows for the text itself as well as font and other styling information /// to be set and modified. It wraps an inner layout object, and handles /// invalidating and rebuilding it as required. /// /// This object is not valid until the [`rebuild_if_needed`] method has been /// called. You should generally do this in your widget's [`layout`] method. /// Additionally, you should call [`needs_rebuild_after_update`] /// as part of your widget's [`update`] method; if this returns `true`, you will need /// to call [`rebuild_if_needed`] again, generally by scheduling another [`layout`] /// pass. /// /// [`layout`]: crate::Widget::layout /// [`update`]: crate::Widget::update /// [`needs_rebuild_after_update`]: #method.needs_rebuild_after_update /// [`rebuild_if_needed`]: #method.rebuild_if_needed #[derive(Clone)] pub struct TextLayout<T> { text: Option<T>, font: KeyOrValue<FontDescriptor>, // when set, this will be used to override the size in he font descriptor. // This provides an easy way to change only the font size, while still // using a `FontDescriptor` in the `Env`. text_size_override: Option<KeyOrValue<f64>>, text_color: KeyOrValue<Color>, layout: Option<PietTextLayout>, wrap_width: f64, alignment: TextAlignment, links: Rc<[(Rect, usize)]>, text_is_rtl: bool, } /// Metrics describing the layout text. #[derive(Debug, Clone, Copy, Default)] pub struct LayoutMetrics { /// The nominal size of the layout. pub size: Size, /// The distance from the nominal top of the layout to the first baseline. pub first_baseline: f64, /// The width of the layout, inclusive of trailing whitespace. pub trailing_whitespace_width: f64, //TODO: add inking_rect } impl<T> TextLayout<T> { /// Create a new `TextLayout` object. /// /// You must set the text ([`set_text`]) before using this object. /// /// [`set_text`]: TextLayout::set_text pub fn new() -> Self { TextLayout { text: None, font: crate::theme::UI_FONT.into(), text_color: crate::theme::TEXT_COLOR.into(), text_size_override: None, layout: None, wrap_width: f64::INFINITY, alignment: Default::default(), links: Rc::new([]), text_is_rtl: false, } } /// Set the default text color for this layout. pub fn set_text_color(&mut self, color: impl Into<KeyOrValue<Color>>) { let color = color.into(); if color != self.text_color { self.text_color = color; self.layout = None; } } /// Set the default font. /// /// The argument is a [`FontDescriptor`] or a [`Key<FontDescriptor>`] that /// can be resolved from the [`Env`]. /// /// [`Key<FontDescriptor>`]: crate::Key pub fn set_font(&mut self, font: impl Into<KeyOrValue<FontDescriptor>>) { let font = font.into(); if font != self.font { self.font = font; self.layout = None; self.text_size_override = None; } } /// Set the font size. /// /// This overrides the size in the [`FontDescriptor`] provided to [`set_font`]. /// /// [`set_font`]: TextLayout::set_font pub fn set_text_size(&mut self, size: impl Into<KeyOrValue<f64>>) { let size = size.into(); if Some(&size) != self.text_size_override.as_ref() { self.text_size_override = Some(size); self.layout = None; } } /// Set the width at which to wrap words. /// /// You may pass `f64::INFINITY` to disable word wrapping /// (the default behaviour). pub fn set_wrap_width(&mut self, width: f64) { let width = width.max(0.0); // 1e-4 is an arbitrary small-enough value that we don't care to rewrap if (width - self.wrap_width).abs() > 1e-4 { self.wrap_width = width; self.layout = None; } } /// Set the [`TextAlignment`] for this layout. pub fn set_text_alignment(&mut self, alignment: TextAlignment) { if self.alignment != alignment { self.alignment = alignment; self.layout = None; } } /// Returns `true` if this layout's text appears to be right-to-left. /// /// See [`piet::util::first_strong_rtl`] for more information. /// /// [`piet::util::first_strong_rtl`]: crate::piet::util::first_strong_rtl pub fn text_is_rtl(&self) -> bool { self.text_is_rtl } } impl<T: TextStorage> TextLayout<T> { /// Create a new `TextLayout` with the provided text. /// /// This is useful when the text is not tied to application data. pub fn from_text(text: impl Into<T>) -> Self { let mut this = TextLayout::new(); this.set_text(text.into()); this } /// Returns `true` if this layout needs to be rebuilt. /// /// This happens (for instance) after style attributes are modified. /// /// This does not account for things like the text changing, handling that /// is the responsibility of the user. pub fn needs_rebuild(&self) -> bool { self.layout.is_none() } /// Set the text to display. pub fn set_text(&mut self, text: T) { if self.text.is_none() || !self.text.as_ref().unwrap().same(&text) { self.text_is_rtl = crate::piet::util::first_strong_rtl(text.as_str()); self.text = Some(text); self.layout = None; } } /// Returns the [`TextStorage`] backing this layout, if it exists. pub fn text(&self) -> Option<&T> { self.text.as_ref() } /// Returns the inner Piet [`TextLayout`] type. /// /// [`TextLayout`]: crate::piet::TextLayout pub fn layout(&self) -> Option<&PietTextLayout> { self.layout.as_ref() } /// The size of the laid-out text. /// /// This is not meaningful until [`rebuild_if_needed`] has been called. /// /// [`rebuild_if_needed`]: TextLayout::rebuild_if_needed pub fn size(&self) -> Size { self.layout .as_ref() .map(|layout| layout.size()) .unwrap_or_default() } /// Return the text's [`LayoutMetrics`]. /// /// This is not meaningful until [`rebuild_if_needed`] has been called. /// /// [`rebuild_if_needed`]: TextLayout::rebuild_if_needed pub fn layout_metrics(&self) -> LayoutMetrics { debug_assert!( self.layout.is_some(), "TextLayout::layout_metrics called without rebuilding layout object. Text was '{}'", self.text().as_ref().map(|s| s.as_str()).unwrap_or_default() ); if let Some(layout) = self.layout.as_ref() { let first_baseline = layout.line_metric(0).unwrap().baseline; let size = layout.size(); LayoutMetrics { size, first_baseline, trailing_whitespace_width: layout.trailing_whitespace_width(), } } else { LayoutMetrics::default() } } /// For a given `Point` (relative to this object's origin), returns index /// into the underlying text of the nearest grapheme boundary. pub fn text_position_for_point(&self, point: Point) -> usize { self.layout .as_ref() .map(|layout| layout.hit_test_point(point).idx) .unwrap_or_default() } /// Given the utf-8 position of a character boundary in the underlying text, /// return the `Point` (relative to this object's origin) representing the /// boundary of the containing grapheme. /// /// # Panics /// /// Panics if `text_pos` is not a character boundary. pub fn point_for_text_position(&self, text_pos: usize) -> Point { self.layout .as_ref() .map(|layout| layout.hit_test_text_position(text_pos).point) .unwrap_or_default() } /// Given a utf-8 range in the underlying text, return a `Vec` of `Rect`s /// representing the nominal bounding boxes of the text in that range. /// /// # Panics /// /// Panics if the range start or end is not a character boundary. pub fn rects_for_range(&self, range: Range<usize>) -> Vec<Rect> { self.layout .as_ref() .map(|layout| layout.rects_for_range(range)) .unwrap_or_default() } /// Return a line suitable for underlining a range of text. /// /// This is really only intended to be used to indicate the composition /// range while IME is active. /// /// range is expected to be on a single visual line. pub fn underline_for_range(&self, range: Range<usize>) -> Line { self.layout .as_ref() .map(|layout| { let p1 = layout.hit_test_text_position(range.start); let p2 = layout.hit_test_text_position(range.end); let line_metric = layout.line_metric(p1.line).unwrap(); // heuristic; 1/5 of height is a rough guess at the descender pos? let y_pos = line_metric.baseline + (line_metric.height / 5.0); Line::new((p1.point.x, y_pos), (p2.point.x, y_pos)) }) .unwrap_or_else(|| Line::new(Point::ZERO, Point::ZERO)) } /// Given the utf-8 position of a character boundary in the underlying text, /// return a `Line` suitable for drawing a vertical cursor at that boundary. pub fn cursor_line_for_text_position(&self, text_pos: usize) -> Line { self.layout .as_ref() .map(|layout| { let pos = layout.hit_test_text_position(text_pos); let line_metrics = layout.line_metric(pos.line).unwrap(); let p1 = (pos.point.x, line_metrics.y_offset); let p2 = (pos.point.x, (line_metrics.y_offset + line_metrics.height)); Line::new(p1, p2) }) .unwrap_or_else(|| Line::new(Point::ZERO, Point::ZERO)) } /// Returns the [`Link`] at the provided point (relative to the layout's origin) if one exists. /// /// This can be used both for hit-testing (deciding whether to change the mouse cursor, /// or performing some other action when hovering) as well as for retrieving a [`Link`] /// on click. /// /// [`Link`]: super::attribute::Link pub fn link_for_pos(&self, pos: Point) -> Option<&Link> { let (_, i) = self .links .iter() .rfind(|(hit_box, _)| hit_box.contains(pos))?; let text = self.text()?; text.links().get(*i) } /// Called during the containing widget's [`update`] method; this text object /// will check to see if any used environment items have changed, /// and invalidate itself as needed. /// /// Returns `true` if the text item needs to be rebuilt. /// /// [`update`]: crate::Widget::update pub fn needs_rebuild_after_update(&mut self, ctx: &mut UpdateCtx) -> bool { if ctx.env_changed() && self.layout.is_some() { let rebuild = ctx.env_key_changed(&self.font) || ctx.env_key_changed(&self.text_color) || self .text_size_override .as_ref() .map(|k| ctx.env_key_changed(k)) .unwrap_or(false) || self .text .as_ref() .map(|text| text.env_update(&EnvUpdateCtx::for_update(ctx))) .unwrap_or(false); if rebuild { self.layout = None; } } self.layout.is_none() } /// Rebuild the inner layout as needed. /// /// This `TextLayout` object manages a lower-level layout object that may /// need to be rebuilt in response to changes to the text or attributes /// like the font. /// /// This method should be called whenever any of these things may have changed. /// A simple way to ensure this is correct is to always call this method /// as part of your widget's [`layout`] method. /// /// [`layout`]: crate::Widget::layout pub fn rebuild_if_needed(&mut self, factory: &mut PietText, env: &Env) { if let Some(text) = &self.text { if self.layout.is_none() { let font = self.font.resolve(env); let color = self.text_color.resolve(env); let size_override = self.text_size_override.as_ref().map(|key| key.resolve(env)); let descriptor = if let Some(size) = size_override { font.with_size(size) } else { font }; let builder = factory .new_text_layout(text.clone()) .max_width(self.wrap_width) .alignment(self.alignment) .font(descriptor.family.clone(), descriptor.size) .default_attribute(descriptor.weight) .default_attribute(descriptor.style) .default_attribute(TextAttribute::TextColor(color)); let layout = text.add_attributes(builder, env).build().unwrap(); self.links = text .links() .iter() .enumerate() .flat_map(|(i, link)| { layout .rects_for_range(link.range()) .into_iter() .map(move |rect| (rect, i)) }) .collect(); self.layout = Some(layout); } } } /// Draw the layout at the provided `Point`. /// /// The origin of the layout is the top-left corner. /// /// You must call [`rebuild_if_needed`] at some point before you first /// call this method. /// /// [`rebuild_if_needed`]: #method.rebuild_if_needed pub fn draw(&self, ctx: &mut PaintCtx, point: impl Into<Point>) { debug_assert!( self.layout.is_some(), "TextLayout::draw called without rebuilding layout object. Text was '{}'", self.text .as_ref() .map(|t| t.as_str()) .unwrap_or("layout is missing text") ); if let Some(layout) = self.layout.as_ref() { ctx.draw_text(layout, point); } } } impl<T> std::fmt::Debug for TextLayout<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("TextLayout") .field("font", &self.font) .field("text_size_override", &self.text_size_override) .field("text_color", &self.text_color) .field( "layout", if self.layout.is_some() { &"Some" } else { &"None" }, ) .finish() } } impl<T: TextStorage> Default for TextLayout<T> { fn default() -> Self { Self::new() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/format.rs
druid/src/text/format.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Creating, interpreting, and validating textual representations of values. use std::str::FromStr; use std::sync::Arc; use super::Selection; use crate::Data; /// A trait for types that create, interpret, and validate textual representations /// of values. /// /// A formatter has two responsibilities: converting a value into an appropriate /// string representation, and attempting to convert a string back into the /// appropriate value. /// /// In addition, a formatter performs validation on *partial* strings; that is, /// it determines whether or not a string represents a potentially valid value, /// even if it is not currently valid. pub trait Formatter<T> { /// Return the string representation of this value. fn format(&self, value: &T) -> String; /// Return the string representation of this value, to be used during editing. /// /// This can be used if you want the text to differ based on whether or not /// it is being edited; for instance you might display a dollar sign when /// not editing, but not display it during editing. fn format_for_editing(&self, value: &T) -> String { self.format(value) } /// Determine whether the newly edited text is valid for this value type. /// /// This always returns a [`Validation`] object which indicates if /// validation was successful or not, and which can also optionally, /// regardless of success or failure, include new text and selection values /// that should replace the current ones. /// /// /// # Replacing the text or selection during validation /// /// Your `Formatter` may wish to change the current text or selection during /// editing for a number of reasons. For instance if validation fails, you /// may wish to allow editing to continue, but select the invalid region; /// alternatively you may consider input valid but want to transform it, /// such as by changing case or inserting spaces. /// /// If you do *not* explicitly set replacement text, and validation is not /// successful, the edit will be ignored. /// /// [`Validation`]: Validation fn validate_partial_input(&self, input: &str, sel: &Selection) -> Validation; /// The value represented by the input, or an error if the input is invalid. /// /// This must return `Ok()` for any string created by [`format`]. /// /// [`format`]: Formatter::format fn value(&self, input: &str) -> Result<T, ValidationError>; } /// The result of a [`Formatter`] attempting to validate some partial input. /// /// [`Formatter`]: Formatter pub struct Validation { result: Result<(), ValidationError>, /// A manual selection override. /// /// This will be set as the new selection (regardless of whether or not /// validation succeeded or failed) pub selection_change: Option<Selection>, /// A manual text override. /// /// This will be set as the new text, regardless of whether or not /// validation failed. pub text_change: Option<String>, } /// An error returned by a [`Formatter`] when it cannot parse input. /// /// This implements [`source`] so you can access the inner error type. /// /// [`source`]: std::error::Error::source // This is currently just a wrapper around the inner error; in the future // it may grow to contain information such as invalid spans? // TODO: the fact that this uses `Arc` to work with `Data` is a bit inefficient; // it means that we will update when a new instance of an identical error occurs. #[derive(Debug, Clone, Data)] pub struct ValidationError { inner: Arc<dyn std::error::Error>, } /// A naive [`Formatter`] for types that implement [`FromStr`]. /// /// For types that implement [`std::fmt::Display`], the [`ParseFormatter::new`] /// constructor creates a formatter that format's its value using that trait. /// If you would like to customize the formatting, you can use the /// [`ParseFormatter::with_format_fn`] constructor, and pass your own formatting /// function. /// /// [`Formatter`]: Formatter /// [`FromStr`]: std::str::FromStr #[non_exhaustive] pub struct ParseFormatter<T> { fmt_fn: Box<dyn Fn(&T) -> String>, } impl Validation { /// Create a `Validation` indicating success. pub fn success() -> Self { Validation { result: Ok(()), selection_change: None, text_change: None, } } /// Create a `Validation` with an error indicating the failure reason. pub fn failure(err: impl std::error::Error + 'static) -> Self { Validation { result: Err(ValidationError::new(err)), ..Validation::success() } } /// Optionally set a `String` that will replace the current contents. pub fn change_text(mut self, text: String) -> Self { self.text_change = Some(text); self } /// Optionally set a [`Selection`] that will replace the current one. pub fn change_selection(mut self, sel: Selection) -> Self { self.selection_change = Some(sel); self } /// Returns `true` if this `Validation` indicates failure. pub fn is_err(&self) -> bool { self.result.is_err() } /// If validation failed, return the underlying [`ValidationError`]. /// /// [`ValidationError`]: ValidationError pub fn error(&self) -> Option<&ValidationError> { self.result.as_ref().err() } } impl ValidationError { /// Create a new `ValidationError` with the given error type. pub fn new(e: impl std::error::Error + 'static) -> Self { ValidationError { inner: Arc::new(e) } } } impl<T: std::fmt::Display> ParseFormatter<T> { /// Create a new `ParseFormatter`. pub fn new() -> Self { ParseFormatter { fmt_fn: Box::new(|val| val.to_string()), } } } impl<T> ParseFormatter<T> { /// Create a new `ParseFormatter` using the provided formatting function. /// provided function. pub fn with_format_fn(f: impl Fn(&T) -> String + 'static) -> Self { ParseFormatter { fmt_fn: Box::new(f), } } } impl<T> Formatter<T> for ParseFormatter<T> where T: FromStr, <T as FromStr>::Err: std::error::Error + 'static, { fn format(&self, value: &T) -> String { (self.fmt_fn)(value) } fn validate_partial_input(&self, input: &str, _sel: &Selection) -> Validation { match input.parse::<T>() { Ok(_) => Validation::success(), Err(e) => Validation::failure(e), } } fn value(&self, input: &str) -> Result<T, ValidationError> { input.parse().map_err(ValidationError::new) } } impl std::fmt::Display for ValidationError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", &self.inner) } } impl std::error::Error for ValidationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&*self.inner) } } impl<T: std::fmt::Display> Default for ParseFormatter<T> { fn default() -> Self { ParseFormatter::new() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/font_descriptor.rs
druid/src/text/font_descriptor.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Font attributes use crate::{Data, FontFamily, FontStyle, FontWeight}; /// A collection of attributes that describe a font. /// /// This is provided as a convenience; library consumers may wish to have /// a single type that represents a specific font face at a specific size. #[derive(Debug, Data, Clone, PartialEq)] pub struct FontDescriptor { /// The font's [`FontFamily`]. pub family: FontFamily, /// The font's size. pub size: f64, /// The font's [`FontWeight`]. pub weight: FontWeight, /// The font's [`FontStyle`]. pub style: FontStyle, } impl FontDescriptor { /// Create a new descriptor with the provided [`FontFamily`]. pub const fn new(family: FontFamily) -> Self { FontDescriptor { family, size: crate::piet::util::DEFAULT_FONT_SIZE, weight: FontWeight::REGULAR, style: FontStyle::Regular, } } /// Buider-style method to set the descriptor's font size. pub const fn with_size(mut self, size: f64) -> Self { self.size = size; self } /// Buider-style method to set the descriptor's [`FontWeight`]. pub const fn with_weight(mut self, weight: FontWeight) -> Self { self.weight = weight; self } /// Buider-style method to set the descriptor's [`FontStyle`]. pub const fn with_style(mut self, style: FontStyle) -> Self { self.style = style; self } } impl Default for FontDescriptor { fn default() -> Self { FontDescriptor { family: Default::default(), weight: Default::default(), style: Default::default(), size: crate::piet::util::DEFAULT_FONT_SIZE, } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/text/movement.rs
druid/src/text/movement.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Text editing movements. use std::ops::Range; use unicode_segmentation::UnicodeSegmentation; use crate::kurbo::Point; use crate::piet::TextLayout as _; use crate::text::{ EditableText, Movement, Selection, TextLayout, TextStorage, VerticalMovement, WritingDirection, }; /// Compute the result of a [`Movement`] on a [`Selection`]. /// /// returns a new selection representing the state after the movement. /// /// If `modify` is true, only the 'active' edge (the `end`) of the selection /// should be changed; this is the case when the user moves with the shift /// key pressed. pub fn movement<T: EditableText + TextStorage>( m: Movement, s: Selection, layout: &TextLayout<T>, modify: bool, ) -> Selection { let (text, layout) = match (layout.text(), layout.layout()) { (Some(text), Some(layout)) => (text, layout), _ => { debug_assert!(false, "movement() called before layout rebuild"); return s; } }; let writing_direction = if crate::piet::util::first_strong_rtl(text.as_str()) { WritingDirection::RightToLeft } else { WritingDirection::LeftToRight }; let (offset, h_pos) = match m { Movement::Grapheme(d) if d.is_upstream_for_direction(writing_direction) => { if s.is_caret() || modify { text.prev_grapheme_offset(s.active) .map(|off| (off, None)) .unwrap_or((0, s.h_pos)) } else { (s.min(), None) } } Movement::Grapheme(_) => { if s.is_caret() || modify { text.next_grapheme_offset(s.active) .map(|off| (off, None)) .unwrap_or((s.active, s.h_pos)) } else { (s.max(), None) } } Movement::Vertical(VerticalMovement::LineUp) => { let cur_pos = layout.hit_test_text_position(s.active); let h_pos = s.h_pos.unwrap_or(cur_pos.point.x); if cur_pos.line == 0 { (0, Some(h_pos)) } else { let lm = layout.line_metric(cur_pos.line).unwrap(); let point_above = Point::new(h_pos, cur_pos.point.y - lm.height); let up_pos = layout.hit_test_point(point_above); if up_pos.is_inside { (up_pos.idx, Some(h_pos)) } else { // because we can't specify affinity, moving up when h_pos // is wider than both the current line and the previous line // can result in a cursor position at the visual start of the // current line; so we handle this as a special-case. let lm_prev = layout.line_metric(cur_pos.line.saturating_sub(1)).unwrap(); let up_pos = lm_prev.end_offset - lm_prev.trailing_whitespace; (up_pos, Some(h_pos)) } } } Movement::Vertical(VerticalMovement::LineDown) => { let cur_pos = layout.hit_test_text_position(s.active); let h_pos = s.h_pos.unwrap_or(cur_pos.point.x); if cur_pos.line == layout.line_count() - 1 { (text.len(), Some(h_pos)) } else { let lm = layout.line_metric(cur_pos.line).unwrap(); // may not work correctly for point sizes below 1.0 let y_below = lm.y_offset + lm.height + 1.0; let point_below = Point::new(h_pos, y_below); let up_pos = layout.hit_test_point(point_below); (up_pos.idx, Some(point_below.x)) } } Movement::Vertical(VerticalMovement::DocumentStart) => (0, None), Movement::Vertical(VerticalMovement::DocumentEnd) => (text.len(), None), Movement::ParagraphStart => (text.preceding_line_break(s.active), None), Movement::ParagraphEnd => (text.next_line_break(s.active), None), Movement::Line(d) => { let hit = layout.hit_test_text_position(s.active); let lm = layout.line_metric(hit.line).unwrap(); let offset = if d.is_upstream_for_direction(writing_direction) { lm.start_offset } else { lm.end_offset - lm.trailing_whitespace }; (offset, None) } Movement::Word(d) if d.is_upstream_for_direction(writing_direction) => { let offset = if s.is_caret() || modify { text.prev_word_offset(s.active).unwrap_or(0) } else { s.min() }; (offset, None) } Movement::Word(_) => { let offset = if s.is_caret() || modify { text.next_word_offset(s.active).unwrap_or(s.active) } else { s.max() }; (offset, None) } // These two are not handled; they require knowledge of the size // of the viewport. Movement::Vertical(VerticalMovement::PageDown) | Movement::Vertical(VerticalMovement::PageUp) => (s.active, s.h_pos), other => { tracing::warn!("unhandled movement {:?}", other); (s.anchor, s.h_pos) } }; let start = if modify { s.anchor } else { offset }; Selection::new(start, offset).with_h_pos(h_pos) } /// Given a position in some text, return the containing word boundaries. /// /// The returned range may not necessary be a 'word'; for instance it could be /// the sequence of whitespace between two words. /// /// If the position is on a word boundary, that will be considered the start /// of the range. /// /// This uses Unicode word boundaries, as defined in [UAX#29]. /// /// [UAX#29]: http://www.unicode.org/reports/tr29/ pub(crate) fn word_range_for_pos(text: &str, pos: usize) -> Range<usize> { text.split_word_bound_indices() .map(|(ix, word)| ix..(ix + word.len())) .find(|range| range.contains(&pos)) .unwrap_or(pos..pos) } #[cfg(test)] mod tests { use super::*; #[test] fn word_range_simple() { assert_eq!(word_range_for_pos("hello world", 3), 0..5); assert_eq!(word_range_for_pos("hello world", 8), 6..11); } #[test] fn word_range_whitespace() { assert_eq!(word_range_for_pos("hello world", 5), 5..6); } #[test] fn word_range_rtl() { let rtl = "مرحبا بالعالم"; assert_eq!(word_range_for_pos(rtl, 5), 0..10); assert_eq!(word_range_for_pos(rtl, 16), 11..25); assert_eq!(word_range_for_pos(rtl, 10), 10..11); } #[test] fn word_range_mixed() { let mixed = "hello مرحبا بالعالم world"; assert_eq!(word_range_for_pos(mixed, 3), 0..5); assert_eq!(word_range_for_pos(mixed, 8), 6..16); assert_eq!(word_range_for_pos(mixed, 19), 17..31); assert_eq!(word_range_for_pos(mixed, 36), 32..37); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/button.rs
druid/src/widget/button.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A button widget. use crate::debug_state::DebugState; use crate::widget::prelude::*; use crate::widget::{Click, ControllerHost, Label, LabelText}; use crate::{theme, Affine, Data, Insets, LinearGradient, UnitPoint}; use tracing::{instrument, trace}; // the minimum padding added to a button. // NOTE: these values are chosen to match the existing look of TextBox; these // should be reevaluated at some point. const LABEL_INSETS: Insets = Insets::uniform_xy(8., 2.); /// A button with a text label. pub struct Button<T> { label: Label<T>, label_size: Size, } impl<T: Data> Button<T> { /// Create a new button with a text label. /// /// Use the [`on_click`] method to provide a closure to be called when the /// button is clicked. /// /// # Examples /// /// ``` /// use druid::widget::Button; /// /// let button = Button::new("Increment").on_click(|_ctx, data: &mut u32, _env| { /// *data += 1; /// }); /// ``` /// /// [`on_click`]: #method.on_click pub fn new(text: impl Into<LabelText<T>>) -> Button<T> { Button::from_label(Label::new(text)) } /// Create a new button with the provided [`Label`]. /// /// Use the [`on_click`] method to provide a closure to be called when the /// button is clicked. /// /// # Examples /// /// ``` /// use druid::Color; /// use druid::widget::{Button, Label}; /// /// let button = Button::from_label(Label::new("Increment").with_text_color(Color::grey(0.5))).on_click(|_ctx, data: &mut u32, _env| { /// *data += 1; /// }); /// ``` /// /// [`on_click`]: #method.on_click pub fn from_label(label: Label<T>) -> Button<T> { Button { label, label_size: Size::ZERO, } } /// Construct a new dynamic button. /// /// The contents of this button are generated from the data using a closure. /// /// This is provided as a convenience; a closure can also be passed to [`new`], /// but due to limitations of the implementation of that method, the types in /// the closure need to be annotated, which is not true for this method. /// /// # Examples /// /// The following are equivalent. /// /// ``` /// use druid::Env; /// use druid::widget::Button; /// let button1: Button<u32> = Button::new(|data: &u32, _: &Env| format!("total is {}", data)); /// let button2: Button<u32> = Button::dynamic(|data, _| format!("total is {}", data)); /// ``` /// /// [`new`]: #method.new pub fn dynamic(text: impl Fn(&T, &Env) -> String + 'static) -> Self { let text: LabelText<T> = text.into(); Button::new(text) } /// Provide a closure to be called when this button is clicked. pub fn on_click( self, f: impl Fn(&mut EventCtx, &mut T, &Env) + 'static, ) -> ControllerHost<Self, Click<T>> { ControllerHost::new(self, Click::new(f)) } } impl<T: Data> Widget<T> for Button<T> { #[instrument(name = "Button", level = "trace", skip(self, ctx, event, _data, _env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, _data: &mut T, _env: &Env) { match event { Event::MouseDown(_) => { if !ctx.is_disabled() { ctx.set_active(true); ctx.request_paint(); trace!("Button {:?} pressed", ctx.widget_id()); } } Event::MouseUp(_) => { if ctx.is_active() && !ctx.is_disabled() { ctx.request_paint(); trace!("Button {:?} released", ctx.widget_id()); } ctx.set_active(false); } _ => (), } } #[instrument(name = "Button", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { if let LifeCycle::HotChanged(_) | LifeCycle::DisabledChanged(_) = event { ctx.request_paint(); } self.label.lifecycle(ctx, event, data, env) } #[instrument(name = "Button", level = "trace", skip(self, ctx, old_data, data, env))] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.label.update(ctx, old_data, data, env) } #[instrument(name = "Button", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("Button"); let padding = Size::new(LABEL_INSETS.x_value(), LABEL_INSETS.y_value()); let label_bc = bc.shrink(padding).loosen(); self.label_size = self.label.layout(ctx, &label_bc, data, env); // HACK: to make sure we look okay at default sizes when beside a textbox, // we make sure we will have at least the same height as the default textbox. let min_height = env.get(theme::BORDERED_WIDGET_HEIGHT); let baseline = self.label.baseline_offset(); ctx.set_baseline_offset(baseline + LABEL_INSETS.y1); let button_size = bc.constrain(Size::new( self.label_size.width + padding.width, (self.label_size.height + padding.height).max(min_height), )); trace!("Computed button size: {}", button_size); button_size } #[instrument(name = "Button", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let is_active = ctx.is_active() && !ctx.is_disabled(); let is_hot = ctx.is_hot(); let size = ctx.size(); let stroke_width = env.get(theme::BUTTON_BORDER_WIDTH); let rounded_rect = size .to_rect() .inset(-stroke_width / 2.0) .to_rounded_rect(env.get(theme::BUTTON_BORDER_RADIUS)); let bg_gradient = if ctx.is_disabled() { LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, ( env.get(theme::DISABLED_BUTTON_LIGHT), env.get(theme::DISABLED_BUTTON_DARK), ), ) } else if is_active { LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, (env.get(theme::BUTTON_DARK), env.get(theme::BUTTON_LIGHT)), ) } else { LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, (env.get(theme::BUTTON_LIGHT), env.get(theme::BUTTON_DARK)), ) }; let border_color = if is_hot && !ctx.is_disabled() { env.get(theme::BORDER_LIGHT) } else { env.get(theme::BORDER_DARK) }; ctx.stroke(rounded_rect, &border_color, stroke_width); ctx.fill(rounded_rect, &bg_gradient); let label_offset = (size.to_vec2() - self.label_size.to_vec2()) / 2.0; ctx.with_save(|ctx| { ctx.transform(Affine::translate(label_offset)); self.label.paint(ctx, data, env); }); } fn debug_state(&self, _data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), main_value: self.label.text().to_string(), ..Default::default() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/z_stack.rs
druid/src/widget/z_stack.rs
// Copyright 2022 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A ZStack widget. use crate::{ BoxConstraints, Data, Env, Event, EventCtx, InternalEvent, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx, Point, Rect, Size, UnitPoint, UpdateCtx, Vec2, Widget, WidgetExt, WidgetPod, }; /// A container that stacks its children on top of each other. /// /// The container has a baselayer which has the lowest z-index and determines the size of the /// container. pub struct ZStack<T> { layers: Vec<ZChild<T>>, } struct ZChild<T> { child: WidgetPod<T, Box<dyn Widget<T>>>, relative_size: Vec2, absolute_size: Vec2, position: UnitPoint, offset: Vec2, } impl<T: Data> ZStack<T> { /// Creates a new ZStack with a baselayer. /// /// The baselayer is used by the ZStack to determine its own size. pub fn new(base_layer: impl Widget<T> + 'static) -> Self { Self { layers: vec![ZChild { child: WidgetPod::new(base_layer.boxed()), relative_size: Vec2::new(1.0, 1.0), absolute_size: Vec2::ZERO, position: UnitPoint::CENTER, offset: Vec2::ZERO, }], } } /// Builder-style method to add a new child to the Z-Stack. /// /// The child is added directly above the base layer. /// /// `relative_size` is the space the child is allowed to take up relative to its parent. The /// values are between 0 and 1. /// `absolute_size` is a fixed amount of pixels added to `relative_size`. /// /// `position` is the alignment of the child inside the remaining space of its parent. /// /// `offset` is a fixed amount of pixels added to `position`. pub fn with_child( mut self, child: impl Widget<T> + 'static, relative_size: Vec2, absolute_size: Vec2, position: UnitPoint, offset: Vec2, ) -> Self { let next_index = self.layers.len() - 1; self.layers.insert( next_index, ZChild { child: WidgetPod::new(child.boxed()), relative_size, absolute_size, position, offset, }, ); self } /// Builder-style method to add a new child to the Z-Stack. /// /// The child is added directly above the base layer, is positioned in the center and has no /// size constraints. pub fn with_centered_child(self, child: impl Widget<T> + 'static) -> Self { self.with_aligned_child(child, UnitPoint::CENTER) } /// Builder-style method to add a new child to the Z-Stack. /// /// The child is added directly above the base layer, uses the given alignment and has no /// size constraints. pub fn with_aligned_child(self, child: impl Widget<T> + 'static, alignment: UnitPoint) -> Self { self.with_child( child, Vec2::new(1.0, 1.0), Vec2::ZERO, alignment, Vec2::ZERO, ) } } impl<T: Data> Widget<T> for ZStack<T> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { let mut previous_hot = false; for layer in self.layers.iter_mut() { if event.is_pointer_event() && previous_hot { if layer.child.is_active() { ctx.set_handled(); layer.child.event(ctx, event, data, env); } else { layer .child .event(ctx, &Event::Internal(InternalEvent::MouseLeave), data, env); } } else { layer.child.event(ctx, event, data, env); } previous_hot |= layer.child.is_hot(); } } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { let mut previous_hot = false; for layer in self.layers.iter_mut() { let inner_event = event.ignore_hot(previous_hot); layer.child.lifecycle(ctx, &inner_event, data, env); previous_hot |= layer.child.is_hot(); } } fn update(&mut self, ctx: &mut UpdateCtx, _: &T, data: &T, env: &Env) { for layer in self.layers.iter_mut().rev() { layer.child.update(ctx, data, env); } } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { //Layout base layer let base_layer = self.layers.last_mut().unwrap(); let base_size = base_layer.child.layout(ctx, bc, data, env); //Layout other layers let other_layers = self.layers.len() - 1; for layer in self.layers.iter_mut().take(other_layers) { let max_size = layer.resolve_max_size(base_size); layer .child .layout(ctx, &BoxConstraints::new(Size::ZERO, max_size), data, env); } //Set origin for all Layers and calculate paint insets let mut paint_rect = Rect::ZERO; for layer in self.layers.iter_mut() { let remaining = base_size - layer.child.layout_rect().size(); let origin = layer.resolve_point(remaining); layer.child.set_origin(ctx, origin); paint_rect = paint_rect.union(layer.child.paint_rect()); } ctx.set_paint_insets(paint_rect - base_size.to_rect()); ctx.set_baseline_offset(self.layers.last().unwrap().child.baseline_offset()); base_size } fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { //Painters algorithm (Painting back to front) for layer in self.layers.iter_mut().rev() { layer.child.paint(ctx, data, env); } } } impl<T: Data> ZChild<T> { fn resolve_max_size(&self, availible: Size) -> Size { self.absolute_size.to_size() + Size::new( availible.width * self.relative_size.x, availible.height * self.relative_size.y, ) } fn resolve_point(&self, remaining_space: Size) -> Point { (self.position.resolve(remaining_space.to_rect()).to_vec2() + self.offset).to_point() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/identity_wrapper.rs
druid/src/widget/identity_wrapper.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget that provides an explicit identity to a child. use crate::debug_state::DebugState; use crate::kurbo::Size; use crate::widget::prelude::*; use crate::widget::WidgetWrapper; use crate::Data; use tracing::instrument; /// A wrapper that adds an identity to an otherwise anonymous widget. pub struct IdentityWrapper<W> { id: WidgetId, child: W, } impl<W> IdentityWrapper<W> { /// Assign an identity to a widget. pub fn wrap(child: W, id: WidgetId) -> IdentityWrapper<W> { IdentityWrapper { id, child } } } impl<T: Data, W: Widget<T>> Widget<T> for IdentityWrapper<W> { #[instrument( name = "IdentityWrapper", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.child.event(ctx, event, data, env); } #[instrument( name = "IdentityWrapper", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.child.lifecycle(ctx, event, data, env) } #[instrument( name = "IdentityWrapper", level = "trace", skip(self, ctx, old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.child.update(ctx, old_data, data, env); } #[instrument( name = "IdentityWrapper", level = "trace", skip(self, ctx, bc, data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, data, env) } #[instrument(name = "IdentityWrapper", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.child.paint(ctx, data, env); } fn id(&self) -> Option<WidgetId> { Some(self.id) } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.child.debug_state(data)], ..Default::default() } } } impl<W> WidgetWrapper for IdentityWrapper<W> { widget_wrapper_body!(W, child); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/widget_ext.rs
druid/src/widget/widget_ext.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Convenience methods for widgets. use super::invalidation::DebugInvalidation; #[allow(deprecated)] use super::Parse; use super::{ Added, Align, BackgroundBrush, Click, Container, Controller, ControllerHost, EnvScope, IdentityWrapper, LensWrap, Padding, SizedBox, WidgetId, }; use crate::widget::{DisabledIf, Scroll}; use crate::{ Color, Data, Env, EventCtx, Insets, KeyOrValue, Lens, LifeCycleCtx, UnitPoint, Widget, }; /// A trait that provides extra methods for combining `Widget`s. pub trait WidgetExt<T: Data>: Widget<T> + Sized + 'static { /// Wrap this widget in a [`Padding`] widget with the given [`Insets`]. /// /// Like [`Padding::new`], this can accept a variety of arguments, including /// a [`Key`] referring to [`Insets`] in the [`Env`]. /// /// [`Key`]: crate::Key fn padding(self, insets: impl Into<KeyOrValue<Insets>>) -> Padding<T, Self> { Padding::new(insets, self) } /// Wrap this widget in an [`Align`] widget, configured to center it. fn center(self) -> Align<T> { Align::centered(self) } /// Wrap this widget in an [`Align`] widget, configured to align left. fn align_left(self) -> Align<T> { Align::left(self) } /// Wrap this widget in an [`Align`] widget, configured to align right. fn align_right(self) -> Align<T> { Align::right(self) } /// Wrap this widget in an [`Align`] widget, configured to align vertically. fn align_vertical(self, align: UnitPoint) -> Align<T> { Align::vertical(align, self) } /// Wrap this widget in an [`Align`] widget, configured to align horizontally. fn align_horizontal(self, align: UnitPoint) -> Align<T> { Align::horizontal(align, self) } /// Wrap this widget in a [`SizedBox`] with an explicit width. fn fix_width(self, width: impl Into<KeyOrValue<f64>>) -> SizedBox<T> { SizedBox::new(self).width(width) } /// Wrap this widget in a [`SizedBox`] with an explicit height. fn fix_height(self, height: impl Into<KeyOrValue<f64>>) -> SizedBox<T> { SizedBox::new(self).height(height) } /// Wrap this widget in an [`SizedBox`] with an explicit width and height fn fix_size( self, width: impl Into<KeyOrValue<f64>>, height: impl Into<KeyOrValue<f64>>, ) -> SizedBox<T> { SizedBox::new(self).width(width).height(height) } /// Wrap this widget in a [`SizedBox`] with an infinite width and height. /// /// Only call this method if you want your widget to occupy all available /// space. If you only care about expanding in one of width or height, use /// [`expand_width`] or [`expand_height`] instead. /// /// [`expand_height`]: WidgetExt::expand_height /// [`expand_width`]: WidgetExt::expand_width fn expand(self) -> SizedBox<T> { SizedBox::new(self).expand() } /// Wrap this widget in a [`SizedBox`] with an infinite width. /// /// This will force the child to use all available space on the x-axis. fn expand_width(self) -> SizedBox<T> { SizedBox::new(self).expand_width() } /// Wrap this widget in a [`SizedBox`] with an infinite width. /// /// This will force the child to use all available space on the y-axis. fn expand_height(self) -> SizedBox<T> { SizedBox::new(self).expand_height() } /// Wrap this widget in a [`Container`] with the provided background `brush`. /// /// See [`Container::background`] for more information. fn background(self, brush: impl Into<BackgroundBrush<T>>) -> Container<T> { Container::new(self).background(brush) } /// Wrap this widget in a [`Container`] with the provided foreground `brush`. /// /// See [`Container::foreground`] for more information. fn foreground(self, brush: impl Into<BackgroundBrush<T>>) -> Container<T> { Container::new(self).foreground(brush) } /// Wrap this widget in a [`Container`] with the given border. /// /// Arguments can be either concrete values, or a [`Key`] of the respective /// type. /// /// [`Key`]: crate::Key fn border( self, color: impl Into<KeyOrValue<Color>>, width: impl Into<KeyOrValue<f64>>, ) -> Container<T> { Container::new(self).border(color, width) } /// Wrap this widget in a [`EnvScope`] widget, modifying the parent /// [`Env`] with the provided closure. fn env_scope(self, f: impl Fn(&mut Env, &T) + 'static) -> EnvScope<T, Self> { EnvScope::new(f, self) } /// Wrap this widget with the provided [`Controller`]. fn controller<C: Controller<T, Self>>(self, controller: C) -> ControllerHost<Self, C> { ControllerHost::new(self, controller) } /// Provide a closure that will be called when this widget is added to the widget tree. /// /// You can use this to perform any initial setup. /// /// This is equivalent to handling the [`LifeCycle::WidgetAdded`] event in a /// custom [`Controller`]. /// /// [`LifeCycle::WidgetAdded`]: crate::LifeCycle::WidgetAdded fn on_added( self, f: impl Fn(&mut Self, &mut LifeCycleCtx, &T, &Env) + 'static, ) -> ControllerHost<Self, Added<T, Self>> { ControllerHost::new(self, Added::new(f)) } /// Control the events of this widget with a [`Click`] widget. The closure /// provided will be called when the widget is clicked with the left mouse /// button. /// /// The child widget will also be updated on [`LifeCycle::HotChanged`] and /// mouse down, which can be useful for painting based on `ctx.is_active()` /// and `ctx.is_hot()`. /// /// [`LifeCycle::HotChanged`]: crate::LifeCycle::HotChanged fn on_click( self, f: impl Fn(&mut EventCtx, &mut T, &Env) + 'static, ) -> ControllerHost<Self, Click<T>> { ControllerHost::new(self, Click::new(f)) } /// Draw the [`layout`] `Rect`s of this widget and its children. /// /// [`layout`]: Widget::layout fn debug_paint_layout(self) -> EnvScope<T, Self> { EnvScope::new(|env, _| env.set(Env::DEBUG_PAINT, true), self) } /// Display the `WidgetId`s for this widget and its children, when hot. /// /// When this is `true`, widgets that are `hot` (are under the mouse cursor) /// will display their ids in their bottom right corner. /// /// These ids may overlap; in this case the id of a child will obscure /// the id of its parent. fn debug_widget_id(self) -> EnvScope<T, Self> { EnvScope::new(|env, _| env.set(Env::DEBUG_WIDGET_ID, true), self) } /// Draw a color-changing rectangle over this widget, allowing you to see the /// invalidation regions. fn debug_invalidation(self) -> DebugInvalidation<T, Self> { DebugInvalidation::new(self) } /// Set the [`DEBUG_WIDGET`] env variable for this widget (and its descendants). /// /// This does nothing by default, but you can use this variable while /// debugging to only print messages from particular instances of a widget. /// /// [`DEBUG_WIDGET`]: crate::Env::DEBUG_WIDGET fn debug_widget(self) -> EnvScope<T, Self> { EnvScope::new(|env, _| env.set(Env::DEBUG_WIDGET, true), self) } /// Wrap this widget in a [`LensWrap`] widget for the provided [`Lens`]. fn lens<S: Data, L: Lens<S, T>>(self, lens: L) -> LensWrap<S, T, L, Self> { LensWrap::new(self, lens) } /// Parse a `Widget<String>`'s contents #[doc(hidden)] #[deprecated(since = "0.7.0", note = "Use TextBox::with_formatter instead")] #[allow(deprecated)] fn parse(self) -> Parse<Self> where Self: Widget<String>, { Parse::new(self) } /// Assign the widget a specific [`WidgetId`]. /// /// You must ensure that a given [`WidgetId`] is only ever used for /// a single widget at a time. /// /// An id _may_ be reused over time; for instance if you replace one /// widget with another, you may reuse the first widget's id. fn with_id(self, id: WidgetId) -> IdentityWrapper<Self> { IdentityWrapper::wrap(self, id) } /// Wrap this widget in a `Box`. fn boxed(self) -> Box<dyn Widget<T>> { Box::new(self) } /// Wrap this widget in a [`Scroll`] widget. fn scroll(self) -> Scroll<T, Self> { Scroll::new(self) } /// Wrap this widget in a [`DisabledIf`] widget. /// /// The provided closure will determine if the widget is disabled. /// See [`is_disabled`] or [`set_disabled`] for more info about disabled state. /// /// [`is_disabled`]: EventCtx::is_disabled /// [`set_disabled`]: EventCtx::set_disabled fn disabled_if(self, disabled_if: impl Fn(&T, &Env) -> bool + 'static) -> DisabledIf<T, Self> { DisabledIf::new(self, disabled_if) } } impl<T: Data, W: Widget<T> + 'static> WidgetExt<T> for W {} // these are 'soft overrides' of methods on WidgetExt; resolution // will choose an impl on a type over an impl in a trait for methods with the same // name. #[doc(hidden)] impl<T: Data> SizedBox<T> { pub fn fix_width(self, width: impl Into<KeyOrValue<f64>>) -> SizedBox<T> { self.width(width) } pub fn fix_height(self, height: impl Into<KeyOrValue<f64>>) -> SizedBox<T> { self.height(height) } } // if two things are modifying an env one after another, just combine the modifications #[doc(hidden)] impl<T: Data, W> EnvScope<T, W> { pub fn env_scope(self, f2: impl Fn(&mut Env, &T) + 'static) -> EnvScope<T, W> { let EnvScope { f, child } = self; let new_f = move |env: &mut Env, data: &T| { f(env, data); f2(env, data); }; EnvScope { f: Box::new(new_f), child, } } pub fn debug_paint_layout(self) -> EnvScope<T, W> { self.env_scope(|env, _| env.set(Env::DEBUG_PAINT, true)) } } #[cfg(test)] mod tests { use super::*; use crate::widget::Slider; use crate::{Color, Key}; use test_log::test; #[test] fn container_reuse() { // this should be Container<Align<Container<Slider>>> let widget = Slider::new() .background(Color::BLACK) .foreground(Color::WHITE) .align_left() .border(Color::BLACK, 1.0); assert!(widget.border_is_some()); assert!(!widget.background_is_some()); assert!(!widget.foreground_is_some()); // this should be Container<Slider> let widget = Slider::new() .background(Color::BLACK) .border(Color::BLACK, 1.0) .foreground(Color::WHITE); assert!(widget.background_is_some()); assert!(widget.border_is_some()); assert!(widget.foreground_is_some()); } #[test] fn sized_box_reuse() { let mut env = Env::empty(); // this should be SizedBox<Align<SizedBox<Slider>>> let widget = Slider::new().fix_height(10.0).align_left().fix_width(1.0); assert_eq!(widget.width_and_height(&env), (Some(1.0), None)); // this should be SizedBox<Slider> let widget = Slider::new().fix_height(10.0).fix_width(1.0); assert_eq!(widget.width_and_height(&env), (Some(1.0), Some(10.0))); const HEIGHT_KEY: Key<f64> = Key::new("test-sized-box-reuse-height"); const WIDTH_KEY: Key<f64> = Key::new("test-sized-box-reuse-width"); env.set(HEIGHT_KEY, 10.0); env.set(WIDTH_KEY, 1.0); // this should be SizedBox<Align<SizedBox<Slider>>> let widget = Slider::new() .fix_height(HEIGHT_KEY) .align_left() .fix_width(WIDTH_KEY); assert_eq!(widget.width_and_height(&env), (Some(1.0), None)); // this should be SizedBox<Slider> let widget = Slider::new().fix_height(HEIGHT_KEY).fix_width(WIDTH_KEY); assert_eq!(widget.width_and_height(&env), (Some(1.0), Some(10.0))); } /// we only care that this will compile; see /// https://github.com/linebender/druid/pull/1414/ #[test] fn lens_with_generic_param() { use crate::widget::{Checkbox, Flex, Slider}; #[derive(Debug, Clone, Data, Lens)] struct MyData<T> { data: T, floatl: f64, } #[allow(dead_code)] fn make_widget() -> impl Widget<MyData<bool>> { Flex::row() .with_child(Slider::new().lens(MyData::<bool>::floatl)) .with_child(Checkbox::new("checkbox").lens(MyData::<bool>::data)) } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/scroll.rs
druid/src/widget/scroll.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A container that scrolls its contents. use crate::commands::SCROLL_TO_VIEW; use crate::contexts::ChangeCtx; use crate::debug_state::DebugState; use crate::widget::prelude::*; use crate::widget::{Axis, ClipBox}; use crate::{scroll_component::*, Data, Rect, Vec2}; use tracing::{instrument, trace}; /// A container that scrolls its contents. /// /// This container holds a single child, and uses the wheel to scroll it /// when the child's bounds are larger than the viewport. /// /// The child is laid out with completely unconstrained layout bounds by /// default. Restrict to a specific axis with [`vertical`] or [`horizontal`]. /// When restricted to scrolling on a specific axis the child's size is /// locked on the opposite axis. /// /// [`vertical`]: struct.Scroll.html#method.vertical /// [`horizontal`]: struct.Scroll.html#method.horizontal pub struct Scroll<T, W> { clip: ClipBox<T, W>, scroll_component: ScrollComponent, } impl<T, W: Widget<T>> Scroll<T, W> { /// Create a new scroll container. /// /// This method will allow scrolling in all directions if child's bounds /// are larger than the viewport. Use [vertical](#method.vertical) and /// [horizontal](#method.horizontal) methods to limit scrolling to a specific axis. pub fn new(child: W) -> Scroll<T, W> { Scroll { clip: ClipBox::managed(child), scroll_component: ScrollComponent::new(), } } /// Scroll by `delta` units. /// /// Returns `true` if the scroll offset has changed. pub fn scroll_by<C: ChangeCtx>(&mut self, ctx: &mut C, delta: Vec2) -> bool { self.clip.pan_by(ctx, delta) } /// Scroll the minimal distance to show the target `region`. /// /// If the target region is larger than the viewport, we will display the /// portion that fits, prioritizing the portion closest to the origin. pub fn scroll_to<C: ChangeCtx>(&mut self, ctx: &mut C, region: Rect) -> bool { self.clip.pan_to_visible(ctx, region) } /// Scroll to this position on a particular axis. /// /// Returns `true` if the scroll offset has changed. pub fn scroll_to_on_axis<C: ChangeCtx>( &mut self, ctx: &mut C, axis: Axis, position: f64, ) -> bool { self.clip.pan_to_on_axis(ctx, axis, position) } } impl<T, W> Scroll<T, W> { /// Restrict scrolling to the vertical axis while locking child width. pub fn vertical(mut self) -> Self { self.scroll_component.enabled = ScrollbarsEnabled::Vertical; self.clip.set_constrain_vertical(false); self.clip.set_constrain_horizontal(true); self } /// Restrict scrolling to the horizontal axis while locking child height. pub fn horizontal(mut self) -> Self { self.scroll_component.enabled = ScrollbarsEnabled::Horizontal; self.clip.set_constrain_vertical(true); self.clip.set_constrain_horizontal(false); self } /// Builder-style method to set whether the child must fill the view. /// /// If `false` (the default) there is no minimum constraint on the child's /// size. If `true`, the child must have at least the same size as the parent /// `Scroll` widget. pub fn content_must_fill(mut self, must_fill: bool) -> Self { self.set_content_must_fill(must_fill); self } /// Disable both scrollbars pub fn disable_scrollbars(mut self) -> Self { self.scroll_component.enabled = ScrollbarsEnabled::None; self } /// Set whether the child's size must be greater than or equal the size of /// the `Scroll` widget. /// /// See [`content_must_fill`] for more details. /// /// [`content_must_fill`]: Scroll::content_must_fill pub fn set_content_must_fill(&mut self, must_fill: bool) { self.clip.set_content_must_fill(must_fill); } /// Set which scrollbars should be enabled. /// /// If scrollbars are disabled, scrolling will still occur as a result of /// scroll events from a trackpad or scroll wheel. pub fn set_enabled_scrollbars(&mut self, enabled: ScrollbarsEnabled) { self.scroll_component.enabled = enabled; } /// Set whether the content can be scrolled in the vertical direction. pub fn set_vertical_scroll_enabled(&mut self, enabled: bool) { self.clip.set_constrain_vertical(!enabled); self.scroll_component .enabled .set_vertical_scrollbar_enabled(enabled); } /// Set whether the content can be scrolled in the horizontal direction. pub fn set_horizontal_scroll_enabled(&mut self, enabled: bool) { self.clip.set_constrain_horizontal(!enabled); self.scroll_component .enabled .set_horizontal_scrollbar_enabled(enabled); } /// Returns a reference to the child widget. pub fn child(&self) -> &W { self.clip.child() } /// Returns a mutable reference to the child widget. pub fn child_mut(&mut self) -> &mut W { self.clip.child_mut() } /// Returns the size of the child widget. pub fn child_size(&self) -> Size { self.clip.content_size() } /// Returns the current scroll offset. pub fn offset(&self) -> Vec2 { self.clip.viewport_origin().to_vec2() } /// Returns a [`Rect`] representing the currently visible region. /// /// This is relative to the bounds of the content. pub fn viewport_rect(&self) -> Rect { self.clip.viewport().view_rect() } /// Return the scroll offset on a particular axis pub fn offset_for_axis(&self, axis: Axis) -> f64 { axis.major_pos(self.clip.viewport_origin()) } } impl<T: Data, W: Widget<T>> Widget<T> for Scroll<T, W> { #[instrument(name = "Scroll", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { let scroll_component = &mut self.scroll_component; self.clip.with_port(ctx, |ctx, port| { scroll_component.event(port, ctx, event, env); }); if !ctx.is_handled() { self.clip.event(ctx, event, data, env); } // Handle scroll after the inner widget processed the events, to prefer inner widgets while // scrolling. self.clip.with_port(ctx, |ctx, port| { scroll_component.handle_scroll(port, ctx, event, env); if !scroll_component.are_bars_held() { // We only scroll to the component if the user is not trying to move the scrollbar. if let Event::Notification(notification) = event { if let Some(&global_highlight_rect) = notification.get(SCROLL_TO_VIEW) { ctx.set_handled(); let view_port_changed = port.default_scroll_to_view_handling(ctx, global_highlight_rect); if view_port_changed { scroll_component .reset_scrollbar_fade(|duration| ctx.request_timer(duration), env); } } } } }); } #[instrument(name = "Scroll", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.scroll_component.lifecycle(ctx, event, env); self.clip.lifecycle(ctx, event, data, env); } #[instrument(name = "Scroll", level = "trace", skip(self, ctx, old_data, data, env))] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.clip.update(ctx, old_data, data, env); } #[instrument(name = "Scroll", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("Scroll"); let old_size = self.clip.viewport().view_size; let child_size = self.clip.layout(ctx, bc, data, env); log_size_warnings(child_size); let self_size = bc.constrain(child_size); if old_size != self_size { self.scroll_component .reset_scrollbar_fade(|d| ctx.request_timer(d), env); } trace!("Computed size: {}", self_size); self_size } #[instrument(name = "Scroll", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.clip.paint(ctx, data, env); self.scroll_component .draw_bars(ctx, &self.clip.viewport(), env); } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.clip.debug_state(data)], ..Default::default() } } } fn log_size_warnings(size: Size) { if size.width.is_infinite() { tracing::warn!("Scroll widget's child has an infinite width."); } if size.height.is_infinite() { tracing::warn!("Scroll widget's child has an infinite height."); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/flex.rs
druid/src/widget/flex.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget that arranges its children in a one-dimensional array. use std::ops::Add; use crate::debug_state::DebugState; use crate::kurbo::{common::FloatExt, Vec2}; use crate::widget::prelude::*; use crate::{Data, KeyOrValue, Point, Rect, WidgetPod}; use tracing::{instrument, trace}; /// A container with either horizontal or vertical layout. /// /// This widget is the foundation of most layouts, and is highly configurable. /// /// # Flex layout algorithm /// /// Children of a `Flex` container can have an optional `flex` parameter. /// Layout occurs in several passes. First we measure (calling their [`layout`] /// method) our non-flex children, providing them with unbounded space on the /// main axis. Next, the remaining space is divided between the flex children /// according to their flex factor, and they are measured. Unlike a non-flex /// child, a child with a non-zero flex factor has a maximum allowed size /// on the main axis; non-flex children are allowed to choose their size first, /// and freely. /// /// If you would like a child to be forced to use up all of the flex space /// passed to it, you can place it in a [`SizedBox`] set to `expand` in the /// appropriate axis. There are convenience methods for this available on /// [`WidgetExt`]: [`expand_width`] and [`expand_height`]. /// /// # Flex or non-flex? /// /// When should your children be flexible? With other things being equal, /// a flexible child has lower layout priority than a non-flexible child. /// Imagine, for instance, we have a row that is 30dp wide, and we have /// two children, both of which want to be 20dp wide. If child #1 is non-flex /// and child #2 is flex, the first widget will take up its 20dp, and the second /// widget will be constrained to 10dp. /// /// If, instead, both widgets are flex, they will each be given equal space, /// and both will end up taking up 15dp. /// /// If both are non-flex they will both take up 20dp, and will overflow the /// container. /// /// ```no_compile /// -------non-flex----- -flex----- /// | child #1 | child #2 | /// /// /// ----flex------- ----flex------- /// | child #1 | child #2 | /// /// ``` /// /// In general, if you are using widgets that are opinionated about their size /// (such as most control widgets, which are designed to lay out nicely together, /// or text widgets that are sized to fit their text) you should make them /// non-flexible. /// /// If you are trying to divide space evenly, or if you want a particular item /// to have access to all left over space, then you should make it flexible. /// /// **note**: by default, a widget will not necessarily use all the space that /// is available to it. For instance, the [`TextBox`] widget has a default /// width, and will choose this width if possible, even if more space is /// available to it. If you want to force a widget to use all available space, /// you should expand it, with [`expand_width`] or [`expand_height`]. /// /// /// # Options /// /// To experiment with these options, see the `flex` example in `druid/examples`. /// /// - [`CrossAxisAlignment`] determines how children are positioned on the /// cross or 'minor' axis. The default is `CrossAxisAlignment::Center`. /// /// - [`MainAxisAlignment`] determines how children are positioned on the main /// axis; this is only meaningful if the container has more space on the main /// axis than is taken up by its children. /// /// - [`must_fill_main_axis`] determines whether the container is obliged to /// be maximally large on the major axis, as determined by its own constraints. /// If this is `true`, then the container must fill the available space on that /// axis; otherwise it may be smaller if its children are smaller. /// /// Additional options can be set (or overridden) in the [`FlexParams`]. /// /// # Examples /// /// Construction with builder methods /// /// ``` /// use druid::widget::{Flex, FlexParams, Label, Slider, CrossAxisAlignment}; /// /// let my_row = Flex::row() /// .cross_axis_alignment(CrossAxisAlignment::Center) /// .must_fill_main_axis(true) /// .with_child(Label::new("hello")) /// .with_default_spacer() /// .with_flex_child(Slider::new(), 1.0); /// ``` /// /// Construction with mutating methods /// /// ``` /// use druid::widget::{Flex, FlexParams, Label, Slider, CrossAxisAlignment}; /// /// let mut my_row = Flex::row(); /// my_row.set_must_fill_main_axis(true); /// my_row.set_cross_axis_alignment(CrossAxisAlignment::Center); /// my_row.add_child(Label::new("hello")); /// my_row.add_default_spacer(); /// my_row.add_flex_child(Slider::new(), 1.0); /// ``` /// /// [`layout`]: Widget::layout /// [`must_fill_main_axis`]: Flex::must_fill_main_axis /// [`WidgetExt`]: super::WidgetExt /// [`expand_height`]: super::WidgetExt::expand_height /// [`expand_width`]: super::WidgetExt::expand_width /// [`TextBox`]: super::TextBox /// [`SizedBox`]: super::SizedBox pub struct Flex<T> { direction: Axis, cross_alignment: CrossAxisAlignment, main_alignment: MainAxisAlignment, fill_major_axis: bool, children: Vec<Child<T>>, old_bc: BoxConstraints, } /// Optional parameters for an item in a [`Flex`] container (row or column). /// /// Generally, when you would like to add a flexible child to a container, /// you can simply call [`with_flex_child`] or [`add_flex_child`], passing the /// child and the desired flex factor as a `f64`, which has an impl of /// `Into<FlexParams>`. /// /// If you need to set additional parameters, such as a custom [`CrossAxisAlignment`], /// you can construct `FlexParams` directly. By default, the child has the /// same `CrossAxisAlignment` as the container. /// /// For an overview of the flex layout algorithm, see the [`Flex`] docs. /// /// # Examples /// ``` /// use druid::widget::{FlexParams, Label, CrossAxisAlignment}; /// /// let mut row = druid::widget::Flex::<()>::row(); /// let child_1 = Label::new("I'm hungry"); /// let child_2 = Label::new("I'm scared"); /// // normally you just use a float: /// row.add_flex_child(child_1, 1.0); /// // you can construct FlexParams if needed: /// let params = FlexParams::new(2.0, CrossAxisAlignment::End); /// row.add_flex_child(child_2, params); /// ``` /// /// [`CrossAxisAlignment`]: enum.CrossAxisAlignment.html /// [`Flex`]: struct.Flex.html /// [`with_flex_child`]: struct.Flex.html#method.with_flex_child /// [`add_flex_child`]: struct.Flex.html#method.add_flex_child #[derive(Debug, Copy, Clone, PartialEq)] pub struct FlexParams { flex: f64, alignment: Option<CrossAxisAlignment>, } /// An axis in visual space. /// /// Most often used by widgets to describe /// the direction in which they grow as their number of children increases. /// Has some methods for manipulating geometry with respect to the axis. #[derive(Data, Debug, Clone, Copy, PartialEq, Eq)] pub enum Axis { /// The x axis Horizontal, /// The y axis Vertical, } impl Axis { /// Get the axis perpendicular to this one. pub fn cross(self) -> Axis { match self { Axis::Horizontal => Axis::Vertical, Axis::Vertical => Axis::Horizontal, } } /// Extract from the argument the magnitude along this axis pub fn major(self, coords: Size) -> f64 { match self { Axis::Horizontal => coords.width, Axis::Vertical => coords.height, } } /// Extract from the argument the magnitude along the perpendicular axis pub fn minor(self, coords: Size) -> f64 { self.cross().major(coords) } /// Extract the extent of the argument in this axis as a pair. pub fn major_span(self, rect: Rect) -> (f64, f64) { match self { Axis::Horizontal => (rect.x0, rect.x1), Axis::Vertical => (rect.y0, rect.y1), } } /// Extract the extent of the argument in the minor axis as a pair. pub fn minor_span(self, rect: Rect) -> (f64, f64) { self.cross().major_span(rect) } /// Extract the coordinate locating the argument with respect to this axis. pub fn major_pos(self, pos: Point) -> f64 { match self { Axis::Horizontal => pos.x, Axis::Vertical => pos.y, } } /// Extract the coordinate locating the argument with respect to this axis. pub fn major_vec(self, vec: Vec2) -> f64 { match self { Axis::Horizontal => vec.x, Axis::Vertical => vec.y, } } /// Extract the coordinate locating the argument with respect to the perpendicular axis. pub fn minor_pos(self, pos: Point) -> f64 { self.cross().major_pos(pos) } /// Extract the coordinate locating the argument with respect to the perpendicular axis. pub fn minor_vec(self, vec: Vec2) -> f64 { self.cross().major_vec(vec) } /// Arrange the major and minor measurements with respect to this axis such that it forms /// an (x, y) pair. pub fn pack(self, major: f64, minor: f64) -> (f64, f64) { match self { Axis::Horizontal => (major, minor), Axis::Vertical => (minor, major), } } /// Generate constraints with new values on the major axis. pub(crate) fn constraints( self, bc: &BoxConstraints, min_major: f64, major: f64, ) -> BoxConstraints { match self { Axis::Horizontal => BoxConstraints::new( Size::new(min_major, bc.min().height), Size::new(major, bc.max().height), ), Axis::Vertical => BoxConstraints::new( Size::new(bc.min().width, min_major), Size::new(bc.max().width, major), ), } } } /// The alignment of the widgets on the container's cross (or minor) axis. /// /// If a widget is smaller than the container on the minor axis, this determines /// where it is positioned. #[derive(Debug, Clone, Copy, PartialEq, Eq, Data)] pub enum CrossAxisAlignment { /// Top or leading. /// /// In a vertical container, widgets are top aligned. In a horizontal /// container, their leading edges are aligned. Start, /// Widgets are centered in the container. Center, /// Bottom or trailing. /// /// In a vertical container, widgets are bottom aligned. In a horizontal /// container, their trailing edges are aligned. End, /// Align on the baseline. /// /// In a horizontal container, widgets are aligned along the calculated /// baseline. In a vertical container, this is equivalent to `End`. /// /// The calculated baseline is the maximum baseline offset of the children. Baseline, /// Fill the available space. /// /// The size on this axis is the size of the largest widget; /// other widgets must fill that space. Fill, } /// Arrangement of children on the main axis. /// /// If there is surplus space on the main axis after laying out children, this /// enum represents how children are laid out in this space. #[derive(Debug, Clone, Copy, PartialEq, Eq, Data)] pub enum MainAxisAlignment { /// Top or leading. /// /// Children are aligned with the top or leading edge, without padding. Start, /// Children are centered, without padding. Center, /// Bottom or trailing. /// /// Children are aligned with the bottom or trailing edge, without padding. End, /// Extra space is divided evenly between each child. SpaceBetween, /// Extra space is divided evenly between each child, as well as at the ends. SpaceEvenly, /// Space between each child, with less at the start and end. /// /// This divides space such that each child is separated by `n` units, /// and the start and end have `n/2` units of padding. SpaceAround, } impl FlexParams { /// Create custom `FlexParams` with a specific `flex_factor` and an optional /// [`CrossAxisAlignment`]. /// /// You likely only need to create these manually if you need to specify /// a custom alignment; if you only need to use a custom `flex_factor` you /// can pass an `f64` to any of the functions that take `FlexParams`. /// /// By default, the widget uses the alignment of its parent [`Flex`] container. pub fn new(flex: f64, alignment: impl Into<Option<CrossAxisAlignment>>) -> Self { if flex <= 0.0 { debug_panic!("Flex value should be > 0.0. Flex given was: {}", flex); } let flex = flex.max(0.0); FlexParams { flex, alignment: alignment.into(), } } } impl<T: Data> Flex<T> { /// Create a new Flex oriented along the provided axis. pub fn for_axis(axis: Axis) -> Self { Flex { direction: axis, children: Vec::new(), cross_alignment: CrossAxisAlignment::Center, main_alignment: MainAxisAlignment::Start, fill_major_axis: false, old_bc: BoxConstraints::tight(Size::ZERO), } } /// Create a new horizontal stack. /// /// The child widgets are laid out horizontally, from left to right. /// pub fn row() -> Self { Self::for_axis(Axis::Horizontal) } /// Create a new vertical stack. /// /// The child widgets are laid out vertically, from top to bottom. pub fn column() -> Self { Self::for_axis(Axis::Vertical) } /// Builder-style method for specifying the childrens' [`CrossAxisAlignment`]. /// /// [`CrossAxisAlignment`]: enum.CrossAxisAlignment.html pub fn cross_axis_alignment(mut self, alignment: CrossAxisAlignment) -> Self { self.cross_alignment = alignment; self } /// Builder-style method for specifying the childrens' [`MainAxisAlignment`]. /// /// [`MainAxisAlignment`]: enum.MainAxisAlignment.html pub fn main_axis_alignment(mut self, alignment: MainAxisAlignment) -> Self { self.main_alignment = alignment; self } /// Builder-style method for setting whether the container must expand /// to fill the available space on its main axis. /// /// If any children have flex then this container will expand to fill all /// available space on its main axis; But if no children are flex, /// this flag determines whether or not the container should shrink to fit, /// or must expand to fill. /// /// If it expands, and there is extra space left over, that space is /// distributed in accordance with the [`MainAxisAlignment`]. /// /// The default value is `false`. /// /// [`MainAxisAlignment`]: enum.MainAxisAlignment.html pub fn must_fill_main_axis(mut self, fill: bool) -> Self { self.fill_major_axis = fill; self } /// Builder-style variant of `add_child`. /// /// Convenient for assembling a group of widgets in a single expression. pub fn with_child(mut self, child: impl Widget<T> + 'static) -> Self { self.add_child(child); self } /// Builder-style method to add a flexible child to the container. /// /// This method is used when you need more control over the behaviour /// of the widget you are adding. In the general case, this likely /// means giving that child a 'flex factor', but it could also mean /// giving the child a custom [`CrossAxisAlignment`], or a combination /// of the two. /// /// This function takes a child widget and [`FlexParams`]; importantly /// you can pass in a float as your [`FlexParams`] in most cases. /// /// For the non-builder variant, see [`add_flex_child`]. /// /// # Examples /// /// ``` /// use druid::widget::{Flex, FlexParams, Label, Slider, CrossAxisAlignment}; /// /// let my_row = Flex::row() /// .with_flex_child(Slider::new(), 1.0) /// .with_flex_child(Slider::new(), FlexParams::new(1.0, CrossAxisAlignment::End)); /// ``` /// /// [`FlexParams`]: struct.FlexParams.html /// [`add_flex_child`]: #method.add_flex_child /// [`CrossAxisAlignment`]: enum.CrossAxisAlignment.html pub fn with_flex_child( mut self, child: impl Widget<T> + 'static, params: impl Into<FlexParams>, ) -> Self { self.add_flex_child(child, params); self } /// Builder-style method to add a spacer widget with a standard size. /// /// The actual value of this spacer depends on whether this container is /// a row or column, as well as theme settings. pub fn with_default_spacer(mut self) -> Self { self.add_default_spacer(); self } /// Builder-style method for adding a fixed-size spacer to the container. /// /// If you are laying out standard controls in this container, you should /// generally prefer to use [`add_default_spacer`]. /// /// [`add_default_spacer`]: #method.add_default_spacer pub fn with_spacer(mut self, len: impl Into<KeyOrValue<f64>>) -> Self { self.add_spacer(len); self } /// Builder-style method for adding a `flex` spacer to the container. pub fn with_flex_spacer(mut self, flex: f64) -> Self { self.add_flex_spacer(flex); self } /// Set the childrens' [`CrossAxisAlignment`]. /// /// [`CrossAxisAlignment`]: enum.CrossAxisAlignment.html pub fn set_cross_axis_alignment(&mut self, alignment: CrossAxisAlignment) { self.cross_alignment = alignment; } /// Set the childrens' [`MainAxisAlignment`]. /// /// [`MainAxisAlignment`]: enum.MainAxisAlignment.html pub fn set_main_axis_alignment(&mut self, alignment: MainAxisAlignment) { self.main_alignment = alignment; } /// Set whether the container must expand to fill the available space on /// its main axis. pub fn set_must_fill_main_axis(&mut self, fill: bool) { self.fill_major_axis = fill; } /// Add a non-flex child widget. /// /// See also [`with_child`]. /// /// [`with_child`]: Flex::with_child pub fn add_child(&mut self, child: impl Widget<T> + 'static) { let child = Child::Fixed { widget: WidgetPod::new(Box::new(child)), alignment: None, }; self.children.push(child); } /// Add a flexible child widget. /// /// This method is used when you need more control over the behaviour /// of the widget you are adding. In the general case, this likely /// means giving that child a 'flex factor', but it could also mean /// giving the child a custom [`CrossAxisAlignment`], or a combination /// of the two. /// /// This function takes a child widget and [`FlexParams`]; importantly /// you can pass in a float as your [`FlexParams`] in most cases. /// /// For the builder-style variant, see [`with_flex_child`]. /// /// # Examples /// /// ``` /// use druid::widget::{Flex, FlexParams, Label, Slider, CrossAxisAlignment}; /// /// let mut my_row = Flex::row(); /// my_row.add_flex_child(Slider::new(), 1.0); /// my_row.add_flex_child(Slider::new(), FlexParams::new(1.0, CrossAxisAlignment::End)); /// ``` /// /// [`with_flex_child`]: Flex::with_flex_child pub fn add_flex_child( &mut self, child: impl Widget<T> + 'static, params: impl Into<FlexParams>, ) { let params = params.into(); let child = if params.flex > 0.0 { Child::Flex { widget: WidgetPod::new(Box::new(child)), alignment: params.alignment, flex: params.flex, } } else { tracing::warn!("Flex value should be > 0.0. To add a non-flex child use the add_child or with_child methods.\nSee the docs for more information: https://docs.rs/druid/0.8.3/druid/widget/struct.Flex.html"); Child::Fixed { widget: WidgetPod::new(Box::new(child)), alignment: None, } }; self.children.push(child); } /// Add a spacer widget with a standard size. /// /// The actual value of this spacer depends on whether this container is /// a row or column, as well as theme settings. pub fn add_default_spacer(&mut self) { let key = match self.direction { Axis::Vertical => crate::theme::WIDGET_PADDING_VERTICAL, Axis::Horizontal => crate::theme::WIDGET_PADDING_HORIZONTAL, }; self.add_spacer(key); } /// Add an empty spacer widget with the given size. /// /// If you are laying out standard controls in this container, you should /// generally prefer to use [`add_default_spacer`]. /// /// [`add_default_spacer`]: Flex::add_default_spacer pub fn add_spacer(&mut self, len: impl Into<KeyOrValue<f64>>) { let mut value = len.into(); if let KeyOrValue::Concrete(ref mut len) = value { if *len < 0.0 { tracing::warn!("Provided spacer length was less than 0. Value was: {}", len); } *len = len.clamp(0.0, f64::MAX); } let new_child = Child::FixedSpacer(value, 0.0); self.children.push(new_child); } /// Add an empty spacer widget with a specific `flex` factor. pub fn add_flex_spacer(&mut self, flex: f64) { let flex = if flex >= 0.0 { flex } else { debug_assert!( flex >= 0.0, "flex value for space should be greater than equal to 0, received: {flex}" ); tracing::warn!("Provided flex value was less than 0: {}", flex); 0.0 }; let new_child = Child::FlexedSpacer(flex, 0.0); self.children.push(new_child); } } impl<T: Data> Widget<T> for Flex<T> { #[instrument(name = "Flex", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { for child in self.children.iter_mut().filter_map(|x| x.widget_mut()) { child.event(ctx, event, data, env); } } #[instrument(name = "Flex", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { for child in self.children.iter_mut().filter_map(|x| x.widget_mut()) { child.lifecycle(ctx, event, data, env); } } #[instrument(name = "Flex", level = "trace", skip(self, ctx, _old_data, data, env))] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) { for child in self.children.iter_mut() { match child { Child::Fixed { widget, .. } | Child::Flex { widget, .. } => { widget.update(ctx, data, env) } Child::FixedSpacer(key_or_val, _) if ctx.env_key_changed(key_or_val) => { ctx.request_layout() } _ => {} } } } #[instrument(name = "Flex", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("Flex"); // we loosen our constraints when passing to children. let loosened_bc = bc.loosen(); // minor-axis values for all children let mut minor = self.direction.minor(bc.min()); // these two are calculated but only used if we're baseline aligned let mut max_above_baseline = 0f64; let mut max_below_baseline = 0f64; let mut any_use_baseline = false; // indicates that the box constrains for the following children have changed. Therefore they // have to calculate layout again. let bc_changed = self.old_bc != *bc; let mut any_changed = bc_changed; self.old_bc = *bc; // Measure non-flex children. let mut major_non_flex = 0.0; let mut flex_sum = 0.0; for child in &mut self.children { match child { Child::Fixed { widget, alignment } => { // The BoxConstrains of fixed-children only depends on the BoxConstrains of the // Flex widget. let child_size = if bc_changed || widget.layout_requested() { let alignment = alignment.unwrap_or(self.cross_alignment); any_use_baseline |= alignment == CrossAxisAlignment::Baseline; let old_size = widget.layout_rect().size(); let child_bc = self.direction.constraints(&loosened_bc, 0.0, f64::INFINITY); let child_size = widget.layout(ctx, &child_bc, data, env); if child_size.width.is_infinite() { tracing::warn!("A non-Flex child has an infinite width."); } if child_size.height.is_infinite() { tracing::warn!("A non-Flex child has an infinite height."); } if old_size != child_size { any_changed = true; } child_size } else { widget.layout_rect().size() }; let baseline_offset = widget.baseline_offset(); major_non_flex += self.direction.major(child_size).expand(); minor = minor.max(self.direction.minor(child_size).expand()); max_above_baseline = max_above_baseline.max(child_size.height - baseline_offset); max_below_baseline = max_below_baseline.max(baseline_offset); } Child::FixedSpacer(kv, calculated_siz) => { *calculated_siz = kv.resolve(env); if *calculated_siz < 0.0 { tracing::warn!("Length provided to fixed spacer was less than 0"); } *calculated_siz = calculated_siz.max(0.0); major_non_flex += *calculated_siz; } Child::Flex { flex, .. } | Child::FlexedSpacer(flex, _) => flex_sum += *flex, } } let total_major = self.direction.major(bc.max()); let remaining = (total_major - major_non_flex).max(0.0); let mut remainder: f64 = 0.0; let mut major_flex: f64 = 0.0; let px_per_flex = remaining / flex_sum; // Measure flex children. for child in &mut self.children { match child { Child::Flex { widget, flex, alignment, } => { // The BoxConstrains of flex-children depends on the size of every sibling, which // received layout earlier. Therefore we use any_changed. let child_size = if any_changed || widget.layout_requested() { let alignment = alignment.unwrap_or(self.cross_alignment); any_use_baseline |= alignment == CrossAxisAlignment::Baseline; let desired_major = (*flex) * px_per_flex + remainder; let actual_major = desired_major.round(); remainder = desired_major - actual_major; let old_size = widget.layout_rect().size(); let child_bc = self.direction.constraints(&loosened_bc, 0.0, actual_major); let child_size = widget.layout(ctx, &child_bc, data, env); if old_size != child_size { any_changed = true; } child_size } else { widget.layout_rect().size() }; let baseline_offset = widget.baseline_offset(); major_flex += self.direction.major(child_size).expand(); minor = minor.max(self.direction.minor(child_size).expand()); max_above_baseline = max_above_baseline.max(child_size.height - baseline_offset); max_below_baseline = max_below_baseline.max(baseline_offset); } Child::FlexedSpacer(flex, calculated_size) => { let desired_major = (*flex) * px_per_flex + remainder; *calculated_size = desired_major.round(); remainder = desired_major - *calculated_size; major_flex += *calculated_size; } _ => {} } } // figure out if we have extra space on major axis, and if so how to use it let extra = if self.fill_major_axis { (remaining - major_flex).max(0.0) } else { // if we are *not* expected to fill our available space this usually // means we don't have any extra, unless dictated by our constraints. (self.direction.major(bc.min()) - (major_non_flex + major_flex)).max(0.0) }; let mut spacing = Spacing::new(self.main_alignment, extra, self.children.len()); // the actual size needed to tightly fit the children on the minor axis. // Unlike the 'minor' var, this ignores the incoming constraints. let minor_dim = match self.direction { Axis::Horizontal if any_use_baseline => max_below_baseline + max_above_baseline, _ => minor, }; let extra_height = minor - minor_dim.min(minor); let mut major = spacing.next().unwrap_or(0.); let mut child_paint_rect = Rect::ZERO; for child in &mut self.children { match child { Child::Fixed { widget, alignment } | Child::Flex { widget, alignment, .. } => { let child_size = widget.layout_rect().size(); let alignment = alignment.unwrap_or(self.cross_alignment); let child_minor_offset = match alignment { // This will ignore baseline alignment if it is overridden on children, // but is not the default for the container. Is this okay? CrossAxisAlignment::Baseline if matches!(self.direction, Axis::Horizontal) => { let child_baseline = widget.baseline_offset(); let child_above_baseline = child_size.height - child_baseline; extra_height + (max_above_baseline - child_above_baseline) } CrossAxisAlignment::Fill => { let fill_size: Size = self .direction .pack(self.direction.major(child_size), minor_dim) .into(); if widget.layout_rect().size() != fill_size { let child_bc = BoxConstraints::tight(fill_size); //TODO: this is the second call of layout on the same child, which // is bad, because it can lead to exponential increase in layout calls // when used multiple times in the widget hierarchy. widget.layout(ctx, &child_bc, data, env); } 0.0 } _ => { let extra_minor = minor_dim - self.direction.minor(child_size); alignment.align(extra_minor) } }; let child_pos: Point = self.direction.pack(major, child_minor_offset).into(); widget.set_origin(ctx, child_pos); child_paint_rect = child_paint_rect.union(widget.paint_rect()); major += self.direction.major(child_size).expand(); major += spacing.next().unwrap_or(0.); } Child::FlexedSpacer(_, calculated_size)
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/tabs.rs
druid/src/widget/tabs.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget that can switch between one of many views, hiding the inactive ones. use instant::Duration; use std::collections::HashMap; use std::fmt::Debug; use std::hash::Hash; use std::marker::PhantomData; use std::rc::Rc; use tracing::{instrument, trace}; use crate::commands::SCROLL_TO_VIEW; use crate::kurbo::{Circle, Line}; use crate::widget::prelude::*; use crate::widget::{Axis, Flex, Label, LabelText, LensScopeTransfer, Painter, Scope, ScopePolicy}; use crate::{theme, Affine, Data, Insets, Lens, Point, SingleUse, WidgetExt, WidgetPod}; type TabsScope<TP> = Scope<TabsScopePolicy<TP>, Box<dyn Widget<TabsState<TP>>>>; type TabBodyPod<TP> = WidgetPod<<TP as TabsPolicy>::Input, <TP as TabsPolicy>::BodyWidget>; type TabBarPod<TP> = WidgetPod<TabsState<TP>, Box<dyn Widget<TabsState<TP>>>>; type TabIndex = usize; type Nanos = u64; /// Information about a tab that may be used by the TabPolicy to /// drive the visual presentation and behaviour of its label pub struct TabInfo<Input> { /// Name of the tab pub name: LabelText<Input>, /// Should the user be able to close the tab? pub can_close: bool, } impl<Input> TabInfo<Input> { /// Create a new TabInfo pub fn new(name: impl Into<LabelText<Input>>, can_close: bool) -> Self { TabInfo { name: name.into(), can_close, } } } /// A policy that determines how a Tabs instance derives its tabs from its app data. pub trait TabsPolicy: Data { /// The identity of a tab. type Key: Hash + Eq + Clone; /// The input data that will: /// a) be used to determine the tabs present /// b) be the input data for all of the child widgets. type Input: Data; /// The common type for all body widgets in this set of tabs. /// A flexible default is Box<dyn Widget<Self::Input>> type BodyWidget: Widget<Self::Input>; /// The common type for all label widgets in this set of tabs /// Usually this would be Label<Self::Input> type LabelWidget: Widget<Self::Input>; /// The information required to build up this policy. /// This is to support policies where at least some tabs are provided up front during widget /// construction. If the Build type implements the AddTab trait, the add_tab and with_tab /// methods will be available on the Tabs instance to allow the /// It can be filled in with () by implementations that do not require it. type Build; /// Examining the input data, has the set of tabs present changed? /// Expected to be cheap, eg pointer or numeric comparison. fn tabs_changed(&self, old_data: &Self::Input, data: &Self::Input) -> bool; /// From the input data, return the new set of tabs fn tabs(&self, data: &Self::Input) -> Vec<Self::Key>; /// For this tab key, return the relevant tab information that will drive label construction fn tab_info(&self, key: Self::Key, data: &Self::Input) -> TabInfo<Self::Input>; /// For this tab key, return the body widget fn tab_body(&self, key: Self::Key, data: &Self::Input) -> Self::BodyWidget; /// Label widget for the tab. /// Usually implemented with a call to default_make_label ( can't default here because Self::LabelWidget isn't determined) fn tab_label( &self, key: Self::Key, info: TabInfo<Self::Input>, data: &Self::Input, ) -> Self::LabelWidget; /// Change the data to reflect the user requesting to close a tab. #[allow(unused_variables)] fn close_tab(&self, key: Self::Key, data: &mut Self::Input) {} #[allow(unused_variables)] /// Construct an instance of this TabsFromData from its Build type. /// The main use case for this is StaticTabs, where the tabs are provided by the app developer up front. fn build(build: Self::Build) -> Self { panic!("TabsPolicy::Build called on a policy that does not support incremental building") } /// A default implementation for make label, if you do not wish to construct a custom widget. fn default_make_label(info: TabInfo<Self::Input>) -> Label<Self::Input> { Label::new(info.name).with_text_color(theme::FOREGROUND_LIGHT) } } /// A TabsPolicy that allows the app developer to provide static tabs up front when building the /// widget. #[derive(Clone)] pub struct StaticTabs<T> { // This needs be able to avoid cloning the widgets we are given - // as such it is Rc tabs: Rc<[InitialTab<T>]>, } impl<T> Default for StaticTabs<T> { fn default() -> Self { StaticTabs { tabs: Rc::new([]) } } } impl<T: Data> Data for StaticTabs<T> { fn same(&self, _other: &Self) -> bool { // Changing the tabs after construction shouldn't be possible for static tabs true } } impl<T: Data> TabsPolicy for StaticTabs<T> { type Key = usize; type Input = T; type BodyWidget = Box<dyn Widget<T>>; type LabelWidget = Label<T>; type Build = Vec<InitialTab<T>>; fn tabs_changed(&self, _old_data: &T, _data: &T) -> bool { false } fn tabs(&self, _data: &T) -> Vec<Self::Key> { (0..self.tabs.len()).collect() } fn tab_info(&self, key: Self::Key, _data: &T) -> TabInfo<Self::Input> { // This only allows a static tabs label to be retrieved once, // but as we never indicate that the tabs have changed, // it should only be called once per key. TabInfo::new( self.tabs[key] .name .take() .expect("StaticTabs LabelText can only be retrieved once"), false, ) } fn tab_body(&self, key: Self::Key, _data: &T) -> Self::BodyWidget { // This only allows a static tab to be retrieved once, // but as we never indicate that the tabs have changed, // it should only be called once per key. self.tabs .get(key) .and_then(|initial_tab| initial_tab.child.take()) .expect("StaticTabs body widget can only be retrieved once") } fn tab_label( &self, _key: Self::Key, info: TabInfo<Self::Input>, _data: &Self::Input, ) -> Self::LabelWidget { Self::default_make_label(info) } fn build(build: Self::Build) -> Self { StaticTabs { tabs: build.into() } } } /// AddTabs is an extension to TabsPolicy. /// If a policy implements AddTab, then the add_tab and with_tab methods will be available on /// the Tabs instance. pub trait AddTab: TabsPolicy { /// Add a tab to the build type. fn add_tab( build: &mut Self::Build, name: impl Into<LabelText<Self::Input>>, child: impl Widget<Self::Input> + 'static, ); } impl<T: Data> AddTab for StaticTabs<T> { fn add_tab( build: &mut Self::Build, name: impl Into<LabelText<T>>, child: impl Widget<T> + 'static, ) { build.push(InitialTab::new(name, child)) } } /// This is the current state of the tabs widget as a whole. /// This expands the input data to include a policy that determines how tabs are derived, /// and the index of the currently selected tab #[derive(Clone, Lens, Data)] pub struct TabsState<TP: TabsPolicy> { inner: TP::Input, selected: TabIndex, policy: TP, } impl<TP: TabsPolicy> TabsState<TP> { /// Create a new TabsState pub fn new(inner: TP::Input, selected: usize, policy: TP) -> Self { TabsState { inner, selected, policy, } } } /// This widget is the tab bar. It contains widgets that when pressed switch the active tab. struct TabBar<TP: TabsPolicy> { axis: Axis, edge: TabsEdge, tabs: Vec<(TP::Key, TabBarPod<TP>)>, hot: Option<TabIndex>, phantom_tp: PhantomData<TP>, } impl<TP: TabsPolicy> TabBar<TP> { /// Create a new TabBar widget. fn new(axis: Axis, edge: TabsEdge) -> Self { TabBar { axis, edge, tabs: vec![], hot: None, phantom_tp: Default::default(), } } fn find_idx(&self, pos: Point) -> Option<TabIndex> { let major_pix = self.axis.major_pos(pos); let axis = self.axis; let res = self .tabs .binary_search_by_key(&((major_pix * 10.) as i64), |(_, tab)| { let rect = tab.layout_rect(); let far_pix = axis.major_pos(rect.origin()) + axis.major(rect.size()); (far_pix * 10.) as i64 }); match res { Ok(idx) => Some(idx), Err(idx) if idx < self.tabs.len() => Some(idx), _ => None, } } fn ensure_tabs(&mut self, data: &TabsState<TP>) { ensure_for_tabs(&mut self.tabs, &data.policy, &data.inner, |policy, key| { let info = policy.tab_info(key.clone(), &data.inner); let can_close = info.can_close; let label = data .policy .tab_label(key.clone(), info, &data.inner) .lens(TabsState::<TP>::inner) .padding(Insets::uniform_xy(9., 5.)); if can_close { let close_button = Painter::new(|ctx, _, env| { let circ_bounds = ctx.size().to_rect().inset(-2.); let cross_bounds = circ_bounds.inset(-5.); if ctx.is_hot() { ctx.render_ctx.fill( Circle::new( circ_bounds.center(), f64::min(circ_bounds.height(), circ_bounds.width()) / 2., ), &env.get(theme::BORDER_LIGHT), ); } let cross_color = &env.get(if ctx.is_hot() { theme::BACKGROUND_DARK } else { theme::BORDER_LIGHT }); ctx.render_ctx.stroke( Line::new( (cross_bounds.x0, cross_bounds.y0), (cross_bounds.x1, cross_bounds.y1), ), cross_color, 2., ); ctx.render_ctx.stroke( Line::new( (cross_bounds.x1, cross_bounds.y0), (cross_bounds.x0, cross_bounds.y1), ), cross_color, 2., ); }) .fix_size(20., 20.); let row = Flex::row() .with_child(label) .with_child(close_button.on_click( move |_ctx, data: &mut TabsState<TP>, _env| { data.policy.close_tab(key.clone(), &mut data.inner); }, )); WidgetPod::new(Box::new(row)) } else { WidgetPod::new(Box::new(label)) } }); } } impl<TP: TabsPolicy> Widget<TabsState<TP>> for TabBar<TP> { #[instrument(name = "TabBar", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut TabsState<TP>, env: &Env) { match event { Event::MouseDown(e) => { if let Some(idx) = self.find_idx(e.pos) { data.selected = idx; } } Event::MouseMove(e) => { let new_hot = if ctx.is_hot() { self.find_idx(e.pos) } else { None }; if new_hot != self.hot { self.hot = new_hot; ctx.request_paint(); } } _ => {} } for (_, tab) in self.tabs.iter_mut() { tab.event(ctx, event, data, env); } } #[instrument(name = "TabBar", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &TabsState<TP>, env: &Env, ) { if let LifeCycle::WidgetAdded = event { self.ensure_tabs(data); ctx.children_changed(); } for (_, tab) in self.tabs.iter_mut() { tab.lifecycle(ctx, event, data, env); } } #[instrument(name = "TabBar", level = "trace", skip(self, ctx, old_data, data, env))] fn update( &mut self, ctx: &mut UpdateCtx, old_data: &TabsState<TP>, data: &TabsState<TP>, env: &Env, ) { for (_, tab) in self.tabs.iter_mut() { tab.update(ctx, data, env) } if data.policy.tabs_changed(&old_data.inner, &data.inner) { self.ensure_tabs(data); ctx.children_changed(); } else if old_data.selected != data.selected { ctx.request_paint(); } } #[instrument(name = "TabBar", level = "trace", skip(self, ctx, bc, data, env))] fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &TabsState<TP>, env: &Env, ) -> Size { let mut major: f64 = 0.; let mut minor: f64 = 0.; for (_, tab) in self.tabs.iter_mut() { let size = tab.layout(ctx, bc, data, env); tab.set_origin(ctx, self.axis.pack(major, 0.).into()); major += self.axis.major(size); minor = minor.max(self.axis.minor(size)); } let wanted = self.axis.pack(major.max(self.axis.major(bc.max())), minor); let size = bc.constrain(wanted); trace!("Computed size: {}", size); size } #[instrument(name = "TabBar", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &TabsState<TP>, env: &Env) { let hl_thickness = 2.; let highlight = env.get(theme::PRIMARY_LIGHT); for (idx, (_, tab)) in self.tabs.iter_mut().enumerate() { let layout_rect = tab.layout_rect(); let expanded_size = self.axis.pack( self.axis.major(layout_rect.size()), self.axis.minor(ctx.size()), ); let rect = layout_rect.with_size(expanded_size); let bg = match (idx == data.selected, Some(idx) == self.hot) { (_, true) => env.get(theme::BUTTON_DARK), (true, false) => env.get(theme::BACKGROUND_LIGHT), _ => env.get(theme::BACKGROUND_DARK), }; ctx.fill(rect, &bg); tab.paint(ctx, data, env); if idx == data.selected { let (maj_near, maj_far) = self.axis.major_span(rect); let (min_near, min_far) = self.axis.minor_span(rect); let minor_pos = if let TabsEdge::Trailing = self.edge { min_near + (hl_thickness / 2.) } else { min_far - (hl_thickness / 2.) }; ctx.stroke( Line::new( self.axis.pack(maj_near, minor_pos), self.axis.pack(maj_far, minor_pos), ), &highlight, hl_thickness, ) } } } } struct TabsTransitionState { previous_idx: TabIndex, current_time: u64, duration: Nanos, increasing: bool, } impl TabsTransitionState { fn new(previous_idx: TabIndex, duration: Nanos, increasing: bool) -> Self { TabsTransitionState { previous_idx, current_time: 0, duration, increasing, } } fn live(&self) -> bool { self.current_time < self.duration } fn fraction(&self) -> f64 { (self.current_time as f64) / (self.duration as f64) } fn previous_transform(&self, axis: Axis, main: f64) -> Affine { let x = if self.increasing { -main * self.fraction() } else { main * self.fraction() }; Affine::translate(axis.pack(x, 0.)) } fn selected_transform(&self, axis: Axis, main: f64) -> Affine { let x = if self.increasing { main * (1.0 - self.fraction()) } else { -main * (1.0 - self.fraction()) }; Affine::translate(axis.pack(x, 0.)) } } fn ensure_for_tabs<Content, TP: TabsPolicy>( contents: &mut Vec<(TP::Key, Content)>, policy: &TP, data: &TP::Input, f: impl Fn(&TP, TP::Key) -> Content, ) -> Vec<usize> { let mut existing_by_key: HashMap<TP::Key, Content> = contents.drain(..).collect(); let mut existing_idx = Vec::new(); for key in policy.tabs(data).into_iter() { let next = if let Some(child) = existing_by_key.remove(&key) { existing_idx.push(contents.len()); child } else { f(policy, key.clone()) }; contents.push((key.clone(), next)) } existing_idx } /// This widget is the tabs body. It shows the active tab, keeps other tabs hidden, and can /// animate transitions between them. struct TabsBody<TP: TabsPolicy> { children: Vec<(TP::Key, TabBodyPod<TP>)>, axis: Axis, transition: TabsTransition, transition_state: Option<TabsTransitionState>, phantom_tp: PhantomData<TP>, } impl<TP: TabsPolicy> TabsBody<TP> { fn new(axis: Axis, transition: TabsTransition) -> TabsBody<TP> { TabsBody { children: vec![], axis, transition, transition_state: None, phantom_tp: Default::default(), } } fn make_tabs(&mut self, data: &TabsState<TP>) -> Vec<usize> { ensure_for_tabs( &mut self.children, &data.policy, &data.inner, |policy, key| WidgetPod::new(policy.tab_body(key, &data.inner)), ) } fn active_child(&mut self, state: &TabsState<TP>) -> Option<&mut TabBodyPod<TP>> { Self::child(&mut self.children, state.selected) } // Doesn't take self to allow separate borrowing fn child( children: &mut [(TP::Key, TabBodyPod<TP>)], idx: usize, ) -> Option<&mut TabBodyPod<TP>> { children.get_mut(idx).map(|x| &mut x.1) } fn child_pods(&mut self) -> impl Iterator<Item = &mut TabBodyPod<TP>> { self.children.iter_mut().map(|x| &mut x.1) } } impl<TP: TabsPolicy> Widget<TabsState<TP>> for TabsBody<TP> { #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut TabsState<TP>, env: &Env) { if let Event::Notification(notification) = event { if notification.is(SCROLL_TO_VIEW) && Some(notification.route()) != self.active_child(data).map(|w| w.id()) { // Ignore SCROLL_TO_VIEW requests from every widget except the active. ctx.set_handled(); } } else if event.should_propagate_to_hidden() { for child in self.child_pods() { child.event(ctx, event, &mut data.inner, env); } } else if let Some(child) = self.active_child(data) { child.event(ctx, event, &mut data.inner, env); } if let (Some(t_state), Event::AnimFrame(interval)) = (&mut self.transition_state, event) { // We can get a high interval on the first frame due to other widgets or old animations. let interval = if t_state.current_time == 0 { 1 } else { *interval }; t_state.current_time += interval; if t_state.live() { ctx.request_anim_frame(); } else { self.transition_state = None; } ctx.request_paint(); } } #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &TabsState<TP>, env: &Env, ) { if let LifeCycle::WidgetAdded = event { self.make_tabs(data); ctx.children_changed(); } if event.should_propagate_to_hidden() { for child in self.child_pods() { child.lifecycle(ctx, event, &data.inner, env); } } else if let Some(child) = self.active_child(data) { // Pick which events go to all and which just to active child.lifecycle(ctx, event, &data.inner, env); } } #[instrument( name = "TabsBody", level = "trace", skip(self, ctx, old_data, data, env) )] fn update( &mut self, ctx: &mut UpdateCtx, old_data: &TabsState<TP>, data: &TabsState<TP>, env: &Env, ) { let init = if data.policy.tabs_changed(&old_data.inner, &data.inner) { ctx.children_changed(); Some(self.make_tabs(data)) } else { None }; if old_data.selected != data.selected { self.transition_state = self .transition .tab_changed(old_data.selected, data.selected); ctx.children_changed(); if self.transition_state.is_some() { ctx.request_anim_frame(); } } // Make sure to only pass events to initialised children if let Some(init) = init { for idx in init { if let Some(child) = Self::child(&mut self.children, idx) { child.update(ctx, &data.inner, env) } } } else { for child in self.child_pods() { child.update(ctx, &data.inner, env); } } } #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, bc, data, env))] fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &TabsState<TP>, env: &Env, ) -> Size { let inner = &data.inner; // Laying out all children so events can be delivered to them. for child in self.child_pods() { child.layout(ctx, bc, inner, env); child.set_origin(ctx, Point::ORIGIN); } bc.max() } #[instrument(name = "TabsBody", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &TabsState<TP>, env: &Env) { if let Some(trans) = &self.transition_state { let axis = self.axis; let size = ctx.size(); let major = axis.major(size); ctx.clip(size.to_rect()); let children = &mut self.children; if let Some(ref mut prev) = Self::child(children, trans.previous_idx) { ctx.with_save(|ctx| { ctx.transform(trans.previous_transform(axis, major)); prev.paint_raw(ctx, &data.inner, env); }) } if let Some(ref mut child) = Self::child(children, data.selected) { ctx.with_save(|ctx| { ctx.transform(trans.selected_transform(axis, major)); child.paint_raw(ctx, &data.inner, env); }) } } else if let Some(ref mut child) = Self::child(&mut self.children, data.selected) { child.paint_raw(ctx, &data.inner, env); } } } // This only needs to exist to be able to give a reasonable type to the TabScope struct TabsScopePolicy<TP> { tabs_from_data: TP, selected: TabIndex, } impl<TP> TabsScopePolicy<TP> { fn new(tabs_from_data: TP, selected: TabIndex) -> Self { Self { tabs_from_data, selected, } } } impl<TP: TabsPolicy> ScopePolicy for TabsScopePolicy<TP> { type In = TP::Input; type State = TabsState<TP>; type Transfer = LensScopeTransfer<tabs_state_derived_lenses::inner<TP>, Self::In, Self::State>; fn create(self, inner: &Self::In) -> (Self::State, Self::Transfer) { ( TabsState::new(inner.clone(), self.selected, self.tabs_from_data), LensScopeTransfer::new(Self::State::inner), ) } } /// Determines whether the tabs will have a transition animation when a new tab is selected. #[derive(Data, Copy, Clone, Debug, PartialOrd, PartialEq, Eq)] pub enum TabsTransition { /// Change tabs instantly with no animation Instant, /// Slide tabs across in the appropriate direction. The argument is the duration in nanoseconds Slide(Nanos), } impl Default for TabsTransition { fn default() -> Self { TabsTransition::Slide(Duration::from_millis(250).as_nanos() as Nanos) } } impl TabsTransition { fn tab_changed(self, old: TabIndex, new: TabIndex) -> Option<TabsTransitionState> { match self { TabsTransition::Instant => None, TabsTransition::Slide(dur) => Some(TabsTransitionState::new(old, dur, old < new)), } } } /// Determines where the tab bar should be placed relative to the cross axis #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Data)] pub enum TabsEdge { /// For horizontal tabs, top. For vertical tabs, left. #[default] Leading, /// For horizontal tabs, bottom. For vertical tabs, right. Trailing, } pub struct InitialTab<T> { name: SingleUse<LabelText<T>>, // This is to avoid cloning provided label texts child: SingleUse<Box<dyn Widget<T>>>, // This is to avoid cloning provided tabs } impl<T: Data> InitialTab<T> { fn new(name: impl Into<LabelText<T>>, child: impl Widget<T> + 'static) -> Self { InitialTab { name: SingleUse::new(name.into()), child: SingleUse::new(child.boxed()), } } } #[allow(clippy::large_enum_variant)] enum TabsContent<TP: TabsPolicy> { Building { tabs: TP::Build, index: TabIndex, }, Complete { tabs: TP, index: TabIndex, }, Running { scope: WidgetPod<TP::Input, TabsScope<TP>>, }, Swapping, } /// A tabs widget. /// /// The tabs can be provided up front, using Tabs::new() and add_tab()/with_tab(). /// /// Or, the tabs can be derived from the input data by implementing TabsPolicy, and providing it to /// Tabs::from_policy() /// /// ``` /// use druid::widget::{Tabs, Label, WidgetExt}; /// use druid::{Data, Lens}; /// /// #[derive(Data, Clone, Lens)] /// struct AppState{ /// name: String /// } /// /// let tabs = Tabs::new() /// .with_tab("Connection", Label::new("Connection information")) /// .with_tab("Proxy", Label::new("Proxy settings")) /// .lens(AppState::name); /// /// /// ``` /// pub struct Tabs<TP: TabsPolicy> { axis: Axis, edge: TabsEdge, transition: TabsTransition, content: TabsContent<TP>, } impl<T: Data> Tabs<StaticTabs<T>> { /// Create a new Tabs widget, using the static tabs policy. /// Use with_tab or add_tab to configure the set of tabs available. pub fn new() -> Self { Tabs::building(Vec::new()) } } impl<T: Data> Default for Tabs<StaticTabs<T>> { fn default() -> Self { Self::new() } } impl<TP: TabsPolicy> Tabs<TP> { fn of_content(content: TabsContent<TP>) -> Self { Tabs { axis: Axis::Horizontal, edge: Default::default(), transition: Default::default(), content, } } /// Create a Tabs widget using the provided policy. /// This is useful for tabs derived from data. pub fn for_policy(tabs: TP) -> Self { Self::of_content(TabsContent::Complete { tabs, index: 0 }) } // This could be public if there is a case for custom policies that support static tabs - ie the AddTab method. // It seems very likely that the whole way we do dynamic vs static will change before that // becomes an issue. fn building(tabs_from_data: TP::Build) -> Self where TP: AddTab, { Self::of_content(TabsContent::Building { tabs: tabs_from_data, index: 0, }) } /// Lay out the tab bar along the provided axis. pub fn with_axis(mut self, axis: Axis) -> Self { self.axis = axis; self } /// Put the tab bar on the specified edge of the cross axis. pub fn with_edge(mut self, edge: TabsEdge) -> Self { self.edge = edge; self } /// Use the provided transition when tabs change pub fn with_transition(mut self, transition: TabsTransition) -> Self { self.transition = transition; self } /// Available when the policy implements AddTab - e.g StaticTabs. /// Return this Tabs widget with the named tab added. pub fn with_tab( mut self, name: impl Into<LabelText<TP::Input>>, child: impl Widget<TP::Input> + 'static, ) -> Tabs<TP> where TP: AddTab, { self.add_tab(name, child); self } /// A builder-style method to specify the (zero-based) index of the selected tab. pub fn with_tab_index(mut self, idx: TabIndex) -> Self { self.set_tab_index(idx); self } /// Available when the policy implements AddTab - e.g StaticTabs. /// Return this Tabs widget with the named tab added. pub fn add_tab( &mut self, name: impl Into<LabelText<TP::Input>>, child: impl Widget<TP::Input> + 'static, ) where TP: AddTab, { if let TabsContent::Building { tabs, .. } = &mut self.content { TP::add_tab(tabs, name, child) } else { tracing::warn!("Can't add static tabs to a running or complete tabs instance!") } } /// The (zero-based) index of the currently selected tab. pub fn tab_index(&self) -> TabIndex { let index = match &self.content { TabsContent::Running { scope, .. } => scope.widget().state().map(|s| s.selected), TabsContent::Building { index, .. } | TabsContent::Complete { index, .. } => { Some(*index) } TabsContent::Swapping => None, }; index.unwrap_or(0) } /// Set the selected (zero-based) tab index. /// /// This tab will become visible if it exists. If animations are enabled /// (and the widget is laid out), the tab transition will be animated. pub fn set_tab_index(&mut self, idx: TabIndex) { match &mut self.content { TabsContent::Running { scope, .. } => { if let Some(state) = scope.widget_mut().state_mut() { state.selected = idx } } TabsContent::Building { index, .. } | TabsContent::Complete { index, .. } => { *index = idx; } TabsContent::Swapping => (), } } fn make_scope(&self, tabs_from_data: TP, idx: TabIndex) -> WidgetPod<TP::Input, TabsScope<TP>> { let tabs_bar = TabBar::new(self.axis, self.edge); let tabs_body = TabsBody::new(self.axis, self.transition) .padding(5.) .border(theme::BORDER_DARK, 0.5); let mut layout: Flex<TabsState<TP>> = Flex::for_axis(self.axis.cross()); if let TabsEdge::Trailing = self.edge { layout.add_flex_child(tabs_body, 1.); layout.add_child(tabs_bar); } else { layout.add_child(tabs_bar); layout.add_flex_child(tabs_body, 1.); }; WidgetPod::new(Scope::new( TabsScopePolicy::new(tabs_from_data, idx), Box::new(layout), )) } } impl<TP: TabsPolicy> Widget<TP::Input> for Tabs<TP> { #[instrument(name = "Tabs", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut TP::Input, env: &Env) { if let TabsContent::Running { scope } = &mut self.content { scope.event(ctx, event, data, env); } } #[instrument(name = "Tabs", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &TP::Input, env: &Env,
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
true
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/sized_box.rs
druid/src/widget/sized_box.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget with predefined size. use crate::debug_state::DebugState; use tracing::{instrument, trace, warn}; use crate::widget::prelude::*; use crate::widget::Axis; use crate::{Data, KeyOrValue}; /// A widget with predefined size. /// /// If given a child, this widget forces its child to have a specific width and/or height /// (assuming values are permitted by this widget's parent). If either the width or height is not /// set, this widget will size itself to match the child's size in that dimension. /// /// If not given a child, SizedBox will try to size itself as close to the specified height /// and width as possible given the parent's constraints. If height or width is not set, /// it will be treated as zero. pub struct SizedBox<T> { child: Option<Box<dyn Widget<T>>>, width: Option<KeyOrValue<f64>>, height: Option<KeyOrValue<f64>>, } impl<T> SizedBox<T> { /// Construct container with child, and both width and height not set. pub fn new(child: impl Widget<T> + 'static) -> Self { Self { child: Some(Box::new(child)), width: None, height: None, } } /// Construct container without child, and both width and height not set. /// /// If the widget is unchanged, it will do nothing, which can be useful if you want to draw a /// widget some of the time (for example, it is used to implement /// [`Maybe`][crate::widget::Maybe]). #[doc(alias = "null")] pub fn empty() -> Self { Self { child: None, width: None, height: None, } } /// Set container's width. pub fn width(mut self, width: impl Into<KeyOrValue<f64>>) -> Self { self.width = Some(width.into()); self } /// Set container's height. pub fn height(mut self, height: impl Into<KeyOrValue<f64>>) -> Self { self.height = Some(height.into()); self } /// Expand container to fit the parent. /// /// Only call this method if you want your widget to occupy all available /// space. If you only care about expanding in one of width or height, use /// [`expand_width`] or [`expand_height`] instead. /// /// [`expand_height`]: #method.expand_height /// [`expand_width`]: #method.expand_width pub fn expand(mut self) -> Self { self.width = Some(KeyOrValue::Concrete(f64::INFINITY)); self.height = Some(KeyOrValue::Concrete(f64::INFINITY)); self } /// Expand the container on the x-axis. /// /// This will force the child to have maximum width. pub fn expand_width(mut self) -> Self { self.width = Some(KeyOrValue::Concrete(f64::INFINITY)); self } /// Expand the container on the y-axis. /// /// This will force the child to have maximum height. pub fn expand_height(mut self) -> Self { self.height = Some(KeyOrValue::Concrete(f64::INFINITY)); self } fn child_constraints(&self, bc: &BoxConstraints, env: &Env) -> BoxConstraints { // if we don't have a width/height, we don't change that axis. // if we have a width/height, we clamp it on that axis. let (min_width, max_width) = match &self.width { Some(width) => { let width = width.resolve(env); let w = width.clamp(bc.min().width, bc.max().width); (w, w) } None => (bc.min().width, bc.max().width), }; let (min_height, max_height) = match &self.height { Some(height) => { let height = height.resolve(env); let h = height.clamp(bc.min().height, bc.max().height); (h, h) } None => (bc.min().height, bc.max().height), }; BoxConstraints::new( Size::new(min_width, min_height), Size::new(max_width, max_height), ) } #[cfg(test)] pub(crate) fn width_and_height(&self, env: &Env) -> (Option<f64>, Option<f64>) { ( self.width.as_ref().map(|w| w.resolve(env)), self.height.as_ref().map(|h| h.resolve(env)), ) } } impl<T: Data> Widget<T> for SizedBox<T> { #[instrument(name = "SizedBox", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if let Some(ref mut child) = self.child { child.event(ctx, event, data, env); } } #[instrument(name = "SizedBox", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { if let Some(ref mut child) = self.child { child.lifecycle(ctx, event, data, env) } } #[instrument( name = "SizedBox", level = "trace", skip(self, ctx, old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { if let Some(ref mut child) = self.child { child.update(ctx, old_data, data, env); } } #[instrument(name = "SizedBox", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("SizedBox"); let child_bc = self.child_constraints(bc, env); let size = match self.child.as_mut() { Some(child) => child.layout(ctx, &child_bc, data, env), None => bc.constrain(( self.width .as_ref() .unwrap_or(&KeyOrValue::Concrete(0.0)) .resolve(env), self.height .as_ref() .unwrap_or(&KeyOrValue::Concrete(0.0)) .resolve(env), )), }; trace!("Computed size: {}", size); if size.width.is_infinite() { warn!("SizedBox is returning an infinite width."); } if size.height.is_infinite() { warn!("SizedBox is returning an infinite height."); } size } #[instrument(name = "SizedBox", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { if let Some(ref mut child) = self.child { child.paint(ctx, data, env); } } fn id(&self) -> Option<WidgetId> { self.child.as_ref().and_then(|child| child.id()) } fn debug_state(&self, data: &T) -> DebugState { let children = if let Some(child) = &self.child { vec![child.debug_state(data)] } else { vec![] }; DebugState { display_name: self.short_type_name().to_string(), children, ..Default::default() } } fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64 { let kv = match axis { Axis::Horizontal => self.width.as_ref(), Axis::Vertical => self.height.as_ref(), }; match (self.child.as_mut(), kv) { (Some(c), Some(v)) => { let v = v.resolve(env); if v == f64::INFINITY { c.compute_max_intrinsic(axis, ctx, bc, data, env) } else { v } } (Some(c), None) => c.compute_max_intrinsic(axis, ctx, bc, data, env), (None, Some(v)) => { let v = v.resolve(env); if v == f64::INFINITY { // If v infinite, we can only warn. warn!("SizedBox is without a child and its dim is infinite. Either give SizedBox a child or make its dim finite. ") } v } (None, None) => 0., } } } #[cfg(test)] mod tests { use super::*; use crate::{widget::Label, Key}; use test_log::test; #[test] fn expand() { let env = Env::empty(); let expand = SizedBox::<()>::new(Label::new("hello!")).expand(); let bc = BoxConstraints::tight(Size::new(400., 400.)).loosen(); let child_bc = expand.child_constraints(&bc, &env); assert_eq!(child_bc.min(), Size::new(400., 400.,)); } #[test] fn no_width() { let mut env = Env::empty(); let expand = SizedBox::<()>::new(Label::new("hello!")).height(200.); let bc = BoxConstraints::tight(Size::new(400., 400.)).loosen(); let child_bc = expand.child_constraints(&bc, &env); assert_eq!(child_bc.min(), Size::new(0., 200.,)); assert_eq!(child_bc.max(), Size::new(400., 200.,)); const HEIGHT_KEY: Key<f64> = Key::new("test-no-width-height"); env.set(HEIGHT_KEY, 200.); let expand = SizedBox::<()>::new(Label::new("hello!")).height(HEIGHT_KEY); let child_bc = expand.child_constraints(&bc, &env); assert_eq!(child_bc.min(), Size::new(0., 200.,)); assert_eq!(child_bc.max(), Size::new(400., 200.,)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/click.rs
druid/src/widget/click.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A clickable [`Controller`] widget. use crate::widget::Controller; use crate::{Data, Env, Event, EventCtx, LifeCycle, LifeCycleCtx, MouseButton, Widget}; use tracing::{instrument, trace}; /// A clickable [`Controller`] widget. Pass this and a child widget to a /// [`ControllerHost`] to make the child interactive. More conveniently, this is /// available as an [`on_click`] method via [`WidgetExt`]. /// /// This is an alternative to the standard [`Button`] widget, for when you want /// to make an arbitrary widget clickable. /// /// The child widget will also be updated on [`LifeCycle::HotChanged`] and /// mouse down, which can be useful for painting based on `ctx.is_active()` /// and `ctx.is_hot()`. /// /// [`ControllerHost`]: super::ControllerHost /// [`on_click`]: super::WidgetExt::on_click /// [`WidgetExt`]: super::WidgetExt /// [`Button`]: super::Button pub struct Click<T> { /// A closure that will be invoked when the child widget is clicked. action: Box<dyn Fn(&mut EventCtx, &mut T, &Env)>, } impl<T: Data> Click<T> { /// Create a new clickable [`Controller`] widget. pub fn new(action: impl Fn(&mut EventCtx, &mut T, &Env) + 'static) -> Self { Click { action: Box::new(action), } } } impl<T: Data, W: Widget<T>> Controller<T, W> for Click<T> { #[instrument( name = "Click", level = "trace", skip(self, child, ctx, event, data, env) )] fn event(&mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { match event { Event::MouseDown(mouse_event) => { if mouse_event.button == MouseButton::Left && !ctx.is_disabled() { ctx.set_active(true); ctx.request_paint(); trace!("Widget {:?} pressed", ctx.widget_id()); } } Event::MouseUp(mouse_event) => { if ctx.is_active() && mouse_event.button == MouseButton::Left { ctx.set_active(false); if ctx.is_hot() && !ctx.is_disabled() { (self.action)(ctx, data, env); } ctx.request_paint(); trace!("Widget {:?} released", ctx.widget_id()); } } _ => {} } child.event(ctx, event, data, env); } #[instrument( name = "Click", level = "trace", skip(self, child, ctx, event, data, env) )] fn lifecycle( &mut self, child: &mut W, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env, ) { if let LifeCycle::HotChanged(_) | LifeCycle::FocusChanged(_) = event { ctx.request_paint(); } child.lifecycle(ctx, event, data, env); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/svg.rs
druid/src/widget/svg.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! An SVG widget. use std::sync::Arc; use resvg; use usvg::Tree; use crate::piet::{ImageBuf, ImageFormat, InterpolationMode}; use crate::widget::prelude::*; use crate::{Rect, ScaledArea}; /// A widget that renders a SVG pub struct Svg { tree: Arc<Tree>, default_size: Size, cached: Option<ImageBuf>, } impl Svg { /// Create an SVG-drawing widget from SvgData. /// /// The SVG will scale to fit its box constraints. pub fn new(tree: impl Into<Arc<Tree>>) -> Self { let tree = tree.into(); Svg { default_size: Size::new(tree.size.width(), tree.size.height()), cached: None, tree, } } /// Rasterize the SVG into the specified size in pixels. fn render(&self, size_px: Size) -> Option<ImageBuf> { let fit = usvg::FitTo::Size(size_px.width as u32, size_px.height as u32); let mut pixmap = tiny_skia::Pixmap::new(size_px.width as u32, size_px.height as u32).unwrap(); if resvg::render( &self.tree, fit, tiny_skia::Transform::identity(), pixmap.as_mut(), ) .is_none() { tracing::error!("unable to render svg"); return None; } Some(ImageBuf::from_raw( pixmap.data(), ImageFormat::RgbaPremul, size_px.width as usize, size_px.height as usize, )) } } impl<T: Data> Widget<T> for Svg { fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut T, _env: &Env) {} fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &T, _env: &Env) {} fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &T, _data: &T, _env: &Env) {} fn layout( &mut self, _layout_ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, _env: &Env, ) -> Size { // preferred size comes from the svg let size = self.default_size; bc.constrain_aspect_ratio(size.height / size.width, size.width) } fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, _env: &Env) { let size = ctx.size(); let area = ScaledArea::from_dp(size, ctx.scale()); let size_px = area.size_px(); let needs_render = self .cached .as_ref() .filter(|image_buf| image_buf.size() == size_px) .is_none(); if needs_render { self.cached = self.render(size_px); } if self.cached.is_none() { tracing::error!("unable to paint SVG due to no rendered image"); return; } let clip_rect = Rect::ZERO.with_size(size); let img = self.cached.as_ref().unwrap().to_image(ctx.render_ctx); ctx.clip(clip_rect); ctx.draw_image(&img, clip_rect, InterpolationMode::NearestNeighbor); } } /// Stored parsed SVG tree. #[derive(Clone, Data)] pub struct SvgData { tree: Arc<Tree>, } impl SvgData { /// Create a new SVG fn new(tree: Arc<Tree>) -> Self { Self { tree } } /// Create an empty SVG pub fn empty() -> Self { use std::str::FromStr; let empty_svg = r###" <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <g fill="none"> </g> </svg> "###; SvgData::from_str(empty_svg).unwrap() } } impl std::str::FromStr for SvgData { type Err = Box<dyn std::error::Error>; fn from_str(svg_str: &str) -> Result<Self, Self::Err> { let re_opt = usvg::Options { keep_named_groups: false, ..usvg::Options::default() }; match Tree::from_str(svg_str, &re_opt.to_ref()) { // TODO: Figure out if this needs to stay Arc, or if it can be switched to Rc #[allow(clippy::arc_with_non_send_sync)] Ok(tree) => Ok(SvgData::new(Arc::new(tree))), Err(err) => Err(err.into()), } } } impl From<SvgData> for Arc<Tree> { fn from(d: SvgData) -> Self { d.tree } } impl Default for SvgData { fn default() -> Self { SvgData::empty() } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/widget.rs
druid/src/widget/widget.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use std::num::NonZeroU64; use std::ops::{Deref, DerefMut}; use super::prelude::*; use crate::debug_state::DebugState; use crate::widget::Axis; /// A unique identifier for a single [`Widget`]. /// /// `WidgetId`s are generated automatically for all widgets that participate /// in layout. More specifically, each [`WidgetPod`] has a unique `WidgetId`. /// /// These ids are used internally to route events, and can be used to communicate /// between widgets, by submitting a command (as with [`EventCtx::submit_command`]) /// and passing a `WidgetId` as the [`Target`]. /// /// A widget can retrieve its id via methods on the various contexts, such as /// [`LifeCycleCtx::widget_id`]. /// /// ## Explicit `WidgetId`s. /// /// Sometimes, you may want to know a widget's id when constructing the widget. /// You can give a widget an _explicit_ id by wrapping it in an [`IdentityWrapper`] /// widget, or by using the [`WidgetExt::with_id`] convenience method. /// /// If you set a `WidgetId` directly, you are responsible for ensuring that it /// is unique in time. That is: only one widget can exist with a given id at a /// given time. /// /// [`Target`]: crate::Target /// [`WidgetPod`]: crate::WidgetPod /// [`WidgetExt::with_id`]: super::WidgetExt::with_id /// [`IdentityWrapper`]: super::IdentityWrapper // this is NonZeroU64 because we regularly store Option<WidgetId> #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] pub struct WidgetId(NonZeroU64); /// The trait implemented by all widgets. /// /// All appearance and behavior for a widget is encapsulated in an /// object that implements this trait. /// /// The trait is parametrized by a type (`T`) for associated data. /// All trait methods are provided with access to this data, and /// in the case of [`event`] the reference is mutable, so that events /// can directly update the data. /// /// Whenever the application data changes, the framework traverses /// the widget hierarchy with an [`update`] method. The framework /// needs to know whether the data has actually changed or not, which /// is why `T` has a [`Data`] bound. /// /// All the trait methods are provided with a corresponding context. /// The widget can request things and cause actions by calling methods /// on that context. /// /// In addition, all trait methods are provided with an environment /// ([`Env`]). /// /// Container widgets will generally not call `Widget` methods directly /// on their child widgets, but rather will own their widget wrapped in /// a [`WidgetPod`], and call the corresponding method on that. The /// `WidgetPod` contains state and logic for these traversals. On the /// other hand, particularly light-weight containers might contain their /// child `Widget` directly (when no layout or event flow logic is /// needed), and in those cases will call these methods. /// /// As a general pattern, container widgets will call the corresponding /// `WidgetPod` method on all their children. The `WidgetPod` applies /// logic to determine whether to recurse, as needed. /// /// [`event`]: Widget::event /// [`update`]: Widget::update /// [`WidgetPod`]: crate::WidgetPod pub trait Widget<T> { /// Handle an event. /// /// A number of different events (in the [`Event`] enum) are handled in this /// method call. A widget can handle these events in a number of ways: /// requesting things from the [`EventCtx`], mutating the data, or submitting /// a [`Command`]. /// /// [`Command`]: crate::Command fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env); /// Handle a life cycle notification. /// /// This method is called to notify your widget of certain special events, /// (available in the [`LifeCycle`] enum) that are generally related to /// changes in the widget graph or in the state of your specific widget. /// /// A widget is not expected to mutate the application state in response /// to these events, but only to update its own internal state as required; /// if a widget needs to mutate data, it can submit a [`Command`] that will /// be executed at the next opportunity. /// /// [`Command`]: crate::Command fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env); /// Update the widget's appearance in response to a change in the app's /// [`Data`] or [`Env`]. /// /// This method is called whenever the data or environment changes. /// When the appearance of the widget needs to be updated in response to /// these changes, you can call [`request_paint`] or [`request_layout`] on /// the provided [`UpdateCtx`] to schedule calls to [`paint`] and [`layout`] /// as required. /// /// The previous value of the data is provided in case the widget wants to /// compute a fine-grained delta; you should try to only request a new /// layout or paint pass if it is actually required. /// /// To determine if the [`Env`] has changed, you can call [`env_changed`] /// on the provided [`UpdateCtx`]; you can then call [`env_key_changed`] /// with any keys that are used in your widget, to see if they have changed; /// you can then request layout or paint as needed. /// /// [`env_changed`]: UpdateCtx::env_changed /// [`env_key_changed`]: UpdateCtx::env_key_changed /// [`request_paint`]: UpdateCtx::request_paint /// [`request_layout`]: UpdateCtx::request_layout /// [`layout`]: Widget::layout /// [`paint`]: Widget::paint fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env); /// Compute layout. /// /// A leaf widget should determine its size (subject to the provided /// constraints) and return it. /// /// A container widget will recursively call [`WidgetPod::layout`] on its /// child widgets, providing each of them an appropriate box constraint, /// compute layout, then call [`set_origin`] on each of its children. /// Finally, it should return the size of the container. The container /// can recurse in any order, which can be helpful to, for example, compute /// the size of non-flex widgets first, to determine the amount of space /// available for the flex widgets. /// /// For efficiency, a container should only invoke layout of a child widget /// once, though there is nothing enforcing this. /// /// The layout strategy is strongly inspired by Flutter. /// /// [`WidgetPod::layout`]: crate::WidgetPod::layout /// [`set_origin`]: crate::WidgetPod::set_origin fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size; /// Paint the widget appearance. /// /// The [`PaintCtx`] derefs to something that implements the [`RenderContext`] /// trait, which exposes various methods that the widget can use to paint /// its appearance. /// /// Container widgets can paint a background before recursing to their /// children, or annotations (for example, scrollbars) by painting /// afterwards. In addition, they can apply masks and transforms on /// the render context, which is especially useful for scrolling. fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env); #[doc(hidden)] /// Get the identity of the widget; this is basically only implemented by /// `IdentityWrapper`. Widgets should not implement this on their own. fn id(&self) -> Option<WidgetId> { None } #[doc(hidden)] /// Get the (verbose) type name of the widget for debugging purposes. /// You should not override this method. fn type_name(&self) -> &'static str { std::any::type_name::<Self>() } #[doc(hidden)] /// Get the (abridged) type name of the widget for debugging purposes. /// You should not override this method. fn short_type_name(&self) -> &'static str { let name = self.type_name(); name.split('<') .next() .unwrap_or(name) .split("::") .last() .unwrap_or(name) } #[doc(hidden)] /// From the current data, get a best-effort description of the state of /// this widget and its children for debugging purposes. fn debug_state(&self, data: &T) -> DebugState { #![allow(unused_variables)] DebugState { display_name: self.short_type_name().to_string(), ..Default::default() } } /// Computes max intrinsic/preferred dimension of a widget on the provided axis. /// /// Max intrinsic/preferred dimension is the dimension the widget could take, provided infinite /// constraint on that axis. /// /// If axis == Axis::Horizontal, widget is being asked to calculate max intrinsic width. /// If axis == Axis::Vertical, widget is being asked to calculate max intrinsic height. /// /// Box constraints must be honored in intrinsics computation. /// /// AspectRatioBox is an example where constraints are honored. If height is finite, max intrinsic /// width is *height * ratio*. /// Only when height is infinite, child's max intrinsic width is calculated. /// /// Intrinsic is a *could-be* value. It's the value a widget *could* have given infinite constraints. /// This does not mean the value returned by layout() would be the same. /// /// This method **must** return a finite value. fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64 { match axis { Axis::Horizontal => self.layout(ctx, bc, data, env).width, Axis::Vertical => self.layout(ctx, bc, data, env).height, } } } impl WidgetId { /// Allocate a new, unique `WidgetId`. /// /// All widgets are assigned ids automatically; you should only create /// an explicit id if you need to know it ahead of time, for instance /// if you want two sibling widgets to know each others' ids. /// /// You must ensure that a given `WidgetId` is only ever used for one /// widget at a time. pub fn next() -> WidgetId { use crate::shell::Counter; static WIDGET_ID_COUNTER: Counter = Counter::new(); WidgetId(WIDGET_ID_COUNTER.next_nonzero()) } /// Create a reserved `WidgetId`, suitable for reuse. /// /// The caller is responsible for ensuring that this ID is in fact assigned /// to a single widget at any time, or your code may become haunted. /// /// The actual inner representation of the returned `WidgetId` will not /// be the same as the raw value that is passed in; it will be /// `u64::max_value() - raw`. #[allow(unsafe_code)] pub const fn reserved(raw: u16) -> WidgetId { let id = u64::MAX - raw as u64; // safety: by construction this can never be zero. WidgetId(unsafe { std::num::NonZeroU64::new_unchecked(id) }) } pub(crate) fn to_raw(self) -> u64 { self.0.into() } } impl<T> Widget<T> for Box<dyn Widget<T>> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.deref_mut().event(ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.deref_mut().lifecycle(ctx, event, data, env); } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.deref_mut().update(ctx, old_data, data, env); } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { self.deref_mut().layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.deref_mut().paint(ctx, data, env); } fn id(&self) -> Option<WidgetId> { self.deref().id() } fn type_name(&self) -> &'static str { self.deref().type_name() } fn debug_state(&self, data: &T) -> DebugState { self.deref().debug_state(data) } fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64 { self.deref_mut() .compute_max_intrinsic(axis, ctx, bc, data, env) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/parse.rs
druid/src/widget/parse.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 // This whole widget was deprecated in Druid 0.7 // https://github.com/linebender/druid/pull/1377 #![allow(deprecated)] use std::fmt::Display; use std::mem; use std::str::FromStr; use tracing::instrument; use crate::debug_state::DebugState; use crate::widget::prelude::*; use crate::Data; /// Converts a `Widget<String>` to a `Widget<Option<T>>`, mapping parse errors to None #[doc(hidden)] #[deprecated(since = "0.7.0", note = "Use the Formatter trait instead")] pub struct Parse<T> { widget: T, state: String, } impl<T> Parse<T> { /// Create a new `Parse` widget. pub fn new(widget: T) -> Self { Self { widget, state: String::new(), } } } impl<T: FromStr + Display + Data, W: Widget<String>> Widget<Option<T>> for Parse<W> { #[instrument(name = "Parse", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut Option<T>, env: &Env) { self.widget.event(ctx, event, &mut self.state, env); *data = self.state.parse().ok(); } #[instrument(name = "Parse", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &Option<T>, env: &Env, ) { if let LifeCycle::WidgetAdded = event { if let Some(data) = data { self.state = data.to_string(); } } self.widget.lifecycle(ctx, event, &self.state, env) } #[instrument(name = "Parse", level = "trace", skip(self, ctx, _old_data, data, env))] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &Option<T>, data: &Option<T>, env: &Env) { let old = match *data { None => return, // Don't clobber the input Some(ref x) => { // Its possible that the current self.state already represents the data value // in that case we shouldn't clobber the self.state. This helps deal // with types where parse()/to_string() round trips can lose information // e.g. with floating point numbers, text of "1.0" becomes "1" in the // round trip, and this makes it impossible to type in the . otherwise match self.state.parse() { Err(_) => Some(mem::replace(&mut self.state, x.to_string())), Ok(v) => { if !Data::same(&v, x) { Some(mem::replace(&mut self.state, x.to_string())) } else { None } } } } }; // if old is None here, that means that self.state hasn't changed let old_data = old.as_ref().unwrap_or(&self.state); self.widget.update(ctx, old_data, &self.state, env) } #[instrument(name = "Parse", level = "trace", skip(self, ctx, bc, _data, env))] fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &Option<T>, env: &Env, ) -> Size { self.widget.layout(ctx, bc, &self.state, env) } #[instrument(name = "Parse", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &Option<T>, env: &Env) { self.widget.paint(ctx, &self.state, env) } fn id(&self) -> Option<WidgetId> { self.widget.id() } fn debug_state(&self, _data: &Option<T>) -> DebugState { DebugState { display_name: "Parse".to_string(), main_value: self.state.clone(), ..Default::default() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/textbox.rs
druid/src/widget/textbox.rs
// Copyright 2018 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A textbox widget. use std::time::Duration; use tracing::{instrument, trace}; use crate::contexts::ChangeCtx; use crate::debug_state::DebugState; use crate::kurbo::Insets; use crate::piet::TextLayout as _; use crate::text::{ EditableText, ImeInvalidation, Selection, TextComponent, TextLayout, TextStorage, }; use crate::widget::prelude::*; use crate::widget::{Padding, Scroll, WidgetWrapper}; use crate::{ theme, ArcStr, Color, Command, FontDescriptor, HotKey, KeyEvent, KeyOrValue, Point, Rect, SysMods, TextAlignment, TimerToken, Vec2, }; use super::LabelText; const CURSOR_BLINK_DURATION: Duration = Duration::from_millis(500); const MAC_OR_LINUX_OR_BSD: bool = cfg!(any( target_os = "freebsd", target_os = "macos", target_os = "linux", target_os = "openbsd" )); /// When we scroll after editing or movement, we show a little extra of the document. const SCROLL_TO_INSETS: Insets = Insets::uniform_xy(40.0, 0.0); /// A widget that allows user text input. /// /// # Editing values /// /// If the text you are editing represents a value of some other type, such /// as a number, you should use a [`ValueTextBox`] and an appropriate /// [`Formatter`]. You can create a [`ValueTextBox`] by passing the appropriate /// [`Formatter`] to [`TextBox::with_formatter`]. /// /// [`Formatter`]: crate::text::Formatter /// [`ValueTextBox`]: super::ValueTextBox pub struct TextBox<T> { placeholder_text: LabelText<T>, placeholder_layout: TextLayout<ArcStr>, inner: Scroll<T, Padding<T, TextComponent<T>>>, scroll_to_selection_after_layout: bool, multiline: bool, /// true if a click event caused us to gain focus. /// /// On macOS, if focus happens via click then we set the selection based /// on the click position; if focus happens automatically (e.g. on tab) /// then we select our entire contents. was_focused_from_click: bool, cursor_on: bool, cursor_timer: TimerToken, /// if `true` (the default), this textbox will attempt to change focus on tab. /// /// You can override this in a controller if you want to customize tab /// behaviour. pub handles_tab_notifications: bool, text_pos: Point, } impl<T: EditableText + TextStorage> TextBox<T> { /// Create a new TextBox widget. /// /// # Examples /// /// ``` /// use druid::widget::TextBox; /// use druid::{ WidgetExt, Data, Lens }; /// /// #[derive(Clone, Data, Lens)] /// struct AppState { /// name: String, /// } /// /// let _ = TextBox::new() /// .with_placeholder("placeholder text") /// .lens(AppState::name); /// ``` pub fn new() -> Self { let placeholder_text = ArcStr::from(""); let mut placeholder_layout = TextLayout::new(); placeholder_layout.set_text_color(theme::PLACEHOLDER_COLOR); placeholder_layout.set_text(placeholder_text.clone()); let mut scroll = Scroll::new(Padding::new( theme::TEXTBOX_INSETS, TextComponent::default(), )) .content_must_fill(true); scroll.set_enabled_scrollbars(crate::scroll_component::ScrollbarsEnabled::None); Self { inner: scroll, scroll_to_selection_after_layout: false, placeholder_text: placeholder_text.into(), placeholder_layout, multiline: false, was_focused_from_click: false, cursor_on: false, cursor_timer: TimerToken::INVALID, handles_tab_notifications: true, text_pos: Point::ZERO, } } /// Create a new multi-line `TextBox`. /// /// # Examples /// /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// let multiline = TextBox::multiline() /// .lens(AppState::name); /// ``` pub fn multiline() -> Self { let mut this = TextBox::new(); this.inner .set_enabled_scrollbars(crate::scroll_component::ScrollbarsEnabled::Both); this.text_mut().borrow_mut().set_accepts_newlines(true); this.inner.set_horizontal_scroll_enabled(false); this.multiline = true; this } /// If `true` (and this is a [`multiline`] text box) lines will be wrapped /// at the maximum layout width. /// /// If `false`, lines will not be wrapped, and horizontal scrolling will /// be enabled. /// /// # Examples /// /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// //will scroll horizontally /// let scroll_text_box = TextBox::new() /// .with_line_wrapping(false) /// .lens(AppState::name); /// /// //will wrap only for a single line /// let wrap_text_box = TextBox::new() /// .with_line_wrapping(true) /// .lens(AppState::name); /// /// //will scroll as well as having multiple lines /// let scroll_multi_line_text_box = TextBox::multiline() /// .with_line_wrapping(false) /// .lens(AppState::name); /// /// //will wrap for each line /// let wrap_multi_line_text_box = TextBox::multiline() /// .with_line_wrapping(true) // this is default and can be removed for the same result /// .lens(AppState::name); /// /// ``` /// [`multiline`]: TextBox::multiline pub fn with_line_wrapping(mut self, wrap_lines: bool) -> Self { self.inner.set_horizontal_scroll_enabled(!wrap_lines); self } } impl<T> TextBox<T> { /// Builder-style method for setting the text size. /// /// The argument can be either an `f64` or a [`Key<f64>`]. /// /// # Examples /// /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// let text_box = TextBox::new() /// .with_text_size(14.) /// .lens(AppState::name); /// ``` /// /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// use druid::Key; /// /// const FONT_SIZE : Key<f64> = Key::new("font-size"); /// /// let text_box = TextBox::new() /// .with_text_size(FONT_SIZE) /// .lens(AppState::name); /// ``` /// [`Key<f64>`]: crate::Key pub fn with_text_size(mut self, size: impl Into<KeyOrValue<f64>>) -> Self { self.set_text_size(size); self } /// Builder-style method to set the [`TextAlignment`]. /// /// This is only relevant when the `TextBox` is *not* [`multiline`], /// in which case it determines how the text is positioned inside the /// `TextBox` when it does not fill the available space. /// /// # Note: /// /// This does not behave exactly like [`TextAlignment`] does when used /// with label; in particular this does not account for reading direction. /// This means that `TextAlignment::Start` (the default) always means /// *left aligned*, and `TextAlignment::End` always means *right aligned*. /// /// This should be considered a bug, but it will not be fixed until proper /// BiDi support is implemented. /// /// # Examples /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// use druid::TextAlignment; /// /// let text_box = TextBox::new() /// .with_text_alignment(TextAlignment::Center) /// .lens(AppState::name); /// ``` /// /// [`multiline`]: TextBox::multiline pub fn with_text_alignment(mut self, alignment: TextAlignment) -> Self { self.set_text_alignment(alignment); self } /// Builder-style method for setting the font. /// /// The argument can be a [`FontDescriptor`] or a [`Key<FontDescriptor>`] /// that refers to a font defined in the [`Env`]. /// /// # Examples /// /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// use druid::{ FontDescriptor, FontFamily, Key }; /// /// const FONT : Key<FontDescriptor> = Key::new("font"); /// /// let text_box = TextBox::new() /// .with_font(FontDescriptor::new(FontFamily::MONOSPACE)) /// .lens(AppState::name); /// /// let text_box = TextBox::new() /// .with_font(FONT) /// .lens(AppState::name); /// ``` /// /// /// [`Key<FontDescriptor>`]: crate::Key pub fn with_font(mut self, font: impl Into<KeyOrValue<FontDescriptor>>) -> Self { self.set_font(font); self } /// Builder-style method for setting the text color. /// /// The argument can be either a `Color` or a [`Key<Color>`]. /// # Examples /// ``` /// # use druid::widget::TextBox; /// # use druid::{ WidgetExt, Data, Lens }; /// # /// # #[derive(Clone, Data, Lens)] /// # struct AppState { /// # name: String, /// # } /// use druid::{ Color, Key }; /// /// const COLOR : Key<Color> = Key::new("color"); /// /// let text_box = TextBox::new() /// .with_text_color(Color::RED) /// .lens(AppState::name); /// /// let text_box = TextBox::new() /// .with_text_color(COLOR) /// .lens(AppState::name); /// ``` /// /// [`Key<Color>`]: crate::Key pub fn with_text_color(mut self, color: impl Into<KeyOrValue<Color>>) -> Self { self.set_text_color(color); self } /// Set the text size. /// /// The argument can be either an `f64` or a [`Key<f64>`]. /// /// [`Key<f64>`]: crate::Key pub fn set_text_size(&mut self, size: impl Into<KeyOrValue<f64>>) { if !self.text().can_write() { tracing::warn!("set_text_size called with IME lock held."); return; } let size = size.into(); self.text_mut() .borrow_mut() .layout .set_text_size(size.clone()); self.placeholder_layout.set_text_size(size); } /// Set the font. /// /// The argument can be a [`FontDescriptor`] or a [`Key<FontDescriptor>`] /// that refers to a font defined in the [`Env`]. /// /// [`Key<FontDescriptor>`]: crate::Key pub fn set_font(&mut self, font: impl Into<KeyOrValue<FontDescriptor>>) { if !self.text().can_write() { tracing::warn!("set_font called with IME lock held."); return; } let font = font.into(); self.text_mut().borrow_mut().layout.set_font(font.clone()); self.placeholder_layout.set_font(font); } /// Set the [`TextAlignment`] for this `TextBox``. /// /// This is only relevant when the `TextBox` is *not* [`multiline`], /// in which case it determines how the text is positioned inside the /// `TextBox` when it does not fill the available space. /// /// # Note: /// /// This does not behave exactly like [`TextAlignment`] does when used /// with label; in particular this does not account for reading direction. /// This means that `TextAlignment::Start` (the default) always means /// *left aligned*, and `TextAlignment::End` always means *right aligned*. /// /// This should be considered a bug, but it will not be fixed until proper /// BiDi support is implemented. /// /// [`multiline`]: TextBox::multiline pub fn set_text_alignment(&mut self, alignment: TextAlignment) { if !self.text().can_write() { tracing::warn!("set_text_alignment called with IME lock held."); return; } self.text_mut().borrow_mut().set_text_alignment(alignment); } /// Set the text color. /// /// The argument can be either a `Color` or a [`Key<Color>`]. /// /// If you change this property, you are responsible for calling /// [`request_layout`] to ensure the label is updated. /// /// [`request_layout`]: EventCtx::request_layout /// [`Key<Color>`]: crate::Key pub fn set_text_color(&mut self, color: impl Into<KeyOrValue<Color>>) { if !self.text().can_write() { tracing::warn!("set_text_color called with IME lock held."); return; } self.text_mut().borrow_mut().layout.set_text_color(color); } /// The point, relative to the origin, where this text box draws its /// [`TextLayout`]. /// /// This is exposed in case the user wants to do additional drawing based /// on properties of the text. /// /// This is not valid until `layout` has been called. pub fn text_position(&self) -> Point { self.text_pos } } impl<T: Data> TextBox<T> { /// Builder-style method to set the `TextBox`'s placeholder text. pub fn with_placeholder(mut self, placeholder: impl Into<LabelText<T>>) -> Self { self.set_placeholder(placeholder); self } /// Set the `TextBox`'s placeholder text. pub fn set_placeholder(&mut self, placeholder: impl Into<LabelText<T>>) { self.placeholder_text = placeholder.into(); self.placeholder_layout .set_text(self.placeholder_text.display_text()); } } impl<T> TextBox<T> { /// An immutable reference to the inner [`TextComponent`]. /// /// Using this correctly is difficult; please see the [`TextComponent`] /// docs for more information. pub fn text(&self) -> &TextComponent<T> { self.inner.child().wrapped() } /// A mutable reference to the inner [`TextComponent`]. /// /// Using this correctly is difficult; please see the [`TextComponent`] /// docs for more information. pub fn text_mut(&mut self) -> &mut TextComponent<T> { self.inner.child_mut().wrapped_mut() } fn reset_cursor_blink(&mut self, token: TimerToken) { self.cursor_on = true; self.cursor_timer = token; } fn should_draw_cursor(&self) -> bool { if cfg!(target_os = "macos") && self.text().can_read() { self.cursor_on && self.text().borrow().selection().is_caret() } else { self.cursor_on } } } impl<T: TextStorage + EditableText> TextBox<T> { fn rect_for_selection_end(&self) -> Rect { let text = self.text().borrow(); let layout = text.layout.layout().unwrap(); let hit = layout.hit_test_text_position(text.selection().active); let line = layout.line_metric(hit.line).unwrap(); let y0 = line.y_offset; let y1 = y0 + line.height; let x = hit.point.x; Rect::new(x, y0, x, y1) } fn scroll_to_selection_end<C: ChangeCtx>(&mut self, ctx: &mut C) { let rect = self.rect_for_selection_end(); let view_rect = self.inner.viewport_rect(); let is_visible = view_rect.contains(rect.origin()) && view_rect.contains(Point::new(rect.x1, rect.y1)); if !is_visible { self.inner.scroll_to(ctx, rect + SCROLL_TO_INSETS); } } /// These commands may be supplied by menus; but if they aren't, we /// inject them again, here. fn fallback_do_builtin_command( &mut self, ctx: &mut EventCtx, key: &KeyEvent, ) -> Option<Command> { use crate::commands as sys; let our_id = ctx.widget_id(); match key { key if HotKey::new(SysMods::Cmd, "c").matches(key) => Some(sys::COPY.to(our_id)), key if HotKey::new(SysMods::Cmd, "x").matches(key) => Some(sys::CUT.to(our_id)), // we have to send paste to the window, in order to get it converted into the `Paste` // event key if HotKey::new(SysMods::Cmd, "v").matches(key) => { Some(sys::PASTE.to(ctx.window_id())) } key if HotKey::new(SysMods::Cmd, "z").matches(key) => Some(sys::UNDO.to(our_id)), key if HotKey::new(SysMods::CmdShift, "Z").matches(key) && !cfg!(windows) => { Some(sys::REDO.to(our_id)) } key if HotKey::new(SysMods::Cmd, "y").matches(key) && cfg!(windows) => { Some(sys::REDO.to(our_id)) } key if HotKey::new(SysMods::Cmd, "a").matches(key) => Some(sys::SELECT_ALL.to(our_id)), _ => None, } } } impl<T: TextStorage + EditableText> Widget<T> for TextBox<T> { #[instrument(name = "TextBox", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { match event { Event::Notification(cmd) => match cmd { cmd if cmd.is(TextComponent::SCROLL_TO) => { let after_edit = *cmd.get(TextComponent::SCROLL_TO).unwrap_or(&false); if after_edit { ctx.request_layout(); self.scroll_to_selection_after_layout = true; } else { self.scroll_to_selection_end(ctx); } ctx.set_handled(); ctx.request_paint(); } cmd if cmd.is(TextComponent::TAB) && self.handles_tab_notifications => { ctx.focus_next(); ctx.request_paint(); ctx.set_handled(); } cmd if cmd.is(TextComponent::BACKTAB) && self.handles_tab_notifications => { ctx.focus_prev(); ctx.request_paint(); ctx.set_handled(); } cmd if cmd.is(TextComponent::CANCEL) => { ctx.resign_focus(); ctx.request_paint(); ctx.set_handled(); } _ => (), }, Event::KeyDown(key) if !self.text().is_composing() => { if let Some(cmd) = self.fallback_do_builtin_command(ctx, key) { ctx.submit_command(cmd); ctx.set_handled(); } } Event::MouseDown(mouse) if self.text().can_write() => { if !ctx.is_disabled() { if !mouse.focus { ctx.request_focus(); self.was_focused_from_click = true; self.reset_cursor_blink(ctx.request_timer(CURSOR_BLINK_DURATION)); } else { ctx.set_handled(); } } } Event::Timer(id) => { if !ctx.is_disabled() { if *id == self.cursor_timer && ctx.has_focus() { self.cursor_on = !self.cursor_on; ctx.request_paint(); self.cursor_timer = ctx.request_timer(CURSOR_BLINK_DURATION); } } else if self.cursor_on { self.cursor_on = false; ctx.request_paint(); } } Event::ImeStateChange => { self.reset_cursor_blink(ctx.request_timer(CURSOR_BLINK_DURATION)); } Event::Command(ref cmd) if !self.text().is_composing() && ctx.is_focused() && cmd.is(crate::commands::COPY) => { self.text().borrow().set_clipboard(); ctx.set_handled(); } Event::Command(cmd) if !self.text().is_composing() && ctx.is_focused() && cmd.is(crate::commands::CUT) => { if self.text().borrow().set_clipboard() { let inval = self.text_mut().borrow_mut().insert_text(data, ""); ctx.invalidate_text_input(inval); } ctx.set_handled(); } Event::Command(cmd) if !self.text().is_composing() && ctx.is_focused() && cmd.is(crate::commands::SELECT_ALL) => { if let Some(inval) = self .text_mut() .borrow_mut() .set_selection(Selection::new(0, data.as_str().len())) { ctx.request_paint(); ctx.invalidate_text_input(inval); } ctx.set_handled(); } Event::Paste(ref item) if self.text().can_write() => { if let Some(string) = item.get_string() { let text = if self.multiline { &string } else { string.lines().next().unwrap_or("") }; if !text.is_empty() { let inval = self.text_mut().borrow_mut().insert_text(data, text); ctx.invalidate_text_input(inval); } } } _ => (), } self.inner.event(ctx, event, data, env) } #[instrument(name = "TextBox", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::WidgetAdded => { if matches!(event, LifeCycle::WidgetAdded) { self.placeholder_text.resolve(data, env); } ctx.register_text_input(self.text().input_handler()); } LifeCycle::BuildFocusChain => { //TODO: make this a configurable option? maybe? ctx.register_for_focus(); } LifeCycle::FocusChanged(true) => { if self.text().can_write() && !self.multiline && !self.was_focused_from_click { let selection = Selection::new(0, data.len()); let _ = self.text_mut().borrow_mut().set_selection(selection); ctx.invalidate_text_input(ImeInvalidation::SelectionChanged); } self.text_mut().has_focus = true; self.reset_cursor_blink(ctx.request_timer(CURSOR_BLINK_DURATION)); self.was_focused_from_click = false; ctx.request_paint(); ctx.scroll_to_view(); } LifeCycle::FocusChanged(false) => { if self.text().can_write() && MAC_OR_LINUX_OR_BSD && !self.multiline { let selection = self.text().borrow().selection(); let selection = Selection::new(selection.active, selection.active); let _ = self.text_mut().borrow_mut().set_selection(selection); ctx.invalidate_text_input(ImeInvalidation::SelectionChanged); } self.text_mut().has_focus = false; if !self.multiline { self.inner.scroll_to(ctx, Rect::ZERO); } self.cursor_timer = TimerToken::INVALID; self.was_focused_from_click = false; ctx.request_paint(); } _ => (), } self.inner.lifecycle(ctx, event, data, env); } #[instrument(name = "TextBox", level = "trace", skip(self, ctx, old, data, env))] fn update(&mut self, ctx: &mut UpdateCtx, old: &T, data: &T, env: &Env) { let placeholder_changed = self.placeholder_text.resolve(data, env); if placeholder_changed { let new_text = self.placeholder_text.display_text(); self.placeholder_layout.set_text(new_text); } self.inner.update(ctx, old, data, env); if placeholder_changed || (ctx.env_changed() && self.placeholder_layout.needs_rebuild_after_update(ctx)) { ctx.request_layout(); } if self.text().can_write() { if let Some(ime_invalidation) = self.text_mut().borrow_mut().pending_ime_invalidation() { ctx.invalidate_text_input(ime_invalidation); } } } #[instrument(name = "TextBox", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { if !self.text().can_write() { tracing::warn!("Widget::layout called with outstanding IME lock."); } let min_width = env.get(theme::WIDE_WIDGET_WIDTH); let textbox_insets = env.get(theme::TEXTBOX_INSETS); self.placeholder_layout.rebuild_if_needed(ctx.text(), env); let min_size = bc.constrain((min_width, 0.0)); let child_bc = BoxConstraints::new(min_size, bc.max()); let size = self.inner.layout(ctx, &child_bc, data, env); let text_metrics = if !self.text().can_read() || data.is_empty() { self.placeholder_layout.layout_metrics() } else { self.text().borrow().layout.layout_metrics() }; let layout_baseline = text_metrics.size.height - text_metrics.first_baseline; let baseline_off = layout_baseline - (self.inner.child_size().height - self.inner.viewport_rect().height()) + textbox_insets.y1; ctx.set_baseline_offset(baseline_off); if self.scroll_to_selection_after_layout { self.scroll_to_selection_end(ctx); self.scroll_to_selection_after_layout = false; } trace!( "Computed layout: size={}, baseline_offset={:?}", size, baseline_off ); size } #[instrument(name = "TextBox", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { if !self.text().can_read() { tracing::warn!("Widget::paint called with outstanding IME lock, skipping"); return; } let size = ctx.size(); let background_color = env.get(theme::BACKGROUND_LIGHT); let cursor_color = env.get(theme::CURSOR_COLOR); let border_width = env.get(theme::TEXTBOX_BORDER_WIDTH); let textbox_insets = env.get(theme::TEXTBOX_INSETS); let is_focused = ctx.is_focused(); let border_color = if is_focused { env.get(theme::PRIMARY_LIGHT) } else { env.get(theme::BORDER_DARK) }; // Paint the background let clip_rect = size .to_rect() .inset(-border_width / 2.0) .to_rounded_rect(env.get(theme::TEXTBOX_BORDER_RADIUS)); ctx.fill(clip_rect, &background_color); if !data.is_empty() { self.inner.paint(ctx, data, env); } else { let text_width = self.placeholder_layout.layout_metrics().size.width; let extra_width = (size.width - text_width - textbox_insets.x_value()).max(0.); let alignment = self.text().borrow().text_alignment(); // alignment is only used for single-line text boxes let x_offset = if self.multiline { 0.0 } else { x_offset_for_extra_width(alignment, extra_width) }; // clip when we draw the placeholder, since it isn't in a clipbox ctx.with_save(|ctx| { ctx.clip(clip_rect); self.placeholder_layout .draw(ctx, (textbox_insets.x0 + x_offset, textbox_insets.y0)); }) } // Paint the cursor if focused and there's no selection if is_focused && self.should_draw_cursor() { // if there's no data, we always draw the cursor based on // our alignment. let cursor_pos = self.text().borrow().selection().active; let cursor_line = self .text() .borrow() .cursor_line_for_text_position(cursor_pos); let padding_offset = Vec2::new(textbox_insets.x0, textbox_insets.y0); let mut cursor = if data.is_empty() { cursor_line + padding_offset } else { cursor_line + padding_offset - self.inner.offset() }; // Snap the cursor to the pixel grid so it stays sharp. cursor.p0.x = cursor.p0.x.trunc() + 0.5; cursor.p1.x = cursor.p0.x; ctx.with_save(|ctx| { ctx.clip(clip_rect); ctx.stroke(cursor, &cursor_color, 1.); }) } // Paint the border ctx.stroke(clip_rect, &border_color, border_width); } fn debug_state(&self, data: &T) -> DebugState { let text = data.slice(0..data.len()).unwrap_or_default(); DebugState { display_name: self.short_type_name().to_string(), main_value: text.to_string(), ..Default::default() } } } impl<T: TextStorage + EditableText> Default for TextBox<T> { fn default() -> Self { TextBox::new() } } fn x_offset_for_extra_width(alignment: TextAlignment, extra_width: f64) -> f64 { match alignment { TextAlignment::Start | TextAlignment::Justified => 0.0, TextAlignment::End => extra_width, TextAlignment::Center => extra_width / 2.0, } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/image.rs
druid/src/widget/image.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! An Image widget. //! Please consider using SVG and the SVG widget as it scales much better. use crate::{ kurbo::Rect, piet::{Image as _, ImageBuf, InterpolationMode, PietImage}, widget::common::FillStrat, widget::prelude::*, Data, }; use tracing::{instrument, trace}; /// A widget that renders a bitmap Image. /// /// Contains data about how to fill the given space and interpolate pixels. /// Configuration options are provided via the builder pattern. /// /// Note: when [scaling a bitmap image], such as supporting multiple /// screen sizes and resolutions, interpolation can lead to blurry /// or pixelated images and so is not recommended for things like icons. /// Instead consider using [SVG files] and enabling the `svg` feature with `cargo`. /// /// (See also: [`ImageBuf`], [`FillStrat`], [`InterpolationMode`]) /// /// # Example /// /// Create an image widget and configure it using builder methods /// ``` /// use druid::{ /// widget::{Image, FillStrat}, /// piet::{ImageBuf, InterpolationMode}, /// }; /// /// let image_data = ImageBuf::empty(); /// let image_widget = Image::new(image_data) /// // set the fill strategy /// .fill_mode(FillStrat::Fill) /// // set the interpolation mode /// .interpolation_mode(InterpolationMode::Bilinear); /// ``` /// Create an image widget and configure it using setters /// ``` /// use druid::{ /// widget::{Image, FillStrat}, /// piet::{ImageBuf, InterpolationMode}, /// }; /// /// let image_data = ImageBuf::empty(); /// let mut image_widget = Image::new(image_data); /// // set the fill strategy /// image_widget.set_fill_mode(FillStrat::FitWidth); /// // set the interpolation mode /// image_widget.set_interpolation_mode(InterpolationMode::Bilinear); /// ``` /// /// [scaling a bitmap image]: crate::Scale#pixels-and-display-points /// [SVG files]: https://en.wikipedia.org/wiki/Scalable_Vector_Graphics pub struct Image { image_data: ImageBuf, paint_data: Option<PietImage>, fill: FillStrat, interpolation: InterpolationMode, clip_area: Option<Rect>, } impl Image { /// Create an image drawing widget from an image buffer. /// /// By default, the Image will scale to fit its box constraints ([`FillStrat::Fill`]) /// and will be scaled bilinearly ([`InterpolationMode::Bilinear`]) /// /// The underlying `ImageBuf` uses `Arc` for buffer data, making it cheap to clone. /// /// [`FillStrat::Fill`]: crate::widget::FillStrat::Fill /// [`InterpolationMode::Bilinear`]: crate::piet::InterpolationMode::Bilinear #[inline] pub fn new(image_data: ImageBuf) -> Self { Image { image_data, paint_data: None, fill: FillStrat::default(), interpolation: InterpolationMode::Bilinear, clip_area: None, } } /// Builder-style method for specifying the fill strategy. #[inline] pub fn fill_mode(mut self, mode: FillStrat) -> Self { self.fill = mode; // Invalidation not necessary self } /// Modify the widget's fill strategy. #[inline] pub fn set_fill_mode(&mut self, newfil: FillStrat) { self.fill = newfil; // Invalidation not necessary } /// Builder-style method for specifying the interpolation strategy. #[inline] pub fn interpolation_mode(mut self, interpolation: InterpolationMode) -> Self { self.interpolation = interpolation; // Invalidation not necessary self } /// Modify the widget's interpolation mode. #[inline] pub fn set_interpolation_mode(&mut self, interpolation: InterpolationMode) { self.interpolation = interpolation; // Invalidation not necessary } /// Builder-style method for setting the area of the image that will be displayed. /// /// If `None`, then the whole image will be displayed. #[inline] pub fn clip_area(mut self, clip_area: Option<Rect>) -> Self { self.clip_area = clip_area; // Invalidation not necessary self } /// Set the area of the image that will be displayed. /// /// If `None`, then the whole image will be displayed. #[inline] pub fn set_clip_area(&mut self, clip_area: Option<Rect>) { self.clip_area = clip_area; // Invalidation not necessary } /// Set new `ImageBuf`. #[inline] pub fn set_image_data(&mut self, image_data: ImageBuf) { self.image_data = image_data; self.invalidate(); } /// Invalidate the image cache, forcing it to be recreated. #[inline] fn invalidate(&mut self) { self.paint_data = None; } /// The size of the effective image, considering clipping if it's in effect. #[inline] fn image_size(&mut self) -> Size { self.clip_area .map(|a| a.size()) .unwrap_or_else(|| self.image_data.size()) } } impl<T: Data> Widget<T> for Image { #[instrument(name = "Image", level = "trace", skip(self, _ctx, _event, _data, _env))] fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut T, _env: &Env) {} #[instrument(name = "Image", level = "trace", skip(self, _ctx, _event, _data, _env))] fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &T, _env: &Env) {} #[instrument( name = "Image", level = "trace", skip(self, _ctx, _old_data, _data, _env) )] fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &T, _data: &T, _env: &Env) {} #[instrument( name = "Image", level = "trace", skip(self, _layout_ctx, bc, _data, _env) )] fn layout( &mut self, _layout_ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, _env: &Env, ) -> Size { bc.debug_check("Image"); // If either the width or height is constrained calculate a value so that the image fits // in the size exactly. If it is unconstrained by both width and height take the size of // the image. let max = bc.max(); let image_size = self.image_size(); let size = if bc.is_width_bounded() && !bc.is_height_bounded() { let ratio = max.width / image_size.width; Size::new(max.width, ratio * image_size.height) } else if bc.is_height_bounded() && !bc.is_width_bounded() { let ratio = max.height / image_size.height; Size::new(ratio * image_size.width, max.height) } else { bc.constrain(image_size) }; trace!("Computed size: {}", size); size } #[instrument(name = "Image", level = "trace", skip(self, ctx, _data, _env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, _env: &Env) { let image_size = self.image_size(); let offset_matrix = self.fill.affine_to_fill(ctx.size(), image_size); // The ImageData's to_piet function does not clip to the image's size // CairoRenderContext is very like druids but with some extra goodies like clip if self.fill != FillStrat::Contain { let clip_rect = ctx.size().to_rect(); ctx.clip(clip_rect); } let piet_image = { let image_data = &self.image_data; self.paint_data .get_or_insert_with(|| image_data.to_image(ctx.render_ctx)) }; if piet_image.size().is_zero_area() { // zero-sized image = nothing to draw return; } ctx.with_save(|ctx| { // we have to re-do this because the whole struct is moved into the closure. let piet_image = { let image_data = &self.image_data; self.paint_data .get_or_insert_with(|| image_data.to_image(ctx.render_ctx)) }; ctx.transform(offset_matrix); if let Some(area) = self.clip_area { ctx.draw_image_area(piet_image, area, image_size.to_rect(), self.interpolation); } else { ctx.draw_image(piet_image, image_size.to_rect(), self.interpolation); } }); } } #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests { use super::*; use crate::piet::ImageFormat; use test_log::test; /// Painting an empty image shouldn't crash Druid. #[test] fn empty_paint() { use crate::{tests::harness::Harness, WidgetId}; let _id_1 = WidgetId::next(); let image_data = ImageBuf::empty(); let image_widget = Image::new(image_data).interpolation_mode(InterpolationMode::NearestNeighbor); Harness::create_with_render( (), image_widget, Size::new(400., 600.), |harness| { harness.send_initial_events(); harness.just_layout(); harness.paint(); }, |_target| { // if we painted the image, then success! }, ) } #[test] fn tall_paint() { use crate::{tests::harness::Harness, WidgetId}; let _id_1 = WidgetId::next(); let image_data = ImageBuf::from_raw( vec![255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255], ImageFormat::Rgb, 2, 2, ); let image_widget = Image::new(image_data).interpolation_mode(InterpolationMode::NearestNeighbor); Harness::create_with_render( (), image_widget, Size::new(400., 600.), |harness| { harness.send_initial_events(); harness.just_layout(); harness.paint(); }, |target| { let raw_pixels = target.into_raw(); assert_eq!(raw_pixels.len(), 400 * 600 * 4); // Being a tall widget with a square image the top and bottom rows will be // the padding color and the middle rows will not have any padding. // Check that the middle row 400 pix wide is 200 black then 200 white. let expecting: Vec<u8> = [[0, 0, 0, 255].repeat(200), [255, 255, 255, 255].repeat(200)].concat(); assert_eq!(raw_pixels[400 * 300 * 4..400 * 301 * 4], expecting[..]); // Check that all of the last 100 rows are all the background color. let expecting: Vec<u8> = [41, 41, 41, 255].repeat(400 * 100); assert_eq!( raw_pixels[400 * 600 * 4 - 4 * 400 * 100..400 * 600 * 4], expecting[..] ); }, ) } #[test] fn wide_paint() { use crate::{tests::harness::Harness, WidgetId}; let _id_1 = WidgetId::next(); let image_data = ImageBuf::from_raw( vec![255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255], ImageFormat::Rgb, 2, 2, ); let image_widget = Image::new(image_data).interpolation_mode(InterpolationMode::NearestNeighbor); Harness::create_with_render( true, image_widget, Size::new(600., 400.), |harness| { harness.send_initial_events(); harness.just_layout(); harness.paint(); }, |target| { let raw_pixels = target.into_raw(); assert_eq!(raw_pixels.len(), 400 * 600 * 4); // Being a wide widget every row will have some padding at the start and end // the last row will be like this too and there will be no padding rows at the end. // A middle row of 600 pixels is 100 padding 200 black, 200 white and then 100 padding. let expecting: Vec<u8> = [ [41, 41, 41, 255].repeat(100), [255, 255, 255, 255].repeat(200), [0, 0, 0, 255].repeat(200), [41, 41, 41, 255].repeat(100), ] .concat(); assert_eq!(raw_pixels[199 * 600 * 4..200 * 600 * 4], expecting[..]); // The final row of 600 pixels is 100 padding 200 black, 200 white and then 100 padding. let expecting: Vec<u8> = [ [41, 41, 41, 255].repeat(100), [0, 0, 0, 255].repeat(200), [255, 255, 255, 255].repeat(200), [41, 41, 41, 255].repeat(100), ] .concat(); assert_eq!(raw_pixels[399 * 600 * 4..400 * 600 * 4], expecting[..]); }, ); } #[test] fn into_png() { use crate::{ tests::{harness::Harness, temp_dir_for_test}, WidgetId, }; let _id_1 = WidgetId::next(); let image_data = ImageBuf::from_raw( vec![255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255], ImageFormat::Rgb, 2, 2, ); let image_widget = Image::new(image_data).interpolation_mode(InterpolationMode::NearestNeighbor); Harness::create_with_render( true, image_widget, Size::new(600., 400.), |harness| { harness.send_initial_events(); harness.just_layout(); harness.paint(); }, |target| { let tmp_dir = temp_dir_for_test(); target.into_png(tmp_dir.join("image.png")).unwrap(); }, ); } #[test] fn width_bound_layout() { use crate::{ tests::harness::Harness, widget::{Container, Scroll}, WidgetExt, WidgetId, }; use float_cmp::assert_approx_eq; let id_1 = WidgetId::next(); let image_data = ImageBuf::from_raw( vec![255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255], ImageFormat::Rgb, 2, 2, ); let image_widget = Scroll::new(Container::new(Image::new(image_data)).with_id(id_1)).vertical(); Harness::create_simple(true, image_widget, |harness| { harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id_1); assert_approx_eq!(f64, state.layout_rect().x1, 400.0); }) } #[test] fn height_bound_layout() { use crate::{ tests::harness::Harness, widget::{Container, Scroll}, WidgetExt, WidgetId, }; use float_cmp::assert_approx_eq; let id_1 = WidgetId::next(); let image_data = ImageBuf::from_raw( vec![255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255], ImageFormat::Rgb, 2, 2, ); let image_widget = Scroll::new(Container::new(Image::new(image_data)).with_id(id_1)).horizontal(); Harness::create_simple(true, image_widget, |harness| { harness.send_initial_events(); harness.just_layout(); let state = harness.get_state(id_1); assert_approx_eq!(f64, state.layout_rect().x1, 400.0); }) } #[test] fn image_clip_area() { use crate::{tests::harness::Harness, WidgetId}; use std::iter; let _id_1 = WidgetId::next(); let image_data = ImageBuf::from_raw( vec![255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255], ImageFormat::Rgb, 2, 2, ); let image_widget = Image::new(image_data) .interpolation_mode(InterpolationMode::NearestNeighbor) .clip_area(Some(Rect::new(1., 1., 2., 2.))); Harness::create_with_render( true, image_widget, Size::new(2., 2.), |harness| { harness.send_initial_events(); harness.just_layout(); harness.paint(); }, |target| { let raw_pixels = target.into_raw(); assert_eq!(raw_pixels.len(), 4 * 4); // Because we clipped to the bottom pixel, all pixels in the final image should // match it. let expecting: Vec<u8> = iter::repeat_n(255, 16).collect(); assert_eq!(&*raw_pixels, &*expecting); }, ) } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/painter.rs
druid/src/widget/painter.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::piet::{FixedGradient, LinearGradient, PaintBrush, RadialGradient}; use crate::widget::prelude::*; use crate::{Color, Data, Key}; use tracing::instrument; /// A widget that only handles painting. /// /// This is useful in a situation where layout is controlled elsewhere and you /// do not need to handle events, but you would like to customize appearance. /// /// **When is paint called?** /// /// The `Painter` widget will call its [`paint`] method anytime its [`Data`] /// is changed. If you would like it to repaint at other times (such as when /// hot or active state changes) you will need to call [`request_paint`] further /// up the tree, perhaps in a [`Controller`] widget. /// /// # Examples /// /// Changing background color based on some part of data: /// /// ``` /// use druid::{Env, PaintCtx,Rect, RenderContext}; /// use druid::widget::Painter; /// # const ENABLED_BG_COLOR: druid::Key<druid::Color> = druid::Key::new("fake key"); /// # const DISABLED_BG_COLOR: druid::Key<druid::Color> = druid::Key::new("fake key 2"); /// /// struct MyData { is_enabled: bool } /// /// let my_painter = Painter::new(|ctx, data: &MyData, env| { /// let bounds = ctx.size().to_rect(); /// if data.is_enabled { /// ctx.fill(bounds, &env.get(ENABLED_BG_COLOR)); /// } else { /// /// ctx.fill(bounds, &env.get(DISABLED_BG_COLOR)); /// } /// }); /// ``` /// /// Using painter to make a simple widget that will draw a selected color /// /// /// ``` /// use druid::{Color, Env, PaintCtx,Rect, RenderContext}; /// use druid::widget::Painter; /// /// const CORNER_RADIUS: f64 = 4.0; /// const STROKE_WIDTH: f64 = 2.0; /// /// let colorwell: Painter<Color> = Painter::new(|ctx, data: &Color, env| { /// // Shrink the bounds a little, to ensure that our stroke remains within /// // the paint bounds. /// let bounds = ctx.size().to_rect().inset(-STROKE_WIDTH / 2.0); /// let rounded = bounds.to_rounded_rect(CORNER_RADIUS); /// ctx.fill(rounded, data); /// ctx.stroke(rounded, &env.get(druid::theme::PRIMARY_DARK), STROKE_WIDTH); /// }); /// ``` /// /// [`paint`]: Widget::paint /// [`request_paint`]: EventCtx::request_paint /// [`Controller`]: super::Controller pub struct Painter<T>(Box<dyn FnMut(&mut PaintCtx, &T, &Env)>); /// Something that can be used as the background for a widget. /// /// This represents anything that can be painted inside a widgets [`paint`] /// method; that is, it may have access to the [`Data`] and the [`Env`]. /// /// [`paint`]: Widget::paint #[non_exhaustive] #[allow(missing_docs)] pub enum BackgroundBrush<T> { Color(Color), ColorKey(Key<Color>), Linear(LinearGradient), Radial(RadialGradient), Fixed(FixedGradient), Painter(Painter<T>), } impl<T> Painter<T> { /// Create a new `Painter` with the provided [`paint`] fn. /// /// [`paint`]: Widget::paint pub fn new(f: impl FnMut(&mut PaintCtx, &T, &Env) + 'static) -> Self { Painter(Box::new(f)) } } impl<T: Data> BackgroundBrush<T> { /// Request paint if the BackgroundBrush changed. pub fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { match self { Self::ColorKey(key) if ctx.env_key_changed(key) => { ctx.request_paint(); } Self::Painter(p) => p.update(ctx, old_data, data, env), _ => (), } } /// Draw this `BackgroundBrush` into a provided [`PaintCtx`]. pub fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let bounds = ctx.size().to_rect(); match self { Self::Color(color) => ctx.fill(bounds, color), Self::ColorKey(key) => ctx.fill(bounds, &env.get(key)), Self::Linear(grad) => ctx.fill(bounds, grad), Self::Radial(grad) => ctx.fill(bounds, grad), Self::Fixed(grad) => ctx.fill(bounds, grad), Self::Painter(painter) => painter.paint(ctx, data, env), } } } impl<T: Data> Widget<T> for Painter<T> { fn event(&mut self, _: &mut EventCtx, _: &Event, _: &mut T, _: &Env) {} fn lifecycle(&mut self, _: &mut LifeCycleCtx, _: &LifeCycle, _: &T, _: &Env) {} #[instrument(name = "Painter", level = "trace", skip(self, ctx, old_data, data))] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, _: &Env) { if !old_data.same(data) { ctx.request_paint(); } } #[instrument(name = "Painter", level = "trace", skip(self, _ctx, bc))] fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints, _: &T, _: &Env) -> Size { bc.max() } #[instrument(name = "Painter", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { (self.0)(ctx, data, env) } } impl<T> From<Color> for BackgroundBrush<T> { fn from(src: Color) -> BackgroundBrush<T> { BackgroundBrush::Color(src) } } impl<T> From<Key<Color>> for BackgroundBrush<T> { fn from(src: Key<Color>) -> BackgroundBrush<T> { BackgroundBrush::ColorKey(src) } } impl<T> From<LinearGradient> for BackgroundBrush<T> { fn from(src: LinearGradient) -> BackgroundBrush<T> { BackgroundBrush::Linear(src) } } impl<T> From<RadialGradient> for BackgroundBrush<T> { fn from(src: RadialGradient) -> BackgroundBrush<T> { BackgroundBrush::Radial(src) } } impl<T> From<FixedGradient> for BackgroundBrush<T> { fn from(src: FixedGradient) -> BackgroundBrush<T> { BackgroundBrush::Fixed(src) } } impl<T> From<Painter<T>> for BackgroundBrush<T> { fn from(src: Painter<T>) -> BackgroundBrush<T> { BackgroundBrush::Painter(src) } } impl<T> From<PaintBrush> for BackgroundBrush<T> { fn from(src: PaintBrush) -> BackgroundBrush<T> { match src { PaintBrush::Linear(grad) => BackgroundBrush::Linear(grad), PaintBrush::Radial(grad) => BackgroundBrush::Radial(grad), PaintBrush::Fixed(grad) => BackgroundBrush::Fixed(grad), PaintBrush::Color(color) => BackgroundBrush::Color(color), } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/invalidation.rs
druid/src/widget/invalidation.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::debug_state::DebugState; use crate::widget::prelude::*; use crate::Data; use tracing::instrument; /// A widget that draws semi-transparent rectangles of changing colors to help debug invalidation /// regions. pub struct DebugInvalidation<T, W> { child: W, debug_color: u64, marker: std::marker::PhantomData<T>, } impl<T: Data, W: Widget<T>> DebugInvalidation<T, W> { /// Wraps a widget in a `DebugInvalidation`. pub fn new(child: W) -> Self { Self { child, debug_color: 0, marker: std::marker::PhantomData, } } } impl<T: Data, W: Widget<T>> Widget<T> for DebugInvalidation<T, W> { #[instrument( name = "DebugInvalidation", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.child.event(ctx, event, data, env); } #[instrument( name = "DebugInvalidation", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.child.lifecycle(ctx, event, data, env) } #[instrument( name = "DebugInvalidation", level = "trace", skip(self, ctx, old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.child.update(ctx, old_data, data, env); } #[instrument( name = "DebugInvalidation", level = "trace", skip(self, ctx, bc, data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, data, env) } #[instrument( name = "DebugInvalidation", level = "trace", skip(self, ctx, data, env) )] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.child.paint(ctx, data, env); let color = env.get_debug_color(self.debug_color); let stroke_width = 2.0; let region = ctx.region().rects().to_owned(); for rect in &region { let rect = rect.inset(-stroke_width / 2.0); ctx.stroke(rect, &color, stroke_width); } self.debug_color += 1; } fn id(&self) -> Option<WidgetId> { self.child.id() } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.child.debug_state(data)], ..Default::default() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/list.rs
druid/src/widget/list.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! Simple list view widget. use std::cmp::Ordering; use std::collections::VecDeque; use std::f64; use std::ops::Deref; use std::sync::Arc; use tracing::{instrument, trace}; #[cfg(feature = "im")] use crate::im::{OrdMap, Vector}; use crate::kurbo::{Point, Rect, Size}; use crate::debug_state::DebugState; use crate::{ widget::Axis, BoxConstraints, Data, Env, Event, EventCtx, KeyOrValue, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx, UpdateCtx, Widget, WidgetPod, }; /// A list widget for a variable-size collection of items. pub struct List<T> { closure: Box<dyn Fn() -> Box<dyn Widget<T>>>, children: Vec<WidgetPod<T, Box<dyn Widget<T>>>>, axis: Axis, spacing: KeyOrValue<f64>, old_bc: BoxConstraints, } impl<T: Data> List<T> { /// Create a new list widget. Closure will be called every time when a new child /// needs to be constructed. pub fn new<W: Widget<T> + 'static>(closure: impl Fn() -> W + 'static) -> Self { List { closure: Box::new(move || Box::new(closure())), children: Vec::new(), axis: Axis::Vertical, spacing: KeyOrValue::Concrete(0.), old_bc: BoxConstraints::tight(Size::ZERO), } } /// Sets the widget to display the list horizontally, not vertically. pub fn horizontal(mut self) -> Self { self.axis = Axis::Horizontal; self } /// Set the spacing between elements. pub fn with_spacing(mut self, spacing: impl Into<KeyOrValue<f64>>) -> Self { self.spacing = spacing.into(); self } /// Set the spacing between elements. pub fn set_spacing(&mut self, spacing: impl Into<KeyOrValue<f64>>) -> &mut Self { self.spacing = spacing.into(); self } /// When the widget is created or the data changes, create or remove children as needed /// /// Returns `true` if children were added or removed. fn update_child_count(&mut self, data: &impl ListIter<T>, _env: &Env) -> bool { let len = self.children.len(); match len.cmp(&data.data_len()) { Ordering::Greater => self.children.truncate(data.data_len()), Ordering::Less => data.for_each(|_, i| { if i >= len { let child = WidgetPod::new((self.closure)()); self.children.push(child); } }), Ordering::Equal => (), } len != data.data_len() } } /// This iterator enables writing List widget for any `Data`. pub trait ListIter<T>: Data { /// Iterate over each data child. fn for_each(&self, cb: impl FnMut(&T, usize)); /// Iterate over each data child. Keep track of changed data and update self. fn for_each_mut(&mut self, cb: impl FnMut(&mut T, usize)); /// Return data length. fn data_len(&self) -> usize; } #[cfg(feature = "im")] impl<T: Data> ListIter<T> for Vector<T> { fn for_each(&self, mut cb: impl FnMut(&T, usize)) { for (i, item) in self.iter().enumerate() { cb(item, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut T, usize)) { for (index, element) in self.clone().iter().enumerate() { let mut new_element = element.to_owned(); cb(&mut new_element, index); if !new_element.same(element) { self[index] = new_element; } } } fn data_len(&self) -> usize { self.len() } } //An implementation for ListIter<(K, V)> has been omitted due to problems //with how the List Widget handles the reordering of its data. #[cfg(feature = "im")] impl<K, V> ListIter<V> for OrdMap<K, V> where K: Data + Ord, V: Data, { fn for_each(&self, mut cb: impl FnMut(&V, usize)) { for (i, item) in self.iter().enumerate() { let ret = (item.0.to_owned(), item.1.to_owned()); cb(&ret.1, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut V, usize)) { for (i, item) in self.clone().iter().enumerate() { let mut ret = item.1.clone(); cb(&mut ret, i); if !item.1.same(&ret) { self[item.0] = ret; } } } fn data_len(&self) -> usize { self.len() } } // S == shared data type #[cfg(feature = "im")] impl<S: Data, T: Data> ListIter<(S, T)> for (S, Vector<T>) { fn for_each(&self, mut cb: impl FnMut(&(S, T), usize)) { for (i, item) in self.1.iter().enumerate() { let d = (self.0.to_owned(), item.to_owned()); cb(&d, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut (S, T), usize)) { for (index, element) in self.1.clone().iter().enumerate() { let mut d = (self.0.clone(), element.to_owned()); cb(&mut d, index); if !self.0.same(&d.0) { self.0 = d.0; } if !element.same(&d.1) { self.1[index] = d.1; } } } fn data_len(&self) -> usize { self.1.len() } } impl<T: Data> ListIter<T> for Arc<Vec<T>> { fn for_each(&self, mut cb: impl FnMut(&T, usize)) { for (i, item) in self.iter().enumerate() { cb(item, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut T, usize)) { let mut new_data: Option<Vec<T>> = None; for (i, item) in self.iter().enumerate() { let mut d = item.to_owned(); cb(&mut d, i); if !item.same(&d) { match &mut new_data { Some(vec) => { vec[i] = d; } None => { let mut new = (**self).clone(); new[i] = d; new_data = Some(new); } } } } if let Some(vec) = new_data { *self = Arc::new(vec); } } fn data_len(&self) -> usize { self.len() } } // S == shared data type impl<S: Data, T: Data> ListIter<(S, T)> for (S, Arc<Vec<T>>) { fn for_each(&self, mut cb: impl FnMut(&(S, T), usize)) { for (i, item) in self.1.iter().enumerate() { let d = (self.0.clone(), item.to_owned()); cb(&d, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut (S, T), usize)) { let mut new_data: Option<Vec<T>> = None; for (i, item) in self.1.iter().enumerate() { let mut d = (self.0.clone(), item.to_owned()); cb(&mut d, i); self.0 = d.0; if !item.same(&d.1) { match &mut new_data { Some(vec) => { vec[i] = d.1; } None => { let mut new = self.1.deref().clone(); new[i] = d.1; new_data = Some(new); } } } } if let Some(vec) = new_data { self.1 = Arc::new(vec); } } fn data_len(&self) -> usize { self.1.len() } } impl<T: Data> ListIter<T> for Arc<VecDeque<T>> { fn for_each(&self, mut cb: impl FnMut(&T, usize)) { for (i, item) in self.iter().enumerate() { cb(item, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut T, usize)) { let mut new_data: Option<VecDeque<T>> = None; for (i, item) in self.iter().enumerate() { let mut d = item.to_owned(); cb(&mut d, i); if !item.same(&d) { match &mut new_data { Some(vec) => { vec[i] = d; } None => { let mut new = (**self).clone(); new[i] = d; new_data = Some(new); } } } } if let Some(vec) = new_data { *self = Arc::new(vec); } } fn data_len(&self) -> usize { self.len() } } // S == shared data type impl<S: Data, T: Data> ListIter<(S, T)> for (S, Arc<VecDeque<T>>) { fn for_each(&self, mut cb: impl FnMut(&(S, T), usize)) { for (i, item) in self.1.iter().enumerate() { let d = (self.0.clone(), item.to_owned()); cb(&d, i); } } fn for_each_mut(&mut self, mut cb: impl FnMut(&mut (S, T), usize)) { let mut new_data: Option<VecDeque<T>> = None; for (i, item) in self.1.iter().enumerate() { let mut d = (self.0.clone(), item.to_owned()); cb(&mut d, i); self.0 = d.0; if !item.same(&d.1) { match &mut new_data { Some(vec) => { vec[i] = d.1; } None => { let mut new = self.1.deref().clone(); new[i] = d.1; new_data = Some(new); } } } } if let Some(vec) = new_data { self.1 = Arc::new(vec); } } fn data_len(&self) -> usize { self.1.len() } } impl<C: Data, T: ListIter<C>> Widget<T> for List<C> { #[instrument(name = "List", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { let mut children = self.children.iter_mut(); data.for_each_mut(|child_data, _| { if let Some(child) = children.next() { child.event(ctx, event, child_data, env); } }); } #[instrument(name = "List", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { if let LifeCycle::WidgetAdded = event { if self.update_child_count(data, env) { ctx.children_changed(); } } let mut children = self.children.iter_mut(); data.for_each(|child_data, _| { if let Some(child) = children.next() { child.lifecycle(ctx, event, child_data, env); } }); } #[instrument(name = "List", level = "trace", skip(self, ctx, _old_data, data, env))] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) { // we send update to children first, before adding or removing children; // this way we avoid sending update to newly added children, at the cost // of potentially updating children that are going to be removed. let mut children = self.children.iter_mut(); data.for_each(|child_data, _| { if let Some(child) = children.next() { child.update(ctx, child_data, env); } }); if self.update_child_count(data, env) { ctx.children_changed(); } if ctx.env_key_changed(&self.spacing) { ctx.request_layout(); } } #[instrument(name = "List", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { let axis = self.axis; let spacing = self.spacing.resolve(env); let mut minor = axis.minor(bc.min()); let mut major_pos = 0.0; let mut paint_rect = Rect::ZERO; let bc_changed = self.old_bc != *bc; self.old_bc = *bc; let mut children = self.children.iter_mut(); let child_bc = axis.constraints(bc, 0., f64::INFINITY); data.for_each(|child_data, _| { let child = match children.next() { Some(child) => child, None => { return; } }; let child_size = if bc_changed || child.layout_requested() { child.layout(ctx, &child_bc, child_data, env) } else { child.layout_rect().size() }; let child_pos: Point = axis.pack(major_pos, 0.).into(); child.set_origin(ctx, child_pos); paint_rect = paint_rect.union(child.paint_rect()); minor = minor.max(axis.minor(child_size)); major_pos += axis.major(child_size) + spacing; }); // correct overshoot at end. major_pos -= spacing; let my_size = bc.constrain(Size::from(axis.pack(major_pos, minor))); let insets = paint_rect - my_size.to_rect(); ctx.set_paint_insets(insets); trace!("Computed layout: size={}, insets={:?}", my_size, insets); my_size } #[instrument(name = "List", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let mut children = self.children.iter_mut(); data.for_each(|child_data, _| { if let Some(child) = children.next() { child.paint(ctx, child_data, env); } }); } fn debug_state(&self, data: &T) -> DebugState { let mut children = self.children.iter(); let mut children_state = Vec::with_capacity(data.data_len()); data.for_each(|child_data, _| { if let Some(child) = children.next() { children_state.push(child.widget().debug_state(child_data)); } }); DebugState { display_name: "List".to_string(), children: children_state, ..Default::default() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/container.rs
druid/src/widget/container.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget that provides simple visual styling options to a child. use super::BackgroundBrush; use crate::debug_state::DebugState; use crate::kurbo::RoundedRectRadii; use crate::widget::prelude::*; use crate::widget::Axis; use crate::{Color, Data, KeyOrValue, Point, WidgetPod}; use tracing::{instrument, trace, trace_span}; struct BorderStyle { width: KeyOrValue<f64>, color: KeyOrValue<Color>, } /// A widget that provides simple visual styling options to a child. pub struct Container<T> { background: Option<BackgroundBrush<T>>, foreground: Option<BackgroundBrush<T>>, border: Option<BorderStyle>, corner_radius: KeyOrValue<RoundedRectRadii>, child: WidgetPod<T, Box<dyn Widget<T>>>, } impl<T: Data> Container<T> { /// Create Container with a child pub fn new(child: impl Widget<T> + 'static) -> Self { Self { background: None, foreground: None, border: None, corner_radius: 0.0.into(), child: WidgetPod::new(child).boxed(), } } /// Builder-style method for setting the background for this widget. /// /// This can be passed anything which can be represented by a [`BackgroundBrush`]; /// notably, it can be any [`Color`], a [`Key<Color>`] resolvable in the [`Env`], /// any gradient, or a fully custom [`Painter`] widget. /// /// [`Key<Color>`]: crate::Key /// [`Painter`]: super::Painter pub fn background(mut self, brush: impl Into<BackgroundBrush<T>>) -> Self { self.set_background(brush); self } /// Set the background for this widget. /// /// This can be passed anything which can be represented by a [`BackgroundBrush`]; /// notably, it can be any [`Color`], a [`Key<Color>`] resolvable in the [`Env`], /// any gradient, or a fully custom [`Painter`] widget. /// /// [`Key<Color>`]: crate::Key /// [`Painter`]: super::Painter pub fn set_background(&mut self, brush: impl Into<BackgroundBrush<T>>) { self.background = Some(brush.into()); } /// Clears background. pub fn clear_background(&mut self) { self.background = None; } /// Builder-style method for setting the foreground for this widget. /// /// This can be passed anything which can be represented by a [`BackgroundBrush`]; /// notably, it can be any [`Color`], a [`Key<Color>`] resolvable in the [`Env`], /// any gradient, or a fully custom [`Painter`] widget. /// /// [`Key<Color>`]: crate::Key /// [`Painter`]: super::Painter pub fn foreground(mut self, brush: impl Into<BackgroundBrush<T>>) -> Self { self.set_foreground(brush); self } /// Set the foreground for this widget. /// /// This can be passed anything which can be represented by a [`BackgroundBrush`]; /// notably, it can be any [`Color`], a [`Key<Color>`] resolvable in the [`Env`], /// any gradient, or a fully custom [`Painter`] widget. /// /// [`Key<Color>`]: crate::Key /// [`Painter`]: super::Painter pub fn set_foreground(&mut self, brush: impl Into<BackgroundBrush<T>>) { self.foreground = Some(brush.into()); } /// Clears foreground. pub fn clear_foreground(&mut self) { self.foreground = None; } /// Builder-style method for painting a border around the widget with a color and width. /// /// Arguments can be either concrete values, or a [`Key`] of the respective /// type. /// /// [`Key`]: crate::Key pub fn border( mut self, color: impl Into<KeyOrValue<Color>>, width: impl Into<KeyOrValue<f64>>, ) -> Self { self.set_border(color, width); self } /// Paint a border around the widget with a color and width. /// /// Arguments can be either concrete values, or a [`Key`] of the respective /// type. /// /// [`Key`]: crate::Key pub fn set_border( &mut self, color: impl Into<KeyOrValue<Color>>, width: impl Into<KeyOrValue<f64>>, ) { self.border = Some(BorderStyle { color: color.into(), width: width.into(), }); } /// Clears border. pub fn clear_border(&mut self) { self.border = None; } /// Builder style method for rounding off corners of this container by setting a corner radius pub fn rounded(mut self, radius: impl Into<KeyOrValue<RoundedRectRadii>>) -> Self { self.set_rounded(radius); self } /// Round off corners of this container by setting a corner radius pub fn set_rounded(&mut self, radius: impl Into<KeyOrValue<RoundedRectRadii>>) { self.corner_radius = radius.into(); } #[cfg(test)] pub(crate) fn background_is_some(&self) -> bool { self.background.is_some() } #[cfg(test)] pub(crate) fn foreground_is_some(&self) -> bool { self.foreground.is_some() } #[cfg(test)] pub(crate) fn border_is_some(&self) -> bool { self.border.is_some() } } impl<T: Data> Widget<T> for Container<T> { #[instrument(name = "Container", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.child.event(ctx, event, data, env); } #[instrument(name = "Container", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.child.lifecycle(ctx, event, data, env) } #[instrument( name = "Container", level = "trace", skip(self, ctx, old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { if let Some(brush) = self.background.as_mut() { trace_span!("update background").in_scope(|| { brush.update(ctx, old_data, data, env); }); } if let Some(brush) = self.foreground.as_mut() { trace_span!("update foreground").in_scope(|| { brush.update(ctx, old_data, data, env); }); } if let Some(border) = &self.border { if ctx.env_key_changed(&border.width) { ctx.request_layout(); } if ctx.env_key_changed(&border.color) { ctx.request_paint(); } } if ctx.env_key_changed(&self.corner_radius) { ctx.request_paint(); } self.child.update(ctx, data, env); } #[instrument(name = "Container", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("Container"); // Shrink constraints by border offset let border_width = match &self.border { Some(border) => border.width.resolve(env), None => 0.0, }; let child_bc = bc.shrink((2.0 * border_width, 2.0 * border_width)); let size = self.child.layout(ctx, &child_bc, data, env); let origin = Point::new(border_width, border_width); self.child.set_origin(ctx, origin); let my_size = Size::new( size.width + 2.0 * border_width, size.height + 2.0 * border_width, ); let my_insets = self.child.compute_parent_paint_insets(my_size); ctx.set_paint_insets(my_insets); let baseline_offset = self.child.baseline_offset(); if baseline_offset > 0f64 { ctx.set_baseline_offset(baseline_offset + border_width); } trace!("Computed layout: size={}, insets={:?}", my_size, my_insets); my_size } #[instrument(name = "Container", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let corner_radius = self.corner_radius.resolve(env); if let Some(background) = self.background.as_mut() { let panel = ctx.size().to_rounded_rect(corner_radius); trace_span!("paint background").in_scope(|| { ctx.with_save(|ctx| { ctx.clip(panel); background.paint(ctx, data, env); }); }); } if let Some(border) = &self.border { let border_width = border.width.resolve(env); let border_rect = ctx .size() .to_rect() .inset(border_width / -2.0) .to_rounded_rect(corner_radius); ctx.stroke(border_rect, &border.color.resolve(env), border_width); }; self.child.paint(ctx, data, env); if let Some(foreground) = self.foreground.as_mut() { let panel = ctx.size().to_rounded_rect(corner_radius); trace_span!("paint foreground").in_scope(|| { ctx.with_save(|ctx| { ctx.clip(panel); foreground.paint(ctx, data, env); }); }); } } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.child.widget().debug_state(data)], ..Default::default() } } fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64 { let container_width = match &self.border { Some(border) => border.width.resolve(env), None => 0.0, }; let child_bc = bc.shrink((2.0 * container_width, 2.0 * container_width)); let child_size = self .child .widget_mut() .compute_max_intrinsic(axis, ctx, &child_bc, data, env); let border_width_on_both_sides = container_width * 2.; child_size + border_width_on_both_sides } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/env_scope.rs
druid/src/widget/env_scope.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget that accepts a closure to update the environment for its child. use crate::debug_state::DebugState; use crate::widget::prelude::*; use crate::widget::WidgetWrapper; use crate::{Data, Point, WidgetPod}; use tracing::instrument; /// A widget that accepts a closure to update the environment for its child. pub struct EnvScope<T, W> { pub(crate) f: Box<dyn Fn(&mut Env, &T)>, pub(crate) child: WidgetPod<T, W>, } impl<T, W: Widget<T>> EnvScope<T, W> { /// Create a widget that updates the environment for its descendants. /// /// Accepts a closure that sets Env values. /// /// This is available as [`WidgetExt::env_scope`] for convenience. /// /// # Examples /// ``` /// # use druid::{theme, Widget}; /// # use druid::piet::{Color}; /// # use druid::widget::{Label, EnvScope}; /// # fn build_widget() -> impl Widget<String> { /// EnvScope::new( /// |env, data| { /// env.set(theme::TEXT_COLOR, Color::WHITE); /// }, /// Label::new("White text!") /// ) /// /// # } /// ``` /// /// [`WidgetExt::env_scope`]: super::WidgetExt::env_scope pub fn new(f: impl Fn(&mut Env, &T) + 'static, child: W) -> EnvScope<T, W> { EnvScope { f: Box::new(f), child: WidgetPod::new(child), } } } impl<T: Data, W: Widget<T>> Widget<T> for EnvScope<T, W> { #[instrument(name = "EnvScope", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { let mut new_env = env.clone(); (self.f)(&mut new_env, data); self.child.event(ctx, event, data, &new_env) } #[instrument(name = "EnvScope", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { let mut new_env = env.clone(); (self.f)(&mut new_env, data); self.child.lifecycle(ctx, event, data, &new_env) } #[instrument( name = "EnvScope", level = "trace", skip(self, ctx, _old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) { let mut new_env = env.clone(); (self.f)(&mut new_env, data); self.child.update(ctx, data, &new_env); } #[instrument(name = "EnvScope", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("EnvScope"); let mut new_env = env.clone(); (self.f)(&mut new_env, data); let size = self.child.layout(ctx, bc, data, &new_env); self.child.set_origin(ctx, Point::ORIGIN); size } #[instrument(name = "EnvScope", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let mut new_env = env.clone(); (self.f)(&mut new_env, data); self.child.paint(ctx, data, &new_env); } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.child.widget().debug_state(data)], ..Default::default() } } } impl<T, W: Widget<T>> WidgetWrapper for EnvScope<T, W> { widget_wrapper_pod_body!(W, child); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/stepper.rs
druid/src/widget/stepper.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A stepper widget. use std::time::Duration; use tracing::{instrument, trace}; use crate::debug_state::DebugState; use crate::kurbo::BezPath; use crate::piet::{LinearGradient, RenderContext, UnitPoint}; use crate::widget::prelude::*; use crate::{theme, Point, Rect, TimerToken}; // Delay until stepper starts automatically changing value when one of the buttons is held down. const STEPPER_REPEAT_DELAY: Duration = Duration::from_millis(500); // Delay between value changes when one of the buttons is held down. const STEPPER_REPEAT: Duration = Duration::from_millis(200); /// A stepper widget for step-wise increasing and decreasing a value. pub struct Stepper { max: f64, min: f64, step: f64, wrap: bool, /// Keeps track of which button is currently triggered. increase_active: bool, decrease_active: bool, timer_id: TimerToken, } impl Stepper { /// Create a new `Stepper`. pub fn new() -> Self { Stepper { max: f64::MAX, min: f64::MIN, step: 1.0, wrap: false, increase_active: false, decrease_active: false, timer_id: TimerToken::INVALID, } } /// Set the range covered by this slider. /// /// The default range is `std::f64::MIN..std::f64::MAX`. pub fn with_range(mut self, min: f64, max: f64) -> Self { self.min = min; self.max = max; self } /// Set the steppers amount by which the value increases or decreases. /// /// The default step is `1.0`. pub fn with_step(mut self, step: f64) -> Self { self.step = step; self } /// Set whether the stepper should wrap around the minimum/maximum values. /// /// When wraparound is enabled incrementing above max behaves like this: /// - if the previous value is < max it becomes max /// - if the previous value is = max it becomes min /// /// Same logic applies for decrementing. /// /// The default is `false`. pub fn with_wraparound(mut self, wrap: bool) -> Self { self.wrap = wrap; self } fn increment(&mut self, data: &mut f64) { let next = *data + self.step; let was_greater = *data + f64::EPSILON >= self.max; let is_greater = next + f64::EPSILON > self.max; *data = match (self.wrap, was_greater, is_greater) { (true, true, true) => self.min, (true, false, true) => self.max, (false, _, true) => self.max, _ => next, } } fn decrement(&mut self, data: &mut f64) { let next = *data - self.step; let was_less = *data - f64::EPSILON <= self.min; let is_less = next - f64::EPSILON < self.min; *data = match (self.wrap, was_less, is_less) { (true, true, true) => self.max, (true, false, true) => self.min, (false, _, true) => self.min, _ => next, } } } impl Default for Stepper { fn default() -> Self { Self::new() } } impl Widget<f64> for Stepper { #[instrument(name = "Stepper", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &f64, env: &Env) { let stroke_width = 2.0; let rounded_rect = ctx .size() .to_rect() .inset(-stroke_width / 2.0) .to_rounded_rect(4.0); let height = ctx.size().height; let width = env.get(theme::BASIC_WIDGET_HEIGHT); let button_size = Size::new(width, height / 2.); ctx.stroke(rounded_rect, &env.get(theme::BORDER_DARK), stroke_width); ctx.clip(rounded_rect); // draw buttons for increase/decrease let increase_button_origin = Point::ORIGIN; let decrease_button_origin = Point::new(0., height / 2.0); let increase_button_rect = Rect::from_origin_size(increase_button_origin, button_size); let decrease_button_rect = Rect::from_origin_size(decrease_button_origin, button_size); let disabled_gradient = LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, ( env.get(theme::DISABLED_BUTTON_LIGHT), env.get(theme::DISABLED_BUTTON_DARK), ), ); let active_gradient = LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, (env.get(theme::PRIMARY_LIGHT), env.get(theme::PRIMARY_DARK)), ); let inactive_gradient = LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, (env.get(theme::BUTTON_DARK), env.get(theme::BUTTON_LIGHT)), ); // draw buttons that are currently triggered as active if ctx.is_disabled() { ctx.fill(increase_button_rect, &disabled_gradient); } else if self.increase_active { ctx.fill(increase_button_rect, &active_gradient); } else { ctx.fill(increase_button_rect, &inactive_gradient); }; if ctx.is_disabled() { ctx.fill(decrease_button_rect, &disabled_gradient); } else if self.decrease_active { ctx.fill(decrease_button_rect, &active_gradient); } else { ctx.fill(decrease_button_rect, &inactive_gradient); }; // draw up and down triangles let mut arrows = BezPath::new(); arrows.move_to(Point::new(4., height / 2. - 4.)); arrows.line_to(Point::new(width - 4., height / 2. - 4.)); arrows.line_to(Point::new(width / 2., 4.)); arrows.close_path(); arrows.move_to(Point::new(4., height / 2. + 4.)); arrows.line_to(Point::new(width - 4., height / 2. + 4.)); arrows.line_to(Point::new(width / 2., height - 4.)); arrows.close_path(); let color = if ctx.is_disabled() { env.get(theme::DISABLED_TEXT_COLOR) } else { env.get(theme::TEXT_COLOR) }; ctx.fill(arrows, &color); } #[instrument( name = "Stepper", level = "trace", skip(self, _layout_ctx, bc, _data, env) )] fn layout( &mut self, _layout_ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &f64, env: &Env, ) -> Size { let size = bc.constrain(Size::new( env.get(theme::BASIC_WIDGET_HEIGHT), env.get(theme::BORDERED_WIDGET_HEIGHT), )); trace!("Computed size: {}", size); size } #[instrument(name = "Stepper", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env) { let height = env.get(theme::BORDERED_WIDGET_HEIGHT); match event { Event::MouseDown(mouse) => { if !ctx.is_disabled() { ctx.set_active(true); if mouse.pos.y > height / 2. { self.decrease_active = true; self.decrement(data); } else { self.increase_active = true; self.increment(data); } self.timer_id = ctx.request_timer(STEPPER_REPEAT_DELAY); ctx.request_paint(); } } Event::MouseUp(_) => { ctx.set_active(false); self.decrease_active = false; self.increase_active = false; self.timer_id = TimerToken::INVALID; ctx.request_paint(); } Event::Timer(id) if *id == self.timer_id => { if !ctx.is_disabled() { if self.increase_active { self.increment(data); } if self.decrease_active { self.decrement(data); } self.timer_id = ctx.request_timer(STEPPER_REPEAT); } else { ctx.set_active(false); } } _ => (), } } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &f64, _env: &Env) { if let LifeCycle::DisabledChanged(_) = event { ctx.request_paint(); } } #[instrument( name = "Stepper", level = "trace", skip(self, ctx, old_data, data, _env) )] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &f64, data: &f64, _env: &Env) { if (*data - old_data).abs() > f64::EPSILON { ctx.request_paint(); } } fn debug_state(&self, data: &f64) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), main_value: data.to_string(), ..Default::default() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/aspect_ratio_box.rs
druid/src/widget/aspect_ratio_box.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::debug_state::DebugState; use crate::widget::Axis; use druid::widget::prelude::*; use druid::Data; use tracing::{instrument, warn}; /// A widget that preserves the aspect ratio given to it. /// /// If given a child, this widget forces the child to have a width and height that preserves /// the aspect ratio. /// /// If not given a child, The box will try to size itself as large or small as possible /// to preserve the aspect ratio. pub struct AspectRatioBox<T> { child: Box<dyn Widget<T>>, ratio: f64, } impl<T> AspectRatioBox<T> { /// Create container with a child and aspect ratio. /// /// The aspect ratio is defined as width / height. /// /// If aspect ratio <= 0.0, the ratio will be set to 1.0 pub fn new(child: impl Widget<T> + 'static, ratio: f64) -> Self { Self { child: Box::new(child), ratio: clamp_ratio(ratio), } } /// Set the ratio of the box. /// /// The ratio has to be a value between 0 and f64::MAX, excluding 0. It will be clamped /// to those values if they exceed the bounds. If the ratio is 0, then the ratio /// will become 1. pub fn set_ratio(&mut self, ratio: f64) { self.ratio = clamp_ratio(ratio); } /// Generate `BoxConstraints` that fit within the provided `BoxConstraints`. /// /// If the generated constraints do not fit then they are constrained to the /// provided `BoxConstraints`. fn generate_constraints(&self, bc: &BoxConstraints) -> BoxConstraints { let (mut new_width, mut new_height) = (bc.max().width, bc.max().height); if new_width == f64::INFINITY { new_width = new_height * self.ratio; } else { new_height = new_width / self.ratio; } if new_width > bc.max().width { new_width = bc.max().width; new_height = new_width / self.ratio; } if new_height > bc.max().height { new_height = bc.max().height; new_width = new_height * self.ratio; } if new_width < bc.min().width { new_width = bc.min().width; new_height = new_width / self.ratio; } if new_height < bc.min().height { new_height = bc.min().height; new_width = new_height * self.ratio; } BoxConstraints::tight(bc.constrain(Size::new(new_width, new_height))) } } /// Clamps the ratio between 0.0 and f64::MAX /// If ratio is 0.0 then it will return 1.0 to avoid creating NaN fn clamp_ratio(mut ratio: f64) -> f64 { ratio = f64::clamp(ratio, 0.0, f64::MAX); if ratio == 0.0 { warn!("Provided ratio was <= 0.0."); 1.0 } else { ratio } } impl<T: Data> Widget<T> for AspectRatioBox<T> { #[instrument( name = "AspectRatioBox", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.child.event(ctx, event, data, env); } #[instrument( name = "AspectRatioBox", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.child.lifecycle(ctx, event, data, env) } #[instrument( name = "AspectRatioBox", level = "trace", skip(self, ctx, old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.child.update(ctx, old_data, data, env); } #[instrument( name = "AspectRatioBox", level = "trace", skip(self, ctx, bc, data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("AspectRatioBox"); if bc.max() == bc.min() { warn!("Box constraints are tight. Aspect ratio box will not be able to preserve aspect ratio."); return self.child.layout(ctx, bc, data, env); } if bc.max().width == f64::INFINITY && bc.max().height == f64::INFINITY { warn!("Box constraints are INFINITE. Aspect ratio box won't be able to choose a size because the constraints given by the parent widget are INFINITE."); return self.child.layout(ctx, bc, data, env); } let bc = self.generate_constraints(bc); self.child.layout(ctx, &bc, data, env) } #[instrument(name = "AspectRatioBox", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.child.paint(ctx, data, env); } fn id(&self) -> Option<WidgetId> { self.child.id() } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.child.debug_state(data)], ..Default::default() } } fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64 { match axis { Axis::Horizontal => { if bc.is_height_bounded() { bc.max().height * self.ratio } else { self.child.compute_max_intrinsic(axis, ctx, bc, data, env) } } Axis::Vertical => { if bc.is_width_bounded() { bc.max().width / self.ratio } else { self.child.compute_max_intrinsic(axis, ctx, bc, data, env) } } } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/slider.rs
druid/src/widget/slider.rs
// Copyright 2019 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A slider widget. use crate::debug_state::DebugState; use crate::kurbo::{Circle, Line}; use crate::theme::TEXT_COLOR; use crate::widget::prelude::*; use crate::widget::Axis; use crate::{theme, Color, KeyOrValue, LinearGradient, Point, Rect, UnitPoint, Vec2, WidgetPod}; use druid::kurbo::{PathEl, Shape}; use druid::piet::{PietText, PietTextLayout, Text, TextLayout, TextLayoutBuilder}; use tracing::{instrument, trace, warn}; const TRACK_THICKNESS: f64 = 4.0; const BORDER_WIDTH: f64 = 2.0; const KNOB_STROKE_WIDTH: f64 = 2.0; /// A slider, allowing interactive update of a numeric value. /// /// This slider implements `Widget<f64>`, and works on values clamped /// in the range `min..max`. #[derive(Debug, Clone, Default)] pub struct Slider { mapping: SliderValueMapping, knob: SliderKnob, track_color: Option<KeyOrValue<Color>>, knob_style: KnobStyle, } /// A range slider, allowing interactive update of two numeric values . /// /// This slider implements `Widget<(f64, f64)>`, and works on value pairs clamped /// in the range `min..max`, where the left value is always smaller than the right. #[derive(Debug, Clone, Default)] pub struct RangeSlider { mapping: SliderValueMapping, left_knob: SliderKnob, right_knob: SliderKnob, track_color: Option<KeyOrValue<Color>>, knob_style: KnobStyle, } /// A annotated Slider or RangeSlider pub struct Annotated<T, W: Widget<T>> { inner: WidgetPod<T, W>, mapping: SliderValueMapping, labeled_steps: f64, unlabeled_steps: f64, labels: Vec<PietTextLayout>, } #[derive(Copy, Clone, Debug)] pub struct SliderValueMapping { min: f64, max: f64, step: Option<f64>, axis: Axis, } #[derive(Debug, Clone, Default)] struct SliderKnob { hovered: bool, active: bool, offset: f64, } /// The shape of the slider knobs. #[derive(Default, Debug, Copy, Clone)] pub enum KnobStyle { /// Circle #[default] Circle, /// Wedge Wedge, } impl Slider { /// Create a new `Slider`. pub fn new() -> Slider { Default::default() } /// Builder-style method to set the range covered by this slider. /// /// The default range is `0.0..1.0`. pub fn with_range(mut self, min: f64, max: f64) -> Self { self.mapping.min = min; self.mapping.max = max; self } /// Builder-style method to set the stepping. /// /// The default step size is `0.0` (smooth). pub fn with_step(mut self, step: f64) -> Self { if step < 0.0 { warn!("bad stepping (must be positive): {}", step); return self; } self.mapping.step = if step > 0.0 { Some(step) } else { // A stepping value of 0.0 would yield an infinite amount of steps. // Enforce no stepping instead. None }; self } /// Builder-style method to set the track color. /// /// The default color is `None`. pub fn track_color(mut self, color: impl Into<Option<KeyOrValue<Color>>>) -> Self { self.track_color = color.into(); self } /// Builder-style method to set the knob style. /// /// The default is `Circle`. pub fn knob_style(mut self, knob_style: KnobStyle) -> Self { self.knob_style = knob_style; self } /// Builder-style method to the axis on which the slider moves. /// /// The default is `Horizontal`. pub fn axis(mut self, axis: Axis) -> Self { self.mapping.axis = axis; self } /// Returns the Mapping of this Slider. pub fn get_mapping(&self) -> SliderValueMapping { self.mapping } /// Builder-style method to create an annotated range slider. /// pub fn annotated(self, named_steps: f64, unnamed_steps: f64) -> Annotated<f64, Self> { let mapping = self.mapping; Annotated::new(self, mapping, named_steps, unnamed_steps) } } impl Widget<f64> for Slider { #[instrument(name = "Slider", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env) { if !ctx.is_disabled() { self.knob .handle_input(ctx, event, data, env, self.mapping, self.knob_style); ctx.set_active(self.knob.is_active()); if let Event::MouseDown(me) = event { if !self.knob.active { self.knob.activate(0.0); let knob_size = env.get(theme::BASIC_WIDGET_HEIGHT); *data = self .mapping .calculate_value(me.pos, knob_size, ctx.size(), 0.0); ctx.request_paint(); ctx.set_active(true); } } } } #[instrument(name = "Slider", level = "trace", skip(self, ctx, event, _data, _env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &f64, _env: &Env) { match event { // checked in LifeCycle::WidgetAdded because logging may not be setup in with_range LifeCycle::WidgetAdded => self.mapping.check_range(), LifeCycle::DisabledChanged(_) => ctx.request_paint(), _ => (), } } #[instrument( name = "Slider", level = "trace", skip(self, ctx, _old_data, _data, _env) )] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &f64, _data: &f64, _env: &Env) { ctx.request_paint(); } #[instrument(name = "Slider", level = "trace", skip(self, ctx, bc, _data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &f64, env: &Env) -> Size { bc.debug_check("Slider"); slider_layout(ctx, bc, env, self.mapping) } #[instrument(name = "Slider", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) { paint_slider_background(ctx, 0.0, *data, &self.track_color, self.mapping, env); self.knob .paint(ctx, *data, env, self.mapping, self.knob_style); } fn debug_state(&self, data: &f64) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), main_value: data.to_string(), ..Default::default() } } } impl RangeSlider { /// Create a new `RangeSlider`. pub fn new() -> RangeSlider { Default::default() } /// Builder-style method to set the range covered by this range slider. /// /// The default range is `0.0..1.0`. pub fn with_range(mut self, min: f64, max: f64) -> Self { self.mapping.min = min; self.mapping.max = max; self } /// Builder-style method to set the stepping. /// /// The default step size is `0.0` (smooth). pub fn with_step(mut self, step: f64) -> Self { if step < 0.0 { warn!("bad stepping (must be positive): {}", step); return self; } self.mapping.step = if step > 0.0 { Some(step) } else { // A stepping value of 0.0 would yield an infinite amount of steps. // Enforce no stepping instead. None }; self } /// Builder-style method to set the track color. /// /// The default color is `None`. pub fn track_color(mut self, color: impl Into<Option<KeyOrValue<Color>>>) -> Self { self.track_color = color.into(); self } /// Builder-style method to set the knob style. /// /// The default is `Circle`. pub fn knob_style(mut self, knob_style: KnobStyle) -> Self { self.knob_style = knob_style; self } /// Builder-style method to set the axis on which the slider moves. /// /// The default is `Horizontal`. pub fn axis(mut self, axis: Axis) -> Self { self.mapping.axis = axis; self } /// Returns the Mapping of this Slider. pub fn get_mapping(&self) -> SliderValueMapping { self.mapping } /// Builder-style method to create an annotated range slider. /// pub fn annotated(self, named_steps: f64, unnamed_steps: f64) -> Annotated<(f64, f64), Self> { let mapping = self.mapping; Annotated::new(self, mapping, named_steps, unnamed_steps) } } impl Widget<(f64, f64)> for RangeSlider { #[instrument( name = "RangeSlider", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut (f64, f64), env: &Env) { if !ctx.is_disabled() { if !self.right_knob.is_active() { self.left_knob.handle_input( ctx, event, &mut data.0, env, self.mapping, self.knob_style, ); data.0 = data.0.min(data.1); //Ensure that the left knob stays left if self.left_knob.is_active() { self.right_knob.deactivate(); } } if !self.left_knob.is_active() { self.right_knob.handle_input( ctx, event, &mut data.1, env, self.mapping, self.knob_style, ); //Ensure that the right knob stays right data.1 = data.1.max(data.0); if self.right_knob.is_active() { self.left_knob.deactivate(); } } ctx.set_active(self.left_knob.is_active() || self.right_knob.is_active()); if let Event::MouseDown(me) = event { if !self.left_knob.is_active() && !self.right_knob.is_active() { let knob_size = env.get(theme::BASIC_WIDGET_HEIGHT); let press_value = self.mapping .calculate_value(me.pos, knob_size, ctx.size(), 0.0); if press_value - data.0 < data.1 - press_value { self.left_knob.activate(0.0); data.0 = press_value; } else { self.right_knob.activate(0.0); data.1 = press_value; } ctx.set_active(true); ctx.request_paint(); } } } } #[instrument( name = "RangeSlider", level = "trace", skip(self, ctx, event, _data, _env) )] fn lifecycle( &mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, _data: &(f64, f64), _env: &Env, ) { match event { // checked in LifeCycle::WidgetAdded because logging may not be setup in with_range LifeCycle::WidgetAdded => self.mapping.check_range(), LifeCycle::DisabledChanged(_) => ctx.request_paint(), _ => (), } } #[instrument( name = "RangeSlider", level = "trace", skip(self, ctx, _old_data, _data, _env) )] fn update( &mut self, ctx: &mut UpdateCtx, _old_data: &(f64, f64), _data: &(f64, f64), _env: &Env, ) { ctx.request_paint(); } #[instrument(name = "RangeSlider", level = "trace", skip(self, ctx, bc, _data, env))] fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &(f64, f64), env: &Env, ) -> Size { bc.debug_check("Slider"); slider_layout(ctx, bc, env, self.mapping) } #[instrument(name = "RangeSlider", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &(f64, f64), env: &Env) { paint_slider_background(ctx, data.0, data.1, &self.track_color, self.mapping, env); // We paint the left knob at last since it receives events first and therefore behaves like // being "on top". self.right_knob .paint(ctx, data.1, env, self.mapping, self.knob_style); self.left_knob .paint(ctx, data.0, env, self.mapping, self.knob_style); } fn debug_state(&self, data: &(f64, f64)) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), main_value: format!("{data:?}"), ..Default::default() } } } impl<T, W: Widget<T>> Annotated<T, W> { pub fn new( inner: W, mapping: SliderValueMapping, labeled_steps: f64, unlabeled_steps: f64, ) -> Self { Annotated { inner: WidgetPod::new(inner), mapping, labeled_steps: labeled_steps.abs(), unlabeled_steps: unlabeled_steps.abs(), labels: Vec::new(), } } fn sanitise_values(&mut self) { let labeled = self.mapping.range() / self.labeled_steps; if !labeled.is_finite() || labeled > 100.0 { warn!("Annotated: provided labeled interval \"{}\" has too many steps inside the sliders range {}..{}", self.labeled_steps, self.mapping.min, self.mapping.max); self.labeled_steps = self.mapping.range() / 5.0; } let unlabeled = self.mapping.range() / self.unlabeled_steps; if !unlabeled.is_finite() || unlabeled > 10000.0 { warn!("Annotated: provided unlabeled interval \"{}\" has too many steps inside the sliders range {}..{}", self.unlabeled_steps, self.mapping.min, self.mapping.max); self.unlabeled_steps = self.mapping.range() / 20.0; } } fn build_labels(&mut self, text: &mut PietText, text_color: Color) { self.labels.clear(); let mut walk = self.mapping.min; while walk < self.mapping.max + f64::EPSILON * 10.0 { let layout = text .new_text_layout(format!("{walk}")) .text_color(text_color) .build() .unwrap(); self.labels.push(layout); walk += self.labeled_steps; } } fn line_dir(&self) -> Vec2 { match self.mapping.axis { Axis::Horizontal => Vec2::new(0.0, 1.0), Axis::Vertical => Vec2::new(-1.0, 0.0), } } } impl<T: Data, W: Widget<T>> Widget<T> for Annotated<T, W> { #[instrument(name = "Annotated", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.inner.event(ctx, event, data, env); } #[instrument(name = "Annotated", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { if let LifeCycle::WidgetAdded = event { self.sanitise_values(); self.build_labels(ctx.text(), env.get(TEXT_COLOR)); } self.inner.lifecycle(ctx, event, data, env); } #[instrument( name = "Annotated", level = "trace", skip(self, ctx, _old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) { self.inner.update(ctx, data, env); if ctx.env_key_changed(&TEXT_COLOR) { self.build_labels(ctx.text(), env.get(TEXT_COLOR)); ctx.request_paint(); } } #[instrument(name = "Annotated", level = "trace", skip(self, bc, ctx, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { let label_size = Size::new(40.0, 20.0); match self.mapping.axis { Axis::Vertical => { let child_bc = bc.shrink((label_size.width, 0.0)); let child_size = self.inner.layout(ctx, &child_bc, data, env); self.inner .set_origin(ctx, Point::new(label_size.width, 0.0)); Size::new(child_size.width + label_size.width, child_size.height) } Axis::Horizontal => { let child_bc = bc.shrink((0.0, label_size.height)); let child_size = self.inner.layout(ctx, &child_bc, data, env); self.inner.set_origin(ctx, Point::ZERO); ctx.set_baseline_offset(self.inner.baseline_offset() + label_size.height); Size::new(child_size.width, child_size.height + label_size.height) } } } #[instrument(name = "Annotated", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let short_stroke = 3.0; let long_stroke = 6.0; let stroke_offset = 6.0; let slider_offset = Point::new(self.inner.layout_rect().x0, self.inner.layout_rect().y0); let knob_size = env.get(theme::BASIC_WIDGET_HEIGHT); let slider_size = self.inner.layout_rect().size(); let text_color = env.get(TEXT_COLOR); let mut walk = self.mapping.min; while walk < self.mapping.max + f64::EPSILON * 10.0 { let center = self .mapping .get_point(walk, knob_size, slider_size) .to_vec2() + slider_offset.to_vec2(); let line = Line::new( (center + self.line_dir() * stroke_offset).to_point(), (center + self.line_dir() * (stroke_offset + short_stroke)).to_point(), ); ctx.stroke(line, &text_color, 1.0); walk += self.unlabeled_steps; } let mut walk = self.mapping.min; let mut labels = self.labels.iter(); while walk < self.mapping.max + f64::EPSILON * 10.0 { let center = self .mapping .get_point(walk, knob_size, slider_size) .to_vec2() + slider_offset.to_vec2(); let line = Line::new( (center + self.line_dir() * stroke_offset).to_point(), (center + self.line_dir() * (stroke_offset + long_stroke)).to_point(), ); ctx.stroke(line, &text_color, 1.0); let label = labels.next().unwrap(); let origin = match self.mapping.axis { Axis::Horizontal => Vec2::new(label.size().width / 2.0, 0.0), Axis::Vertical => Vec2::new(label.size().width, label.size().height / 2.0), }; ctx.draw_text( label, (center + self.line_dir() * (stroke_offset + long_stroke) - origin).to_point(), ); walk += self.labeled_steps; } self.inner.paint(ctx, data, env); } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: "Annotated".to_string(), children: vec![self.inner.widget().debug_state(data)], ..Default::default() } } } impl SliderValueMapping { pub fn new() -> Self { Self { min: 0.0, max: 1.0, step: None, axis: Axis::Horizontal, } } fn calculate_value( &self, mouse_pos: Point, knob_size: f64, slider_size: Size, offset: f64, ) -> f64 { // The vertical slider has its lowest value at the bottom. let mouse_pos = Point::new(mouse_pos.x, slider_size.height - mouse_pos.y); let scalar = (self.axis.major_pos(mouse_pos) - knob_size / 2.) / (self.axis.major(slider_size) - knob_size); let mut value = (self.min + scalar * (self.max - self.min) + offset).clamp(self.min, self.max); if let Some(step) = self.step { let max_step_value = ((self.max - self.min) / step).floor() * step + self.min; if value > max_step_value { // edge case: make sure max is reachable let left_dist = value - max_step_value; let right_dist = self.max - value; value = if left_dist < right_dist { max_step_value } else { self.max }; } else { // snap to discrete intervals value = (((value - self.min) / step).round() * step + self.min).min(self.max); } } value } fn get_point(&self, value: f64, knob_size: f64, widget_size: Size) -> Point { let knob_major = (self.axis.major(widget_size) - knob_size) * self.normalize(value) + knob_size / 2.; let (w, h) = self.axis.pack(knob_major, knob_size / 2.); Point::new(w, widget_size.height - h) } fn normalize(&self, data: f64) -> f64 { (data.clamp(self.min, self.max) - self.min) / (self.max - self.min) } /// check self.min <= self.max, if not swaps the values. fn check_range(&mut self) { if self.max < self.min { warn!( "min({}) should be less than max({}), swapping the values", self.min, self.max ); std::mem::swap(&mut self.max, &mut self.min); } } /// the distance between min and max fn range(&self) -> f64 { self.max - self.min } } impl Default for SliderValueMapping { fn default() -> Self { SliderValueMapping { min: 0.0, max: 1.0, step: None, axis: Axis::Horizontal, } } } impl SliderKnob { fn handle_input( &mut self, ctx: &mut EventCtx, event: &Event, data: &mut f64, env: &Env, mapping: SliderValueMapping, knob_style: KnobStyle, ) { let knob_size = env.get(theme::BASIC_WIDGET_HEIGHT); let slider_size = ctx.size(); let point_to_val = |point: Point, offset: f64| { mapping.calculate_value(point, knob_size, slider_size, offset) }; let hit_test = |val: &mut f64, mouse_pos: Point| { let center = mapping.get_point(*val, knob_size, slider_size); match knob_style { KnobStyle::Circle => center.distance(mouse_pos) < knob_size, KnobStyle::Wedge => { (&knob_wedge(center, knob_size, mapping.axis)[..]).winding(mouse_pos) != 0 } } }; match event { Event::MouseDown(mouse) => { if !ctx.is_disabled() && hit_test(data, mouse.pos) { self.offset = *data - point_to_val(mouse.pos, 0.0); self.active = true; ctx.request_paint(); } } Event::MouseUp(mouse) => { if self.active && !ctx.is_disabled() { *data = point_to_val(mouse.pos, self.offset); ctx.request_paint(); } self.active = false; } Event::MouseMove(mouse) => { if !ctx.is_disabled() { if self.active { *data = point_to_val(mouse.pos, self.offset); ctx.request_paint(); } if ctx.is_hot() { let knob_hover = hit_test(data, mouse.pos); if knob_hover != self.hovered { self.hovered = knob_hover; ctx.request_paint(); } } } else { self.active = false } } _ => (), } } fn deactivate(&mut self) { self.hovered = false; self.active = false; } fn activate(&mut self, x_offset: f64) { self.hovered = true; self.active = true; self.offset = x_offset; } fn is_active(&self) -> bool { self.active } fn paint( &self, ctx: &mut PaintCtx, value: f64, env: &Env, settings: SliderValueMapping, knob_style: KnobStyle, ) { let knob_size = env.get(theme::BASIC_WIDGET_HEIGHT); let knob_gradient = if ctx.is_disabled() { LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, ( env.get(theme::DISABLED_FOREGROUND_LIGHT), env.get(theme::DISABLED_FOREGROUND_DARK), ), ) } else if self.active { LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, ( env.get(theme::FOREGROUND_DARK), env.get(theme::FOREGROUND_LIGHT), ), ) } else { LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, ( env.get(theme::FOREGROUND_LIGHT), env.get(theme::FOREGROUND_DARK), ), ) }; //Paint the border let border_color = if (self.hovered || self.active) && !ctx.is_disabled() { env.get(theme::FOREGROUND_LIGHT) } else { env.get(theme::FOREGROUND_DARK) }; match knob_style { KnobStyle::Circle => { let knob_circle = Circle::new( settings.get_point(value, knob_size, ctx.size()), (knob_size - KNOB_STROKE_WIDTH) / 2., ); ctx.stroke(knob_circle, &border_color, KNOB_STROKE_WIDTH); //Actually paint the knob ctx.fill(knob_circle, &knob_gradient); } KnobStyle::Wedge => { let center = settings.get_point(value, knob_size, ctx.size()); let knob_wedge = knob_wedge(center, knob_size, settings.axis); ctx.stroke(&knob_wedge[..], &border_color, KNOB_STROKE_WIDTH); //Actually paint the knob ctx.fill(&knob_wedge[..], &knob_gradient); } } } } fn knob_wedge(center: Point, knob_size: f64, axis: Axis) -> [PathEl; 6] { let (top, right, left, middle, down) = match axis { Axis::Horizontal => ( Vec2::new(0.0, center.y - knob_size / 2.0), Vec2::new(center.x + knob_size / 3.5, 0.0), Vec2::new(center.x - knob_size / 3.5, 0.0), Vec2::new(0.0, center.y + knob_size / 5.0), Vec2::new(center.x, center.y + knob_size / 2.0), ), Axis::Vertical => ( Vec2::new(center.x + knob_size / 2.0, 0.0), Vec2::new(0.0, center.y + knob_size / 3.5), Vec2::new(0.0, center.y - knob_size / 3.5), Vec2::new(center.x - knob_size / 5.0, 0.0), Vec2::new(center.x - knob_size / 2.0, center.y), ), }; [ PathEl::MoveTo(down.to_point()), PathEl::LineTo((right + middle).to_point()), PathEl::LineTo((right + top).to_point()), PathEl::LineTo((left + top).to_point()), PathEl::LineTo((left + middle).to_point()), PathEl::ClosePath, ] } fn paint_slider_background( ctx: &mut PaintCtx, lower: f64, higher: f64, track_color: &Option<KeyOrValue<Color>>, mapping: SliderValueMapping, env: &Env, ) { let size = ctx.size(); let knob_size = env.get(theme::BASIC_WIDGET_HEIGHT); //Paint the background let background_rect = Rect::from_points( mapping.get_point(mapping.min, knob_size, size), mapping.get_point(mapping.max, knob_size, size), ) .inset((TRACK_THICKNESS - BORDER_WIDTH) / 2.) .to_rounded_rect(2.); let background_gradient = LinearGradient::new( UnitPoint::TOP, UnitPoint::BOTTOM, ( env.get(theme::BACKGROUND_LIGHT), env.get(theme::BACKGROUND_DARK), ), ); ctx.stroke(background_rect, &env.get(theme::BORDER_DARK), BORDER_WIDTH); ctx.fill(background_rect, &background_gradient); if let Some(color) = track_color { let color = color.resolve(env); let shape = Rect::from_points( mapping.get_point(lower, knob_size, size), mapping.get_point(higher, knob_size, size), ) .inset(TRACK_THICKNESS / 2.0) .to_rounded_rect(2.); ctx.fill(shape, &color); } } fn slider_layout( ctx: &mut LayoutCtx, bc: &BoxConstraints, env: &Env, mapping: SliderValueMapping, ) -> Size { let height = env.get(theme::BASIC_WIDGET_HEIGHT); let width = env.get(theme::WIDE_WIDGET_WIDTH); let size = bc.constrain(mapping.axis.pack(width, height)); if mapping.axis == Axis::Horizontal { let baseline_offset = (height / 2.0) - TRACK_THICKNESS; ctx.set_baseline_offset(baseline_offset); trace!( "Computed layout: size={}, baseline_offset={:?}", size, baseline_offset ); } else { trace!("Computed layout: size={}", size,); } size }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/controller.rs
druid/src/widget/controller.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A widget-controlling widget. use crate::debug_state::DebugState; use crate::widget::prelude::*; use crate::widget::{Axis, WidgetWrapper}; /// A trait for types that modify behaviour of a child widget. /// /// A `Controller` is a type that manages a child widget, overriding or /// customizing its event handling or update behaviour. /// /// A controller can only handle events and update; it cannot effect layout /// or paint. /// /// `Controller` is a convenience; anything it can do could also be done /// by creating a custom [`Widget`] that owned a child. This is somewhat cumbersome, /// however, especially when you only want to intercept or modify one or two events. /// /// The methods on `Controller` are identical to the methods on [`Widget`], /// except that they are also passed the controller's child. The controller /// is responsible for **explicitly** forwarding calls on to the child as needed. /// /// A `Controller` is used with a [`ControllerHost`], which manages the relationship /// between it and its child; although in general you would use the /// [`WidgetExt::controller`] method instead of instantiating a host directly. /// /// # Examples /// /// A [`TextBox`] that takes focus on launch: /// /// ``` /// # use druid::widget::{Controller, TextBox}; /// # use druid::{Env, Event, EventCtx, Widget}; /// struct TakeFocus; /// /// impl<T, W: Widget<T>> Controller<T, W> for TakeFocus { /// fn event(&mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { /// if let Event::WindowConnected = event { /// ctx.request_focus(); /// } /// child.event(ctx, event, data, env) /// } /// } /// ``` /// /// [`TextBox`]: super::TextBox /// [`WidgetExt::controller`]: super::WidgetExt::controller pub trait Controller<T, W: Widget<T>> { /// Analogous to [`Widget::event`]. fn event(&mut self, child: &mut W, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { child.event(ctx, event, data, env) } /// Analogous to [`Widget::lifecycle`]. fn lifecycle( &mut self, child: &mut W, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env, ) { child.lifecycle(ctx, event, data, env) } /// Analogous to [`Widget::update`]. fn update(&mut self, child: &mut W, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { child.update(ctx, old_data, data, env) } } /// A [`Widget`] that manages a child and a [`Controller`]. pub struct ControllerHost<W, C> { widget: W, controller: C, } impl<W, C> ControllerHost<W, C> { /// Create a new `ControllerHost`. pub fn new(widget: W, controller: C) -> ControllerHost<W, C> { ControllerHost { widget, controller } } } impl<T, W: Widget<T>, C: Controller<T, W>> Widget<T> for ControllerHost<W, C> { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { self.controller .event(&mut self.widget, ctx, event, data, env) } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { self.controller .lifecycle(&mut self.widget, ctx, event, data, env) } fn update(&mut self, ctx: &mut UpdateCtx, old_data: &T, data: &T, env: &Env) { self.controller .update(&mut self.widget, ctx, old_data, data, env) } fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { self.widget.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { self.widget.paint(ctx, data, env) } fn id(&self) -> Option<WidgetId> { self.widget.id() } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.widget.debug_state(data)], ..Default::default() } } fn compute_max_intrinsic( &mut self, axis: Axis, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env, ) -> f64 { self.widget.compute_max_intrinsic(axis, ctx, bc, data, env) } } impl<W, C> WidgetWrapper for ControllerHost<W, C> { widget_wrapper_body!(W, widget); }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/value_textbox.rs
druid/src/widget/value_textbox.rs
// Copyright 2021 the Druid Authors // SPDX-License-Identifier: Apache-2.0 //! A textbox that that parses and validates data. use tracing::instrument; use super::TextBox; use crate::debug_state::DebugState; use crate::text::{Formatter, Selection, TextComponent, ValidationError}; use crate::widget::prelude::*; use crate::{Data, Selector}; const BEGIN_EDITING: Selector = Selector::new("druid.builtin.textbox-begin-editing"); const COMPLETE_EDITING: Selector = Selector::new("druid.builtin.textbox-complete-editing"); /// A `TextBox` that uses a [`Formatter`] to handle formatting and validation /// of its data. /// /// There are a number of ways to customize the behaviour of the text box /// in relation to the provided [`Formatter`]: /// /// - [`ValueTextBox::validate_while_editing`] takes a flag that determines whether /// or not the textbox can display text that is not valid, while editing is /// in progress. (Text will still be validated when the user attempts to complete /// editing.) /// /// - [`ValueTextBox::update_data_while_editing`] takes a flag that determines /// whether the output value is updated during editing, when possible. /// /// - [`ValueTextBox::delegate`] allows you to provide some implementation of /// the [`ValidationDelegate`] trait, which receives a callback during editing; /// this can be used to report errors further back up the tree. pub struct ValueTextBox<T> { child: TextBox<String>, formatter: Box<dyn Formatter<T>>, callback: Option<Box<dyn ValidationDelegate>>, is_editing: bool, validate_while_editing: bool, update_data_while_editing: bool, /// the last data that this textbox saw or created. /// This is used to determine when a change to the data is originating /// elsewhere in the application, which we need to special-case last_known_data: Option<T>, force_selection: Option<Selection>, old_buffer: String, buffer: String, } /// A type that can be registered to receive callbacks as the state of a /// [`ValueTextBox`] changes. pub trait ValidationDelegate { /// Called with a [`TextBoxEvent`] whenever the validation state of a /// [`ValueTextBox`] changes. fn event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent, current_text: &str); } /// Events sent to a [`ValidationDelegate`]. pub enum TextBoxEvent { /// The textbox began editing. Began, /// An edit occurred which was considered valid by the [`Formatter`]. Changed, /// An edit occurred which was rejected by the [`Formatter`]. PartiallyInvalid(ValidationError), /// The user attempted to finish editing, but the input was not valid. Invalid(ValidationError), /// The user finished editing, with valid input. Complete, /// Editing was cancelled. Cancel, } impl TextBox<String> { /// Turn this `TextBox` into a [`ValueTextBox`], using the [`Formatter`] to /// manage the value. /// /// For simple value formatting, you can use the [`ParseFormatter`]. /// /// [`Formatter`]: crate::text::Formatter /// [`ParseFormatter`]: crate::text::ParseFormatter pub fn with_formatter<T: Data>( self, formatter: impl Formatter<T> + 'static, ) -> ValueTextBox<T> { ValueTextBox::new(self, formatter) } } impl<T: Data> ValueTextBox<T> { /// Create a new `ValueTextBox` from a normal [`TextBox`] and a [`Formatter`]. /// /// [`TextBox`]: super::TextBox /// [`Formatter`]: crate::text::Formatter pub fn new(mut child: TextBox<String>, formatter: impl Formatter<T> + 'static) -> Self { child.text_mut().borrow_mut().send_notification_on_return = true; child.text_mut().borrow_mut().send_notification_on_cancel = true; child.handles_tab_notifications = false; ValueTextBox { child, formatter: Box::new(formatter), callback: None, is_editing: false, last_known_data: None, validate_while_editing: true, update_data_while_editing: false, old_buffer: String::new(), buffer: String::new(), force_selection: None, } } /// Builder-style method to set an optional [`ValidationDelegate`] on this /// textbox. pub fn delegate(mut self, delegate: impl ValidationDelegate + 'static) -> Self { self.callback = Some(Box::new(delegate)); self } /// Builder-style method to set whether or not this text box validates /// its contents during editing. /// /// If `true` (the default) edits that fail validation /// ([`Formatter::validate_partial_input`]) will be rejected. If `false`, /// those edits will be accepted, and the text box will be updated. pub fn validate_while_editing(mut self, validate: bool) -> Self { self.validate_while_editing = validate; self } /// Builder-style method to set whether or not this text box updates the /// incoming data during editing. /// /// If `false` (the default) the data is only updated when editing completes. pub fn update_data_while_editing(mut self, flag: bool) -> Self { self.update_data_while_editing = flag; self } fn complete(&mut self, ctx: &mut EventCtx, data: &mut T) -> bool { match self.formatter.value(&self.buffer) { Ok(new_data) => { *data = new_data; self.buffer = self.formatter.format(data); self.is_editing = false; ctx.request_update(); self.send_event(ctx, TextBoxEvent::Complete); true } Err(err) => { if self.child.text().can_write() { if let Some(inval) = self .child .text_mut() .borrow_mut() .set_selection(Selection::new(0, self.buffer.len())) { ctx.invalidate_text_input(inval); } } self.send_event(ctx, TextBoxEvent::Invalid(err)); // our content isn't valid // ideally we would flash the background or something false } } } fn cancel(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = false; self.buffer = self.formatter.format(data); ctx.request_update(); ctx.resign_focus(); self.send_event(ctx, TextBoxEvent::Cancel); } fn begin(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = true; self.buffer = self.formatter.format_for_editing(data); self.last_known_data = Some(data.clone()); ctx.request_update(); self.send_event(ctx, TextBoxEvent::Began); } fn send_event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent) { if let Some(delegate) = self.callback.as_mut() { delegate.event(ctx, event, &self.buffer) } } } impl<T: Data + std::fmt::Debug> Widget<T> for ValueTextBox<T> { #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if matches!(event, Event::Command(cmd) if cmd.is(BEGIN_EDITING)) { return self.begin(ctx, data); } if self.is_editing { // if we reject an edit we want to reset the selection let pre_sel = if self.child.text().can_read() { Some(self.child.text().borrow().selection()) } else { None }; match event { // this is caused by an external focus change, like the mouse being clicked // elsewhere. Event::Command(cmd) if cmd.is(COMPLETE_EDITING) => { if !self.complete(ctx, data) { self.cancel(ctx, data); } return; } Event::Notification(cmd) if cmd.is(TextComponent::TAB) => { ctx.set_handled(); ctx.request_paint(); if self.complete(ctx, data) { ctx.focus_next(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::BACKTAB) => { ctx.request_paint(); ctx.set_handled(); if self.complete(ctx, data) { ctx.focus_prev(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::RETURN) => { ctx.set_handled(); if self.complete(ctx, data) { ctx.resign_focus(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::CANCEL) => { ctx.set_handled(); self.cancel(ctx, data); return; } event => { self.child.event(ctx, event, &mut self.buffer, env); } } // if an edit occurred, validate it with the formatter // notifications can arrive before update, so we always ignore them if !matches!(event, Event::Notification(_)) && self.buffer != self.old_buffer { let mut validation = self .formatter .validate_partial_input(&self.buffer, &self.child.text().borrow().selection()); if self.validate_while_editing { let new_buf = match (validation.text_change.take(), validation.is_err()) { (Some(new_text), _) => { // be helpful: if the formatter is misbehaved, log it. if self .formatter .validate_partial_input(&new_text, &Selection::caret(0)) .is_err() { tracing::warn!( "formatter replacement text does not validate: '{}'", &new_text ); None } else { Some(new_text) } } (None, true) => Some(self.old_buffer.clone()), _ => None, }; let new_sel = match (validation.selection_change.take(), validation.is_err()) { (Some(new_sel), _) => Some(new_sel), (None, true) if pre_sel.is_some() => pre_sel, _ => None, }; if let Some(new_buf) = new_buf { self.buffer = new_buf; } self.force_selection = new_sel; if self.update_data_while_editing && !validation.is_err() { if let Ok(new_data) = self.formatter.value(&self.buffer) { *data = new_data; self.last_known_data = Some(data.clone()); } } } match validation.error() { Some(err) => { self.send_event(ctx, TextBoxEvent::PartiallyInvalid(err.to_owned())) } None => self.send_event(ctx, TextBoxEvent::Changed), }; ctx.request_update(); } // if we *aren't* editing: } else { if let Event::MouseDown(_) = event { self.begin(ctx, data); } self.child.event(ctx, event, &mut self.buffer, env); } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::WidgetAdded => { self.buffer = self.formatter.format(data); self.old_buffer = self.buffer.clone(); } LifeCycle::FocusChanged(true) if !self.is_editing => { ctx.submit_command(BEGIN_EDITING.to(ctx.widget_id())); } LifeCycle::FocusChanged(false) => { ctx.submit_command(COMPLETE_EDITING.to(ctx.widget_id())); } _ => (), } self.child.lifecycle(ctx, event, &self.buffer, env); } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, old, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old: &T, data: &T, env: &Env) { if let Some(sel) = self.force_selection.take() { if self.child.text().can_write() { if let Some(change) = self.child.text_mut().borrow_mut().set_selection(sel) { ctx.invalidate_text_input(change); } } } let changed_by_us = self .last_known_data .as_ref() .map(|d| d.same(data)) .unwrap_or(false); if self.is_editing { if changed_by_us { self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else { // textbox is not well equipped to deal with the fact that, in // Druid, data can change anywhere in the tree. If we are actively // editing, and new data arrives, we ignore the new data and keep // editing; the alternative would be to cancel editing, which // could also make sense. tracing::warn!( "ValueTextBox data changed externally, idk: '{}'", self.formatter.format(data) ); } } else { if !old.same(data) { // we aren't editing and data changed let new_text = self.formatter.format(data); // it's possible for different data inputs to produce the same formatted // output, in which case we would overwrite our actual previous data if !new_text.same(&self.buffer) { self.old_buffer = std::mem::replace(&mut self.buffer, new_text); } } if !self.old_buffer.same(&self.buffer) { // child widget handles calling request_layout, as needed self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else if ctx.env_changed() { self.child.update(ctx, &self.buffer, &self.buffer, env); } } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, bc, _data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, &self.buffer, env) } #[instrument(name = "ValueTextBox", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { self.child.paint(ctx, &self.buffer, env); } fn debug_state(&self, _data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), main_value: self.buffer.clone(), ..Default::default() } } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false
linebender/druid
https://github.com/linebender/druid/blob/b27ea6a618c32f9ea0e8a56822f9487d23401c0d/druid/src/widget/clip_box.rs
druid/src/widget/clip_box.rs
// Copyright 2020 the Druid Authors // SPDX-License-Identifier: Apache-2.0 use crate::commands::SCROLL_TO_VIEW; use crate::contexts::ChangeCtx; use crate::debug_state::DebugState; use crate::kurbo::{Point, Rect, Size, Vec2}; use crate::widget::prelude::*; use crate::widget::Axis; use crate::{Data, InternalLifeCycle, WidgetPod}; use tracing::{info, instrument, trace, warn}; /// Represents the size and position of a rectangular "viewport" into a larger area. #[derive(Clone, Copy, Default, Debug, PartialEq)] pub struct Viewport { /// The size of the area that we have a viewport into. pub content_size: Size, /// The origin of the view rectangle, relative to the content. pub view_origin: Point, /// The size of the view rectangle. pub view_size: Size, } impl Viewport { /// The view rectangle. pub fn view_rect(&self) -> Rect { Rect::from_origin_size(self.view_origin, self.view_size) } /// Tries to find a position for the view rectangle that is contained in the content rectangle. /// /// If the supplied origin is good, returns it; if it isn't, we try to return the nearest /// origin that would make the view rectangle contained in the content rectangle. (This will /// fail if the content is smaller than the view, and we return `0.0` in each dimension where /// the content is smaller.) pub fn clamp_view_origin(&self, origin: Point) -> Point { #![allow(clippy::manual_clamp)] let x = origin .x .min(self.content_size.width - self.view_size.width) .max(0.0); let y = origin .y .min(self.content_size.height - self.view_size.height) .max(0.0); Point::new(x, y) } fn sanitize_view_origin(&mut self) { self.view_origin = self.clamp_view_origin(self.view_origin); } /// Changes the viewport offset by `delta`, while trying to keep the view rectangle inside the /// content rectangle. /// /// Returns true if the offset actually changed. Even if `delta` is non-zero, the offset might /// not change. For example, if you try to move the viewport down but it is already at the /// bottom of the child widget, then the offset will not change and this function will return /// false. pub fn pan_by(&mut self, delta: Vec2) -> bool { self.pan_to(self.view_origin + delta) } /// Sets the viewport origin to `pos`, while trying to keep the view rectangle inside the /// content rectangle. /// /// Returns true if the position changed. Note that the valid values for the viewport origin /// are constrained by the size of the child, and so the origin might not get set to exactly /// `pos`. pub fn pan_to(&mut self, pos: Point) -> bool { let new_origin = self.clamp_view_origin(pos); if (new_origin - self.view_origin).hypot2() > 1e-12 { self.view_origin = new_origin; true } else { false } } /// Sets the component selected by `axis` of viewport origin to `pos`, while trying to keep the /// view rectangle inside the content rectangle. /// /// Returns `true` if the position changed. Note that the valid values for the viewport origin /// are constrained by the size of the child, and so the origin might not get set to exactly /// `pos`. pub fn pan_to_on_axis(&mut self, axis: Axis, pos: f64) -> bool { self.pan_to(Point::from( axis.pack(pos, axis.minor_pos(self.view_origin)), )) } /// Pan the smallest distance that makes the target [`Rect`] visible. /// /// If the target rect is larger than viewport size, we will prioritize /// the region of the target closest to its origin. pub fn pan_to_visible(&mut self, rect: Rect) -> bool { /// Given a position and the min and max edges of an axis, /// return a delta by which to adjust that axis such that the value /// falls between its edges. /// /// if the value already falls between the two edges, return 0.0. fn closest_on_axis(val: f64, min: f64, max: f64) -> f64 { assert!(min <= max); if val > min && val < max { 0.0 } else if val <= min { val - min } else { val - max } } // clamp the target region size to our own size. // this means we will show the portion of the target region that // includes the origin. let target_size = Size::new( rect.width().min(self.view_size.width), rect.height().min(self.view_size.height), ); let rect = rect.with_size(target_size); let my_rect = self.view_rect(); let x0 = closest_on_axis(rect.min_x(), my_rect.min_x(), my_rect.max_x()); let x1 = closest_on_axis(rect.max_x(), my_rect.min_x(), my_rect.max_x()); let y0 = closest_on_axis(rect.min_y(), my_rect.min_y(), my_rect.max_y()); let y1 = closest_on_axis(rect.max_y(), my_rect.min_y(), my_rect.max_y()); let delta_x = if x0.abs() > x1.abs() { x0 } else { x1 }; let delta_y = if y0.abs() > y1.abs() { y0 } else { y1 }; let new_origin = self.view_origin + Vec2::new(delta_x, delta_y); self.pan_to(new_origin) } /// The default handling of the [`SCROLL_TO_VIEW`] notification for a scrolling container. /// /// The [`SCROLL_TO_VIEW`] notification is sent when [`EventCtx::scroll_to_view`] /// or [`EventCtx::scroll_area_to_view`] are called. /// /// [`SCROLL_TO_VIEW`]: crate::commands::SCROLL_TO_VIEW pub fn default_scroll_to_view_handling( &mut self, ctx: &mut EventCtx, global_highlight_rect: Rect, ) -> bool { let mut viewport_changed = false; let global_content_offset = ctx.window_origin().to_vec2() - self.view_origin.to_vec2(); let content_highlight_rect = global_highlight_rect - global_content_offset; if self .content_size .to_rect() .intersect(content_highlight_rect) != content_highlight_rect { warn!("tried to bring area outside of the content to view!"); } if self.pan_to_visible(content_highlight_rect) { ctx.request_paint(); viewport_changed = true; } // This is a new value since view_origin has changed in the meantime let global_content_offset = ctx.window_origin().to_vec2() - self.view_origin.to_vec2(); ctx.submit_notification_without_warning( SCROLL_TO_VIEW.with(content_highlight_rect + global_content_offset), ); viewport_changed } /// This method handles SCROLL_TO_VIEW by clipping the view_rect to the content rect. /// /// The [`SCROLL_TO_VIEW`] notification is sent when [`EventCtx::scroll_to_view`] /// or [`EventCtx::scroll_area_to_view`] are called. /// /// [`SCROLL_TO_VIEW`]: crate::commands::SCROLL_TO_VIEW pub fn fixed_scroll_to_view_handling( &self, ctx: &mut EventCtx, global_highlight_rect: Rect, source: WidgetId, ) { let global_viewport_rect = self.view_rect() + ctx.window_origin().to_vec2(); let clipped_highlight_rect = global_highlight_rect.intersect(global_viewport_rect); if clipped_highlight_rect.area() > 0.0 { ctx.submit_notification_without_warning(SCROLL_TO_VIEW.with(clipped_highlight_rect)); } else { info!("Hidden Widget({}) in unmanaged clip requested SCROLL_TO_VIEW. The request is ignored.", source.to_raw()); } } } /// A widget exposing a rectangular view into its child, which can be used as a building block for /// widgets that scroll their child. pub struct ClipBox<T, W> { child: WidgetPod<T, W>, port: Viewport, constrain_horizontal: bool, constrain_vertical: bool, must_fill: bool, old_bc: BoxConstraints, old_size: Size, //This ClipBox is wrapped by a widget which manages the viewport_offset managed: bool, } impl<T, W> ClipBox<T, W> { /// Builder-style method for deciding whether to constrain the child vertically. /// /// The default is `false`. /// /// This setting affects how a `ClipBox` lays out its child. /// /// - When it is `false` (the default), the child does not receive any upper /// bound on its height: the idea is that the child can be as tall as it /// wants, and the viewport will somehow get moved around to see all of it. /// - When it is `true`, the viewport's maximum height will be passed down /// as an upper bound on the height of the child, and the viewport will set /// its own height to be the same as its child's height. pub fn constrain_vertical(mut self, constrain: bool) -> Self { self.constrain_vertical = constrain; self } /// Builder-style method for deciding whether to constrain the child horizontally. /// /// The default is `false`. See [`constrain_vertical`] for more details. /// /// [`constrain_vertical`]: ClipBox::constrain_vertical pub fn constrain_horizontal(mut self, constrain: bool) -> Self { self.constrain_horizontal = constrain; self } /// Builder-style method to set whether the child must fill the view. /// /// If `false` (the default) there is no minimum constraint on the child's /// size. If `true`, the child is passed the same minimum constraints as /// the `ClipBox`. pub fn content_must_fill(mut self, must_fill: bool) -> Self { self.must_fill = must_fill; self } /// Returns a reference to the child widget. pub fn child(&self) -> &W { self.child.widget() } /// Returns a mutable reference to the child widget. pub fn child_mut(&mut self) -> &mut W { self.child.widget_mut() } /// Returns a the viewport describing this `ClipBox`'s position. pub fn viewport(&self) -> Viewport { self.port } /// Returns the origin of the viewport rectangle. pub fn viewport_origin(&self) -> Point { self.port.view_origin } /// Returns the size of the rectangular viewport into the child widget. /// To get the position of the viewport, see [`viewport_origin`]. /// /// [`viewport_origin`]: ClipBox::viewport_origin pub fn viewport_size(&self) -> Size { self.port.view_size } /// Returns the size of the child widget. pub fn content_size(&self) -> Size { self.port.content_size } /// Set whether to constrain the child horizontally. /// /// See [`constrain_vertical`] for more details. /// /// [`constrain_vertical`]: ClipBox::constrain_vertical pub fn set_constrain_horizontal(&mut self, constrain: bool) { self.constrain_horizontal = constrain; } /// Set whether to constrain the child vertically. /// /// See [`constrain_vertical`] for more details. /// /// [`constrain_vertical`]: ClipBox::constrain_vertical pub fn set_constrain_vertical(&mut self, constrain: bool) { self.constrain_vertical = constrain; } /// Set whether the child's size must be greater than or equal the size of /// the `ClipBox`. /// /// See [`content_must_fill`] for more details. /// /// [`content_must_fill`]: ClipBox::content_must_fill pub fn set_content_must_fill(&mut self, must_fill: bool) { self.must_fill = must_fill; } } impl<T, W: Widget<T>> ClipBox<T, W> { /// Creates a new `ClipBox` wrapping `child`. /// /// This method should only be used when creating your own widget, which uses `ClipBox` /// internally. /// /// `ClipBox` will forward [`SCROLL_TO_VIEW`] notifications to its parent unchanged. /// In this case the parent has to handle said notification itself. By default the `ClipBox` /// will filter out [`SCROLL_TO_VIEW`] notifications which refer to areas not visible. /// /// [`SCROLL_TO_VIEW`]: crate::commands::SCROLL_TO_VIEW pub fn managed(child: W) -> Self { ClipBox { child: WidgetPod::new(child), port: Default::default(), constrain_horizontal: false, constrain_vertical: false, must_fill: false, old_bc: BoxConstraints::tight(Size::ZERO), old_size: Size::ZERO, managed: true, } } /// Creates a new unmanaged `ClipBox` wrapping `child`. /// /// This method should be used when you are using `ClipBox` in the widget tree directly. pub fn unmanaged(child: W) -> Self { ClipBox { child: WidgetPod::new(child), port: Default::default(), constrain_horizontal: false, constrain_vertical: false, must_fill: false, old_bc: BoxConstraints::tight(Size::ZERO), old_size: Size::ZERO, managed: false, } } /// Pans by `delta` units. /// /// Returns `true` if the scroll offset has changed. pub fn pan_by<C: ChangeCtx>(&mut self, ctx: &mut C, delta: Vec2) -> bool { self.with_port(ctx, |_, port| { port.pan_by(delta); }) } /// Pans the minimal distance to show the `region`. /// /// If the target region is larger than the viewport, we will display the /// portion that fits, prioritizing the portion closest to the origin. pub fn pan_to_visible<C: ChangeCtx>(&mut self, ctx: &mut C, region: Rect) -> bool { self.with_port(ctx, |_, port| { port.pan_to_visible(region); }) } /// Pan to this position on a particular axis. /// /// Returns `true` if the scroll offset has changed. pub fn pan_to_on_axis<C: ChangeCtx>(&mut self, ctx: &mut C, axis: Axis, position: f64) -> bool { self.with_port(ctx, |_, port| { port.pan_to_on_axis(axis, position); }) } /// Modify the `ClipBox`'s viewport rectangle with a closure. /// /// The provided callback function can modify its argument, and when it is /// done then this `ClipBox` will be modified to have the new viewport rectangle. pub fn with_port<C: ChangeCtx, F: FnOnce(&mut C, &mut Viewport)>( &mut self, ctx: &mut C, f: F, ) -> bool { f(ctx, &mut self.port); self.port.sanitize_view_origin(); let new_content_origin = (Point::ZERO - self.port.view_origin).to_point(); if new_content_origin != self.child.layout_rect().origin() { self.child.set_origin(ctx, new_content_origin); true } else { false } } } impl<T: Data, W: Widget<T>> Widget<T> for ClipBox<T, W> { #[instrument(name = "ClipBox", level = "trace", skip(self, ctx, event, data, env))] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if let Event::Notification(notification) = event { if let Some(global_highlight_rect) = notification.get(SCROLL_TO_VIEW) { if !self.managed { // If the parent widget does not handle SCROLL_TO_VIEW notifications, we // prevent unexpected behaviour, by clipping SCROLL_TO_VIEW notifications // to this ClipBox's viewport. ctx.set_handled(); self.with_port(ctx, |ctx, port| { port.fixed_scroll_to_view_handling( ctx, *global_highlight_rect, notification.source(), ); }); } } } else { self.child.event(ctx, event, data, env); } } #[instrument(name = "ClipBox", level = "trace", skip(self, ctx, event, data, env))] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::ViewContextChanged(view_context) => { let mut view_context = *view_context; view_context.clip = view_context.clip.intersect(ctx.size().to_rect()); let modified_event = LifeCycle::ViewContextChanged(view_context); self.child.lifecycle(ctx, &modified_event, data, env); } LifeCycle::Internal(InternalLifeCycle::RouteViewContextChanged(view_context)) => { let mut view_context = *view_context; view_context.clip = view_context.clip.intersect(ctx.size().to_rect()); let modified_event = LifeCycle::Internal(InternalLifeCycle::RouteViewContextChanged(view_context)); self.child.lifecycle(ctx, &modified_event, data, env); } _ => { self.child.lifecycle(ctx, event, data, env); } } } #[instrument( name = "ClipBox", level = "trace", skip(self, ctx, _old_data, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &T, data: &T, env: &Env) { self.child.update(ctx, data, env); } #[instrument(name = "ClipBox", level = "trace", skip(self, ctx, bc, data, env))] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &T, env: &Env) -> Size { bc.debug_check("ClipBox"); let max_child_width = if self.constrain_horizontal { bc.max().width } else { f64::INFINITY }; let max_child_height = if self.constrain_vertical { bc.max().height } else { f64::INFINITY }; let min_child_size = if self.must_fill { bc.min() } else { Size::ZERO }; let child_bc = BoxConstraints::new(min_child_size, Size::new(max_child_width, max_child_height)); let bc_changed = child_bc != self.old_bc; self.old_bc = child_bc; let content_size = if bc_changed || self.child.layout_requested() { self.child.layout(ctx, &child_bc, data, env) } else { self.child.layout_rect().size() }; self.port.content_size = content_size; self.port.view_size = bc.constrain(content_size); self.port.sanitize_view_origin(); self.child .set_origin(ctx, (Point::ZERO - self.port.view_origin).to_point()); if self.viewport_size() != self.old_size { ctx.view_context_changed(); self.old_size = self.viewport_size(); } trace!("Computed sized: {}", self.viewport_size()); self.viewport_size() } #[instrument(name = "ClipBox", level = "trace", skip(self, ctx, data, env))] fn paint(&mut self, ctx: &mut PaintCtx, data: &T, env: &Env) { let clip_rect = ctx.size().to_rect(); ctx.clip(clip_rect); self.child.paint(ctx, data, env); } fn debug_state(&self, data: &T) -> DebugState { DebugState { display_name: self.short_type_name().to_string(), children: vec![self.child.widget().debug_state(data)], ..Default::default() } } } #[cfg(test)] mod tests { use super::*; use test_log::test; #[test] fn pan_to_visible() { let mut viewport = Viewport { content_size: Size::new(400., 400.), view_size: (20., 20.).into(), view_origin: (20., 20.).into(), }; assert!(!viewport.pan_to_visible(Rect::from_origin_size((22., 22.,), (5., 5.)))); assert!(viewport.pan_to_visible(Rect::from_origin_size((10., 10.,), (5., 5.)))); assert_eq!(viewport.view_origin, Point::new(10., 10.)); assert_eq!(viewport.view_size, Size::new(20., 20.)); assert!(!viewport.pan_to_visible(Rect::from_origin_size((10., 10.,), (50., 50.)))); assert_eq!(viewport.view_origin, Point::new(10., 10.)); assert!(viewport.pan_to_visible(Rect::from_origin_size((30., 10.,), (5., 5.)))); assert_eq!(viewport.view_origin, Point::new(15., 10.)); assert!(viewport.pan_to_visible(Rect::from_origin_size((5., 5.,), (5., 5.)))); assert_eq!(viewport.view_origin, Point::new(5., 5.)); } }
rust
Apache-2.0
b27ea6a618c32f9ea0e8a56822f9487d23401c0d
2026-01-04T15:44:39.941670Z
false