/
menuaction.go
510 lines (429 loc) · 13.2 KB
/
menuaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
package gtkutil
import (
"encoding/json"
"log"
"reflect"
"strings"
"github.com/diamondburned/gotk4/pkg/gdk/v4"
"github.com/diamondburned/gotk4/pkg/gio/v2"
"github.com/diamondburned/gotk4/pkg/glib/v2"
"github.com/diamondburned/gotk4/pkg/gtk/v4"
"github.com/diamondburned/gotkit/app/locale"
)
// ActionFunc creates a CallbackActionFunc from a function.
func ActionFunc(name string, f func()) *CallbackAction {
c := NewCallbackAction(name)
c.OnActivate(f)
return c
}
// CallbackAction extends SimpleAction to provide idiomatic callback APIs.
type CallbackAction struct {
*gio.SimpleAction
}
// NewCallbackAction creates a new CallbackAction.
func NewCallbackAction(name string) *CallbackAction {
a := gio.NewSimpleAction(name, nil)
return &CallbackAction{a}
}
// NewCallbackActionParam creates a new CallbackAction with a single parameter.
func NewCallbackActionParam(name string, paramType *glib.VariantType) *CallbackAction {
a := gio.NewSimpleAction(name, paramType)
return &CallbackAction{a}
}
// OnActivate binds the given function callback to be called when the action is
// activated.
func (a *CallbackAction) OnActivate(f interface{}) {
if f != nil {
a.SimpleAction.ConnectActivate(func(variant *glib.Variant) {
switch f := f.(type) {
case func():
f()
case func(*glib.Variant):
f(variant)
}
})
}
}
// ActionData describes a CallbackAction's data.
type ActionData struct {
Name string
Func func()
}
// ActionGroup constructs an action group from the diven action data.
func ActionGroup(data ...gio.Actioner) *gio.SimpleActionGroup {
group := gio.NewSimpleActionGroup()
for _, data := range data {
group.AddAction(data)
}
return group
}
// BindActionMap binds the given map of actions (of key prefixed appropriately)
// to the given widget.
func BindActionMap(w gtk.Widgetter, m map[string]func()) {
actions := make(map[string]*gio.SimpleActionGroup)
for k, v := range m {
parts := strings.SplitN(k, ".", 2)
if len(parts) != 2 {
log.Panicf("invalid action key %q", k)
}
group, ok := actions[parts[0]]
if !ok {
group = gio.NewSimpleActionGroup()
gtk.BaseWidget(w).InsertActionGroup(parts[0], group)
actions[parts[0]] = group
}
group.AddAction(ActionFunc(parts[1], v))
}
}
// JSONVariantType is the GVariantType that describes the JSON argument that
// NewJSONActionCallback outputs.
var JSONVariantType = glib.NewVariantType("ay") // array of bytes
// NewJSONVariant creates a new GVariant instance from any Go value that can be
// encoded into JSON. If the value cannot be encoded, then the function panics.
func NewJSONVariant(v interface{}) *glib.Variant {
b, err := json.Marshal(v)
if err != nil {
log.Panicln("cannot encode JSON for GVariant:", err.Error())
return nil
}
return glib.NewVariantBytestring(b)
}
// NewJSONActionCallback creates a new ActionCallback that uses JSON to marshal
// and unmarshal data.
func NewJSONActionCallback(f interface{}) ActionCallback {
funcType := reflect.TypeOf(f)
if funcType.Kind() != reflect.Func || funcType.NumIn() != 1 || funcType.NumOut() != 0 {
panic("f must be of type func(T)")
}
funcValue := reflect.ValueOf(f)
argType := funcType.In(0)
return ActionCallback{
ArgType: JSONVariantType,
Func: func(variant *glib.Variant) {
v := reflect.New(argType)
b := variant.Bytestring()
if err := json.Unmarshal(b, v.Interface()); err != nil {
log.Printf("received JSON action with invalid JSON %q: %v", b, err)
return
}
funcValue.Call([]reflect.Value{v.Elem()})
},
}
}
// ActionCallback is a type holding a callback with a GVariant argument and a
// GVariantType field describing its internal structure.
type ActionCallback struct {
Func func(*glib.Variant)
ArgType *glib.VariantType
}
// BindActionCallbackMap is a more verbose variant of BindActionMap.
func BindActionCallbackMap(w gtk.Widgetter, m map[string]ActionCallback) {
actions := make(map[string]*gio.SimpleActionGroup)
for k, v := range m {
parts := strings.SplitN(k, ".", 2)
if len(parts) != 2 {
log.Panicf("invalid action key %q", k)
}
group, ok := actions[parts[0]]
if !ok {
group = gio.NewSimpleActionGroup()
gtk.BaseWidget(w).InsertActionGroup(parts[0], group)
actions[parts[0]] = group
}
action := gio.NewSimpleAction(parts[1], v.ArgType)
action.ConnectActivate(v.Func)
group.AddAction(action)
}
}
// AddActions adds the given actions to the given widget.
// Unlike BindActionMap, this function does not need prefixed action names.
func AddActions(actionMapper gio.ActionMapper, m map[string]func()) {
for k, v := range m {
if strings.Contains(k, ".") {
log.Panicf("invalid action key %q: must not contain prefixed name", k)
}
actionMapper.AddAction(ActionFunc(k, v))
}
}
// AddActionCallbacks adds the given action callbacks to the given widget.
// Unlike BindActionCallbackMap, this function does not need prefixed action
// names.
func AddActionCallbacks(actionMapper gio.ActionMapper, m map[string]ActionCallback) {
for k, v := range m {
if strings.Contains(k, ".") {
log.Panicf("invalid action key %q: must not contain prefixed name", k)
}
action := gio.NewSimpleAction(k, v.ArgType)
action.ConnectActivate(v.Func)
actionMapper.AddAction(action)
}
}
func NewCustomMenuItem(label locale.Localized, id string) *gio.MenuItem {
item := gio.NewMenuItem(label.String(), id)
setCustomMenuItem(item, id)
return item
}
func setCustomMenuItem(item *gio.MenuItem, id string) {
item.SetAttributeValue("custom", glib.NewVariantString(id))
}
// MenuPair creates a gtk.Menu out of the given menu pair. The returned Menu
// instance satisfies gio.MenuModeller. The first value of a pair should be the
// name.
func MenuPair(pairs [][2]string) *gio.Menu {
menu := gio.NewMenu()
for _, pair := range pairs {
menu.Append(locale.Get(pair[0]), pair[1])
}
return menu
}
// PopoverWidth is the default popover width.
const PopoverWidth = 150
// BindPopoverMenu binds the given widget to a popover menu to be displayed on
// right-clicking.
func BindPopoverMenu(w gtk.Widgetter, pos gtk.PositionType, pairs [][2]string) {
BindRightClick(w, func() { ShowPopoverMenu(w, pos, pairs) })
}
// BindPopoverMenuAtMouse binds the given widget to a popover menu to be
// displayed on right-clicking, but at the mouse position.
func BindPopoverMenuAtMouse(w gtk.Widgetter, pos gtk.PositionType, pairs [][2]string) {
BindRightClickAt(w, func(x, y float64) {
at := gdk.NewRectangle(int(x), int(y), 0, 0)
popover := NewPopoverMenu(w, pos, pairs)
popover.SetPointingTo(&at)
PopupFinally(popover)
})
}
// ShowPopoverMenu is like ShowPopoverMenuCustom but uses a regular string pair
// list.
func ShowPopoverMenu(w gtk.Widgetter, pos gtk.PositionType, pairs [][2]string) *gtk.PopoverMenu {
p := NewPopoverMenu(w, pos, pairs)
PopupFinally(p)
return p
}
// Popupper describes the Popover's Popup interface.
type Popupper interface {
gtk.Widgetter
Popup()
Unparent()
ConnectHide(func()) glib.SignalHandle
}
var (
_ Popupper = (*gtk.Popover)(nil)
_ Popupper = (*gtk.PopoverMenu)(nil)
)
// PopupFinally pops up the Popover and schedules it to destroy itself when it's
// closed.
func PopupFinally(p Popupper) {
var sig glib.SignalHandle
sig = p.ConnectHide(func() {
glib.TimeoutSecondsAdd(2, p.Unparent)
p.HandlerDisconnect(sig)
})
p.Popup()
}
// NewPopoverMenu creates a new Popover menu.
func NewPopoverMenu(w gtk.Widgetter, pos gtk.PositionType, pairs [][2]string) *gtk.PopoverMenu {
popover := gtk.NewPopoverMenuFromModel(MenuPair(pairs))
popover.SetMnemonicsVisible(true)
popover.SetSizeRequest(PopoverWidth, -1)
popover.SetPosition(pos)
popover.SetParent(w)
return popover
}
// PopoverMenuItem defines a popover menu item constructed from one of the
// constructors.
type PopoverMenuItem interface {
menu()
}
type popoverMenuItem struct {
label locale.Localized
action string
icon string
widget gtk.Widgetter
}
func (p popoverMenuItem) menu() {}
// MenuItem creates a simple popover menu item. If action is empty, then the
// item is disabled; if action is "---", then a new section is created.
func MenuItem(label locale.Localized, action string, ands ...bool) PopoverMenuItem {
for _, and := range ands {
if !and {
return nil
}
}
return popoverMenuItem{
label: label,
action: action,
}
}
// MenuItemIcon is an icon variant of MenuItem.
func MenuItemIcon(label locale.Localized, action, icon string) PopoverMenuItem {
return popoverMenuItem{
label: label,
action: action,
icon: icon,
}
}
// MenuWidget creates a new menu item that contains a widget.
func MenuWidget(action string, w gtk.Widgetter) PopoverMenuItem {
return popoverMenuItem{
action: action,
widget: w,
}
}
// MenuSeparator creates a new menu separator.
func MenuSeparator(label locale.Localized) PopoverMenuItem {
return popoverMenuItem{
label: label,
action: "---",
}
}
type submenu struct {
label locale.Localized
items []PopoverMenuItem
}
func (p submenu) menu() {}
// Submenu creates a popover menu item that is a submenu.
func Submenu(label locale.Localized, sub []PopoverMenuItem) PopoverMenuItem {
return submenu{
label: label,
items: sub,
}
}
// BindPopoverMenuCustom works similarly to BindPopoverMenu, but the value type
// can be more than just an action string. The key must be a string.
func BindPopoverMenuCustom(w gtk.Widgetter, pos gtk.PositionType, pairs []PopoverMenuItem) {
BindRightClickAt(w, func(x, y float64) {
popover := NewPopoverMenuCustom(w, pos, pairs)
if popover == nil {
return
}
at := gdk.NewRectangle(int(x), int(y), 0, 0)
popover.SetPointingTo(&at)
PopupFinally(popover)
})
}
// BindPopoverMenuLazy is similarl to BindPopoverMenuCustom, except the menu
// items are lazily created.
func BindPopoverMenuLazy(w gtk.Widgetter, pos gtk.PositionType, pairsFn func() []PopoverMenuItem) {
BindRightClick(w, func() { ShowPopoverMenuCustom(w, pos, pairsFn()) })
}
// CustomMenu returns a new Menu from the given popover menu items. All menu
// items that have widgets are ignored.
func CustomMenu(items []PopoverMenuItem) *gio.Menu {
menu := gio.NewMenu()
addMenuItems(menu, items, nil)
return menu
}
// CustomMenuItems is the variadic arguments variant of CustomMenu.
func CustomMenuItems(items ...PopoverMenuItem) *gio.Menu {
return CustomMenu(items)
}
func addMenuItems(menu *gio.Menu, items []PopoverMenuItem, widgets map[string]gtk.Widgetter) int {
section := menu
var added int
for _, item := range items {
if item == nil {
continue
}
switch item := item.(type) {
case popoverMenuItem:
if item.widget != nil && widgets == nil {
// No widgets supported; skip this menu item.
continue
}
if item.action == "---" {
section = gio.NewMenu()
menu.AppendSection(item.label.String(), section)
continue
}
menu := gio.NewMenuItem(item.label.String(), item.action)
if item.icon != "" {
menu.SetIcon(gio.NewThemedIcon(item.icon))
}
if item.widget != nil {
widgets[item.action] = item.widget
setCustomMenuItem(menu, item.action)
}
added++
section.AppendItem(menu)
case submenu:
sub := gio.NewMenu()
if addMenuItems(sub, item.items, widgets) > 0 {
added++
section.AppendSubmenu(item.label.String(), sub)
}
default:
log.Panicf("unknown menu item type %T", item)
}
}
return added
}
// ShowPopoverMenuCustom is like BindPopoverMenuCustom, but it does not bind a
// handler. This is useful if the caller does not want pairs to be in memory all
// the time. If any of the menus cannot be added in, then false is returned, and
// the popover isn't shown.
func ShowPopoverMenuCustom(w gtk.Widgetter, pos gtk.PositionType, items []PopoverMenuItem) bool {
popover := NewPopoverMenuCustom(w, pos, items)
if popover == nil {
return false
}
PopupFinally(popover)
return true
}
// NewPopoverMenuCustom creates a new Popover containing the given items.
func NewPopoverMenuCustom(
w gtk.Widgetter, pos gtk.PositionType, items []PopoverMenuItem) *gtk.PopoverMenu {
menu := gio.NewMenu()
widgets := make(map[string]gtk.Widgetter)
addMenuItems(menu, items, widgets)
popover := gtk.NewPopoverMenuFromModel(menu)
popover.SetAutohide(true)
popover.SetCascadePopdown(false)
popover.SetSizeRequest(PopoverWidth, -1)
popover.SetPosition(pos)
if w != nil {
popover.SetParent(w)
}
for action, widget := range widgets {
if !popover.AddChild(widget, action) {
return nil
}
}
return popover
}
// NewPopoverMenuFromPairs is a convenient function for NewPopoverMenuFromModel
// and MenuPairs.
func NewPopoverMenuFromPairs(pairs [][2]string) *gtk.PopoverMenu {
return gtk.NewPopoverMenuFromModel(MenuPair(pairs))
}
// RadioData describes the data for the set of radio buttons created by
// NewRadioButtons.
type RadioData struct {
Current int
Options []locale.Localized
}
// NewRadioButtons creates a new box of radio buttons.
func NewRadioButtons(d RadioData, f func(int)) gtk.Widgetter {
b := gtk.NewBox(gtk.OrientationVertical, 0)
b.AddCSSClass("radio-buttons")
var first *gtk.CheckButton
for i, opt := range d.Options {
i := i
radio := gtk.NewCheckButtonWithLabel(opt.String())
radio.ConnectToggled(func() {
if radio.Active() {
f(i)
}
})
if d.Current == i {
radio.SetActive(true)
}
if first != nil {
radio.SetGroup(first)
} else {
first = radio
}
b.Append(radio)
}
return b
}