1use egui::{Context, Rect, Ui, Vec2, ViewportCommand};
102use egui_pop_core::frame::{FrameRequest, HitTable, TitleBar};
103use egui_pop_core::icon::{Icon, Size};
104use egui_pop_core::lock;
105use egui_pop_core::overlay::{self, Anchor, Kind, OverlaySpec};
106use egui_pop_core::placement::Side;
107use egui_pop_core::state::Slot;
108use egui_pop_core::strings;
109use egui_pop_model::commands::CommandSpec;
110use egui_pop_model::ids::{BlockId, CommandId, MenuId, PluginId, SettingId, StepId};
111use egui_pop_model::values::Descriptor;
112use serde_json::{Value as Json, json};
113
114use crate::app::{AppHandle, MENU_VIEW};
115use crate::steps::StepSpec;
116use crate::strings as txt;
117use crate::zones::{self, Block};
118use crate::{Ctx, Plugin, PluginError};
119
120pub const SETTING_FRAME: SettingId = SettingId::from_static("window.frame");
122
123pub const SETTING_BAR_IN_FULLSCREEN: SettingId = SettingId::from_static("window.bar_in_fullscreen");
126
127pub const MENU_SYSTEM: MenuId = MenuId::from_static("app.menu.system");
130
131pub const CMD_MINIMIZE: CommandId = CommandId::from_static("app.window.minimize");
132pub const CMD_MAXIMIZE: CommandId = CommandId::from_static("app.window.maximize");
133pub const CMD_CLOSE: CommandId = CommandId::from_static("app.window.close");
134pub const CMD_SYSTEM_MENU: CommandId = CommandId::from_static("app.window.menu");
135
136pub const STEP_MINIMIZE: StepId = StepId::from_static("frame.minimize");
137pub const STEP_MAXIMIZE: StepId = StepId::from_static("frame.maximize");
138pub const STEP_CLOSE: StepId = StepId::from_static("frame.close");
139pub const STEP_SYSTEM_MENU: StepId = StepId::from_static("frame.system_menu");
140pub const STEP_HIT_TEST: StepId = StepId::from_static("frame.hit_test");
141pub const STEP_EXIT_FULLSCREEN: StepId = StepId::from_static("frame.exit_fullscreen");
142
143pub const BLOCK_TITLE: BlockId = BlockId::from_static("egui_pop.frame");
147pub const BLOCK_MENU: BlockId = BlockId::from_static("egui_pop.frame.menu");
150
151pub type Logo = std::sync::Arc<dyn Fn(&Context) -> egui::ImageSource<'static> + Send + Sync>;
154
155#[derive(Clone, Default)]
159pub struct FramePlugin {
160 own: bool,
161 name: String,
162 layout_controls: bool,
163 logo: Option<Logo>,
164}
165
166impl std::fmt::Debug for FramePlugin {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.debug_struct("FramePlugin")
169 .field("own", &self.own)
170 .field("name", &self.name)
171 .field("layout_controls", &self.layout_controls)
172 .field("logo", &self.logo.is_some())
173 .finish()
174 }
175}
176
177impl FramePlugin {
178 pub fn own() -> Self {
180 Self {
181 own: true,
182 ..Self::default()
183 }
184 }
185
186 pub fn system() -> Self {
188 Self::default()
189 }
190
191 pub fn name(mut self, name: &str) -> Self {
194 self.name = name.into();
195 self
196 }
197
198 pub fn logo(
214 mut self,
215 image: impl Fn(&Context) -> egui::ImageSource<'static> + Send + Sync + 'static,
216 ) -> Self {
217 self.logo = Some(std::sync::Arc::new(image));
218 self
219 }
220
221 pub fn layout_controls(mut self, on: bool) -> Self {
227 self.layout_controls = on;
228 self
229 }
230}
231
232fn logo_image(ui: &mut Ui, logo: &Logo, name: &str) {
235 let side = egui_pop_core::theme::Tokens::of(ui.ctx()).size.icon_toolbar;
236 let image = egui::Image::new(logo(ui.ctx()))
237 .fit_to_exact_size(egui::vec2(side, side))
238 .sense(egui::Sense::hover());
239 let response = ui.add(image);
240 let label = strings::tr_args(ui.ctx(), &txt::FRAME_LOGO, &[("application", name)]);
241 egui_pop_core::a11y::name(&response, egui::Role::Image, &label);
242}
243
244pub fn own_frame(app: &AppHandle) -> bool {
246 lock(&app.store())
247 .get(&format!("settings/{SETTING_FRAME}"))
248 .and_then(|e| e.value.as_choice().map(|c| c == "own"))
249 .unwrap_or(false)
250}
251
252pub fn bar_in_fullscreen(app: &AppHandle) -> bool {
255 lock(&app.store())
256 .get(&format!("settings/{SETTING_BAR_IN_FULLSCREEN}"))
257 .and_then(|e| e.value.as_bool())
258 .unwrap_or(true)
259}
260
261fn viewport_name(ctx: &Context) -> String {
262 if ctx.viewport_id() == egui::ViewportId::ROOT {
263 "root".into()
264 } else {
265 format!("{:?}", ctx.viewport_id())
266 }
267}
268
269pub fn request(app: &AppHandle, ctx: &Context, r: FrameRequest) {
271 let c = ctx.clone();
272 match r {
273 FrameRequest::Minimize => {
274 app.step(&STEP_MINIMIZE, json!({}), move |_, _| {
275 c.send_viewport_cmd(ViewportCommand::Minimized(true));
276 Ok(json!({ "minimized": true }))
277 });
278 }
279 FrameRequest::ToggleMaximize => {
280 let to = !ctx.input(|i| i.viewport().maximized.unwrap_or(false));
281 app.step(
282 &STEP_MAXIMIZE,
283 json!({ "maximized": to }),
284 move |_, args| {
285 let to = args["maximized"].as_bool().unwrap_or(true);
286 c.send_viewport_cmd(ViewportCommand::Maximized(to));
287 Ok(json!({ "maximized": to }))
288 },
289 );
290 }
291 FrameRequest::Close => {
292 app.step(
293 &STEP_CLOSE,
294 json!({ "viewport": viewport_name(ctx) }),
295 move |app, _| Ok(json!({ "closed": app.frame_close(&c) })),
296 );
297 }
298 FrameRequest::ExitFullscreen => {
299 app.step(
300 &STEP_EXIT_FULLSCREEN,
301 json!({ "viewport": viewport_name(ctx) }),
302 move |_, _| {
303 c.send_viewport_cmd(ViewportCommand::Fullscreen(false));
304 Ok(json!({ "fullscreen": false }))
305 },
306 );
307 }
308 FrameRequest::SystemMenu(at) => {
309 app.step(
310 &STEP_SYSTEM_MENU,
311 json!({ "x": at.x, "y": at.y }),
312 move |_, args| {
313 let x = args["x"].as_f64().unwrap_or(0.0) as f32;
314 let y = args["y"].as_f64().unwrap_or(0.0) as f32;
315 let pass = c.cumulative_pass_nr();
316 SYSTEM_MENU.set(&c, Some((egui::pos2(x, y), pass)));
317 Ok(json!({ "open": true }))
318 },
319 );
320 }
321 }
322}
323
324const SYSTEM_MENU: Slot<Option<(egui::Pos2, u64)>> = Slot::new("api.frame.system_menu");
326const DECORATED: Slot<bool> = Slot::new("api.frame.decorated");
328const BAR_IN_FULL_SCREEN: Slot<u64> = Slot::new("api.frame.bar_in_full_screen");
330const NATIVE_WINDOW: Slot<isize> = Slot::new("api.frame.native_window");
332const X11_WINDOW: Slot<u64> = Slot::new("api.frame.x11_window");
334
335impl Plugin for FramePlugin {
336 fn id(&self) -> PluginId {
337 PluginId::from_static("egui_pop.frame")
338 }
339
340 fn title(&self) -> String {
341 "Window frame".into()
342 }
343
344 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
345 ctx.setting(
346 SETTING_FRAME,
347 Descriptor::choice(
348 "Window frame",
349 &["own", "system"],
350 if self.own { "own" } else { "system" },
351 )
352 .description(
353 "Who draws the window's title bar and edges: the application (own), or the desktop (system).",
354 ),
355 )?;
356 ctx.setting(
357 SETTING_BAR_IN_FULLSCREEN,
358 Descriptor::bool("Title bar in full screen", true).description(
359 "Keeps the application's title bar (its buttons and items) in full screen; off, full screen hides it.",
360 ),
361 )?;
362 for spec in [
363 StepSpec::new(STEP_MINIMIZE, "The frame minimizes the window.").args(json!({})),
364 StepSpec::new(
365 STEP_MAXIMIZE,
366 "The frame maximizes or restores the window (`maximized`: the state asked for).",
367 )
368 .args(json!({ "maximized": true })),
369 StepSpec::new(
370 STEP_CLOSE,
371 "The frame closes a window (`viewport`: `root` for the main one).",
372 )
373 .args(json!({ "viewport": "root" })),
374 StepSpec::new(
375 STEP_SYSTEM_MENU,
376 "The frame opens the system menu at a point (`x`, `y`).",
377 )
378 .args(json!({ "x": 8.0, "y": 32.0 })),
379 StepSpec::new(
380 STEP_EXIT_FULLSCREEN,
381 "The title bar's button leaves full screen (`viewport`: `root` for the main window).",
382 )
383 .args(json!({ "viewport": "root" })),
384 StepSpec::new(
385 STEP_HIT_TEST,
386 "On Windows, the frame takes over the window's hit testing (`install`: true) or gives it back (false); a veto keeps the system's.",
387 )
388 .args(json!({ "viewport": "root", "install": true })),
389 ] {
390 ctx.step(spec)?;
391 }
392 ctx.zone(zones::CAPTION, "Title bar items")?;
393 ctx.zone(zones::CAPTION_START, "Title bar start")?;
394 ctx.command(
395 CommandSpec::new(CMD_MINIMIZE, "Minimize", "Window")
396 .icon("window-minimize")
397 .description("Minimizes the window.")
398 .menu(MENU_SYSTEM, "1_size", 1)
399 .no_agent(),
400 |call| {
401 request(call.app, &call.app.egui(), FrameRequest::Minimize);
402 Ok(Json::Null)
403 },
404 )?
405 .command(
406 CommandSpec::new(CMD_MAXIMIZE, "Maximize", "Window")
407 .icon("window-maximize")
408 .icon_on("window-restore")
409 .description("Maximizes the window, or restores it.")
410 .checked("windowMaximized")
411 .menu(MENU_SYSTEM, "1_size", 2)
412 .no_agent(),
413 |call| {
414 request(call.app, &call.app.egui(), FrameRequest::ToggleMaximize);
415 Ok(Json::Null)
416 },
417 )?
418 .command(
419 CommandSpec::new(CMD_CLOSE, "Close window", "Window")
420 .icon("window-close")
421 .description("Closes the window, as its close button does.")
422 .menu(MENU_SYSTEM, "9_close", 0)
423 .no_agent(),
424 |call| {
425 request(call.app, &call.app.egui(), FrameRequest::Close);
426 Ok(Json::Null)
427 },
428 )?
429 .command(
430 CommandSpec::new(CMD_SYSTEM_MENU, "Window menu", "Window")
431 .icon("menu")
432 .description("Opens the window's menu (restore, minimize, maximize, close).")
433 .key("Alt+Space")
434 .when("windowOwnFrame")
435 .menu(MENU_VIEW, "9_window", 1)
436 .no_agent(),
437 |call| {
438 let ctx = call.app.egui();
439 let at = HitTable::of(&ctx)
440 .get(egui::ViewportId::ROOT)
441 .and_then(|r| r.caption)
442 .map_or(egui::pos2(0.0, 0.0), |c| {
443 let ppp = ctx.pixels_per_point();
444 egui::pos2(c.x as f32 / ppp, (c.y + c.h) as f32 / ppp)
445 });
446 request(call.app, &ctx, FrameRequest::SystemMenu(at));
447 Ok(Json::Null)
448 },
449 )?;
450 let name = self.name.clone();
451 let logo = self.logo.clone();
452 ctx.block(zones::TITLE, Block::add(BLOCK_TITLE, 0, title_block));
453 if self.layout_controls {
454 ctx.block(
456 zones::CAPTION,
457 Block::add(
458 crate::layout_controls::BLOCK_LAYOUT_CONTROLS,
459 -1000,
460 crate::layout_controls::show,
461 ),
462 );
463 }
464 ctx.block(
465 zones::CAPTION_START,
466 Block::add(BLOCK_MENU, 0, move |ui, app| {
467 menu_button(ui, app);
468 let name = if name.is_empty() {
469 app.name()
470 } else {
471 name.clone()
472 };
473 if let Some(logo) = &logo {
474 logo_image(ui, logo, &name);
475 }
476 if !name.is_empty() {
477 ui.add(
478 egui::Label::new(egui::RichText::new(&name).strong())
479 .selectable(false)
480 .sense(egui::Sense::hover()),
481 );
482 }
483 }),
484 );
485 ctx.block(
486 zones::OVERLAYS,
487 Block::add(
488 BlockId::from_static("egui_pop.frame.edges"),
489 40,
490 |ui, app| {
491 edges(ui, app);
492 },
493 ),
494 );
495 let (w1, w2) = (ctx.app().downgrade(), ctx.app().downgrade());
496 ctx.collector(
497 egui_pop_core::debug::FnCollector::new(
498 "frame",
499 "The window frame: drawn by the application or the system; each window's hit regions in physical pixels (caption, buttons, edges).",
500 )
501 .snapshot(move |ctx| {
502 let Ok(app) = w1.get() else { return Json::Null };
503 let table = HitTable::of(ctx);
504 json!({
505 "own": own_frame(&app),
506 "hit_test": native::describe(ctx),
507 "corners": native::describe_corners(ctx),
508 "windows": table.viewports().into_iter().map(|v| json!({
509 "viewport": if v == egui::ViewportId::ROOT { "root".to_string() } else { format!("{v:?}") },
510 "regions": table.get(v).map(|r| (*r).clone()),
511 })).collect::<Vec<_>>(),
512 })
513 })
514 .action(
515 "hit",
516 "What a point of the main window is (`x`, `y` in physical pixels): caption, a button, an edge or client.",
517 false,
518 move |ctx, args| {
519 w2.get()?;
520 let x = args.get("x").and_then(Json::as_i64).ok_or("`x` is missing")? as i32;
521 let y = args.get("y").and_then(Json::as_i64).ok_or("`y` is missing")? as i32;
522 let r = HitTable::of(ctx)
523 .get(egui::ViewportId::ROOT)
524 .ok_or("the main window publishes no regions (the system draws its frame)")?;
525 Ok(json!(r.hit(x, y)))
526 },
527 )
528 .args(json!({ "x": 10, "y": 10 })),
529 )?;
530 Ok(())
531 }
532}
533
534fn follow_setting(ui: &Ui, app: &AppHandle) -> bool {
537 let ctx = ui.ctx();
538 let own = own_frame(app);
539 app.set_context("windowOwnFrame", if own { "true" } else { "false" });
540 let maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
541 app.set_context("windowMaximized", if maximized { "true" } else { "false" });
542 native::follow(ctx, app, own);
543 native::corners(ctx, own);
544 if DECORATED.keyed(ctx.viewport_id()).get(ctx).is_none() {
547 decorate(ctx, ctx.viewport_id(), own);
548 }
549 own
550}
551
552fn decorate(ctx: &Context, viewport: egui::ViewportId, own: bool) {
555 let key = DECORATED.keyed(viewport);
556 if key.get(ctx) == Some(own) {
557 return;
558 }
559 #[cfg(not(target_arch = "wasm32"))]
562 ctx.send_viewport_cmd_to(viewport, ViewportCommand::Decorations(!own));
563 key.set(ctx, own);
564 if !own {
565 HitTable::of(ctx).forget(viewport);
566 }
567}
568
569pub(crate) fn listen(app: &AppHandle) {
573 use crate::bus::{FRAME_DECORATIONS, OWNER, SettingsChanged, asking};
574 let listened = app.bus().listen_local::<SettingsChanged>(
575 FRAME_DECORATIONS,
576 bus_contract::ListenOpts::new().owner(OWNER),
577 |change, ()| {
578 if change.id() != SETTING_FRAME.as_str() {
579 return Ok(());
580 }
581 let Some(app) = asking() else { return Ok(()) };
582 decorate(&app.egui(), egui::ViewportId::ROOT, own_frame(&app));
583 Ok(())
584 },
585 );
586 if let Err(e) = listened {
587 log::error!(target: "egui_pop", "{FRAME_DECORATIONS}: {e}");
588 }
589}
590
591fn bar_in_full_screen(ctx: &Context) -> Slot<u64> {
592 BAR_IN_FULL_SCREEN.keyed(ctx.viewport_id())
593}
594
595pub(crate) fn bar_shown_in_full_screen(ctx: &Context) -> bool {
600 bar_in_full_screen(ctx)
601 .get(ctx)
602 .is_some_and(|pass| pass + 1 >= ctx.cumulative_pass_nr())
603}
604
605pub fn menu_button(ui: &mut Ui, app: &AppHandle) -> egui::Response {
609 let r = ui.add(
610 Icon::Menu
611 .size(Size::Toolbar)
612 .label(&strings::tr(ui.ctx(), &txt::FRAME_WINDOW_MENU))
613 .sense_click(),
614 );
615 if r.clicked() {
616 request(
617 app,
618 ui.ctx(),
619 FrameRequest::SystemMenu(r.rect.left_bottom()),
620 );
621 }
622 r
623}
624
625fn title_block(ui: &mut Ui, app: &AppHandle) {
628 if !follow_setting(ui, app) {
629 return;
630 }
631 let ctx = ui.ctx().clone();
632 for r in native::requests(&ctx) {
633 request(app, &ctx, r);
634 }
635 if egui_pop_core::frame::full_screen(&ctx) {
636 if !bar_in_fullscreen(app) {
637 egui_pop_core::frame::hide_title_bar(&ctx);
638 return;
639 }
640 let pass = ctx.cumulative_pass_nr();
641 bar_in_full_screen(&ctx).set(&ctx, pass);
642 }
643 let title = ctx
644 .input(|i| i.viewport().title.clone())
645 .unwrap_or_default();
646 let out = TitleBar::new(&title).show(
647 ui,
648 |ui| {
649 if app.zone_has_blocks(&zones::CAPTION_START) {
650 app.show_zone(ui, &zones::CAPTION_START);
651 }
652 },
653 |ui| {
654 if app.zone_has_blocks(&zones::CAPTION) {
655 app.show_zone(ui, &zones::CAPTION);
656 }
657 },
658 );
659 if let Some(r) = out.request {
660 request(app, &ctx, r);
661 }
662}
663
664pub(crate) fn window_frame(
675 ui: &mut Ui,
676 app: &AppHandle,
677 title: &str,
678 caption_start: bool,
679 content: impl FnOnce(&mut Ui),
680) {
681 let ctx = ui.ctx().clone();
682 let root = ctx.viewport_id() == egui::ViewportId::ROOT;
683 let own = if root {
687 follow_setting(ui, app)
688 } else {
689 own_frame(app)
690 };
691 if !own {
692 return content(ui);
693 }
694 if egui_pop_core::frame::full_screen(&ctx) && !bar_in_fullscreen(app) {
695 egui_pop_core::frame::hide_title_bar(&ctx);
696 return content(ui);
697 }
698 if root {
699 for r in native::requests(&ctx) {
702 request(app, &ctx, r);
703 }
704 } else {
705 egui_pop_core::frame::resize_edges(&ctx);
706 egui_pop_core::frame::paint_window_edge(
708 &ctx,
709 egui_pop_core::frame::window_edge(&ctx, &crate::window::screens()),
710 );
711 }
712 let full = ui.max_rect();
713 let out = ui
714 .scope_builder(egui::UiBuilder::new().max_rect(full), |ui| {
715 egui_pop_core::focus::scope(ui, "titleBar", &[], |ui| {
716 TitleBar::new(title).show(
717 ui,
718 |ui| {
719 if caption_start && app.zone_has_blocks(&zones::CAPTION_START) {
720 app.show_zone(ui, &zones::CAPTION_START);
721 }
722 },
723 |_| {},
724 )
725 })
726 })
727 .inner;
728 if let Some(r) = out.request {
729 request(app, &ctx, r);
730 }
731 let rest = Rect::from_min_max(egui::pos2(full.left(), out.rect.bottom()), full.max);
732 ui.scope_builder(egui::UiBuilder::new().max_rect(rest), content);
733}
734
735fn edges(ui: &mut Ui, app: &AppHandle) {
737 let ctx = ui.ctx().clone();
738 if !own_frame(app) {
739 return;
740 }
741 egui_pop_core::frame::resize_edges(&ctx);
742 egui_pop_core::frame::publish(&ctx);
743 let at = SYSTEM_MENU.get(&ctx).flatten();
744 let Some((at, opened)) = at else { return };
745 let spec = OverlaySpec::new("egui_pop.frame.system_menu", "Window menu", Kind::Menu);
746 let mut open = true;
747 let anchor = Anchor {
748 rect: Rect::from_min_size(at, Vec2::ZERO),
749 side: Side::Bottom,
750 };
751 let mut clicked = false;
752 overlay::show(&ctx, &spec, &mut open, Some(anchor), |ui| {
753 crate::menus::show(ui, app, &MENU_SYSTEM);
754 clicked =
757 ui.ctx().cumulative_pass_nr() > opened && ui.ctx().input(|i| i.pointer.any_click());
758 });
759 if !open || clicked {
760 let how = if clicked {
761 overlay::Closing::Chosen
762 } else {
763 overlay::Closing::Owner
764 };
765 app.close_overlay(&ctx, spec.id, how);
766 SYSTEM_MENU.set(&ctx, None);
767 }
768}
769
770pub fn set_native_window(ctx: &Context, viewport: egui::ViewportId, handle: isize) {
775 NATIVE_WINDOW.keyed(viewport).set(ctx, handle);
776}
777
778pub fn forget_native_window(ctx: &Context, viewport: egui::ViewportId) {
781 NATIVE_WINDOW.keyed(viewport).remove(ctx);
782}
783
784pub fn set_x11_window(ctx: &Context, window: u64) {
789 X11_WINDOW.set(ctx, window);
790}
791
792pub fn x11_window(ctx: &Context) -> Option<u64> {
795 X11_WINDOW.get(ctx)
796}
797
798#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
805pub fn record_native_window(cc: &eframe::CreationContext<'_>) {
806 if let Some(window) = cc.winit_window() {
807 let window: std::sync::Arc<dyn crate::files::ParentWindow> = window.clone();
808 crate::files::set_parent_window(&cc.egui_ctx, egui::ViewportId::ROOT, window);
809 }
810 #[cfg(windows)]
811 {
812 use raw_window_handle::{HasWindowHandle, RawWindowHandle};
813 if let Ok(h) = cc.window_handle()
814 && let RawWindowHandle::Win32(w) = h.as_raw()
815 {
816 set_native_window(&cc.egui_ctx, egui::ViewportId::ROOT, w.hwnd.get());
817 }
818 }
819 #[cfg(target_os = "linux")]
820 {
821 use raw_window_handle::{HasWindowHandle, RawWindowHandle};
822 if let Ok(h) = cc.window_handle() {
823 match h.as_raw() {
824 #[allow(
826 clippy::useless_conversion,
827 reason = "`c_ulong` is 64 bits here, 32 on a 32-bit system, where the conversion is needed"
828 )]
829 RawWindowHandle::Xlib(w) => set_x11_window(&cc.egui_ctx, u64::from(w.window)),
830 RawWindowHandle::Xcb(w) => set_x11_window(&cc.egui_ctx, w.window.get().into()),
831 _ => {}
832 }
833 }
834 }
835 #[cfg(not(any(windows, target_os = "linux")))]
836 let _ = cc;
837}
838
839mod native {
842 use std::sync::{Arc, Mutex};
843
844 use egui::{Context, ViewportId};
845 use egui_pop_core::frame::{self as core_frame, Button, FrameRequest, Hit, HitTable};
846 use egui_pop_core::kit::{Kit, WindowCorners};
847 use egui_pop_core::lock;
848 use egui_pop_core::state::Slot;
849 use egui_pop_win32::{Area, Corners, Handler, NcEvent, Subclassed};
850 use serde_json::{Value as Json, json};
851
852 use super::STEP_HIT_TEST;
853 use crate::app::AppHandle;
854
855 fn root_handle(ctx: &Context) -> Option<isize> {
857 super::NATIVE_WINDOW.keyed(ViewportId::ROOT).get(ctx)
858 }
859
860 const NATIVE: Slot<Native> = Slot::new("api.frame.native");
862
863 #[derive(Clone, Debug, Default)]
865 struct Native {
866 installed: Arc<Mutex<Option<Subclassed>>>,
867 events: Arc<Mutex<Vec<NcEvent>>>,
868 error: Arc<Mutex<Option<String>>>,
869 corners: Arc<Mutex<Option<Asked>>>,
871 }
872
873 type Asked = (Corners, Result<(), String>);
875
876 fn native(ctx: &Context) -> Native {
877 NATIVE.get_or_insert_with(ctx, Native::default)
878 }
879
880 pub(super) fn area(hit: Hit) -> Area {
882 match hit {
883 Hit::Client => Area::Client,
884 Hit::Caption => Area::Caption,
885 Hit::Minimize => Area::Minimize,
886 Hit::Maximize => Area::Maximize,
887 Hit::Close => Area::Close,
888 Hit::Left => Area::Left,
889 Hit::Right => Area::Right,
890 Hit::Top => Area::Top,
891 Hit::Bottom => Area::Bottom,
892 Hit::TopLeft => Area::TopLeft,
893 Hit::TopRight => Area::TopRight,
894 Hit::BottomLeft => Area::BottomLeft,
895 Hit::BottomRight => Area::BottomRight,
896 }
897 }
898
899 #[derive(Debug)]
902 pub(super) struct Bridge {
903 pub(super) table: HitTable,
904 pub(super) viewport: ViewportId,
905 pub(super) ctx: Context,
906 pub(super) events: Arc<Mutex<Vec<NcEvent>>>,
907 }
908
909 impl Handler for Bridge {
910 fn hit(&self, x: i32, y: i32) -> Area {
911 self.table.get(self.viewport).map_or(Area::Client, |r| {
912 match r.hit(x, y) {
913 Hit::Caption if r.fullscreen => Area::Client,
916 hit => area(hit),
917 }
918 })
919 }
920
921 fn event(&self, event: NcEvent) {
922 lock(&self.events).push(event);
923 self.ctx.request_repaint_of(self.viewport);
924 }
925 }
926
927 pub(super) fn follow(ctx: &Context, app: &AppHandle, own: bool) {
930 if ctx.viewport_id() != ViewportId::ROOT {
931 return;
932 }
933 let Some(hwnd) = root_handle(ctx) else {
934 return;
935 };
936 let n = native(ctx);
937 if lock(&n.installed).is_some() == own || (own && lock(&n.error).is_some()) {
938 return;
939 }
940 let (c, n2) = (ctx.clone(), n.clone());
941 app.step(
942 &STEP_HIT_TEST,
943 json!({ "viewport": "root", "install": own }),
944 move |_, args| {
945 let install = args["install"].as_bool().unwrap_or(own);
946 let mut slot = lock(&n2.installed);
947 if !install {
948 if let Some(s) = slot.take() {
949 s.remove();
950 }
951 core_frame::set_native_hover(&c, ViewportId::ROOT, None);
952 return Ok(json!({ "installed": false }));
953 }
954 let bridge = Bridge {
955 table: HitTable::of(&c),
956 viewport: ViewportId::ROOT,
957 ctx: c.clone(),
958 events: n2.events.clone(),
959 };
960 match egui_pop_win32::install(hwnd, Arc::new(bridge)) {
961 Ok(s) => {
962 *slot = Some(s);
963 Ok(json!({ "installed": true }))
964 }
965 Err(e) => {
966 *lock(&n2.error) = Some(e.to_string());
967 Err(e.to_string())
968 }
969 }
970 },
971 );
972 if !own {
973 *lock(&n.error) = None;
974 }
975 }
976
977 pub(super) fn corners_of(c: WindowCorners) -> Corners {
979 match c {
980 WindowCorners::Round => Corners::Round,
981 WindowCorners::Small => Corners::Small,
982 WindowCorners::Square => Corners::Square,
983 }
984 }
985
986 fn corners_name(c: Corners) -> &'static str {
987 match c {
988 Corners::System => "system",
989 Corners::Square => "square",
990 Corners::Round => "round",
991 Corners::Small => "small",
992 }
993 }
994
995 pub(super) fn corners(ctx: &Context, own: bool) {
1001 if ctx.viewport_id() != ViewportId::ROOT {
1002 return;
1003 }
1004 let wanted = if own {
1005 corners_of(Kit::of(ctx).window.corners)
1006 } else {
1007 Corners::System
1008 };
1009 let n = native(ctx);
1010 let mut last = lock(&n.corners);
1011 match last.as_ref() {
1012 Some((asked, _)) if *asked == wanted => return,
1013 None if !own => return,
1015 _ => {}
1016 }
1017 let hwnd = root_handle(ctx);
1018 let outcome = match hwnd {
1019 _ if !egui_pop_win32::SUPPORTED => Err(
1020 "not asked: only Windows rounds the corners of a window drawn by the application on request"
1021 .to_string(),
1022 ),
1023 None => Err("not asked: the window's handle is unknown (see `set_native_window`)".into()),
1024 Some(h) => egui_pop_win32::set_corners(h, wanted).map_err(|e| e.to_string()),
1025 };
1026 match &outcome {
1027 Ok(()) => {
1028 log::info!(target: "egui_pop", "frame: corners `{}` applied", corners_name(wanted))
1029 }
1030 Err(e) => {
1031 log::info!(target: "egui_pop", "frame: corners `{}`: {e}", corners_name(wanted))
1032 }
1033 }
1034 *last = Some((wanted, outcome));
1035 }
1036
1037 pub(super) fn describe_corners(ctx: &Context) -> Json {
1039 match lock(&native(ctx).corners).as_ref() {
1040 None => json!({ "asked": Json::Null }),
1041 Some((asked, outcome)) => json!({
1042 "asked": corners_name(*asked),
1043 "applied": outcome.is_ok(),
1044 "error": outcome.as_ref().err(),
1045 }),
1046 }
1047 }
1048
1049 pub(super) fn requests(ctx: &Context) -> Vec<FrameRequest> {
1051 let n = native(ctx);
1052 let events = std::mem::take(&mut *lock(&n.events));
1053 let ppp = ctx.pixels_per_point();
1054 let mut out = Vec::new();
1055 for e in events {
1056 match e {
1057 NcEvent::Hover(b) => {
1058 let b = b.and_then(|a| match a {
1059 Area::Minimize => Some(Button::Minimize),
1060 Area::Maximize => Some(Button::Maximize),
1061 Area::Close => Some(Button::Close),
1062 _ => None,
1063 });
1064 core_frame::set_native_hover(ctx, ViewportId::ROOT, b);
1065 }
1066 NcEvent::Press(_) => {}
1067 NcEvent::Click(Area::Minimize) => out.push(FrameRequest::Minimize),
1068 NcEvent::Click(Area::Maximize) | NcEvent::DoubleClick(_) => {
1069 out.push(FrameRequest::ToggleMaximize);
1070 }
1071 NcEvent::Click(Area::Close) => out.push(FrameRequest::Close),
1072 NcEvent::Click(_) => {}
1073 NcEvent::ContextMenu { x, y } => out.push(FrameRequest::SystemMenu(egui::pos2(
1074 x as f32 / ppp,
1075 y as f32 / ppp,
1076 ))),
1077 }
1078 }
1079 out
1080 }
1081
1082 pub(super) fn describe(ctx: &Context) -> Json {
1084 let n = native(ctx);
1085 json!({
1086 "supported": egui_pop_win32::SUPPORTED,
1087 "window": root_handle(ctx).is_some(),
1088 "installed": lock(&n.installed).is_some(),
1089 "error": lock(&n.error).clone(),
1090 })
1091 }
1092
1093 #[cfg(test)]
1094 mod tests {
1095 use super::*;
1096
1097 #[test]
1098 fn the_kit_corners_are_asked_once_and_reported() {
1099 let ctx = Context::default();
1100 assert_eq!(describe_corners(&ctx), json!({ "asked": null }));
1101 corners(&ctx, false);
1103 assert_eq!(describe_corners(&ctx)["asked"], Json::Null);
1104 corners(&ctx, true);
1105 let d = describe_corners(&ctx);
1106 assert_eq!(d["asked"], "round");
1107 if !egui_pop_win32::SUPPORTED {
1108 assert_eq!(d["applied"], false);
1109 assert!(d["error"].as_str().unwrap().starts_with("not asked"));
1110 }
1111 let mut themes = egui_pop_core::theme::Themes::default();
1113 themes
1114 .add_text(
1115 "square",
1116 r#"
1117 $extends: "pop-dark"
1118 window:
1119 corners: {$type: "string", $value: "square"}
1120 "#,
1121 )
1122 .unwrap();
1123 egui_pop_core::theme::install_tokens(
1124 &ctx,
1125 egui_pop_core::theme::Tokens::new(
1126 themes.resolve(&egui_pop_core::theme::ThemeSpec::new("square")),
1127 ),
1128 );
1129 corners(&ctx, true);
1130 assert_eq!(describe_corners(&ctx)["asked"], "square");
1131 corners(&ctx, false);
1133 assert_eq!(describe_corners(&ctx)["asked"], "system");
1134 assert_eq!(corners_of(WindowCorners::Small), Corners::Small);
1135 }
1136
1137 #[test]
1138 fn the_bridge_answers_from_the_table_and_queues_requests() {
1139 let ctx = Context::default();
1140 let table = HitTable::of(&ctx);
1141 let layout = core_frame::FrameLayout {
1142 window: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)),
1143 caption: Some(egui::Rect::from_min_size(
1144 egui::Pos2::ZERO,
1145 egui::vec2(800.0, 32.0),
1146 )),
1147 maximize: Some(egui::Rect::from_min_size(
1148 egui::pos2(712.0, 0.0),
1149 egui::vec2(44.0, 32.0),
1150 )),
1151 grip: 4.0,
1152 resizable: true,
1153 ..Default::default()
1154 };
1155 table.publish(
1156 ViewportId::ROOT,
1157 core_frame::HitRegions::measure(&layout, 1.5),
1158 );
1159 let events = native(&ctx).events;
1160 let b = Bridge {
1161 table,
1162 viewport: ViewportId::ROOT,
1163 ctx: ctx.clone(),
1164 events: events.clone(),
1165 };
1166 assert_eq!(b.hit(600, 24), Area::Caption);
1167 assert_eq!(b.hit((734.0 * 1.5) as i32, 24), Area::Maximize);
1168 assert_eq!(b.hit(2, 400), Area::Left);
1169 assert_eq!(b.hit(600, 400), Area::Client);
1170 for e in [
1171 NcEvent::Hover(Some(Area::Maximize)),
1172 NcEvent::Click(Area::Maximize),
1173 NcEvent::DoubleClick(Area::Caption),
1174 NcEvent::ContextMenu { x: 30, y: 15 },
1175 NcEvent::Click(Area::Close),
1176 ] {
1177 b.event(e);
1178 }
1179 let r = requests(&ctx);
1180 assert_eq!(
1181 r,
1182 vec![
1183 FrameRequest::ToggleMaximize,
1184 FrameRequest::ToggleMaximize,
1185 FrameRequest::SystemMenu(egui::pos2(30.0, 15.0)),
1186 FrameRequest::Close,
1187 ]
1188 );
1189 assert_eq!(core_frame::native_hover(&ctx), Some(Button::Maximize));
1190 assert!(requests(&ctx).is_empty());
1191 b.table.publish(
1194 ViewportId::ROOT,
1195 core_frame::HitRegions::measure(
1196 &core_frame::FrameLayout {
1197 fullscreen: true,
1198 resizable: false,
1199 ..layout
1200 },
1201 1.5,
1202 ),
1203 );
1204 assert_eq!(b.hit(600, 24), Area::Client);
1205 assert_eq!(b.hit(2, 400), Area::Client);
1206 }
1207 }
1208}