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