This patch implements support for icons in user-defined menus into Openbox
[dana/openbox.git] / openbox / menu.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    menu.c for the Openbox window manager
4    Copyright (c) 2006        Mikael Magnusson
5    Copyright (c) 2003-2007   Dana Jansens
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    See the COPYING file for a copy of the GNU General Public License.
18 */
19
20 #include "debug.h"
21 #include "menu.h"
22 #include "openbox.h"
23 #include "stacking.h"
24 #include "grab.h"
25 #include "client.h"
26 #include "config.h"
27 #include "actions.h"
28 #include "screen.h"
29 #include "menuframe.h"
30 #include "keyboard.h"
31 #include "geom.h"
32 #include "misc.h"
33 #include "client_menu.h"
34 #include "client_list_menu.h"
35 #include "client_list_combined_menu.h"
36 #include "gettext.h"
37 #include "obt/xml.h"
38 #include "obt/paths.h"
39 #include "imageload.h"
40
41 typedef struct _ObMenuParseState ObMenuParseState;
42
43 struct _ObMenuParseState
44 {
45     ObMenu *parent;
46     ObMenu *pipe_creator;
47 };
48
49 static GHashTable *menu_hash = NULL;
50 static ObtXmlInst *menu_parse_inst;
51 static ObMenuParseState menu_parse_state;
52 static gboolean menu_can_hide = FALSE;
53
54 static void menu_destroy_hash_value(ObMenu *self);
55 static void parse_menu_item(xmlNodePtr node, gpointer data);
56 static void parse_menu_separator(xmlNodePtr node, gpointer data);
57 static void parse_menu(xmlNodePtr node, gpointer data);
58 static gunichar parse_shortcut(const gchar *label, gboolean allow_shortcut,
59                                gchar **strippedlabel, guint *position,
60                                gboolean *always_show);
61
62 static void client_dest(ObClient *client, gpointer data)
63 {
64     /* menus can be associated with a client, so close any that are since
65        we are disappearing now */
66     menu_frame_hide_all_client(client);
67 }
68
69 void menu_startup(gboolean reconfig)
70 {
71     gboolean loaded = FALSE;
72     GSList *it;
73
74     menu_hash = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
75                                       (GDestroyNotify)menu_destroy_hash_value);
76
77     client_list_menu_startup(reconfig);
78     client_list_combined_menu_startup(reconfig);
79     client_menu_startup();
80
81     menu_parse_inst = obt_xml_instance_new();
82
83     menu_parse_state.parent = NULL;
84     menu_parse_state.pipe_creator = NULL;
85     obt_xml_register(menu_parse_inst, "menu", parse_menu, &menu_parse_state);
86     obt_xml_register(menu_parse_inst, "item", parse_menu_item,
87                      &menu_parse_state);
88     obt_xml_register(menu_parse_inst, "separator",
89                        parse_menu_separator, &menu_parse_state);
90
91     for (it = config_menu_files; it; it = g_slist_next(it)) {
92         if (obt_xml_load_config_file(menu_parse_inst,
93                                      "openbox",
94                                      it->data,
95                                      "openbox_menu"))
96         {
97             loaded = TRUE;
98             obt_xml_tree_from_root(menu_parse_inst);
99             obt_xml_close(menu_parse_inst);
100         } else
101             g_message(_("Unable to find a valid menu file \"%s\""),
102                       (const gchar*)it->data);
103     }
104     if (!loaded) {
105         if (obt_xml_load_config_file(menu_parse_inst,
106                                      "openbox",
107                                      "menu.xml",
108                                      "openbox_menu"))
109         {
110             obt_xml_tree_from_root(menu_parse_inst);
111             obt_xml_close(menu_parse_inst);
112         } else
113             g_message(_("Unable to find a valid menu file \"%s\""),
114                       "menu.xml");
115     }
116
117     g_assert(menu_parse_state.parent == NULL);
118
119     if (!reconfig)
120         client_add_destroy_notify(client_dest, NULL);
121 }
122
123 void menu_shutdown(gboolean reconfig)
124 {
125     if (!reconfig)
126         client_remove_destroy_notify(client_dest);
127
128     obt_xml_instance_unref(menu_parse_inst);
129     menu_parse_inst = NULL;
130
131     client_list_menu_shutdown(reconfig);
132     client_list_combined_menu_shutdown(reconfig);
133
134     menu_frame_hide_all();
135     g_hash_table_destroy(menu_hash);
136     menu_hash = NULL;
137 }
138
139 static gboolean menu_pipe_submenu(gpointer key, gpointer val, gpointer data)
140 {
141     ObMenu *menu = val;
142     return menu->pipe_creator != NULL;
143 }
144
145 static void clear_cache(gpointer key, gpointer val, gpointer data)
146 {
147     ObMenu *menu = val;
148     if (menu->execute)
149         menu_clear_entries(menu);
150 }
151
152 void menu_clear_pipe_caches(void)
153 {
154     /* delete any pipe menus' submenus */
155     g_hash_table_foreach_remove(menu_hash, menu_pipe_submenu, NULL);
156     /* empty the top level pipe menus */
157     g_hash_table_foreach(menu_hash, clear_cache, NULL);
158 }
159
160 void menu_pipe_execute(ObMenu *self)
161 {
162     gchar *output;
163     GError *err = NULL;
164
165     if (!self->execute)
166         return;
167     if (self->entries) /* the entries are already created and cached */
168         return;
169
170     if (!g_spawn_command_line_sync(self->execute, &output, NULL, NULL, &err)) {
171         g_message(_("Failed to execute command for pipe-menu \"%s\": %s"),
172                   self->execute, err->message);
173         g_error_free(err);
174         return;
175     }
176
177     if (obt_xml_load_mem(menu_parse_inst, output, strlen(output),
178                          "openbox_pipe_menu"))
179     {
180         menu_parse_state.pipe_creator = self;
181         menu_parse_state.parent = self;
182         obt_xml_tree_from_root(menu_parse_inst);
183         obt_xml_close(menu_parse_inst);
184     } else {
185         g_message(_("Invalid output from pipe-menu \"%s\""), self->execute);
186     }
187
188     g_free(output);
189 }
190
191 static ObMenu* menu_from_name(gchar *name)
192 {
193     ObMenu *self = NULL;
194
195     g_assert(name != NULL);
196
197     if (!(self = g_hash_table_lookup(menu_hash, name)))
198         g_message(_("Attempted to access menu \"%s\" but it does not exist"),
199                   name);
200     return self;
201 }
202
203 #define VALID_SHORTCUT(c) (((c) >= '0' && (c) <= '9') || \
204                            ((c) >= 'A' && (c) <= 'Z') || \
205                            ((c) >= 'a' && (c) <= 'z'))
206
207 static gunichar parse_shortcut(const gchar *label, gboolean allow_shortcut,
208                                gchar **strippedlabel, guint *position,
209                                gboolean *always_show)
210 {
211     gunichar shortcut = 0;
212
213     *position = 0;
214     *always_show = FALSE;
215
216     g_assert(strippedlabel != NULL);
217
218     if (label == NULL) {
219         *strippedlabel = NULL;
220     } else {
221         gchar *i;
222
223         *strippedlabel = g_strdup(label);
224
225         /* if allow_shortcut is false, then you can't use the '_', instead you
226            have to just use the first valid character
227         */
228
229         i = strchr(*strippedlabel, '_');
230         if (allow_shortcut && i != NULL) {
231             /* there is an underscore in the string */
232
233             /* you have to use a printable ascii character for shortcuts
234                don't allow space either, so you can have like "a _ b"
235             */
236             if (VALID_SHORTCUT(*(i+1)) || *(i+1) == '_') {
237                 /* Allow you to escape the first _ by putting __ */
238                 if (*(i+1) != '_') {
239                     shortcut = g_unichar_tolower(g_utf8_get_char(i+1));
240                     *position = i - *strippedlabel;
241                     *always_show = TRUE;
242                 }
243
244                 /* remove the '_' from the string */
245                 for (; *i != '\0'; ++i)
246                     *i = *(i+1);
247             } else if (*(i+1) == '\0') {
248                 /* no default shortcut if the '_' is the last character
249                    (eg. "Exit_") for menu entries that you don't want
250                    to be executed by mistake
251                 */
252                     *i = '\0';
253             }
254         } else {
255             /* there is no underscore, so find the first valid character to use
256                instead */
257
258             for (i = *strippedlabel; *i != '\0'; ++i)
259                 if (VALID_SHORTCUT(*i)) {
260                     *position = i - *strippedlabel;
261                     shortcut = g_unichar_tolower(g_utf8_get_char(i));
262                     break;
263                 }
264         }
265     }
266     return shortcut;
267 }
268
269 static void parse_menu_item(xmlNodePtr node,  gpointer data)
270 {
271     ObMenuParseState *state = data;
272     gchar *label;
273     #ifdef USE_IMLIB2
274     gchar *icon;
275     #endif
276     ObMenuEntry *e;
277
278     if (state->parent) {
279         #ifdef USE_IMLIB2
280         /* Don't try to extract "icon" attribute if icons in user-defined
281            menus are not enabled. */
282         if (!(config_menu_user_show_icons &&
283             obt_xml_attr_string(node, "icon", &icon)))
284                icon = NULL;
285         #endif
286
287         if (obt_xml_attr_string(node, "label", &label)) {
288             GSList *acts = NULL;
289
290             node = obt_xml_find_node(node->children, "action");
291             while (node) {
292                 ObActionsAct *action = actions_parse(node);
293                 if (action)
294                     acts = g_slist_append(acts, action);
295                 node = obt_xml_find_node(node->next, "action");
296             }
297             e = menu_add_normal(state->parent, -1, label, acts, TRUE);
298             
299             #ifdef USE_IMLIB2
300             if (icon) { /* Icon will be used. */
301                 e->data.normal.icon = RrImageFetchFromFile(ob_rr_icons, icon);
302                 if (e->data.normal.icon) {
303                     e->data.normal.icon_alpha = 0xff;
304                 }
305                 g_free(icon);
306             }
307
308             menu_add_normal(state->parent, -1, label, acts, TRUE);
309             #endif
310             g_free(label);
311         }
312     }
313 }
314
315 static void parse_menu_separator(xmlNodePtr node, gpointer data)
316 {
317     ObMenuParseState *state = data;
318
319     if (state->parent) {
320         gchar *label;
321
322         if (!obt_xml_attr_string(node, "label", &label))
323             label = NULL;
324
325         menu_add_separator(state->parent, -1, label);
326         g_free(label);
327     }
328 }
329
330 static void parse_menu(xmlNodePtr node, gpointer data)
331 {
332     ObMenuParseState *state = data;
333     gchar *name = NULL, *title = NULL, *script = NULL;
334     ObMenu *menu;
335
336     if (!obt_xml_attr_string(node, "id", &name))
337         goto parse_menu_fail;
338
339     if (!g_hash_table_lookup(menu_hash, name)) {
340         if (!obt_xml_attr_string(node, "label", &title))
341             goto parse_menu_fail;
342
343         if ((menu = menu_new(name, title, TRUE, NULL))) {
344             menu->pipe_creator = state->pipe_creator;
345             if (obt_xml_attr_string(node, "execute", &script)) {
346                 menu->execute = obt_paths_expand_tilde(script);
347             } else {
348                 ObMenu *old;
349
350                 old = state->parent;
351                 state->parent = menu;
352                 obt_xml_tree(menu_parse_inst, node->children);
353                 state->parent = old;
354             }
355         }
356     }
357
358     if (state->parent)
359         menu_add_submenu(state->parent, -1, name);
360
361 parse_menu_fail:
362     g_free(name);
363     g_free(title);
364     g_free(script);
365 }
366
367 ObMenu* menu_new(const gchar *name, const gchar *title,
368                  gboolean allow_shortcut_selection, gpointer data)
369 {
370     ObMenu *self;
371
372     self = g_new0(ObMenu, 1);
373     self->name = g_strdup(name);
374     self->data = data;
375
376     self->shortcut = parse_shortcut(title, allow_shortcut_selection,
377                                     &self->title, &self->shortcut_position,
378                                     &self->shortcut_always_show);
379
380     g_hash_table_replace(menu_hash, self->name, self);
381
382     /* Each menu has a single more_menu.  When the menu spills past what
383        can fit on the screen, a new menu frame entry is created from this
384        more_menu, and a new menu frame for the submenu is created for this
385        menu, also pointing to the more_menu.
386
387        This can be done multiple times using the same more_menu.
388
389        more_menu->more_menu will always be NULL, since there is only 1 for
390        each menu. */
391     self->more_menu = g_new0(ObMenu, 1);
392     self->more_menu->name = _("More...");
393     self->more_menu->title = _("More...");
394     self->more_menu->data = data;
395     self->more_menu->shortcut = g_unichar_tolower(g_utf8_get_char("M"));
396
397     return self;
398 }
399
400 static void menu_destroy_hash_value(ObMenu *self)
401 {
402     /* make sure its not visible */
403     {
404         GList *it;
405         ObMenuFrame *f;
406
407         for (it = menu_frame_visible; it; it = g_list_next(it)) {
408             f = it->data;
409             if (f->menu == self)
410                 menu_frame_hide_all();
411         }
412     }
413
414     if (self->destroy_func)
415         self->destroy_func(self, self->data);
416
417     menu_clear_entries(self);
418     g_free(self->name);
419     g_free(self->title);
420     g_free(self->execute);
421     g_free(self->more_menu);
422
423     g_free(self);
424 }
425
426 void menu_free(ObMenu *menu)
427 {
428     if (menu)
429         g_hash_table_remove(menu_hash, menu->name);
430 }
431
432 static gboolean menu_hide_delay_func(gpointer data)
433 {
434     menu_can_hide = TRUE;
435     return FALSE; /* no repeat */
436 }
437
438 void menu_show(gchar *name, gint x, gint y, gboolean mouse, ObClient *client)
439 {
440     ObMenu *self;
441     ObMenuFrame *frame;
442
443     if (!(self = menu_from_name(name)) ||
444         grab_on_keyboard() || grab_on_pointer()) return;
445
446     /* if the requested menu is already the top visible menu, then don't
447        bother */
448     if (menu_frame_visible) {
449         frame = menu_frame_visible->data;
450         if (frame->menu == self)
451             return;
452     }
453
454     menu_frame_hide_all();
455
456     /* clear the pipe menus when showing a new menu */
457     menu_clear_pipe_caches();
458
459     frame = menu_frame_new(self, 0, client);
460     if (!menu_frame_show_topmenu(frame, x, y, mouse))
461         menu_frame_free(frame);
462     else {
463         if (!mouse) {
464             /* select the first entry if it's not a submenu and we opened
465              * the menu with the keyboard, and skip all headers */
466             GList *it = frame->entries;
467             while (it) {
468                 ObMenuEntryFrame *e = it->data;
469                 if (e->entry->type == OB_MENU_ENTRY_TYPE_NORMAL) {
470                     menu_frame_select(frame, e, FALSE);
471                     break;
472                 } else if (e->entry->type == OB_MENU_ENTRY_TYPE_SEPARATOR)
473                     it = g_list_next(it);
474                 else
475                     break;
476             }
477         }
478
479         /* reset the hide timer */
480         if (!mouse)
481             menu_can_hide = TRUE;
482         else {
483             menu_can_hide = FALSE;
484             obt_main_loop_timeout_add(ob_main_loop,
485                                       config_menu_hide_delay * 1000,
486                                       menu_hide_delay_func,
487                                       NULL, g_direct_equal, NULL);
488         }
489     }
490 }
491
492 gboolean menu_hide_delay_reached(void)
493 {
494     return menu_can_hide;
495 }
496
497 static ObMenuEntry* menu_entry_new(ObMenu *menu, ObMenuEntryType type, gint id)
498 {
499     ObMenuEntry *self;
500
501     g_assert(menu);
502
503     self = g_new0(ObMenuEntry, 1);
504     self->ref = 1;
505     self->type = type;
506     self->menu = menu;
507     self->id = id;
508
509     switch (type) {
510     case OB_MENU_ENTRY_TYPE_NORMAL:
511         self->data.normal.enabled = TRUE;
512         break;
513     case OB_MENU_ENTRY_TYPE_SUBMENU:
514     case OB_MENU_ENTRY_TYPE_SEPARATOR:
515         break;
516     }
517
518     return self;
519 }
520
521 void menu_entry_ref(ObMenuEntry *self)
522 {
523     ++self->ref;
524 }
525
526 void menu_entry_unref(ObMenuEntry *self)
527 {
528     if (self && --self->ref == 0) {
529         switch (self->type) {
530         case OB_MENU_ENTRY_TYPE_NORMAL:
531             RrImageUnref(self->data.normal.icon);
532             g_free(self->data.normal.label);
533             while (self->data.normal.actions) {
534                 actions_act_unref(self->data.normal.actions->data);
535                 self->data.normal.actions =
536                     g_slist_delete_link(self->data.normal.actions,
537                                         self->data.normal.actions);
538             }
539             break;
540         case OB_MENU_ENTRY_TYPE_SUBMENU:
541             g_free(self->data.submenu.name);
542             break;
543         case OB_MENU_ENTRY_TYPE_SEPARATOR:
544             g_free(self->data.separator.label);
545             break;
546         }
547
548         g_free(self);
549     }
550 }
551
552 void menu_clear_entries(ObMenu *self)
553 {
554 #ifdef DEBUG
555     /* assert that the menu isn't visible */
556     {
557         GList *it;
558         ObMenuFrame *f;
559
560         for (it = menu_frame_visible; it; it = g_list_next(it)) {
561             f = it->data;
562             g_assert(f->menu != self);
563         }
564     }
565 #endif
566
567     while (self->entries) {
568         menu_entry_unref(self->entries->data);
569         self->entries = g_list_delete_link(self->entries, self->entries);
570     }
571     self->more_menu->entries = self->entries; /* keep it in sync */
572 }
573
574 void menu_entry_remove(ObMenuEntry *self)
575 {
576     self->menu->entries = g_list_remove(self->menu->entries, self);
577     menu_entry_unref(self);
578 }
579
580 ObMenuEntry* menu_add_normal(ObMenu *self, gint id, const gchar *label,
581                              GSList *actions, gboolean allow_shortcut)
582 {
583     ObMenuEntry *e;
584
585     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_NORMAL, id);
586     e->data.normal.actions = actions;
587
588     menu_entry_set_label(e, label, allow_shortcut);
589
590     self->entries = g_list_append(self->entries, e);
591     self->more_menu->entries = self->entries; /* keep it in sync */
592     return e;
593 }
594
595 ObMenuEntry* menu_get_more(ObMenu *self, guint show_from)
596 {
597     ObMenuEntry *e;
598     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_SUBMENU, -1);
599     /* points to itself */
600     e->data.submenu.name = g_strdup(self->name);
601     e->data.submenu.submenu = self;
602     e->data.submenu.show_from = show_from;
603     return e;
604 }
605
606 ObMenuEntry* menu_add_submenu(ObMenu *self, gint id, const gchar *submenu)
607 {
608     ObMenuEntry *e;
609
610     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_SUBMENU, id);
611     e->data.submenu.name = g_strdup(submenu);
612
613     self->entries = g_list_append(self->entries, e);
614     self->more_menu->entries = self->entries; /* keep it in sync */
615     return e;
616 }
617
618 ObMenuEntry* menu_add_separator(ObMenu *self, gint id, const gchar *label)
619 {
620     ObMenuEntry *e;
621
622     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_SEPARATOR, id);
623
624     menu_entry_set_label(e, label, FALSE);
625
626     self->entries = g_list_append(self->entries, e);
627     self->more_menu->entries = self->entries; /* keep it in sync */
628     return e;
629 }
630
631 void menu_set_show_func(ObMenu *self, ObMenuShowFunc func)
632 {
633     self->show_func = func;
634 }
635
636 void menu_set_hide_func(ObMenu *self, ObMenuHideFunc func)
637 {
638     self->hide_func = func;
639 }
640
641 void menu_set_update_func(ObMenu *self, ObMenuUpdateFunc func)
642 {
643     self->update_func = func;
644 }
645
646 void menu_set_execute_func(ObMenu *self, ObMenuExecuteFunc func)
647 {
648     self->execute_func = func;
649     self->more_menu->execute_func = func; /* keep it in sync */
650 }
651
652 void menu_set_destroy_func(ObMenu *self, ObMenuDestroyFunc func)
653 {
654     self->destroy_func = func;
655 }
656
657 void menu_set_place_func(ObMenu *self, ObMenuPlaceFunc func)
658 {
659     self->place_func = func;
660 }
661
662 ObMenuEntry* menu_find_entry_id(ObMenu *self, gint id)
663 {
664     ObMenuEntry *ret = NULL;
665     GList *it;
666
667     for (it = self->entries; it; it = g_list_next(it)) {
668         ObMenuEntry *e = it->data;
669
670         if (e->id == id) {
671             ret = e;
672             break;
673         }
674     }
675     return ret;
676 }
677
678 void menu_find_submenus(ObMenu *self)
679 {
680     GList *it;
681
682     for (it = self->entries; it; it = g_list_next(it)) {
683         ObMenuEntry *e = it->data;
684
685         if (e->type == OB_MENU_ENTRY_TYPE_SUBMENU)
686             e->data.submenu.submenu = menu_from_name(e->data.submenu.name);
687     }
688 }
689
690 void menu_entry_set_label(ObMenuEntry *self, const gchar *label,
691                           gboolean allow_shortcut)
692 {
693     switch (self->type) {
694     case OB_MENU_ENTRY_TYPE_SEPARATOR:
695         g_free(self->data.separator.label);
696         self->data.separator.label = g_strdup(label);
697         break;
698     case OB_MENU_ENTRY_TYPE_NORMAL:
699         g_free(self->data.normal.label);
700         self->data.normal.shortcut =
701             parse_shortcut(label, allow_shortcut, &self->data.normal.label,
702                            &self->data.normal.shortcut_position,
703                            &self->data.normal.shortcut_always_show);
704         break;
705     default:
706         g_assert_not_reached();
707     }
708 }
709
710 void menu_show_all_shortcuts(ObMenu *self, gboolean show)
711 {
712     self->show_all_shortcuts = show;
713 }