use std::{cell::RefCell, fmt, rc::Rc};
use super::{
AnyElement, Element, ElementRef, ImageSrc, IntoElement, IntoElements, IntoReactive, Owner,
ParentElement, Signal, cleanup, menus::MenuHandler, task::Answer,
};
use crate::{
Command, EventKind, EventPayload,
desktop::{
self, CloseReason, DesktopCommand, Display, DisplayId, MenuAction, MenuBarMode, MenuRole,
Shortcut, TrayTitlePlacement, TrayTitleRun, WindowAttributes, WindowCloseCause,
WindowEvent, WindowFrame, WindowKind, WindowMode, WindowOptions, WindowPlacement,
WindowPosition, WindowRequest, WindowState,
},
geometry::{Bounds, Edges, Point, Points, Size},
keymap::When,
platform::Os,
};
pub fn title_bar() -> Edges<Points> {
current_window().title_bar()
}
pub fn set_menu_bar(mode: MenuBarMode) {
super::desktop_command(DesktopCommand::SetMenuBar(mode));
}
pub fn window_state() -> Option<WindowState> {
current_window().state()
}
pub fn displays() -> Vec<Display> {
super::ambient::displays()
}
pub fn display(id: DisplayId) -> Option<Display> {
displays().into_iter().find(|d| d.id == id)
}
#[derive(Clone, Copy)]
enum Target {
Main,
Own(ElementRef),
}
#[derive(Clone)]
pub struct WindowRef {
id: Rc<str>,
target: Target,
state: Option<Signal<Option<WindowState>>>,
title_bar: Option<Signal<Edges<Points>>>,
close: Option<Rc<dyn Fn(WindowCloseCause)>>,
close_press: Option<Signal<(u64, CloseReason)>>,
early: Option<Signal<WindowAttributes>>,
}
impl fmt::Debug for WindowRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WindowRef")
.field("id", &self.id)
.finish_non_exhaustive()
}
}
impl PartialEq for WindowRef {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
pub fn main_window() -> WindowRef {
WindowRef {
id: Rc::from("main"),
target: Target::Main,
state: None,
title_bar: None,
close: None,
close_press: None,
early: None,
}
}
pub fn current_window() -> WindowRef {
super::use_context::<WindowRef>().unwrap_or_else(main_window)
}
impl WindowRef {
pub fn id(&self) -> &str {
&self.id
}
pub fn is_main(&self) -> bool {
matches!(self.target, Target::Main)
}
pub(crate) fn dialog_root(&self) -> Option<super::ElementRef> {
match &self.target {
Target::Main => None,
Target::Own(element) => Some(*element),
}
}
fn command(&self, command: DesktopCommand) {
match self.target {
Target::Main => super::ambient::desktop_command(command),
Target::Own(element) => match (command, self.early) {
(DesktopCommand::SetAttributes(attributes), Some(early))
if element.node().is_none() =>
{
early.update(|e| e.merge(&attributes));
}
(command, _) => element.send(Command::Desktop(Box::new(command))),
},
}
}
pub fn state(&self) -> Option<WindowState> {
match self.state {
None => super::ambient::window_state(),
Some(state) => state.try_get().flatten(),
}
}
pub fn set(&self, attributes: WindowAttributes) {
if attributes.is_empty() {
return;
}
self.command(DesktopCommand::SetAttributes(Box::new(attributes)));
}
pub fn show(&self) {
self.command(DesktopCommand::Request(WindowRequest::Show));
}
pub fn hide(&self) {
self.command(DesktopCommand::Request(WindowRequest::Hide));
}
pub fn focus(&self) {
self.command(DesktopCommand::Request(WindowRequest::Focus));
}
pub fn close(&self) {
match &self.close {
Some(close) => close(WindowCloseCause::Close),
None => self.command(DesktopCommand::Request(WindowRequest::Close)),
}
}
pub fn title_bar(&self) -> Edges<Points> {
match self.title_bar {
Some(area) => area.try_get().unwrap_or_default(),
None => super::title_bar(),
}
}
pub fn minimize(&self) {
self.command(DesktopCommand::Request(WindowRequest::Minimize));
}
pub fn restore(&self) {
self.command(DesktopCommand::Request(WindowRequest::Restore));
}
pub fn set_mode(&self, mode: WindowMode) {
self.command(DesktopCommand::Request(WindowRequest::SetMode(mode)));
}
pub fn set_bounds(&self, frame: WindowFrame) {
self.command(DesktopCommand::Request(WindowRequest::SetBounds(
WindowFrame {
x: frame.x.filter(|v| v.is_finite()),
y: frame.y.filter(|v| v.is_finite()),
width: frame.width.filter(|v| v.is_finite() && v.0 > 0.0),
height: frame.height.filter(|v| v.is_finite() && v.0 > 0.0),
animated: frame.animated,
},
)));
}
pub fn set_placement(&self, placement: WindowPlacement) {
self.command(DesktopCommand::Request(WindowRequest::SetPlacement(
placement,
)));
}
pub fn center(&self, display: Option<DisplayId>) {
self.command(DesktopCommand::Request(WindowRequest::Center { display }));
}
pub fn request_attention(&self, critical: bool) {
self.command(DesktopCommand::Request(WindowRequest::RequestAttention {
critical,
}));
}
fn on_change<T: 'static>(
&self,
changed: impl Fn(Option<&WindowState>, &WindowState) -> Option<T> + 'static,
f: impl Fn(T) + 'static,
) {
let this = self.clone();
let last = super::stored(None::<WindowState>);
super::effect(move || {
let Some(next) = this.state() else { return };
let previous = last.replace(Some(next));
if let Some(change) = changed(previous.as_ref(), &next) {
super::untracked(|| f(change));
}
});
}
pub fn on_close_press(&self, f: impl Fn(CloseReason) + 'static) {
let signal = self
.close_press
.unwrap_or_else(super::ambient::main_close_press_signal);
let seen = super::stored(signal.with_untracked(|(count, _)| *count));
super::effect(move || {
let (count, reason) = signal.get();
if seen.replace(count) != count {
super::untracked(|| f(reason));
}
});
}
pub fn on_focus_change(&self, f: impl Fn(bool) + 'static) {
self.on_change(
|old, new| (old.is_some_and(|o| o.focused != new.focused)).then_some(new.focused),
f,
);
}
pub fn on_mode_change(&self, f: impl Fn(WindowMode, bool) + 'static) {
self.on_change(
|old, new| {
old.is_some_and(|o| o.mode != new.mode || o.minimized != new.minimized)
.then_some((new.mode, new.minimized))
},
move |(mode, minimized)| f(mode, minimized),
);
}
pub fn on_bounds_change(&self, f: impl Fn(Bounds<Points>) + 'static) {
self.on_change(
|old, new| (old.is_some_and(|o| o.bounds != new.bounds)).then_some(new.bounds),
f,
);
}
pub fn on_display_change(&self, f: impl Fn(DisplayId) + 'static) {
self.on_change(
|old, new| {
(old.is_some_and(|o| o.display != new.display))
.then_some(new.display)
.flatten()
},
f,
);
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct OpenChange {
pub open: bool,
pub reason: WindowCloseCause,
}
type OpenChangeFn = Rc<dyn Fn(&OpenChange)>;
type ClosePressFn = Rc<dyn Fn(CloseReason)>;
type BindFn = Rc<dyn Fn(&mut WindowAttributes)>;
type ContentFn = Rc<dyn Fn() -> Vec<AnyElement>>;
pub struct Window {
options: WindowOptions,
bound: Vec<BindFn>,
reactive: Vec<super::Reactive<WindowAttributes>>,
open: Option<super::Reactive<bool>>,
content: Option<ContentFn>,
on_open_change: Option<OpenChangeFn>,
on_close_press: Option<ClosePressFn>,
opened: Option<WindowRef>,
}
pub fn window() -> Window {
Window {
options: WindowOptions::default(),
bound: Vec::new(),
reactive: Vec::new(),
open: None,
content: None,
on_open_change: None,
on_close_press: None,
opened: None,
}
}
impl Window {
pub fn id(mut self, id: impl Into<String>) -> Self {
self.options.id = id.into();
self
}
pub fn kind(mut self, kind: WindowKind) -> Self {
self.options.kind = kind;
self
}
pub fn parent(mut self, id: impl Into<String>) -> Self {
self.options.parent = Some(id.into());
self
}
pub fn modal(mut self, modal: bool) -> Self {
self.options.modal = modal;
self
}
pub fn default_size(mut self, size: Size<Points>) -> Self {
self.options.default_size = Some(size);
self
}
pub fn default_position(mut self, position: WindowPosition) -> Self {
self.options.default_position = Some(position);
self
}
pub fn display(mut self, display: DisplayId) -> Self {
self.options.display = Some(display);
self
}
pub fn default_mode(mut self, mode: WindowMode) -> Self {
self.options.default_mode = Some(mode);
self
}
pub fn restore_bounds(mut self, restore: bool) -> Self {
self.options.restore_bounds = restore;
self
}
pub fn title(mut self, title: impl IntoReactive<String>) -> Self {
match title.into_reactive() {
super::Reactive::Static(title) => self.options.attributes.title = Some(title),
reactive => {
let reactive = Rc::new(reactive);
self.bound.push(Rc::new(move |a: &mut WindowAttributes| {
a.title = Some(reactive.get());
}));
}
}
self
}
pub fn attributes(mut self, attributes: impl IntoReactive<WindowAttributes>) -> Self {
match attributes.into_reactive() {
super::Reactive::Static(a) => self.options.attributes.merge(&a),
reactive => self.reactive.push(reactive),
}
self
}
pub fn open(mut self, open: impl IntoReactive<bool>) -> Self {
self.open = Some(open.into_reactive());
self
}
pub fn on_open_change(mut self, f: impl Fn(&OpenChange) + 'static) -> Self {
self.on_open_change = Some(Rc::new(f));
self
}
pub fn on_close_press(mut self, f: impl Fn(CloseReason) + 'static) -> Self {
self.on_close_press = Some(Rc::new(f));
self
}
pub fn content<E: IntoElements>(mut self, content: impl Fn() -> E + 'static) -> Self {
self.content = Some(Rc::new(move || content().into_elements()));
self
}
}
impl IntoElement for Window {
fn into_element(self) -> AnyElement {
if !super::os().is_desktop() {
return super::when(false, Vec::<AnyElement>::new).into_element();
}
let Window {
options,
bound,
reactive,
open,
content,
on_open_change,
on_close_press,
opened,
} = self;
let open = open.unwrap_or(super::Reactive::Static(true));
let closed = super::signal(false);
let open = Rc::new(open);
let is_open = {
let open = open.clone();
move || {
let open = open.get();
if !open {
super::untracked(|| closed.set(false));
}
open && !closed.get()
}
};
let options = Rc::new(options);
let bound = Rc::new(bound);
let reactive = Rc::new(reactive);
super::when(is_open, move || {
let (element, state, title_bar, close_press, early) = match &opened {
Some(WindowRef {
target: Target::Own(element),
state: Some(state),
title_bar: Some(title_bar),
close_press: Some(close_press),
early: Some(early),
..
}) => (*element, *state, *title_bar, *close_press, *early),
_ => (
super::element_ref(),
super::signal(None::<WindowState>),
super::signal(Edges::<Points>::default()),
super::signal((0u64, CloseReason::default())),
super::signal(WindowAttributes::default()),
),
};
super::untracked(|| early.set(WindowAttributes::default()));
let close: Rc<dyn Fn(WindowCloseCause)> = {
let on_open_change = on_open_change.clone();
Rc::new(move |cause: WindowCloseCause| {
closed.set(true);
if let Some(f) = &on_open_change {
f(&OpenChange {
open: false,
reason: cause,
});
}
})
};
let this = WindowRef {
id: Rc::from(options.id.as_str()),
target: Target::Own(element),
state: Some(state),
title_bar: Some(title_bar),
close: Some(close.clone()),
close_press: Some(close_press),
early: Some(early),
};
LiveWindows::add(this.clone());
super::provide_context(this);
let mut modal = super::modal().element_ref(&element);
{
let node = modal.node();
let options = options.clone();
let bound = bound.clone();
let reactive = reactive.clone();
let resolve = move || {
let mut o = (*options).clone();
for b in bound.iter() {
b(&mut o.attributes);
}
for r in reactive.iter() {
o.attributes.merge(&r.get());
}
early.with(|e| o.attributes.merge(e));
o
};
let apply = |attrs: &mut super::Attrs, o: WindowOptions| {
attrs.window = Some(Box::new(o));
};
node.bind_attr(super::Reactive::Bound(Rc::new(resolve)), apply);
let on_close_press = on_close_press.clone();
let close_on_dismiss = close.clone();
node.handlers.push((
EventKind::Window,
super::Listener::from(move |payload: &EventPayload| {
let EventPayload::Window(event) = payload else {
return;
};
match event.as_ref() {
WindowEvent::State(next) => {
state.try_set(Some(**next));
}
WindowEvent::TitleBar(area) => {
title_bar.try_set(*area);
}
WindowEvent::ClosePress { reason } => {
if let Some(f) = &on_close_press {
f(*reason);
}
if close_press.is_live() {
close_press.update(|(count, last)| {
*count += 1;
*last = *reason;
});
}
}
WindowEvent::Closed { cause } => close(*cause),
}
}),
));
node.handlers.push((
EventKind::Dismiss,
super::Listener::from(move |_: &EventPayload| {
close_on_dismiss(WindowCloseCause::ClosePress)
}),
));
}
if let Some(content) = &content {
modal = modal.children(content());
}
modal
})
.into_element()
}
}
#[derive(Default, Clone)]
struct LiveWindows(Vec<WindowRef>);
impl LiveWindows {
fn add(window: WindowRef) {
let live = super::global::<Self>();
let id = window.id.clone();
live.update(|l| l.0.push(window));
super::cleanup(move || {
if live.is_live() {
live.update(|l| l.0.retain(|w| !Rc::ptr_eq(&w.id, &id)));
}
});
}
fn get(id: &str) -> Option<WindowRef> {
super::global::<Self>().with_untracked(|l| l.0.iter().find(|w| &*w.id == id).cloned())
}
fn count() -> usize {
super::global::<Self>().with_untracked(|l| l.0.len())
}
}
#[derive(Default, Clone)]
pub(crate) struct WindowAccess(pub(crate) Option<std::sync::Arc<crate::access::Access>>);
#[derive(Default, Clone)]
struct OpenedWindows(Vec<Opened>);
#[derive(Clone)]
struct Opened {
id: Rc<str>,
window: Rc<RefCell<Option<Window>>>,
owner: Owner,
}
impl PartialEq for Opened {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.window, &other.window)
}
}
pub fn open_window(mut window: Window) -> Option<WindowRef> {
if !super::os().is_desktop() {
log::warn!("open_window: windows of the app's own open on the desktops only");
return None;
}
if window.open.is_some() {
log::warn!("open_window: `Window::open` is ignored, the window opens now");
}
let opened = super::global::<OpenedWindows>();
if window.options.id.is_empty() {
thread_local!(static NEXT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) });
let n = NEXT.with(|n| {
n.set(n.get() + 1);
n.get()
});
window.options.id = format!("window-{n}");
}
let id: Rc<str> = Rc::from(window.options.id.as_str());
let open = LiveWindows::get(&id).or_else(|| {
opened.with_untracked(|o| {
o.0.iter()
.find(|w| w.id == id)
.and_then(|w| w.window.borrow().as_ref().and_then(|w| w.opened.clone()))
})
});
if let Some(open) = open {
open.focus();
return Some(open);
}
let access = super::global::<WindowAccess>().get_untracked().0;
if let Some(access) = access {
let pending = opened.with_untracked(|o| {
o.0.iter()
.filter(|w| LiveWindows::get(&w.id).is_none())
.count()
});
if let Err(message) = access.check_window(
window.options.kind,
&window.options.attributes,
LiveWindows::count() + pending,
) {
log::warn!("open_window: {message}: the window does not open");
return None;
}
}
let user = window.on_open_change.take();
let on_open_change: OpenChangeFn = {
let id = id.clone();
Rc::new(move |change: &OpenChange| {
opened.update(|o| o.0.retain(|w| w.id != id));
if let Some(f) = &user {
f(change);
}
})
};
let (owner, this) = Owner::detached().run(|| {
super::create_root(|| WindowRef {
id: id.clone(),
target: Target::Own(super::element_ref()),
state: Some(super::signal(None)),
title_bar: Some(super::signal(Edges::default())),
close: Some({
let on_open_change = on_open_change.clone();
Rc::new(move |reason| {
on_open_change(&OpenChange {
open: false,
reason,
})
})
}),
close_press: Some(super::signal((0, CloseReason::default()))),
early: Some(super::signal(WindowAttributes::default())),
})
});
window.on_open_change = Some(on_open_change);
window.open = None;
window.opened = Some(this.clone());
opened.update(|o| {
o.0.push(Opened {
id,
window: Rc::new(RefCell::new(Some(window))),
owner,
})
});
Some(this)
}
pub(crate) struct OpenedWindowsHost;
impl super::Component for OpenedWindowsHost {
type Props = ();
type Event = super::NoEvent;
fn view(_: (), _: super::Scope<super::NoEvent>) -> impl IntoElement {
super::each(
move || super::global::<OpenedWindows>().get().0,
|w: &Opened| w.id.clone(),
|w, _| {
let w = w.get_untracked();
let owner = w.owner;
super::cleanup(move || owner.dispose());
let window = w.window.borrow().as_ref().map(|w| Window {
options: w.options.clone(),
bound: w.bound.clone(),
reactive: Vec::new(),
open: None,
content: w.content.clone(),
on_open_change: w.on_open_change.clone(),
on_close_press: w.on_close_press.clone(),
opened: w.opened.clone(),
});
let reactive = w
.window
.borrow_mut()
.as_mut()
.map(|w| std::mem::take(&mut w.reactive))
.unwrap_or_default();
window.map(|mut window| {
window.reactive = reactive;
window
})
},
)
}
}
pub fn quit() {
super::desktop_command(DesktopCommand::Quit);
}
pub use super::quit::QUIT_TIMEOUT;
pub fn on_app_quit<F>(f: impl FnMut() -> F + 'static)
where
F: std::future::Future<Output = ()> + 'static,
{
let owner = Owner::current();
let f = RefCell::new(f);
let listener: super::quit::QuitListener = Rc::new(move || {
let future = owner.run(|| (f.borrow_mut())());
super::ambient::owned(owner, future)
});
let subscription = add_quit_listener(listener);
cleanup(move || drop(subscription));
}
pub(crate) fn add_quit_listener(
listener: super::quit::QuitListener,
) -> super::quit::QuitSubscription {
let quit = &super::ambient::executor().quit;
let id = quit.borrow_mut().add(listener);
super::quit::QuitSubscription::new(quit, id)
}
pub fn restart() {
super::desktop_command(DesktopCommand::Restart);
}
#[derive(Clone)]
pub struct MenuItem {
kind: Kind,
label: String,
role: Option<MenuRole>,
shortcut: Option<Rc<str>>,
when: When,
enabled: bool,
checked: Option<bool>,
icon: Option<ImageSrc>,
on_select: Option<MenuHandler>,
}
#[derive(Clone)]
enum Kind {
Action,
Separator,
Submenu(Vec<MenuItem>),
}
impl MenuItem {
fn of(kind: Kind, label: String) -> Self {
MenuItem {
kind,
label,
role: None,
shortcut: None,
when: When::Always,
enabled: true,
checked: None,
icon: None,
on_select: None,
}
}
pub fn new(label: impl Into<String>) -> Self {
Self::of(Kind::Action, label.into())
}
pub fn role(role: MenuRole) -> Self {
MenuItem {
role: Some(role),
..Self::of(Kind::Action, String::new())
}
}
pub fn separator() -> Self {
Self::of(Kind::Separator, String::new())
}
pub fn submenu(label: impl Into<String>, items: impl IntoIterator<Item = MenuItem>) -> Self {
Self::of(Kind::Submenu(items.into_iter().collect()), label.into())
}
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
#[track_caller]
pub fn shortcut(mut self, keystroke: &str) -> Self {
if let Err(e) = Shortcut::parse(keystroke, false) {
panic!("MenuItem::shortcut: {e}");
}
self.shortcut = Some(keystroke.into());
self
}
pub fn shortcut_when(mut self, when: When) -> Self {
self.when = when;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.enabled = !disabled;
self
}
pub fn checked(mut self, checked: bool) -> Self {
self.checked = Some(checked);
self
}
pub fn icon(mut self, src: impl Into<ImageSrc>) -> Self {
self.icon = Some(src.into());
self
}
pub fn on_select(mut self, f: impl Fn() + 'static) -> Self {
self.on_select = Some(Rc::new(f));
self
}
}
impl fmt::Debug for MenuItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
Kind::Separator => f.write_str("Separator"),
Kind::Submenu(items) => f
.debug_struct("Submenu")
.field("label", &self.label)
.field("items", items)
.finish_non_exhaustive(),
Kind::Action => f
.debug_struct("MenuItem")
.field("label", &self.label)
.field("role", &self.role)
.field("shortcut", &self.shortcut)
.finish_non_exhaustive(),
}
}
}
fn decode(
items: Vec<MenuItem>,
mac: bool,
owner: &Owner,
handlers: &mut Vec<(u32, MenuHandler)>,
) -> Vec<desktop::MenuItem> {
let menus = super::view_menus();
items
.into_iter()
.map(|item| match item.kind {
Kind::Separator => desktop::MenuItem::Separator,
Kind::Submenu(items) => desktop::MenuItem::Submenu {
label: item.label,
enabled: item.enabled,
items: decode(items, mac, owner, handlers),
icon: item.icon.as_ref().and_then(ImageSrc::menu_icon),
},
Kind::Action => {
let id = match item.on_select {
Some(f) => {
let id = menus.borrow_mut().next_id();
let owner = *owner;
handlers.push((id, Rc::new(move || owner.run(&*f))));
id
}
None => 0,
};
let shortcut = match item.shortcut {
Some(text) => Shortcut::parse(&text, mac).ok(),
None => item.role.and_then(|r| r.shortcut(mac)),
};
desktop::MenuItem::Action(MenuAction {
id,
label: item.label,
shortcut,
enabled: item.enabled,
checked: item.checked,
role: item.role,
when: item.when,
icon: item.icon.as_ref().and_then(ImageSrc::menu_icon),
})
}
})
.collect()
}
fn desktop_os() -> bool {
super::os().is_desktop()
}
pub fn set_application_menu(items: impl Into<Option<Vec<MenuItem>>>) {
if !desktop_os() {
return;
}
let menus = super::view_menus();
let Some(items) = items.into() else {
let mut m = menus.borrow_mut();
m.app_generation += 1;
let old = std::mem::take(&mut m.app);
drop(m);
drop(old);
super::desktop_command(DesktopCommand::SetMenu(None));
return;
};
let owner = Owner::current();
let mut handlers = Vec::new();
let items = decode(items, super::os() == Os::MacOs, &owner, &mut handlers);
let generation = {
let mut m = menus.borrow_mut();
m.app_generation += 1;
let old = std::mem::replace(&mut m.app, handlers);
let generation = m.app_generation;
drop(m);
drop(old);
generation
};
let weak = Rc::downgrade(&menus);
cleanup(move || {
if let Some(menus) = weak.upgrade() {
let mut m = menus.borrow_mut();
if m.app_generation == generation {
let old = std::mem::take(&mut m.app);
drop(m);
drop(old);
}
}
});
super::desktop_command(DesktopCommand::SetMenu(Some(items.into())));
}
pub fn popup_menu(items: Vec<MenuItem>) -> Answer<()> {
popup(items, None)
}
pub fn popup_menu_at(items: Vec<MenuItem>, at: Point<Points>) -> Answer<()> {
popup(items, Some(at))
}
fn popup(items: Vec<MenuItem>, at: Option<Point<Points>>) -> Answer<()> {
let (answer, slot) = Answer::new();
if !desktop_os() {
slot.borrow_mut().deliver(());
return answer;
}
let menus = super::view_menus();
let owner = Owner::current();
let mut handlers = Vec::new();
let items = decode(items, super::os() == Os::MacOs, &owner, &mut handlers);
let generation = {
let mut m = menus.borrow_mut();
m.settle_popup();
m.closed = Some(slot);
m.popup_generation += 1;
let old = std::mem::replace(&mut m.popup, handlers);
let generation = m.popup_generation;
drop(m);
drop(old);
generation
};
let weak = Rc::downgrade(&menus);
cleanup(move || {
if let Some(menus) = weak.upgrade() {
let mut m = menus.borrow_mut();
if m.popup_generation == generation {
let old = std::mem::take(&mut m.popup);
drop(m);
drop(old);
}
}
});
super::desktop_command(DesktopCommand::PopupMenu {
items: items.into(),
at,
});
answer
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TrayClickEvent {
pub bounds: Option<Bounds<Points>>,
}
#[derive(Default)]
#[must_use = "a tray shows nothing until given to set_tray"]
pub struct Tray {
icon: Option<ImageSrc>,
tooltip: String,
title: Vec<TrayTitleRun>,
title_placement: TrayTitlePlacement,
menu: Vec<MenuItem>,
on_click: Option<TrayClick>,
}
type TrayClick = Rc<dyn Fn(&TrayClickEvent)>;
pub fn tray() -> Tray {
Tray::default()
}
impl Tray {
pub fn icon(mut self, src: impl Into<ImageSrc>) -> Self {
self.icon = Some(src.into());
self
}
pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
self.tooltip = tooltip.into();
self
}
pub fn title(mut self, runs: impl IntoIterator<Item = TrayTitleRun>) -> Self {
self.title = runs.into_iter().collect();
self
}
pub fn title_placement(mut self, placement: TrayTitlePlacement) -> Self {
self.title_placement = placement;
self
}
pub fn menu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
self.menu = items.into_iter().collect();
self
}
pub fn on_click(mut self, f: impl Fn(&TrayClickEvent) + 'static) -> Self {
self.on_click = Some(Rc::new(f));
self
}
}
impl fmt::Debug for Tray {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tray")
.field("tooltip", &self.tooltip)
.field("title", &self.title)
.field("title_placement", &self.title_placement)
.field("menu", &self.menu)
.field("on_click", &self.on_click.is_some())
.finish_non_exhaustive()
}
}
pub fn set_tray(tray: impl Into<Option<Tray>>) {
if !desktop_os() {
return;
}
let menus = super::view_menus();
let Some(tray) = tray.into() else {
let mut m = menus.borrow_mut();
m.tray_generation += 1;
let old = (std::mem::take(&mut m.tray), m.tray_click.take());
drop(m);
drop(old);
super::desktop_command(DesktopCommand::SetTray(None));
return;
};
let owner = Owner::current();
let mut handlers = Vec::new();
let items = decode(tray.menu, super::os() == Os::MacOs, &owner, &mut handlers);
let click = tray.on_click.map(|f| {
let id = menus.borrow_mut().next_id();
let handler: super::menus::TrayClickHandler =
Rc::new(move |bounds| owner.run(|| f(&TrayClickEvent { bounds })));
(id, handler)
});
let command = desktop::Tray {
icon: tray.icon.as_ref().and_then(ImageSrc::menu_icon),
tooltip: tray.tooltip,
title: tray.title,
title_placement: tray.title_placement,
menu: items.into(),
click: click.as_ref().map_or(0, |(id, _)| *id),
};
let generation = {
let mut m = menus.borrow_mut();
m.tray_generation += 1;
let old = (
std::mem::replace(&mut m.tray, handlers),
std::mem::replace(&mut m.tray_click, click),
);
let generation = m.tray_generation;
drop(m);
drop(old);
generation
};
let weak = Rc::downgrade(&menus);
cleanup(move || {
if let Some(menus) = weak.upgrade() {
let mut m = menus.borrow_mut();
if m.tray_generation == generation {
let old = (std::mem::take(&mut m.tray), m.tray_click.take());
drop(m);
drop(old);
}
}
});
super::desktop_command(DesktopCommand::SetTray(Some(command)));
}
pub fn register_global_shortcut(keystroke: &str, on_press: impl Fn() + 'static) -> Answer<bool> {
let shortcut = match Shortcut::parse(keystroke, super::os() == Os::MacOs) {
Ok(shortcut) => shortcut,
Err(e) => panic!("register_global_shortcut: {e}"),
};
let (answer, slot) = Answer::new();
if !desktop_os() {
slot.borrow_mut().deliver(false);
return answer;
}
unregister_where(|g| g.shortcut == shortcut);
let menus = super::view_menus();
let owner = Owner::current();
let id = {
let mut m = menus.borrow_mut();
let id = m.next_id();
m.globals.push(super::menus::Global {
id,
shortcut,
on_press: Rc::new(move || owner.run(&on_press)),
registered: Some(slot),
});
id
};
cleanup(move || unregister_where(|g| g.id == id));
super::desktop_command(DesktopCommand::RegisterGlobalShortcut { id, shortcut });
answer
}
pub fn unregister_global_shortcut(keystroke: &str) {
if let Ok(shortcut) = Shortcut::parse(keystroke, super::os() == Os::MacOs) {
unregister_where(|g| g.shortcut == shortcut);
}
}
pub fn unregister_all_global_shortcuts() {
unregister_where(|_| true);
}
fn unregister_where(remove: impl Fn(&super::menus::Global) -> bool) {
let menus = super::view_menus();
let removed: Vec<super::menus::Global> = {
let mut m = menus.borrow_mut();
let (removed, kept) = std::mem::take(&mut m.globals)
.into_iter()
.partition(&remove);
m.globals = kept;
removed
};
for g in removed {
if let Some(slot) = g.registered {
slot.borrow_mut().deliver(false);
}
super::desktop_command(DesktopCommand::UnregisterGlobalShortcut(g.id));
}
}