on_window_close_quit.rs

 1use gpui::{
 2    App, Bounds, Context, FocusHandle, KeyBinding, Window, WindowBounds, WindowOptions, actions,
 3    div, prelude::*, px, rgb, size,
 4};
 5use gpui_platform::application;
 6
 7actions!(example, [CloseWindow]);
 8
 9struct ExampleWindow {
10    focus_handle: FocusHandle,
11}
12
13impl Render for ExampleWindow {
14    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
15        div()
16            .on_action(|_: &CloseWindow, window, _| {
17                window.remove_window();
18            })
19            .track_focus(&self.focus_handle)
20            .flex()
21            .flex_col()
22            .gap_3()
23            .bg(rgb(0x505050))
24            .size(px(500.0))
25            .justify_center()
26            .items_center()
27            .shadow_lg()
28            .border_1()
29            .border_color(rgb(0x0000ff))
30            .text_xl()
31            .text_color(rgb(0xffffff))
32            .child(
33                "Closing this window with cmd-w or the traffic lights should quit the application!",
34            )
35    }
36}
37
38fn main() {
39    application().run(|cx: &mut App| {
40        let mut bounds = Bounds::centered(None, size(px(500.), px(500.0)), cx);
41
42        cx.bind_keys([KeyBinding::new("cmd-w", CloseWindow, None)]);
43        cx.on_window_closed(|cx| {
44            if cx.windows().is_empty() {
45                cx.quit();
46            }
47        })
48        .detach();
49
50        cx.open_window(
51            WindowOptions {
52                window_bounds: Some(WindowBounds::Windowed(bounds)),
53                ..Default::default()
54            },
55            |window, cx| {
56                cx.activate(false);
57                cx.new(|cx| {
58                    let focus_handle = cx.focus_handle();
59                    focus_handle.focus(window, cx);
60                    ExampleWindow { focus_handle }
61                })
62            },
63        )
64        .unwrap();
65
66        bounds.origin.x += bounds.size.width;
67
68        cx.open_window(
69            WindowOptions {
70                window_bounds: Some(WindowBounds::Windowed(bounds)),
71                ..Default::default()
72            },
73            |window, cx| {
74                cx.new(|cx| {
75                    let focus_handle = cx.focus_handle();
76                    focus_handle.focus(window, cx);
77                    ExampleWindow { focus_handle }
78                })
79            },
80        )
81        .unwrap();
82    });
83}