Skip to content

Commit

Permalink
Merge pull request #5 from ttytm/feat/item-cb-sumtype
Browse files Browse the repository at this point in the history
Allow to set fn() or fn(item &MenuItem) for on_click cbs
  • Loading branch information
Ouri028 authored Oct 8, 2023
2 parents 9fbf071 + fe06789 commit f49940d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 21 deletions.
12 changes: 5 additions & 7 deletions example/basic_usage.v
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@ fn main() {
mut tray := vtray.create(icon, tooltip: 'VTray Demo!')
tray.add_item('Edit',
checkable: true
on_click: fn [tray] () {
if x := tray.get_item('Edit') {
if x.checked {
tray.set_icon('${@VMODROOT}/assets/test.ico')
} else {
tray.set_icon('${@VMODROOT}/assets/icon.ico')
}
on_click: fn [tray] (item &vtray.MenuItem) {
if item.checked {
tray.set_icon('${@VMODROOT}/assets/test.ico')
} else {
tray.set_icon('${@VMODROOT}/assets/icon.ico')
}
}
)
Expand Down
10 changes: 0 additions & 10 deletions src/lib.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,6 @@ struct VTrayParams {
on_click fn (menu_item &MenuItem) = unsafe { nil }
}

[heap]
struct MenuItem {
pub:
id int
text string
checked bool
checkable bool
disabled bool
}

fn C.vtray_init(params &VTrayParams, num_items usize, items []&MenuItem) &VTray
fn C.vtray_run(tray &VTray)
fn C.vtray_exit(tray &VTray)
Expand Down
25 changes: 21 additions & 4 deletions src/lib.v
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,19 @@ mut:
identifier string
tooltip string
items []&MenuItem
callbacks map[int]fn ()
callbacks map[int]ItemCallback
last_id int = 1
}

pub struct MenuItem {
pub:
id int
text string
checked bool
checkable bool
disabled bool
}

[params]
pub struct CreatOptions {
identifier string = 'VTray'
Expand All @@ -25,9 +34,11 @@ pub struct MenuItemOptions {
checked bool
checkable bool
disabled bool
on_click ?fn ()
on_click ?ItemCallback
}

type ItemCallback = fn () | fn (menu_item &MenuItem)

// create creates the tray.
// On macOS, the tray icon size must be 22x22 pixels to be rendered correctly.
pub fn create(icon_path string, opts CreatOptions) &Tray {
Expand Down Expand Up @@ -75,8 +86,14 @@ pub fn (mut t Tray) run() {
tooltip: t.tooltip
icon: t.icon
on_click: fn [t] (menu_item &MenuItem) {
if cb := t.callbacks[menu_item.id] {
cb()
cb := t.callbacks[menu_item.id] or { return }
match cb {
fn (menu_item &MenuItem) {
cb(menu_item)
}
fn () {
cb()
}
}
}
}, usize(t.items.len), t.items.data)
Expand Down

0 comments on commit f49940d

Please sign in to comment.