1use gpui::{
2 App, Application, Context, FocusHandle, KeyBinding, Menu, MenuItem, PromptLevel,
3 SystemMenuType, Window, WindowOptions, actions, div, prelude::*, rgb,
4};
5
6struct SetMenus {
7 focus_handle: FocusHandle,
8}
9
10impl Render for SetMenus {
11 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12 div()
13 .key_context("root")
14 .track_focus(&self.focus_handle)
15 .flex()
16 .bg(rgb(0x2e7d32))
17 .size_full()
18 .justify_center()
19 .items_center()
20 .text_xl()
21 .text_color(rgb(0xffffff))
22 // Actions can also be registered within elements so they are only active when relevant
23 .on_action(|_: &Open, window, cx| {
24 let _ = window.prompt(PromptLevel::Info, "Open action fired", None, &["OK"], cx);
25 })
26 .on_action(|_: &Copy, window, cx| {
27 let _ = window.prompt(PromptLevel::Info, "Copy action fired", None, &["OK"], cx);
28 })
29 .on_action(|_: &Paste, window, cx| {
30 let _ = window.prompt(PromptLevel::Info, "Paste action fired", None, &["OK"], cx);
31 })
32 .child("Set Menus Example")
33 }
34}
35
36fn main() {
37 Application::new().run(|cx: &mut App| {
38 // Bring the menu bar to the foreground (so you can see the menu bar)
39 cx.activate(true);
40 // Bind keys to some menu actions
41 cx.bind_keys([
42 KeyBinding::new("secondary-o", Open, None),
43 KeyBinding::new("secondary-c", Copy, None),
44 KeyBinding::new("secondary-v", Paste, None),
45 ]);
46 // Register the `quit` function so it can be referenced by the `MenuItem::action` in the menu bar
47 cx.on_action(quit);
48 // Add menu items
49 cx.set_menus(vec![
50 Menu {
51 name: "set_menus".into(),
52 items: vec![
53 MenuItem::os_submenu("Services", SystemMenuType::Services),
54 MenuItem::separator(),
55 MenuItem::action("Quit", Quit),
56 ],
57 },
58 Menu {
59 name: "File".into(),
60 items: vec![MenuItem::action("Open", Open)],
61 },
62 Menu {
63 name: "Edit".into(),
64 items: vec![
65 MenuItem::action("Copy", Copy),
66 MenuItem::action("Paste", Paste),
67 ],
68 },
69 ]);
70 cx.open_window(WindowOptions::default(), |_, cx| {
71 cx.new(|cx| SetMenus {
72 focus_handle: cx.focus_handle(),
73 })
74 })
75 .unwrap();
76 });
77}
78
79// Associate actions using the `actions!` macro (or `Action` derive macro)
80actions!(set_menus, [Quit, Open, Copy, Paste]);
81
82// Define the quit function that is registered with the App
83fn quit(_: &Quit, cx: &mut App) {
84 println!("Gracefully quitting the application . . .");
85 cx.quit();
86}