on_window_close_quit.rs

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