| 1 | // vtest build: macos |
| 2 | // Simple windows-less application that shows a icon button on Mac OS tray. |
| 3 | // Tested on Mac OS Monterey (12.3). |
| 4 | |
| 5 | module main |
| 6 | |
| 7 | #include <Cocoa/Cocoa.h> |
| 8 | #flag -framework Cocoa |
| 9 | |
| 10 | #include "@VMODROOT/tray.m" |
| 11 | |
| 12 | fn C.tray_app_init(TrayParams) &TrayInfo |
| 13 | fn C.tray_app_loop(&TrayInfo) |
| 14 | fn C.tray_app_run(&TrayInfo) |
| 15 | fn C.tray_app_exit(&TrayInfo) |
| 16 | |
| 17 | struct TrayMenuItem { |
| 18 | id string @[required] // Unique ID. |
| 19 | text string @[required] // Text to display. |
| 20 | } |
| 21 | |
| 22 | // Parameters to configure the tray button. |
| 23 | struct TrayParams { |
| 24 | items []TrayMenuItem @[required] |
| 25 | on_click fn (item main.TrayMenuItem) @[required] |
| 26 | } |
| 27 | |
| 28 | // Internal Cocoa application state. |
| 29 | struct TrayInfo { |
| 30 | app voidptr // pointer to NSApplication |
| 31 | app_delegate voidptr // pointer to AppDelegate |
| 32 | } |
| 33 | |
| 34 | @[heap] |
| 35 | struct MyApp { |
| 36 | mut: |
| 37 | tray_info &TrayInfo = unsafe { nil } |
| 38 | } |
| 39 | |
| 40 | fn (app &MyApp) on_menu_item_click(item TrayMenuItem) { |
| 41 | println('click ${item.id}') |
| 42 | if item.id == 'quit' { |
| 43 | C.tray_app_exit(app.tray_info) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn main() { |
| 48 | mut my_app := &MyApp{ |
| 49 | tray_info: unsafe { nil } |
| 50 | } |
| 51 | |
| 52 | my_app.tray_info = C.tray_app_init(TrayParams{ |
| 53 | items: [TrayMenuItem{ |
| 54 | id: 'hello' |
| 55 | text: 'Hello' |
| 56 | }, TrayMenuItem{ |
| 57 | id: 'quit' |
| 58 | text: 'Quit!' |
| 59 | }] |
| 60 | on_click: my_app.on_menu_item_click |
| 61 | }) |
| 62 | |
| 63 | //// Use this: |
| 64 | // for { |
| 65 | // C.tray_app_loop(my_app.tray_info) |
| 66 | // // println("loop") |
| 67 | // } |
| 68 | |
| 69 | //// Or this: |
| 70 | C.tray_app_run(my_app.tray_info) |
| 71 | } |
| 72 | |