a4f62f6c7301f87778dbf571dc3e36556a96911f
[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                 RrImage *ic;
298
299                 ic = RrImageCacheFindName(ob_rr_icons, icon);
300                 if (ic)
301                     RrImageRef(ic);
302                 else {
303                     ic = RrImageNew(ob_rr_icons);
304                     if (!RrImageAddPictureName(ic, icon)) {
305                         RrImageUnref(ic); /* no need to keep it around */
306                         ic = NULL;
307                     }
308                 }
309                 e->data.normal.icon = ic;
310
311                 if (e->data.normal.icon)
312                     e->data.normal.icon_alpha = 0xff;
313
314                 g_free(icon);
315             }
316             g_free(label);
317         }
318     }
319 }
320
321 static void parse_menu_separator(xmlNodePtr node, gpointer data)
322 {
323     ObMenuParseState *state = data;
324
325     if (state->parent) {
326         gchar *label;
327
328         if (!obt_xml_attr_string(node, "label", &label))
329             label = NULL;
330
331         menu_add_separator(state->parent, -1, label);
332         g_free(label);
333     }
334 }
335
336 static void parse_menu(xmlNodePtr node, gpointer data)
337 {
338     ObMenuParseState *state = data;
339     gchar *name = NULL, *title = NULL, *script = NULL;
340     ObMenu *menu;
341
342     if (!obt_xml_attr_string(node, "id", &name))
343         goto parse_menu_fail;
344
345     if (!g_hash_table_lookup(menu_hash, name)) {
346         if (!obt_xml_attr_string(node, "label", &title))
347             goto parse_menu_fail;
348
349         if ((menu = menu_new(name, title, TRUE, NULL))) {
350             menu->pipe_creator = state->pipe_creator;
351             if (obt_xml_attr_string(node, "execute", &script)) {
352                 menu->execute = obt_paths_expand_tilde(script);
353             } else {
354                 ObMenu *old;
355
356                 old = state->parent;
357                 state->parent = menu;
358                 obt_xml_tree(menu_parse_inst, node->children);
359                 state->parent = old;
360             }
361         }
362     }
363
364     if (state->parent)
365         menu_add_submenu(state->parent, -1, name);
366
367 parse_menu_fail:
368     g_free(name);
369     g_free(title);
370     g_free(script);
371 }
372
373 ObMenu* menu_new(const gchar *name, const gchar *title,
374                  gboolean allow_shortcut_selection, gpointer data)
375 {
376     ObMenu *self;
377
378     self = g_slice_new0(ObMenu);
379     self->name = g_strdup(name);
380     self->data = data;
381
382     self->shortcut = parse_shortcut(title, allow_shortcut_selection,
383                                     &self->title, &self->shortcut_position,
384                                     &self->shortcut_always_show);
385
386     g_hash_table_replace(menu_hash, self->name, self);
387
388     /* Each menu has a single more_menu.  When the menu spills past what
389        can fit on the screen, a new menu frame entry is created from this
390        more_menu, and a new menu frame for the submenu is created for this
391        menu, also pointing to the more_menu.
392
393        This can be done multiple times using the same more_menu.
394
395        more_menu->more_menu will always be NULL, since there is only 1 for
396        each menu. */
397     self->more_menu = g_slice_new0(ObMenu);
398     self->more_menu->name = _("More...");
399     self->more_menu->title = _("More...");
400     self->more_menu->data = data;
401     self->more_menu->shortcut = g_unichar_tolower(g_utf8_get_char("M"));
402
403     return self;
404 }
405
406 static void menu_destroy_hash_value(ObMenu *self)
407 {
408     /* make sure its not visible */
409     {
410         GList *it;
411         ObMenuFrame *f;
412
413         for (it = menu_frame_visible; it; it = g_list_next(it)) {
414             f = it->data;
415             if (f->menu == self)
416                 menu_frame_hide_all();
417         }
418     }
419
420     if (self->destroy_func)
421         self->destroy_func(self, self->data);
422
423     menu_clear_entries(self);
424     g_free(self->name);
425     g_free(self->title);
426     g_free(self->execute);
427     g_slice_free(ObMenu, self->more_menu);
428
429     g_slice_free(ObMenu, self);
430 }
431
432 void menu_free(ObMenu *menu)
433 {
434     if (menu)
435         g_hash_table_remove(menu_hash, menu->name);
436 }
437
438 static gboolean menu_hide_delay_func(gpointer data)
439 {
440     menu_can_hide = TRUE;
441     menu_timeout_id = 0;
442     return FALSE; /* no repeat */
443 }
444
445 void menu_show(gchar *name, gint x, gint y, gboolean mouse, ObClient *client)
446 {
447     ObMenu *self;
448     ObMenuFrame *frame;
449
450     if (!(self = menu_from_name(name)) ||
451         grab_on_keyboard() || grab_on_pointer()) return;
452
453     /* if the requested menu is already the top visible menu, then don't
454        bother */
455     if (menu_frame_visible) {
456         frame = menu_frame_visible->data;
457         if (frame->menu == self)
458             return;
459     }
460
461     menu_frame_hide_all();
462
463     /* clear the pipe menus when showing a new menu */
464     menu_clear_pipe_caches();
465
466     frame = menu_frame_new(self, 0, client);
467     if (!menu_frame_show_topmenu(frame, x, y, mouse))
468         menu_frame_free(frame);
469     else {
470         if (!mouse) {
471             /* select the first entry if it's not a submenu and we opened
472              * the menu with the keyboard, and skip all headers */
473             GList *it = frame->entries;
474             while (it) {
475                 ObMenuEntryFrame *e = it->data;
476                 if (e->entry->type == OB_MENU_ENTRY_TYPE_NORMAL) {
477                     menu_frame_select(frame, e, FALSE);
478                     break;
479                 } else if (e->entry->type == OB_MENU_ENTRY_TYPE_SEPARATOR)
480                     it = g_list_next(it);
481                 else
482                     break;
483             }
484         }
485
486         /* reset the hide timer */
487         if (!mouse)
488             menu_can_hide = TRUE;
489         else {
490             menu_can_hide = FALSE;
491             if (menu_timeout_id) g_source_remove(menu_timeout_id);
492             menu_timeout_id = g_timeout_add_full(G_PRIORITY_DEFAULT,
493                                                  config_menu_hide_delay,
494                                                  menu_hide_delay_func,
495                                                  NULL, NULL);
496         }
497     }
498 }
499
500 gboolean menu_hide_delay_reached(void)
501 {
502     return menu_can_hide;
503 }
504
505 static ObMenuEntry* menu_entry_new(ObMenu *menu, ObMenuEntryType type, gint id)
506 {
507     ObMenuEntry *self;
508
509     g_assert(menu);
510
511     self = g_slice_new0(ObMenuEntry);
512     self->ref = 1;
513     self->type = type;
514     self->menu = menu;
515     self->id = id;
516
517     switch (type) {
518     case OB_MENU_ENTRY_TYPE_NORMAL:
519         self->data.normal.enabled = TRUE;
520         break;
521     case OB_MENU_ENTRY_TYPE_SUBMENU:
522     case OB_MENU_ENTRY_TYPE_SEPARATOR:
523         break;
524     }
525
526     return self;
527 }
528
529 void menu_entry_ref(ObMenuEntry *self)
530 {
531     ++self->ref;
532 }
533
534 void menu_entry_unref(ObMenuEntry *self)
535 {
536     if (self && --self->ref == 0) {
537         switch (self->type) {
538         case OB_MENU_ENTRY_TYPE_NORMAL:
539             RrImageUnref(self->data.normal.icon);
540             g_free(self->data.normal.label);
541             while (self->data.normal.actions) {
542                 actions_act_unref(self->data.normal.actions->data);
543                 self->data.normal.actions =
544                     g_slist_delete_link(self->data.normal.actions,
545                                         self->data.normal.actions);
546             }
547             break;
548         case OB_MENU_ENTRY_TYPE_SUBMENU:
549             g_free(self->data.submenu.name);
550             break;
551         case OB_MENU_ENTRY_TYPE_SEPARATOR:
552             g_free(self->data.separator.label);
553             break;
554         }
555
556         g_slice_free(ObMenuEntry, self);
557     }
558 }
559
560 void menu_clear_entries(ObMenu *self)
561 {
562 #ifdef DEBUG
563     /* assert that the menu isn't visible */
564     {
565         GList *it;
566         ObMenuFrame *f;
567
568         for (it = menu_frame_visible; it; it = g_list_next(it)) {
569             f = it->data;
570             g_assert(f->menu != self);
571         }
572     }
573 #endif
574
575     while (self->entries) {
576         menu_entry_unref(self->entries->data);
577         self->entries = g_list_delete_link(self->entries, self->entries);
578     }
579     self->more_menu->entries = self->entries; /* keep it in sync */
580 }
581
582 void menu_entry_remove(ObMenuEntry *self)
583 {
584     self->menu->entries = g_list_remove(self->menu->entries, self);
585     menu_entry_unref(self);
586 }
587
588 ObMenuEntry* menu_add_normal(ObMenu *self, gint id, const gchar *label,
589                              GSList *actions, gboolean allow_shortcut)
590 {
591     ObMenuEntry *e;
592
593     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_NORMAL, id);
594     e->data.normal.actions = actions;
595
596     menu_entry_set_label(e, label, allow_shortcut);
597
598     self->entries = g_list_append(self->entries, e);
599     self->more_menu->entries = self->entries; /* keep it in sync */
600     return e;
601 }
602
603 ObMenuEntry* menu_get_more(ObMenu *self, guint show_from)
604 {
605     ObMenuEntry *e;
606     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_SUBMENU, -1);
607     /* points to itself */
608     e->data.submenu.name = g_strdup(self->name);
609     e->data.submenu.submenu = self;
610     e->data.submenu.show_from = show_from;
611     return e;
612 }
613
614 ObMenuEntry* menu_add_submenu(ObMenu *self, gint id, const gchar *submenu)
615 {
616     ObMenuEntry *e;
617
618     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_SUBMENU, id);
619     e->data.submenu.name = g_strdup(submenu);
620
621     self->entries = g_list_append(self->entries, e);
622     self->more_menu->entries = self->entries; /* keep it in sync */
623     return e;
624 }
625
626 ObMenuEntry* menu_add_separator(ObMenu *self, gint id, const gchar *label)
627 {
628     ObMenuEntry *e;
629
630     e = menu_entry_new(self, OB_MENU_ENTRY_TYPE_SEPARATOR, id);
631
632     menu_entry_set_label(e, label, FALSE);
633
634     self->entries = g_list_append(self->entries, e);
635     self->more_menu->entries = self->entries; /* keep it in sync */
636     return e;
637 }
638
639 void menu_set_show_func(ObMenu *self, ObMenuShowFunc func)
640 {
641     self->show_func = func;
642 }
643
644 void menu_set_hide_func(ObMenu *self, ObMenuHideFunc func)
645 {
646     self->hide_func = func;
647 }
648
649 void menu_set_update_func(ObMenu *self, ObMenuUpdateFunc func)
650 {
651     self->update_func = func;
652 }
653
654 void menu_set_execute_func(ObMenu *self, ObMenuExecuteFunc func)
655 {
656     self->execute_func = func;
657     self->more_menu->execute_func = func; /* keep it in sync */
658 }
659
660 void menu_set_cleanup_func(ObMenu *self, ObMenuCleanupFunc func)
661 {
662     self->cleanup_func = func;
663 }
664
665 void menu_set_destroy_func(ObMenu *self, ObMenuDestroyFunc func)
666 {
667     self->destroy_func = func;
668 }
669
670 void menu_set_place_func(ObMenu *self, ObMenuPlaceFunc func)
671 {
672     self->place_func = func;
673 }
674
675 ObMenuEntry* menu_find_entry_id(ObMenu *self, gint id)
676 {
677     ObMenuEntry *ret = NULL;
678     GList *it;
679
680     for (it = self->entries; it; it = g_list_next(it)) {
681         ObMenuEntry *e = it->data;
682
683         if (e->id == id) {
684             ret = e;
685             break;
686         }
687     }
688     return ret;
689 }
690
691 void menu_find_submenus(ObMenu *self)
692 {
693     GList *it;
694
695     for (it = self->entries; it; it = g_list_next(it)) {
696         ObMenuEntry *e = it->data;
697
698         if (e->type == OB_MENU_ENTRY_TYPE_SUBMENU)
699             e->data.submenu.submenu = menu_from_name(e->data.submenu.name);
700     }
701 }
702
703 void menu_entry_set_label(ObMenuEntry *self, const gchar *label,
704                           gboolean allow_shortcut)
705 {
706     switch (self->type) {
707     case OB_MENU_ENTRY_TYPE_SEPARATOR:
708         g_free(self->data.separator.label);
709         self->data.separator.label = g_strdup(label);
710         break;
711     case OB_MENU_ENTRY_TYPE_NORMAL:
712         g_free(self->data.normal.label);
713         self->data.normal.shortcut =
714             parse_shortcut(label, allow_shortcut, &self->data.normal.label,
715                            &self->data.normal.shortcut_position,
716                            &self->data.normal.shortcut_always_show);
717         break;
718     default:
719         g_assert_not_reached();
720     }
721 }
722
723 void menu_show_all_shortcuts(ObMenu *self, gboolean show)
724 {
725     self->show_all_shortcuts = show;
726 }