From 2bea7275c42cb30458d2cb95312fd15ce67adcca Mon Sep 17 00:00:00 2001 From: rabahalawadi Date: Wed, 18 Nov 2026 10:11:45 +0300 Subject: [PATCH] feat: macos top bar plugin, dynamic window controls, and fullscreen hook --- Custom Plugins/fullscreen/Cargo.toml | 22 +++ Custom Plugins/fullscreen/README.md | 28 +++ .../fullscreen/craft-extension.json | 20 +++ .../fullscreen/fullscreen.procraft-plugin | Bin 0 -> 989 bytes Custom Plugins/fullscreen/plugin.wasm | Bin 0 -> 363 bytes Custom Plugins/fullscreen/src/lib.rs | 29 ++++ Custom Plugins/macos topbar/Cargo.toml | 22 +++ Custom Plugins/macos topbar/README.md | 30 ++++ .../macos topbar/craft-extension.json | 15 ++ .../macos topbar/macos-topbar.procraft-plugin | Bin 0 -> 800 bytes Custom Plugins/macos topbar/plugin.wasm | Bin 0 -> 157 bytes Custom Plugins/macos topbar/src/lib.rs | 16 ++ crates/core/src/hooks.rs | 95 +++++++++++ crates/core/src/plugin_run.rs | 72 ++++++++ crates/core/src/plugins.rs | 20 +++ desktop/src/chrome.rs | 38 ++++- desktop/src/gallery.rs | 3 +- desktop/src/main.rs | 56 ++++++ desktop/src/pen.rs | 49 +++++- desktop/src/tool_header.rs | 73 +++++--- desktop/src/window_controls.rs | 161 ++++++++++++++++++ 21 files changed, 718 insertions(+), 31 deletions(-) create mode 100644 Custom Plugins/fullscreen/Cargo.toml create mode 100644 Custom Plugins/fullscreen/README.md create mode 100644 Custom Plugins/fullscreen/craft-extension.json create mode 100644 Custom Plugins/fullscreen/fullscreen.procraft-plugin create mode 100644 Custom Plugins/fullscreen/plugin.wasm create mode 100644 Custom Plugins/fullscreen/src/lib.rs create mode 100644 Custom Plugins/macos topbar/Cargo.toml create mode 100644 Custom Plugins/macos topbar/README.md create mode 100644 Custom Plugins/macos topbar/craft-extension.json create mode 100644 Custom Plugins/macos topbar/macos-topbar.procraft-plugin create mode 100644 Custom Plugins/macos topbar/plugin.wasm create mode 100644 Custom Plugins/macos topbar/src/lib.rs create mode 100644 desktop/src/window_controls.rs diff --git a/Custom Plugins/fullscreen/Cargo.toml b/Custom Plugins/fullscreen/Cargo.toml new file mode 100644 index 00000000..cdadcaa1 --- /dev/null +++ b/Custom Plugins/fullscreen/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "fullscreen" +version = "1.0.0" +edition = "2024" +publish = false +license = "MIT OR Apache-2.0" +description = "Fullscreen mode plugin for ProCraft: toggle between windowed and fullscreen display, configure exclusive fullscreen and keyboard shortcuts" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +kit = { package = "procraft-plugin-kit", path = "../../plugins/kit", default-features = false } + +# Not a member of the app's workspace, and linked into nothing: it builds to a module of its own. +[workspace] + +[profile.release] +opt-level = "s" +lto = true +panic = "abort" +strip = true diff --git a/Custom Plugins/fullscreen/README.md b/Custom Plugins/fullscreen/README.md new file mode 100644 index 00000000..90e8d10c --- /dev/null +++ b/Custom Plugins/fullscreen/README.md @@ -0,0 +1,28 @@ +# Fullscreen Plugin for ProCraft +**Author**: raba7 +**Description**: Immersive fullscreen canvas mode for ProCraft by raba7. Seamlessly switch between windowed and fullscreen display with F11 or Alt+Enter, featuring optional high-refresh rate exclusive fullscreen. + +--- + +## Features +- **Fullscreen Mode Toggle**: + - Switch smoothly between standard windowed mode and fullscreen display. + - Trigger fullscreen toggle directly from the plugin card in **Actions -> Prefs -> Plugins -> Fullscreen -> Toggle Fullscreen**. +- **Exclusive Fullscreen Option**: + - Toggle between **Exclusive Fullscreen** (highest monitor refresh rate, minimal latency) and standard borderless windowed fullscreen. +- **Keyboard Shortcuts**: + - Support for industry standard **F11** and **Alt+Enter** keyboard shortcuts to toggle fullscreen on and off. + - Can be toggled on/off independently via the plugin control switch. + +## How to Install / Import +1. Open **ProCraft**. +2. Open any canvas, or open the Gallery. +3. Open the **Actions** menu (wrench icon in top bar) -> **Help / Prefs** -> **Plugins**. +4. Tap **Import Plugin** and select `fullscreen.procraft-plugin` from this folder. +5. The **Fullscreen** plugin will now appear in your plugins list. + +## Plugin Controls & Actions +- **Enable fullscreen features**: Master switch enabling/disabling fullscreen capability. +- **Exclusive fullscreen (max refresh rate)**: When enabled, runs in exclusive mode for highest monitor refresh rate. +- **Keyboard shortcuts (F11 / Alt+Enter)**: Allows toggling fullscreen via keyboard shortcuts. +- **Toggle Fullscreen**: Action button to immediately toggle fullscreen on or off. diff --git a/Custom Plugins/fullscreen/craft-extension.json b/Custom Plugins/fullscreen/craft-extension.json new file mode 100644 index 00000000..a5aaa734 --- /dev/null +++ b/Custom Plugins/fullscreen/craft-extension.json @@ -0,0 +1,20 @@ +{ + "schema": 1, + "id": "io.github.artcraftandroid.fullscreen", + "name": "Fullscreen", + "version": "1.0.0", + "holds": ["hooks"], + "publisher": { "name": "raba7" }, + "description": "Immersive fullscreen canvas mode for ProCraft by raba7. Seamlessly switch between windowed and fullscreen display with F11 or Alt+Enter, featuring optional high-refresh rate exclusive fullscreen.", + "compat": { "procraft": { "interface": 2 } }, + "permissions": [], + "hooks": ["fullscreen"], + "controls": [ + { "key": "enabled", "type": "switch", "label": "Enable fullscreen features", "starts": true }, + { "key": "exclusive", "type": "switch", "label": "Exclusive fullscreen (max refresh rate)", "starts": false, "under": "enabled" }, + { "key": "shortcuts", "type": "switch", "label": "Keyboard shortcuts (F11 / Alt+Enter)", "starts": true, "under": "enabled" } + ], + "actions": [ + { "key": "toggle", "label": "Toggle Fullscreen" } + ] +} diff --git a/Custom Plugins/fullscreen/fullscreen.procraft-plugin b/Custom Plugins/fullscreen/fullscreen.procraft-plugin new file mode 100644 index 0000000000000000000000000000000000000000..9fe41a806c5940a8b883bb10e69f5421becdcf1e GIT binary patch literal 989 zcmWIWW@Zs#U|`??VnqfA-p%ubm>3uyvoJ7#M3ajW(@JzxD@s!HiZk=`^savqF>UUW3!x& zJ)Zj4<(lW>W^M2AmsuOa+zO}5Jb2EeV0U)1w;03zMcXsIRbySvEDxL(DAdf~cqF&O z=D3GnU*ydn`(^iCDa|NXn(>6uxz>q&>qC}95kJz-J~!Z;Vtb@WvqpW5sO9pig1KMT zG)<}zpJcsq=gSV}EIa*EOS473UGR)Qm^`g<;|I^5<@~oM$2KW^Sv&O?hgz32>r|Vt z_qv?k>zKOdHO!ltwf@R7X8E*NY=2Gal6{xhM;&T&(r(l#IJx+vO;P5FYnNC*O#IYP zy1>S1er|!v`JQjrR%m9u`Q}oq;3MVjYO|`R?7n%SA@lZ=>o%x}%J3T|pUZ1-&f_YR zTg&geH#buvwQ~1g)|=5RcMkBBo7x?&k^XLeg(IZTt$20io)Z%f?r+(3D&l<9`+Evs zw7)KOJe}y%w!0uoe%a|=^{qGmyXfh0yNR9q`1Nm9vCS&UyMcH5Uo_nOzHgPzl10*` z(qBSPSjr;Gv=-Z)3-d_UApadNA9*qu9114d7s{#_jbGMy!F?brZ?56 zEQ-kgzFH}n_5RbO?Mb`;R_zzO`9@*xA6bL--CtD-3jZ+&proOqi=j8}1Jh16BLf3B zkS@q6P0!5JD^D!WZ9Q|)>#&0e>xJKOvpD(|iWNqBls`JPba#nBxZa-@6`tTI4s%Cc6q+PpH%o{g5KUc0iE zZlgP3K8nFwr4mFvD~tTak>VCQ4~NRz|VK}-9jjg!5zn4Er5I)MPc z0=vy2*uxY#eG76Tgs^>#w}>vM8y3PYfb(l2FR+a50;>V<;<`n3KaDvn_Ws*8$PzpU eU+j55J@CH~pMN9x1tI=t2Yv>GB0d*SD1HD#fLW*j literal 0 HcmV?d00001 diff --git a/Custom Plugins/fullscreen/src/lib.rs b/Custom Plugins/fullscreen/src/lib.rs new file mode 100644 index 00000000..082ad5d6 --- /dev/null +++ b/Custom Plugins/fullscreen/src/lib.rs @@ -0,0 +1,29 @@ +//! Fullscreen plugin for ProCraft: controls window fullscreen modes, +//! exclusive fullscreen (maximum monitor refresh rate), and F11 / Alt+Enter shortcut toggles. + +#![no_std] + +/// Controls: +/// 0: enabled (switch, default on) +/// 1: exclusive (switch, default off -> borderless) +/// 2: shortcuts (switch, default on) +static CONTROLS: kit::Controls<3> = kit::Controls::new([1.0, 0.0, 1.0]); +kit::controls!(CONTROLS); + +const ENABLED: usize = 0; +const EXCLUSIVE: usize = 1; +const SHORTCUTS: usize = 2; + +kit::yes!(procraft_fullscreen, || CONTROLS.on(ENABLED)); +kit::yes!(procraft_exclusive_fullscreen, || CONTROLS.on(ENABLED) && CONTROLS.on(EXCLUSIVE)); +kit::yes!(procraft_fullscreen_shortcuts, || CONTROLS.on(ENABLED) && CONTROLS.on(SHORTCUTS)); + +#[unsafe(no_mangle)] +pub extern "C" fn procraft_action(_index: i32) -> i32 { + 0 +} + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo) -> ! { + core::arch::wasm32::unreachable() +} diff --git a/Custom Plugins/macos topbar/Cargo.toml b/Custom Plugins/macos topbar/Cargo.toml new file mode 100644 index 00000000..bc773552 --- /dev/null +++ b/Custom Plugins/macos topbar/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "macos-topbar" +version = "1.0.1" +edition = "2024" +publish = false +license = "MIT OR Apache-2.0" +description = "A plugin for ProCraft: switches the top bar to macOS style with traffic light window controls" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +kit = { package = "procraft-plugin-kit", path = "../kit", default-features = false } + +# Not a member of the app's workspace, and linked into nothing: it builds to a module of its own. +[workspace] + +[profile.release] +opt-level = "s" +lto = true +panic = "abort" +strip = true diff --git a/Custom Plugins/macos topbar/README.md b/Custom Plugins/macos topbar/README.md new file mode 100644 index 00000000..56447a7a --- /dev/null +++ b/Custom Plugins/macos topbar/README.md @@ -0,0 +1,30 @@ +# macOS Style Plugin for ProCraft +**Author**: raba7 +**Version**: 1.0.1 +**Description**: Transforms ProCraft's window into a clean macOS style with traffic light controls by raba7. When disabled, standard window decorations are restored. + +--- + +## Features +- **Enabled (macOS Style)**: + - Frameless / borderless window styling. + - Sleek traffic light window control buttons (Close, Minimize, Maximize) with hover glyphs on the top left. + - Draggable top bar and gallery / tool headers with double-click to maximize/restore. + - Rounded top corner aesthetics. +- **Disabled (Default Windows Style)**: + - Standard native Windows title bar and window decorations. + - Native Windows minimize, maximize, and close controls in the top-right corner. + - Full native window snapping and window dragging. + - Standard default layout and margins. + +## How to Install / Import +1. Open **ProCraft**. +2. Open any canvas, or open the Gallery. +3. Open the **Actions** menu (wrench icon in top bar) -> **Help / Prefs** -> **Plugins**. +4. Tap **Import Plugin** and select `macos-topbar.procraft-plugin` from this folder. +5. The **macOS Style** plugin will now appear in your plugins list. + +## How to Toggle +- You can turn the plugin **ON** or **OFF** at any time from the Plugins page using its master toggle switch or its "macOS style top bar" control switch. +- When enabled, ProCraft instantly switches to the macOS top bar without needing a restart. +- When disabled, ProCraft restores the default Windows top bar and title decorations. diff --git a/Custom Plugins/macos topbar/craft-extension.json b/Custom Plugins/macos topbar/craft-extension.json new file mode 100644 index 00000000..e90336a5 --- /dev/null +++ b/Custom Plugins/macos topbar/craft-extension.json @@ -0,0 +1,15 @@ +{ + "schema": 1, + "id": "io.github.artcraftandroid.macos-topbar", + "name": "macOS Style", + "version": "1.0.1", + "holds": ["hooks"], + "publisher": { "name": "raba7" }, + "description": "Transforms ProCraft's window into a clean macOS style with traffic light controls by raba7. When disabled, standard window decorations are restored.", + "compat": { "procraft": { "interface": 1 } }, + "permissions": [], + "hooks": ["macos_top_bar"], + "controls": [ + { "key": "enabled", "type": "switch", "label": "macOS style top bar", "starts": true } + ] +} diff --git a/Custom Plugins/macos topbar/macos-topbar.procraft-plugin b/Custom Plugins/macos topbar/macos-topbar.procraft-plugin new file mode 100644 index 0000000000000000000000000000000000000000..a77f646dd112e5b1a9f7b90b609d605bfe6ca941 GIT binary patch literal 800 zcmWIWW@Zs#U|`??Vnv3TCO0RoVPs(7W@caji6$2%rj_WXR+OaX6=&w>>17q?=jBdv z?7MBi3rxWax)(_V2+49Qdovxq;=#VNT5)G#+Qp?O^gsPq z-;(XY#?o|_Ajrp4H6>L~GFQENPq*KU=(47wp7uBRY z{r$=s_vBSZ<{vdbvmbY|U*+D_xoT)Jd6n>=I}B5jE4;6=JqUk!th>mp_sCVwd*VlH z?G_)h)6RFz)X3Zx_%HXzxfhoOD!e}Q9-f}_Gq~wym2ldII3|S*_ZNvDXKwPJv9?E{ z=Wv3lMYSAj$%jJ+RRh8`w6lL0PGV0M)^dNw8PwL8^X@Y5%L6ldRUFh3yo6@>>}9!@ z*rm~LGtpUbSC~<${t@O^GFvo{-j*^E@;6JJ#CrQs=D}@2I_p1aDeilg9+`P>^O{4Y z52a&`O+TpyPrbTS?|MYS@|#_9@}=!vcOFj_uM$$av)?gL)p6P$-ycrdJx5O`$o@U< z;Uf9@&I`Tt*RLfne@VR8v3uL;x8Dp*T0D;XX}?;reBJxLRd@MTz3w}HH;z9#YnRye z-+woTS}$F3fA!ym!RON~O5EyaWd0X9mHXdd$Iid30VuI6;@0Th0gTnTK+Fxq1v#bZ znR$BUiN(3LC+xWn8HlhyxL^H|-$dliBN-W6hr-ndnJZdM*yi?VX0pjHd7r>%JFEG@ zkJ=B(Dhwfo=Pyg!W(0LPdb?&^TN`yW+vn%e8$6b+Z}N|}e$lYJ+xT|>BL2)0Ro-`x zj8|k;vfD{rG5E4EWKD<7c~c!8*@zUejJpSt{vYOaxSky=yygVYUWO&VnF72SnM9az wCrF^H!C(n6kz!At=q8|h8ls@-l<>`$UG%3ZPr6LsTO0E3OhxlS_hZwr(?y2d*BgN1IyMN?e7se)qp}D%4$12`~ oPbCaW`dCU^a7Cj3sKG`6951J literal 0 HcmV?d00001 diff --git a/Custom Plugins/macos topbar/src/lib.rs b/Custom Plugins/macos topbar/src/lib.rs new file mode 100644 index 00000000..c336ad64 --- /dev/null +++ b/Custom Plugins/macos topbar/src/lib.rs @@ -0,0 +1,16 @@ +//! macOS Top Bar: changes the window top bar to macOS style with traffic light window controls. +//! When disabled or turned off, ProCraft uses the platform's default window decorations. + +#![no_std] + +/// Controls: an enabled switch that defaults to on (1.0). +static CONTROLS: kit::Controls<1> = kit::Controls::new([1.0]); +kit::controls!(CONTROLS); +const ENABLED: usize = 0; + +kit::yes!(procraft_macos_top_bar, || CONTROLS.on(ENABLED)); + +#[panic_handler] +fn panic(_: &core::panic::PanicInfo) -> ! { + core::arch::wasm32::unreachable() +} diff --git a/crates/core/src/hooks.rs b/crates/core/src/hooks.rs index 7361437b..d684ad02 100644 --- a/crates/core/src/hooks.rs +++ b/crates/core/src/hooks.rs @@ -323,6 +323,31 @@ impl Hooks { && self.through(Hook::KeepClear, false, |running, said| Ok(said | running.keep_clear()?)) } + /// The macOS top bar hook: whether to show macOS style traffic lights and title bar (not 0), + /// or default to the platform's standard window decorations. + pub(crate) fn macos_top_bar(&self) -> bool { + self.has(Hook::MacosTopBar) + && self.through(Hook::MacosTopBar, false, |running, said| Ok(said | running.macos_top_bar()?)) + } + + /// The fullscreen hook: whether fullscreen features are active. + pub(crate) fn fullscreen(&self) -> bool { + self.has(Hook::Fullscreen) + && self.through(Hook::Fullscreen, false, |running, said| Ok(said | running.fullscreen()?)) + } + + /// Whether exclusive fullscreen mode is chosen. + pub(crate) fn exclusive_fullscreen(&self) -> bool { + self.has(Hook::Fullscreen) + && self.through(Hook::Fullscreen, false, |running, said| Ok(said | running.exclusive_fullscreen()?)) + } + + /// Whether keyboard shortcuts for fullscreen are enabled. + pub(crate) fn fullscreen_shortcuts(&self) -> bool { + self.has(Hook::Fullscreen) + && self.through(Hook::Fullscreen, false, |running, said| Ok(said | running.fullscreen_shortcuts()?)) + } + /// The undo notice hook: whether undo and redo go by without the notice naming what they took /// back or brought back. pub(crate) fn hide_undo_notice(&self) -> bool { @@ -2169,6 +2194,76 @@ pub(crate) mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn macos_top_bar_hook_answers_while_a_plugin_asks_for_it() { + let dir = store("macos-top-bar"); + let module = wat::parse_str( + r#"(module + (global $on (mut i32) (i32.const 1)) + (func (export "procraft_macos_top_bar") (result i32) (global.get $on)) + (func (export "procraft_control") (param i32 f32) + (if (f32.ge (local.get 1) (f32.const 0.5)) + (then (global.set $on (i32.const 1))) + (else (global.set $on (i32.const 0))))))"#, + ) + .unwrap(); + let plugins = Plugins::with_store(dir.clone()); + let mut manifest = coded(ID, &module); + manifest["hooks"] = json!(["macos_top_bar"]); + manifest["controls"] = json!([ + { "key": "enabled", "type": "switch", "label": "macOS style top bar", "starts": true } + ]); + assert_eq!(plugins.install(file(&manifest, &module)), None); + // off by default when installed + assert!(!plugins.macos_top_bar()); + // turn on the plugin + assert!(plugins.set_on(ID.to_owned(), true)); + assert!(plugins.macos_top_bar()); + // toggle switch off + assert!(plugins.set_switch(format!("{ID}.enabled"), false)); + assert!(!plugins.macos_top_bar()); + // toggle switch back on + assert!(plugins.set_switch(format!("{ID}.enabled"), true)); + assert!(plugins.macos_top_bar()); + // turn plugin off + assert!(plugins.set_on(ID.to_owned(), false)); + assert!(!plugins.macos_top_bar()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn fullscreen_hook_answers_while_a_plugin_asks_for_it() { + let dir = store("fullscreen-test"); + let module = wat::parse_str( + r#"(module + (global $on (mut i32) (i32.const 1)) + (func (export "procraft_fullscreen") (result i32) (global.get $on)) + (func (export "procraft_exclusive_fullscreen") (result i32) (global.get $on)) + (func (export "procraft_fullscreen_shortcuts") (result i32) (global.get $on)) + (func (export "procraft_control") (param i32 f32) + (if (f32.ge (local.get 1) (f32.const 0.5)) + (then (global.set $on (i32.const 1))) + (else (global.set $on (i32.const 0))))))"#, + ) + .unwrap(); + let plugins = Plugins::with_store(dir.clone()); + let mut manifest = coded(ID, &module); + manifest["hooks"] = json!(["fullscreen"]); + manifest["controls"] = json!([ + { "key": "enabled", "type": "switch", "label": "Enable fullscreen features", "starts": true } + ]); + assert_eq!(plugins.install(file(&manifest, &module)), None); + assert!(!plugins.fullscreen_active()); + assert!(plugins.set_on(ID.to_owned(), true)); + assert!(plugins.fullscreen_active()); + assert!(plugins.exclusive_fullscreen()); + assert!(plugins.fullscreen_shortcuts()); + assert!(plugins.set_switch(format!("{ID}.enabled"), false)); + assert!(!plugins.fullscreen_active()); + assert!(plugins.set_on(ID.to_owned(), false)); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_touch_with_a_panel_open_paints_at_once_and_leaves_it_while_a_plugin_pins_it() { use crate::touch::{TouchCommand, TouchMove}; diff --git a/crates/core/src/plugin_run.rs b/crates/core/src/plugin_run.rs index 3367ae6d..fc6816e3 100644 --- a/crates/core/src/plugin_run.rs +++ b/crates/core/src/plugin_run.rs @@ -203,6 +203,10 @@ const FILL_OUT: &str = "procraft_fill_out"; const FILL_ALL_LAYERS: &str = "procraft_fill_all_layers"; const RADIAL_SEGMENTS: &str = "procraft_radial_segments"; const HIDE_UNDO_NOTICE: &str = "procraft_hide_undo_notice"; +const MACOS_TOP_BAR: &str = "procraft_macos_top_bar"; +const FULLSCREEN: &str = "procraft_fullscreen"; +const EXCLUSIVE_FULLSCREEN: &str = "procraft_exclusive_fullscreen"; +const FULLSCREEN_SHORTCUTS: &str = "procraft_fullscreen_shortcuts"; const INTERFACE_COLOUR: &str = "procraft_interface_colour"; const PIN_PANELS: &str = "procraft_pin_panels"; const OPACITY_TOGETHER: &str = "procraft_opacity_together"; @@ -353,6 +357,10 @@ pub(crate) enum Hook { InterfacePartScale, /// The floating colour window with Classic's picker alone. FloatingPickerOnly, + /// Window top bar and controls styled as macOS traffic lights. + MacosTopBar, + /// Fullscreen mode and window display controls. + Fullscreen, } impl Hook { @@ -379,6 +387,8 @@ impl Hook { "layer_added" => Some(Hook::LayerAdded), "key_shortcut" => Some(Hook::KeyShortcut), "keep_clear" => Some(Hook::KeepClear), + "macos_top_bar" => Some(Hook::MacosTopBar), + "fullscreen" => Some(Hook::Fullscreen), "interface_part_scale" => Some(Hook::InterfacePartScale), "floating_picker_only" => Some(Hook::FloatingPickerOnly), _ => None, @@ -409,6 +419,10 @@ impl Hook { Hook::LayerAdded => "This plugin can act on your artwork each time you add a layer.", Hook::KeyShortcut => "This plugin can change what your keyboard's keys do.", Hook::KeepClear => "This plugin can keep the interface clear of the status bar and the camera.", + Hook::MacosTopBar => { + "This plugin can change the window top bar style to macOS style with traffic light controls." + } + Hook::Fullscreen => "This plugin can control fullscreen display and window shortcuts.", Hook::Layers => "This plugin can add kinds of layer whose strokes it keeps, and draw them again.", Hook::Brushes => "This plugin can read brush files and draw their brushes its own way.", Hook::InterfacePartScale => "This plugin can make parts of the interface bigger or smaller.", @@ -432,6 +446,8 @@ impl Hook { Hook::InterfaceColour => exports(module, INTERFACE_COLOUR, &[ValType::I32], &[ValType::I32]), Hook::PinPanels => exports(module, PIN_PANELS, &[], &[ValType::I32]), Hook::KeepClear => exports(module, KEEP_CLEAR, &[], &[ValType::I32]), + Hook::MacosTopBar => exports(module, MACOS_TOP_BAR, &[], &[ValType::I32]), + Hook::Fullscreen => exports(module, FULLSCREEN, &[], &[ValType::I32]), Hook::InterfacePartScale => exports(module, INTERFACE_PART_SCALE, &[ValType::I32], &[ValType::F32]), Hook::FloatingPickerOnly => exports(module, FLOATING_PICKER_ONLY, &[], &[ValType::I32]), Hook::OpacityTogether => exports(module, OPACITY_TOGETHER, &[], &[ValType::I32]), @@ -784,6 +800,10 @@ pub(crate) struct Running { interface_colour: Option>, pin_panels: Option>, keep_clear: Option>, + macos_top_bar: Option>, + fullscreen: Option>, + exclusive_fullscreen: Option>, + fullscreen_shortcuts: Option>, opacity_together: Option>, randomise: Option>, colour_triangle: Option>, @@ -930,6 +950,10 @@ impl Running { let interface_colour = instance.get_typed_func(&store, INTERFACE_COLOUR).ok(); let pin_panels = instance.get_typed_func(&store, PIN_PANELS).ok(); let keep_clear = instance.get_typed_func(&store, KEEP_CLEAR).ok(); + let macos_top_bar = instance.get_typed_func(&store, MACOS_TOP_BAR).ok(); + let fullscreen = instance.get_typed_func(&store, FULLSCREEN).ok(); + let exclusive_fullscreen = instance.get_typed_func(&store, EXCLUSIVE_FULLSCREEN).ok(); + let fullscreen_shortcuts = instance.get_typed_func(&store, FULLSCREEN_SHORTCUTS).ok(); let opacity_together = instance.get_typed_func(&store, OPACITY_TOGETHER).ok(); let randomise = instance.get_typed_func(&store, RANDOMISE).ok(); let colour_triangle = instance.get_typed_func(&store, COLOUR_TRIANGLE).ok(); @@ -1029,6 +1053,10 @@ impl Running { interface_colour, pin_panels, keep_clear, + macos_top_bar, + fullscreen, + exclusive_fullscreen, + fullscreen_shortcuts, opacity_together, randomise, colour_triangle, @@ -1996,6 +2024,50 @@ impl Running { Ok(said != 0) } + /// Whether it says the top bar uses macOS style window controls. + pub(crate) fn macos_top_bar(&mut self) -> Result { + let Running { store, macos_top_bar, .. } = self; + let Some(macos_top_bar) = macos_top_bar else { return Ok(false) }; + let said = guarded(|| { + store.set_fuel(SAMPLE_FUEL).map_err(|_| Stop::Damaged)?; + macos_top_bar.call(&mut *store, ()).map_err(|e| stop_of(&e)) + })?; + Ok(said != 0) + } + + /// Whether it says fullscreen mode features are active. + pub(crate) fn fullscreen(&mut self) -> Result { + let Running { store, fullscreen, .. } = self; + let Some(fullscreen) = fullscreen else { return Ok(false) }; + let said = guarded(|| { + store.set_fuel(SAMPLE_FUEL).map_err(|_| Stop::Damaged)?; + fullscreen.call(&mut *store, ()).map_err(|e| stop_of(&e)) + })?; + Ok(said != 0) + } + + /// Whether it says exclusive fullscreen mode is enabled. + pub(crate) fn exclusive_fullscreen(&mut self) -> Result { + let Running { store, exclusive_fullscreen, .. } = self; + let Some(exclusive_fullscreen) = exclusive_fullscreen else { return Ok(false) }; + let said = guarded(|| { + store.set_fuel(SAMPLE_FUEL).map_err(|_| Stop::Damaged)?; + exclusive_fullscreen.call(&mut *store, ()).map_err(|e| stop_of(&e)) + })?; + Ok(said != 0) + } + + /// Whether it says keyboard shortcuts (F11 / Alt+Enter) are enabled. + pub(crate) fn fullscreen_shortcuts(&mut self) -> Result { + let Running { store, fullscreen_shortcuts, .. } = self; + let Some(fullscreen_shortcuts) = fullscreen_shortcuts else { return Ok(false) }; + let said = guarded(|| { + store.set_fuel(SAMPLE_FUEL).map_err(|_| Stop::Damaged)?; + fullscreen_shortcuts.call(&mut *store, ()).map_err(|e| stop_of(&e)) + })?; + Ok(said != 0) + } + /// Whether it says undo and redo go by without their notice. pub(crate) fn hide_undo_notice(&mut self) -> Result { let Running { store, hide_undo_notice, .. } = self; diff --git a/crates/core/src/plugins.rs b/crates/core/src/plugins.rs index 830b76e2..1bb50ec5 100644 --- a/crates/core/src/plugins.rs +++ b/crates/core/src/plugins.rs @@ -1579,6 +1579,26 @@ impl Plugins { self.hooks().keep_clear() } + /// Whether an enabled plugin asks for the macOS style top bar and window controls. + pub fn macos_top_bar(&self) -> bool { + self.hooks().macos_top_bar() + } + + /// Whether an enabled plugin asks for fullscreen mode features. + pub fn fullscreen_active(&self) -> bool { + self.hooks().fullscreen() + } + + /// Whether the fullscreen plugin has exclusive fullscreen enabled. + pub fn exclusive_fullscreen(&self) -> bool { + self.hooks().exclusive_fullscreen() + } + + /// Whether the fullscreen plugin enables keyboard shortcuts. + pub fn fullscreen_shortcuts(&self) -> bool { + self.hooks().fullscreen_shortcuts() + } + /// Whether a plugin draws in-betweens: Animation Assist's frame options then offer In-between /// ([`crate::CanvasSession::add_inbetween`]). pub fn tweens(&self) -> bool { diff --git a/desktop/src/chrome.rs b/desktop/src/chrome.rs index 8a89aa97..abf7015f 100644 --- a/desktop/src/chrome.rs +++ b/desktop/src/chrome.rs @@ -72,7 +72,12 @@ pub fn frost(glass: &mut Vec, rect: Rect, corner: f32, ppp: f32) { /// buttons are where they show. pub fn top_bar(ui: &mut Ui, look: &mut Look, tool: ToolKind, colour: Color32, brightness: f32, lit: &Lit) -> Bar { let mut bar = Bar::default(); - let frame = egui::Frame::NONE.fill(argb(pc::BAR)); + let macos = crate::window_controls::is_macos_topbar(); + let frame = if macos { + egui::Frame::NONE.fill(argb(pc::BAR)).corner_radius(egui::CornerRadius { nw: 12, ne: 12, sw: 0, se: 0 }) + } else { + egui::Frame::NONE.fill(argb(pc::BAR)) + }; let k = crate::panel::part_scale(ui.ctx(), InterfacePart::TopBar); egui::Panel::top("bar").exact_size(pc::BAR_HEIGHT * k).frame(frame).show(ui, |ui| { let shown = ui.max_rect(); @@ -81,8 +86,13 @@ pub fn top_bar(ui: &mut Ui, look: &mut Look, tool: ToolKind, colour: Color32, br let ctx = ui.ctx().clone(); let first = ctx.graphics(|g| g.get(ui.layer_id()).map_or(ShapeIdx(0), PaintList::next_idx)); look.set_zoom(ui.layer_id(), k); - let (tool_gap, action_gap) = pc::bar_gaps(r.width()); + let (tool_gap, action_gap) = + if macos { pc::bar_gaps((r.width() - 86.0).max(300.0)) } else { pc::bar_gaps(r.width()) }; let cy = r.center().y; + + // macOS 3 dots (traffic lights) on the left of top bar if enabled + let dots_hovered = if macos { crate::window_controls::traffic_lights(ui, r.left() + 16.0, cy) } else { false }; + let button = |x: f32, width: f32| { Rect::from_min_size(pos2(x, cy - pc::BAR_BUTTON_HEIGHT / 2.0), vec2(width, pc::BAR_BUTTON_HEIGHT)) }; @@ -102,7 +112,11 @@ pub fn top_bar(ui: &mut Ui, look: &mut Look, tool: ToolKind, colour: Color32, br } }; - let mut x = r.left() + pc::BAR_MARGIN; + let mut x = if macos { + r.left() + 16.0 + crate::window_controls::TRAFFIC_LIGHTS_WIDTH + 18.0 + } else { + r.left() + pc::BAR_MARGIN + }; let gallery = button(x, pc::GALLERY_WIDTH); tap(ui, BarButton::Gallery, gallery); text( @@ -175,6 +189,24 @@ pub fn top_bar(ui: &mut Ui, look: &mut Look, tool: ToolKind, colour: Color32, br } }); } + + if macos { + let over_button = dots_hovered + || bar + .rects + .iter() + .any(|(_, rect)| ui.input(|i| i.pointer.hover_pos().is_some_and(|p| rect.expand(4.0).contains(p)))); + if !over_button { + let bar_res = + ui.interact(to_window.mul_rect(r), ui.scope_id().with("top_bar_drag"), Sense::click_and_drag()); + if bar_res.drag_started_by(egui::PointerButton::Primary) { + crate::window_controls::request_drag(); + } + if bar_res.double_clicked() { + crate::window_controls::request_maximize(); + } + } + } }); bar } diff --git a/desktop/src/gallery.rs b/desktop/src/gallery.rs index e4ec37c5..b2869dfc 100644 --- a/desktop/src/gallery.rs +++ b/desktop/src/gallery.rs @@ -501,7 +501,8 @@ impl Gallery { .show(ctx, |ui| { ui.multiply_opacity(alpha); ui.allocate_rect(screen, Sense::hover()); - ui.painter().rect_filled(screen, 0, argb(BACKGROUND)); + let corner = if crate::window_controls::is_macos_topbar() { 12.0 } else { 0.0 }; + ui.painter().rect_filled(screen, corner, argb(BACKGROUND)); let tapped = self.header(ui, look, screen); let grid = Rect::from_min_max(pos2(screen.left(), screen.top() + HEADER), screen.max); let asked = if self.entries.is_empty() { diff --git a/desktop/src/main.rs b/desktop/src/main.rs index 286a7fdb..2d362a71 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -66,6 +66,7 @@ mod transform; mod transform_numeric; mod ui; mod video; +mod window_controls; mod zoom; use std::sync::Arc; @@ -280,6 +281,7 @@ fn main() { interface_touches: input::InterfaceTouches::default(), modifiers: winit::keyboard::ModifiersState::empty(), maximised_before_full_screen: false, + macos_top_bar: false, closed: false, }; // a panic on the window's thread ends the app: said, rather than the window just vanishing @@ -352,6 +354,8 @@ struct App { modifiers: winit::keyboard::ModifiersState, /// The window was maximised as it went full screen, and is maximised again as it comes back. maximised_before_full_screen: bool, + /// Whether the custom macOS top bar is active and window decorations are hidden. + macos_top_bar: bool, /// The window was closed (the artwork open kept): the app's end needs nothing more. closed: bool, } @@ -407,11 +411,15 @@ impl ApplicationHandler for App { if self.screen.is_some() { return; } + let macos = self.ui.plugins().macos_top_bar(); + self.macos_top_bar = macos; + crate::window_controls::set_macos_topbar(macos); let attributes = Window::default_attributes() .with_title("ProCraft") .with_window_icon(window_icon()) .with_inner_size(LogicalSize::new(1440.0, 900.0)) .with_min_inner_size(LogicalSize::new(640.0, 480.0)) + .with_decorations(!macos) // opened for a test (PROCRAFT_BACKGROUND set), it leaves the keyboard where it was .with_active(std::env::var_os("PROCRAFT_BACKGROUND").is_none()); // on Linux the desktop's menus match the window to the app's entry (procraft.desktop) @@ -474,6 +482,7 @@ impl ApplicationHandler for App { } fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + self.handle_window_actions(event_loop); let _timed = Timed(if event == WindowEvent::RedrawRequested { "a frame" } else { "a window event" }, Instant::now()); if self.projection.as_ref().is_some_and(|p| p.window.id() == id) { @@ -609,6 +618,7 @@ impl ApplicationHandler for App { } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + self.handle_window_actions(event_loop); // files opened from the Finder meanwhile come in as files dropped on the window do #[cfg(target_os = "macos")] { @@ -678,6 +688,52 @@ impl ApplicationHandler for App { } impl App { + fn handle_window_actions(&mut self, event_loop: &ActiveEventLoop) { + let macos = self.ui.plugins().macos_top_bar(); + crate::window_controls::set_macos_topbar(macos); + if self.macos_top_bar != macos { + self.macos_top_bar = macos; + if let Some(screen) = &self.screen { + screen.window.set_decorations(!macos); + screen.window.request_redraw(); + } + } + if let Some(action) = window_controls::take_pending_action() { + match action { + window_controls::WindowControlAction::Close => { + let waits = self.hide_while_opening(); + if self.leave_artwork() { + files::finish_writing(); + files::tell_what_was_told(); + self.closed = true; + event_loop.exit(); + } else if waits && let Some(screen) = &self.screen { + screen.window.set_visible(true); + } + } + window_controls::WindowControlAction::Minimize => { + if let Some(screen) = &self.screen { + screen.window.set_minimized(true); + } + } + window_controls::WindowControlAction::Maximize => { + if let Some(screen) = &self.screen { + screen.window.set_maximized(!screen.window.is_maximized()); + } + } + window_controls::WindowControlAction::Drag => { + if let Some(screen) = &self.screen { + let _ = screen.window.drag_window(); + } + } + window_controls::WindowControlAction::ToggleFullscreen => { + if let Some(screen) = &self.screen { + toggle_full_screen(&screen.window, &mut self.maximised_before_full_screen); + } + } + } + } + } /// Shows `session` in the window, in place of the artwork open. fn show(&mut self, session: Arc) { let Some(screen) = self.screen.as_mut() else { return }; diff --git a/desktop/src/pen.rs b/desktop/src/pen.rs index 94857d99..2774f250 100644 --- a/desktop/src/pen.rs +++ b/desktop/src/pen.rs @@ -722,9 +722,10 @@ mod system { POINTER_PEN_INFO, }; use windows::Win32::UI::WindowsAndMessaging::{ - CallWindowProcW, DefWindowProcW, GWLP_WNDPROC, MINMAXINFO, POINTER_INPUT_TYPE, PT_PEN, PT_TOUCH, RemovePropW, - SetPropW, SetWindowLongPtrW, WM_ACTIVATE, WM_DESTROY, WM_ENDSESSION, WM_GETMINMAXINFO, WM_LBUTTONDOWN, - WM_LBUTTONUP, WM_MOUSEMOVE, WM_POINTERDOWN, WM_POINTERLEAVE, WM_POINTERUP, WM_POINTERUPDATE, WNDPROC, + CallWindowProcW, DefWindowProcW, GWLP_WNDPROC, GetWindowRect, IsZoomed, MINMAXINFO, POINTER_INPUT_TYPE, PT_PEN, + PT_TOUCH, RemovePropW, SetPropW, SetWindowLongPtrW, WM_ACTIVATE, WM_DESTROY, WM_ENDSESSION, WM_GETMINMAXINFO, + WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_NCHITTEST, WM_POINTERDOWN, WM_POINTERLEAVE, WM_POINTERUP, + WM_POINTERUPDATE, WNDPROC, }; use windows::core::{PCWSTR, w}; use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; @@ -893,6 +894,48 @@ mod system { return LRESULT(0); } } + // For custom undecorated windows (macOS-style titlebar), provide native border resize hit-testing + if msg == WM_NCHITTEST + && crate::window_controls::is_macos_topbar() + && !FULL_SCREEN.load(Ordering::Relaxed) + && unsafe { !IsZoomed(hwnd).as_bool() } + { + let mut rect = RECT::default(); + if unsafe { GetWindowRect(hwnd, &mut rect).is_ok() } { + let x = (lparam.0 & 0xFFFF) as i16 as i32; + let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32; + let border = 8; + let on_left = x >= rect.left && x < rect.left + border; + let on_right = x < rect.right && x >= rect.right - border; + let on_top = y >= rect.top && y < rect.top + border; + let on_bottom = y < rect.bottom && y >= rect.bottom - border; + + if on_top && on_left { + return LRESULT(13); + } // HTTOPLEFT + if on_top && on_right { + return LRESULT(14); + } // HTTOPRIGHT + if on_bottom && on_left { + return LRESULT(16); + } // HTBOTTOMLEFT + if on_bottom && on_right { + return LRESULT(17); + } // HTBOTTOMRIGHT + if on_top { + return LRESULT(12); + } // HTTOP + if on_bottom { + return LRESULT(15); + } // HTBOTTOM + if on_left { + return LRESULT(10); + } // HTLEFT + if on_right { + return LRESULT(11); + } // HTRIGHT + } + } // the pen's gestures, as the window's property has them (a system that asks) if msg == WM_TABLET_QUERYSYSTEMGESTURESTATUS { return LRESULT(PEN_GESTURES_OFF as isize); diff --git a/desktop/src/tool_header.rs b/desktop/src/tool_header.rs index 8e9a92e3..d656a897 100644 --- a/desktop/src/tool_header.rs +++ b/desktop/src/tool_header.rs @@ -65,38 +65,63 @@ pub fn show_in( ui.allocate_rect(band, Sense::click()); let painter = ui.painter(); painter.rect_filled(band, 0, argb(colours.band)); - text(painter, band.min + vec2(32.0, 27.0), Align2::LEFT_TOP, title, 22.0, Weight::Bold, argb(LABEL)); + let macos = crate::window_controls::is_macos_topbar(); + let dots_hovered = if macos { + let cy = band.top() + 38.0; + crate::window_controls::traffic_lights(ui, band.left() + 16.0, cy) + } else { + false + }; + let title_x = if macos { 84.0 } else { 32.0 }; + text(painter, band.min + vec2(title_x, 27.0), Align2::LEFT_TOP, title, 22.0, Weight::Bold, argb(LABEL)); let done = Rect::from_min_size(pos2(band.right() - 20.0 - 44.0, band.top() + 20.0), vec2(44.0, 44.0)); painter.circle_filled(done.center(), 22.0, argb(DONE)); look.icon(ui, &icons::DONE_TICK, done.center(), 40.0, Color32::WHITE); if ui.interact(done, ui.scope_id().with("done"), Sense::click()).clicked() { tapped = Some(Tapped::Done); } - if buttons.is_empty() { - return; - } - let galleys: Vec<_> = buttons - .iter() - .map(|(label, chosen)| { - let ink = if *chosen { argb(CHOSEN) } else { argb(BUTTON) }; - ui.painter().layout_no_wrap((*label).to_owned(), Weight::Regular.font(17.0), ink) - }) - .collect(); - let width: f32 = galleys.iter().map(|g| g.size().x + 26.0).sum(); - let capsule = Rect::from_min_size(pos2(done.left() - 13.0 - width, band.top() + 20.0), vec2(width, 43.0)); - ui.painter().rect_filled(capsule, 21.5, argb(colours.capsule)); - ui.painter().rect_stroke(capsule, 21.5, Stroke::new(1.0, argb(colours.edge)), egui::StrokeKind::Inside); - let mut x = capsule.left(); - for (i, ((_, chosen), galley)) in buttons.iter().zip(galleys).enumerate() { - let button = Rect::from_min_size(pos2(x, capsule.top()), vec2(galley.size().x + 26.0, 43.0)); - if *chosen { - ui.painter().rect_filled(button, 21.5, argb(CHOSEN_FILL)); + + let mut over_capsule = false; + if !buttons.is_empty() { + let galleys: Vec<_> = buttons + .iter() + .map(|(label, chosen)| { + let ink = if *chosen { argb(CHOSEN) } else { argb(BUTTON) }; + ui.painter().layout_no_wrap((*label).to_owned(), Weight::Regular.font(17.0), ink) + }) + .collect(); + let width: f32 = galleys.iter().map(|g| g.size().x + 26.0).sum(); + let capsule = Rect::from_min_size(pos2(done.left() - 13.0 - width, band.top() + 20.0), vec2(width, 43.0)); + over_capsule = ui.input(|i| i.pointer.hover_pos().is_some_and(|p| capsule.expand(4.0).contains(p))); + ui.painter().rect_filled(capsule, 21.5, argb(colours.capsule)); + ui.painter().rect_stroke(capsule, 21.5, Stroke::new(1.0, argb(colours.edge)), egui::StrokeKind::Inside); + let mut x = capsule.left(); + for (i, ((_, chosen), galley)) in buttons.iter().zip(galleys).enumerate() { + let button = Rect::from_min_size(pos2(x, capsule.top()), vec2(galley.size().x + 26.0, 43.0)); + if *chosen { + ui.painter().rect_filled(button, 21.5, argb(CHOSEN_FILL)); + } + ui.painter().galley(button.center() - galley.size() / 2.0, galley.clone(), Color32::WHITE); + if ui.interact(button, ui.scope_id().with(("tool button", i)), Sense::click()).clicked() { + tapped = Some(Tapped::Button(i)); + } + x = button.right(); } - ui.painter().galley(button.center() - galley.size() / 2.0, galley.clone(), Color32::WHITE); - if ui.interact(button, ui.scope_id().with(("tool button", i)), Sense::click()).clicked() { - tapped = Some(Tapped::Button(i)); + } + + if macos { + let over_element = dots_hovered + || over_capsule + || ui.input(|i| i.pointer.hover_pos().is_some_and(|p| done.expand(4.0).contains(p))); + if !over_element { + let res = ui.interact(band, ui.scope_id().with("tool_header_drag"), Sense::click_and_drag()); + if res.drag_started_by(egui::PointerButton::Primary) { + crate::window_controls::request_drag(); + } + if res.double_clicked() { + crate::window_controls::request_maximize(); + } } - x = button.right(); } }); tapped diff --git a/desktop/src/window_controls.rs b/desktop/src/window_controls.rs new file mode 100644 index 00000000..415c88e0 --- /dev/null +++ b/desktop/src/window_controls.rs @@ -0,0 +1,161 @@ +//! macOS-style traffic lights (3 window control dots: Close, Minimize, Maximize) +//! and window action dispatching for custom top bars. + +use egui::{Color32, Rect, Sense, Stroke, Ui, pos2, vec2}; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; + +static MACOS_TOPBAR: AtomicBool = AtomicBool::new(false); + +/// Sets whether the macOS style top bar is active. +pub fn set_macos_topbar(enabled: bool) { + MACOS_TOPBAR.store(enabled, Ordering::Relaxed); +} + +/// Returns whether the macOS style top bar is active. +pub fn is_macos_topbar() -> bool { + MACOS_TOPBAR.load(Ordering::Relaxed) +} + +/// The pending window action requested by the user interface. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WindowControlAction { + Close, + Minimize, + Maximize, + Drag, + ToggleFullscreen, +} + +static PENDING_ACTION: AtomicU8 = AtomicU8::new(0); +const ACT_NONE: u8 = 0; +const ACT_CLOSE: u8 = 1; +const ACT_MINIMIZE: u8 = 2; +const ACT_MAXIMIZE: u8 = 3; +const ACT_DRAG: u8 = 4; +const ACT_TOGGLE_FULLSCREEN: u8 = 5; + +/// Retrieves and clears any pending window action. +pub fn take_pending_action() -> Option { + match PENDING_ACTION.swap(ACT_NONE, Ordering::Relaxed) { + ACT_CLOSE => Some(WindowControlAction::Close), + ACT_MINIMIZE => Some(WindowControlAction::Minimize), + ACT_MAXIMIZE => Some(WindowControlAction::Maximize), + ACT_DRAG => Some(WindowControlAction::Drag), + ACT_TOGGLE_FULLSCREEN => Some(WindowControlAction::ToggleFullscreen), + _ => None, + } +} + +pub fn request_close() { + PENDING_ACTION.store(ACT_CLOSE, Ordering::Relaxed); +} + +pub fn request_minimize() { + PENDING_ACTION.store(ACT_MINIMIZE, Ordering::Relaxed); +} + +pub fn request_maximize() { + PENDING_ACTION.store(ACT_MAXIMIZE, Ordering::Relaxed); +} + +pub fn request_drag() { + PENDING_ACTION.store(ACT_DRAG, Ordering::Relaxed); +} + +#[allow(dead_code)] +pub fn request_toggle_fullscreen() { + PENDING_ACTION.store(ACT_TOGGLE_FULLSCREEN, Ordering::Relaxed); +} + +pub const DOT_RADIUS: f32 = 6.0; +pub const DOT_DIAMETER: f32 = 12.0; +pub const DOT_SPACING: f32 = 8.0; +pub const TRAFFIC_LIGHTS_WIDTH: f32 = DOT_DIAMETER * 3.0 + DOT_SPACING * 2.0; // 52.0 + +/// Draws the macOS 3 traffic light dots centered at `center_y` starting at `left`. +/// Returns true if the traffic light cluster or any dot was hovered or interacted with. +pub fn traffic_lights(ui: &Ui, left: f32, center_y: f32) -> bool { + let cluster_rect = Rect::from_min_size(pos2(left, center_y - 8.0), vec2(TRAFFIC_LIGHTS_WIDTH, 16.0)); + let cluster_hovered = ui.input(|i| i.pointer.hover_pos().is_some_and(|p| cluster_rect.expand(3.0).contains(p))); + + let red_center = pos2(left + 6.0, center_y); + let yellow_center = pos2(left + 26.0, center_y); + let green_center = pos2(left + 46.0, center_y); + + let red_rect = Rect::from_center_size(red_center, vec2(14.0, 14.0)); + let yellow_rect = Rect::from_center_size(yellow_center, vec2(14.0, 14.0)); + let green_rect = Rect::from_center_size(green_center, vec2(14.0, 14.0)); + + let red_res = ui.interact(red_rect, ui.scope_id().with("mac_dot_red"), Sense::click()); + let yellow_res = ui.interact(yellow_rect, ui.scope_id().with("mac_dot_yellow"), Sense::click()); + let green_res = ui.interact(green_rect, ui.scope_id().with("mac_dot_green"), Sense::click()); + + if red_res.clicked() { + request_close(); + } + if yellow_res.clicked() { + request_minimize(); + } + if green_res.clicked() { + request_maximize(); + } + + let painter = ui.painter(); + + // Red (Close): #FF5F57 + let red_fill = if red_res.is_pointer_button_down_on() { + Color32::from_rgb(190, 60, 55) + } else { + Color32::from_rgb(255, 95, 87) + }; + painter.circle_filled(red_center, DOT_RADIUS, red_fill); + painter.circle_stroke(red_center, DOT_RADIUS - 0.25, Stroke::new(0.5, Color32::from_rgb(224, 68, 62))); + + // Yellow (Minimize): #FEBC2E + let yellow_fill = if yellow_res.is_pointer_button_down_on() { + Color32::from_rgb(205, 145, 30) + } else { + Color32::from_rgb(254, 188, 46) + }; + painter.circle_filled(yellow_center, DOT_RADIUS, yellow_fill); + painter.circle_stroke(yellow_center, DOT_RADIUS - 0.25, Stroke::new(0.5, Color32::from_rgb(222, 161, 35))); + + // Green (Maximize / Zoom): #28C840 + let green_fill = if green_res.is_pointer_button_down_on() { + Color32::from_rgb(28, 150, 45) + } else { + Color32::from_rgb(40, 200, 64) + }; + painter.circle_filled(green_center, DOT_RADIUS, green_fill); + painter.circle_stroke(green_center, DOT_RADIUS - 0.25, Stroke::new(0.5, Color32::from_rgb(26, 171, 41))); + + // Draw macOS symbols on hover + if cluster_hovered { + // Red symbol: 'x' + let x_color = Color32::from_rgba_premultiplied(77, 0, 0, 220); + painter.line_segment([red_center + vec2(-2.5, -2.5), red_center + vec2(2.5, 2.5)], Stroke::new(1.15, x_color)); + painter.line_segment([red_center + vec2(-2.5, 2.5), red_center + vec2(2.5, -2.5)], Stroke::new(1.15, x_color)); + + // Yellow symbol: '-' + let minus_color = Color32::from_rgba_premultiplied(153, 87, 0, 240); + painter.line_segment( + [yellow_center + vec2(-3.0, 0.0), yellow_center + vec2(3.0, 0.0)], + Stroke::new(1.15, minus_color), + ); + + // Green symbol: two opposing diagonal triangles pointing to corners + let glyph_green = Color32::from_rgba_premultiplied(0, 100, 0, 220); + painter.add(egui::Shape::convex_polygon( + vec![green_center + vec2(2.7, -2.7), green_center + vec2(0.5, -2.7), green_center + vec2(2.7, -0.5)], + glyph_green, + Stroke::NONE, + )); + painter.add(egui::Shape::convex_polygon( + vec![green_center + vec2(-2.7, 2.7), green_center + vec2(-0.5, 2.7), green_center + vec2(-2.7, 0.5)], + glyph_green, + Stroke::NONE, + )); + } + + cluster_hovered || red_res.hovered() || yellow_res.hovered() || green_res.hovered() +}