/
mgrgldi.go
564 lines (467 loc) · 18.6 KB
/
mgrgldi.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// Package mgrgldi manages go applets as internal applets.
package mgrgldi
// #cgo pkg-config: gldi
// #include "cairo-dock-applications-manager.h" // myTaskbarParam
// #include "cairo-dock-container.h" // NOTIFICATION_CLICK_ICON ...
// #include "cairo-dock-desklet-manager.h" // myDeskletObjectMgr
// #include "cairo-dock-dock-manager.h" // myDocksParam
// #include "cairo-dock-global-variables.h" // g_pPrimaryContainer
// #include "cairo-dock-keybinder.h" // NOTIFICATION_SHORTKEY_CHANGED
// #include "cairo-dock-module-manager.h" // myModuleObjectMgr
// #include "cairo-dock-module-instance-manager.h" // NOTIFICATION_MODULE_INSTANCE_DETACHED
// #include "gldi-icon-names.h" // GLDI_ICON_NAME_*
// #include "gldi-config.h" // GLDI_VERSION
/*
extern void onAppletInit (GldiModuleInstance *pModuleInstance, GKeyFile *pKeyFile);
extern void onAppletStop (GldiModuleInstance *pModuleInstance);
extern gboolean onAppletReload (GldiModuleInstance *pModuleInstance, GldiContainer *pOldContainer, GKeyFile *pKeyFile);
static GldiModule* newModule (gpointer vc) {
GldiModuleInterface *pInterface = g_new0 (GldiModuleInterface, 1);
pInterface->initModule = onAppletInit;
pInterface->stopModule = onAppletStop;
pInterface->reloadModule = onAppletReload;
return gldi_module_new ((GldiVisitCard*)(vc), pInterface);
}
*/
import "C"
import (
"github.com/sqp/godock/libs/cdapplet" // Start applet.
"github.com/sqp/godock/libs/cdglobal" // Global consts.
"github.com/sqp/godock/libs/cdtype" // Applets types.
"github.com/sqp/godock/libs/gldi"
"github.com/sqp/godock/libs/gldi/appgldi"
"github.com/sqp/godock/libs/gldi/backendmenu"
"github.com/sqp/godock/libs/gldi/globals"
"github.com/sqp/godock/libs/gldi/notif" // Dock notifs.
"github.com/sqp/godock/libs/packages"
"github.com/sqp/godock/widgets/gtk/keyfile"
"path/filepath"
"time"
"unsafe"
)
// apps is the active applet manager.
//
var apps *AppManager
// Register starts the applets manager service to use go internal applets in the dock.
//
func Register(log cdtype.Logger) *AppManager {
apps = NewAppManager(log)
notif.RegisterContainerLeftClick(apps.OnLeftClick)
notif.RegisterContainerMiddleClick(apps.OnMiddleClick)
notif.RegisterContainerMouseScroll(apps.OnMouseScroll)
notif.RegisterContainerDropData(apps.OnDropData)
notif.RegisterWindowChangeFocus(apps.OnChangeFocus)
notif.RegisterContainerMenuIcon(backendmenu.WrapDockMenuCallback(apps.BuildMenu))
apps.registerApplets()
return apps
}
//
//--------------------------------------------------------------[ APPMANAGER ]--
// AppManager is a multi applet manager.
//
type AppManager struct {
actives map[unsafe.Pointer]cdtype.AppInstance // Active services. Key = pointer to dock C Icon.
visitCards []*gldi.VisitCard // Keep reference to registered modules visit cards. Must not free.
// menu *backendmenu.DockMenu
// activeWin *gldi.WindowActor
activeIcon gldi.Icon // Applet whose window has the focus.
stop chan struct{} // Manual exit chan.
log cdtype.Logger
}
// NewAppManager creates an applets manager with the given list of applets services.
//
func NewAppManager(log cdtype.Logger) *AppManager {
load := &AppManager{
actives: make(map[unsafe.Pointer]cdtype.AppInstance), //*AppGldi),
log: log}
return load
}
// CountActive returns the number of managed applets.
//
func (o *AppManager) CountActive() int {
return len(o.actives)
}
// GetApplets return an applet instance.
//
func (o *AppManager) GetApplets(name string) (list []cdtype.AppInstance) {
for _, app := range o.actives {
if app.Name() == name {
list = append(list, app)
}
}
return
}
// Tick ticks all applets pollers.
//
func (o *AppManager) Tick() {
for _, app := range o.actives {
app.Poller().Plop() // Safe to use on nil poller.
}
}
// StartLoop starts the polling loop for applets.
//
func (o *AppManager) StartLoop() {
o.log.Debug("Applets service started")
defer o.log.Debug("Applets service stopped")
o.stop = make(chan struct{})
waiter := time.NewTicker(time.Second)
defer waiter.Stop()
for { // Start pollers loop and handle pollings until StopLoop is called.
select {
case <-waiter.C: // Tick every second to update pollers counters and launch actions.
for _, ref := range o.actives {
ref.Poller().Plop() // Safe to use on nil poller.
}
case <-o.stop:
return
}
}
}
// StopLoop stops the polling loop.
//
func (o *AppManager) StopLoop() {
o.stop <- struct{}{}
}
//
//----------------------------------------------------[ APPLETS REGISTRATION ]--
func (o *AppManager) registerApplets() {
dir := globals.DirShareData(cdglobal.ConfigDirAppletsGo)
packs, e := packages.ListFromDir(o.log, dir, cdtype.PackTypeGoInternal, packages.SourceApplet)
if o.log.Err(e, "registerapplets") {
return
}
for _, pack := range packs {
if cdtype.Applets.GetNewFunc(pack.DisplayedName) != nil {
o.registerOneApplet(pack)
}
}
}
func (o *AppManager) registerOneApplet(pack *packages.AppletPackage) {
if gldi.ModuleGet(pack.DisplayedName) != nil {
o.log.Debug("register applet, already known = dropped", pack.DisplayedName)
return
}
vc := gldi.NewVisitCardFromPackage(pack)
o.visitCards = append(o.visitCards, vc)
c := C.newModule(C.gpointer(vc.Ptr))
mod := gldi.NewModuleFromNative(unsafe.Pointer(c))
o.log.Debug("register applet", mod != nil, vc.GetName(), vc.GetShareDataDir())
}
//
//------------------------------------------------------[ APPLETS LIFE CYCLE ]--
// startApplet starts a new applet instance connected to its dock icon and instance.
//
func (o *AppManager) startApplet(mi *gldi.ModuleInstance, kf *keyfile.KeyFile) {
icon := mi.Icon()
vc := mi.Module().VisitCard()
name := vc.GetName()
// Get the mandatory create applet func.
newfunc := cdtype.Applets.GetNewFunc(name)
if newfunc == nil {
o.log.NewErr(name, "StartApplet: applet unknown (maybe not enabled at compile)")
return
}
// Default desklet renderer.
if desklet := mi.Desklet(); desklet != nil {
desklet.SetRendererByName("Simple")
}
// Default icon image.
if icon != nil && icon.GetFileName() == "" {
icon.SetIcon(mi.Module().VisitCard().GetIconFilePath())
// gtk_widget_queue_draw (pModuleInstance->pContainer->pWidget);
}
// Upgrade configuration file if needed.
// It seem it's already done by the dock, but we'll display a readable info.
if kf != nil && gldi.ConfFileNeedUpdate(kf, vc.GetModuleVersion()) {
original := filepath.Join(vc.GetShareDataDir(), vc.GetConfFileName())
o.log.Info("Conf file upgrade", mi.GetConfFilePath(), original)
}
// Create applet instance and set its core data.
callnew := cdtype.Applets.GetNewFunc(name)
appbase := cdapplet.New()
appbase.SetBase(name, mi.GetConfFilePath(), globals.DirDockData(), vc.GetShareDataDir()) // TODO: need rootdir
app := cdapplet.Start(callnew, appbase)
if app == nil {
o.log.NewErr(name, "failed to start applet")
return
}
if o.log.GetDebug() { // If the service debug is active, force it also on applets.
app.Log().SetDebug(true)
}
o.log.Debug("applet started", name)
app.SetBackend(appgldi.New(mi))
callinit := app.SetEvents(app)
e := callinit()
if app.Log().Err(e, "failed to init") {
return
}
// Everything was fine. We can add the applet in the managed list.
o.actives[unsafe.Pointer(icon.ToNative())] = app
}
// StopApplet close the applet instance.
//
func (o *AppManager) stopApplet(mi *gldi.ModuleInstance) {
icon := mi.Icon()
o.sendApp(icon, "on_stop_module")
if subdock := icon.GetSubDock(); subdock != nil {
gldi.ObjectUnref(subdock)
// mi.Icon().pSubDock = nil
}
icon.RemoveDataRenderer()
desklet := mi.Desklet()
if desklet != nil && desklet.HasIcons() {
desklet.RemoveIcons()
}
o.log.Debug("Applet stopped", mi.Module().VisitCard().GetName())
delete(o.actives, unsafe.Pointer(icon.ToNative()))
}
func (o *AppManager) reloadApplet(mi *gldi.ModuleInstance, oldContainer *gldi.Container, kf *keyfile.KeyFile) bool {
o.log.Info("reload", mi.Module().VisitCard().GetName())
icon := mi.Icon()
o.sendApp(icon, "on_reload_module", kf != nil)
if o.log.GetDebug() { // If the service debug is active, force it also on applets.
app := o.actives[unsafe.Pointer(icon.ToNative())]
if app != nil {
app.Log().SetDebug(true)
}
}
// Default desklet renderer.
if desklet := mi.Desklet(); desklet != nil {
if desklet.HasIcons() {
desklet.SetRendererByNameData("Caroussel", true, false)
} else {
desklet.SetRendererByName("Simple")
}
}
// Default icon image.
if icon != nil && icon.GetFileName() == "" {
icon.SetIcon(mi.Module().VisitCard().GetIconFilePath())
// gtk_widget_queue_draw (pModuleInstance->pContainer->pWidget);
}
// Update data renderer size.
if kf == nil {
// CairoDataRenderer *pDataRenderer = cairo_dock_get_icon_data_renderer (pIcon);
// if (pDataRenderer != NULL)
// {
// CairoDataToRenderer *pData = cairo_data_renderer_get_data (pDataRenderer);
// if (pData->iMemorySize > 2)
// cairo_dock_resize_data_renderer_history (pIcon, pIcon->fWidth);
// }
}
return notif.AnswerIntercept
}
//
/*
//\____________ internationalize the applets (we need to do that before registering applets).
gchar *cLocaleDir = g_strdup_printf ("%s/"CD_DBUS_APPLETS_FOLDER"/"LOCALE_DIR_NAME, g_cCairoDockDataDir); // user version of /usr/share/locale
if (! g_file_test (cLocaleDir, G_FILE_TEST_EXISTS)) // translations not downloaded yet.
{
gchar *cUserAppletsFolder = g_strdup_printf ("%s/"CD_DBUS_APPLETS_FOLDER, g_cCairoDockDataDir);
if (! g_file_test (cUserAppletsFolder, G_FILE_TEST_EXISTS))
{
if (g_mkdir (cUserAppletsFolder, 7*8*8+7*8+5) != 0) // create an empty folder; since there is no date file, the "locale" package will be seen as "to be updated" by the package manager, which will therefore download it.
cd_warning ("couldn't create '%s'; third-party applets can't be added", cUserAppletsFolder);
}
g_free (cUserAppletsFolder);
*/
/*
* create an empty folder; since there is no date file, the "locale"
* package will be seen as "to be updated" by the package manager, and
* will therefore download it.
* But if last-modif file is not available, it will be seen as "to be
* updated" only if the external package is younger than one month:
* => cairo-dock-packages.c:_cairo_dock_parse_package_list
* Solution: added a file with "0" to force the download
*/
/*
if (g_mkdir (cLocaleDir, 7*8*8+7*8+5) != 0)
cd_warning ("couldn't create '%s'; applets won't be translated", cLocaleDir);
else
{
gchar *cVersionFile = g_strdup_printf ("%s/last-modif", cLocaleDir);
g_file_set_contents (cVersionFile,
"0",
-1,
NULL);
g_free (cVersionFile);
}
}
bindtextdomain (GETTEXT_NAME_EXTRAS, cLocaleDir); // bind the applets' domain to the user locale folder.
bind_textdomain_codeset (GETTEXT_NAME_EXTRAS, "UTF-8");
g_free (cLocaleDir);
*/
//
//------------------------------------------------------------------[ EVENTS ]--
// OnLeftClick forwards a click event to the applet.
//
func (o *AppManager) OnLeftClick(icon gldi.Icon, container *gldi.Container, btnState uint) bool {
return o.sendIconOrSub(icon, container, "on_click", "on_click_sub_icon", int(btnState))
}
// OnMiddleClick forwards a click event to the applet.
//
func (o *AppManager) OnMiddleClick(icon gldi.Icon, container *gldi.Container) bool {
return o.sendIconOrSub(icon, container, "on_middle_click", "on_middle_click_sub_icon")
}
// OnMouseScroll forwards a mouse event to the applet.
//
func (o *AppManager) OnMouseScroll(icon gldi.Icon, container *gldi.Container, scrollUp bool) bool {
return o.sendIconOrSub(icon, container, "on_scroll", "on_scroll_sub_icon", scrollUp)
}
// OnDropData forwards a drop event to the applet.
//
func (o *AppManager) OnDropData(icon gldi.Icon, container *gldi.Container, data string, order float64) bool {
return o.sendIconOrSub(icon, container, "on_drop_data", "on_drop_data_sub_icon", data)
}
// OnChangeFocus forwards a window focus event to the applet.
//
func (o *AppManager) OnChangeFocus(win cdglobal.Window) bool {
// Emit signal on the applet that had focus.
if o.activeIcon != nil {
o.sendApp(o.activeIcon, "on_change_focus", false)
o.activeIcon = nil
}
// Emit signal on the applet that now has focus.
if win != nil {
icon := gldi.GetAppliIcon(win)
if icon != nil {
icon = icon.GetInhibitor(false)
if icon != nil && icon.IsApplet() {
o.sendApp(icon, "on_change_focus", true)
o.activeIcon = icon
}
}
}
return notif.AnswerLetPass
}
// BuildMenu forwards a build menu event to the applet.
//
func (o *AppManager) BuildMenu(m *backendmenu.DockMenu) bool {
o.sendIconOrSub(m.Icon, m.Container, "on_build_menu", "on_build_menu_sub_icon", &MenuerLike{*m})
return notif.AnswerLetPass // don't intercept menu. (to check)
}
// sendIconOrSub sends an event to the applet matching the icon or subicon.
//
func (o *AppManager) sendIconOrSub(icon gldi.Icon, container *gldi.Container, mainEvent, subEvent string, data ...interface{}) bool {
var appIcon gldi.Icon
switch { // Find the base icon of the icon that was clicked on (for subdock or desklets).
case container.IsDesklet():
appIcon = container.ToDesklet().GetIcon()
case gldi.ObjectIsDock(container) && container.ToCairoDock().GetRefCount() != 0 && !icon.IsApplet():
appIcon = container.ToCairoDock().SearchIconPointingOnDock(nil)
default:
appIcon = icon
}
if appIcon == nil || icon == nil || icon.ToNative() == nil { // TODO: need to check why.
return notif.AnswerLetPass
}
if appIcon.ToNative() == icon.ToNative() {
return o.sendApp(appIcon, mainEvent, data...) // Main Icon event.
}
data = append(data, icon.GetCommand()) // add reference to subicon key.
return o.sendApp(appIcon, subEvent, data...) // SubIcon event.
}
// sendApp sends an event to the applet matching the icon.
//
func (o *AppManager) sendApp(icon gldi.Icon, event string, data ...interface{}) bool {
app := o.actives[unsafe.Pointer(icon.ToNative())]
if app == nil {
return notif.AnswerLetPass
}
o.log.Debug(event, data...)
app.OnEvent(event, data...)
return notif.AnswerIntercept // an app received the event (even if unused). intercept it.
}
// func (dock *CairoDock) SearchIconPointingOnDock(unknown interface{}) *Icon { // TODO: add param CairoDock **pParentDock
// c := C.cairo_dock_search_icon_pointing_on_dock(dock.Ptr, nil)
// return NewIconFromNative(unsafe.Pointer(c))
// }
// static inline Icon *_get_main_icon_from_clicked_icon (Icon *pIcon, GldiContainer *pContainer)
// {
// Icon *pMainIcon = NULL;
// return pMainIcon;
// }
// if (pClickedIcon == pAppletIcon)
// {
// //g_print ("emit clic on main icon\n");
// g_signal_emit (pDbusApplet, s_iSignals[CLIC], 0, iButtonState);
// }
// else if (pDbusApplet->pSubApplet != NULL)
// {
// //g_print ("emit clic on sub icon\n");
// g_signal_emit (pDbusApplet->pSubApplet, s_iSubSignals[CLIC], 0, iButtonState, pClickedIcon->cCommand);
// }
// // if the applet acts as a launcher, assume it launches the program it controls on click
// // Note: if one day it poses a problem, we can either make a new attribute, or add a dbus method (or even reuse the "Animate" method with a pseudo "launching" animation).
// if (pAppletIcon->pModuleInstance->pModule->pVisitCard->bActAsLauncher
// && pClickedIcon->pAppli == NULL) // if the icon already controls a window, don't notify; most probably, the action the applet will take is to show/minimize this window
// gldi_class_startup_notify (pClickedIcon);
// return GLDI_NOTIFICATION_INTERCEPT;
// }
// void cd_dbus_emit_on_menu_select (GtkMenuItem *pMenuItem, gpointer data)
// {
// g_return_if_fail (myData.pCurrentMenuDbusApplet != NULL);
// if (GTK_IS_RADIO_MENU_ITEM (pMenuItem))
// {
// if (!gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (pMenuItem)))
// return ;
// }
// int iNumEntry = GPOINTER_TO_INT (data);
// g_signal_emit (myData.pCurrentMenuDbusApplet, s_iSignals[MENU_SELECT], 0, iNumEntry); // since there can only be 1 menu at once, and the applet knows when the menu is raised, there is no need to pass the icon in the signal: the applet can remember the clicked icon when it received the 'build-menu' event.
// }
//
//-------------------------------------------------------------[ C CALLBACKS ]--
// struct _GldiModuleInterface {
// gboolean (* read_conf_file) (GldiModuleInstance *pInstance, GKeyFile *pKeyFile);
// void (* reset_config) (GldiModuleInstance *pInstance);
// void (* reset_data) (GldiModuleInstance *pInstance);
// void (* load_custom_widget) (GldiModuleInstance *pInstance, GKeyFile *pKeyFile, GSList *pWidgetList);
// void (* save_custom_widget) (GldiModuleInstance *pInstance, GKeyFile *pKeyFile, GSList *pWidgetList);
// };
//export onAppletInit
func onAppletInit(cInstance *C.GldiModuleInstance, cKeyfile *C.GKeyFile) {
mi := gldi.NewModuleInstanceFromNative(unsafe.Pointer(cInstance))
kf := keyfile.NewFromNative(unsafe.Pointer(cKeyfile))
apps.startApplet(mi, kf)
}
//export onAppletStop
func onAppletStop(cInstance *C.GldiModuleInstance) {
mi := gldi.NewModuleInstanceFromNative(unsafe.Pointer(cInstance))
apps.stopApplet(mi)
}
//export onAppletReload
func onAppletReload(cInstance *C.GldiModuleInstance, oldContainer *C.GldiContainer, cKeyfile *C.GKeyFile) C.gboolean {
mi := gldi.NewModuleInstanceFromNative(unsafe.Pointer(cInstance))
cont := gldi.NewContainerFromNative(unsafe.Pointer(oldContainer))
kf := keyfile.NewFromNative(unsafe.Pointer(cKeyfile))
if apps.reloadApplet(mi, cont, kf) { // if applet matched, which should always be true.
return notif.ActionIntercept
}
return notif.ActionLetPass
}
//
//--------------------------------------------------------------[ MENUERLIKE ]--
// MenuerLike converts the backend menu to match the applets Menuer interface.
//
type MenuerLike struct {
backendmenu.DockMenu
}
// AddSubMenu adds a submenu to the menu.
//
func (m *MenuerLike) AddSubMenu(label, iconPath string) cdtype.Menuer {
return &MenuerLike{*m.DockMenu.AddSubMenu(label, iconPath)}
}
// AddEntry adds an item to the menu with its callback.
//
func (m *MenuerLike) AddEntry(label, iconPath string, call interface{}, userData ...interface{}) cdtype.MenuWidgeter {
return m.DockMenu.AddEntry(label, iconPath, call, userData...)
}
// AddCheckEntry adds a check entry to the menu.
//
func (m *MenuerLike) AddCheckEntry(label string, active bool, call interface{}, userData ...interface{}) cdtype.MenuWidgeter {
return m.DockMenu.AddCheckEntry(label, active, call, userData)
}
// AddRadioEntry adds a radio entry to the menu.
//
func (m *MenuerLike) AddRadioEntry(label string, active bool, group int, call interface{}, userData ...interface{}) cdtype.MenuWidgeter {
return m.DockMenu.AddRadioEntry(label, active, group, call, userData)
}