Don't crash when keyeditor is empty
[ardour.git] / gtk2_ardour / keyeditor.cc
1 /*
2     Copyright (C) 2002 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef WAF_BUILD
21 #include "gtk2ardour-config.h"
22 #endif
23
24 #include <map>
25
26 #include <boost/algorithm/string.hpp>
27
28 #include <gtkmm/stock.h>
29 #include <gtkmm/label.h>
30 #include <gtkmm/accelkey.h>
31 #include <gtkmm/accelmap.h>
32 #include <gtkmm/uimanager.h>
33
34 #include "gtkmm2ext/bindings.h"
35 #include "gtkmm2ext/utils.h"
36
37 #include "pbd/strsplit.h"
38
39 #include "ardour/filesystem_paths.h"
40 #include "ardour/profile.h"
41
42 #include "actions.h"
43 #include "keyboard.h"
44 #include "keyeditor.h"
45
46 #include "i18n.h"
47
48 using namespace std;
49 using namespace Gtk;
50 using namespace Gdk;
51 using namespace PBD;
52
53 using Gtkmm2ext::Keyboard;
54 using Gtkmm2ext::Bindings;
55
56 void bindings_collision_dialog (Gtk::Window& parent)
57 {
58         ArdourDialog dialog (parent, _("Colliding keybindings"), true);
59         Label label (_("The key sequence is already bound. Please remove the other binding first."));
60
61         dialog.get_vbox()->pack_start (label, true, true);
62         dialog.add_button (_("Ok"), Gtk::RESPONSE_ACCEPT);
63         dialog.show_all ();
64         dialog.run();
65 }
66
67 KeyEditor::KeyEditor ()
68         : ArdourWindow (_("Key Bindings"))
69         , unbind_button (_("Remove shortcut"))
70         , unbind_box (BUTTONBOX_END)
71         , filter_entry (_("Search..."), true)
72         , filter_string("")
73         , sort_column(0)
74         , sort_type(Gtk::SORT_ASCENDING)
75 {
76
77         notebook.signal_switch_page ().connect (sigc::mem_fun (*this, &KeyEditor::page_change));
78
79         vpacker.pack_start (notebook, true, true);
80
81         Glib::RefPtr<Gdk::Pixbuf> icon = ARDOUR_UI_UTILS::get_icon ("search");
82         filter_entry.set_icon_from_pixbuf (icon);
83         filter_entry.set_icon_tooltip_text (_("Click to reset search string"));
84         filter_entry.signal_search_string_updated ().connect (sigc::mem_fun (*this, &KeyEditor::search_string_updated));
85         vpacker.pack_start (filter_entry, false, false);
86
87         Label* hint = manage (new Label (_("Select an action, then press the key(s) to (re)set its shortcut")));
88         hint->show ();
89         unbind_box.set_spacing (6);
90         unbind_box.pack_start (*hint, false, true);
91         unbind_box.pack_start (unbind_button, false, false);
92         unbind_button.signal_clicked().connect (sigc::mem_fun (*this, &KeyEditor::unbind));
93
94         vpacker.pack_start (unbind_box, false, false);
95         unbind_box.show ();
96         unbind_button.show ();
97
98         reset_button.add (reset_label);
99         reset_label.set_markup (string_compose ("<span size=\"large\" weight=\"bold\">%1</span>", _("Reset Bindings to Defaults")));
100
101         reset_box.pack_start (reset_button, true, false);
102         reset_box.show ();
103         reset_button.show ();
104         reset_label.show ();
105         reset_button.signal_clicked().connect (sigc::mem_fun (*this, &KeyEditor::reset));
106         vpacker.pack_start (reset_box, false, false);
107
108         add (vpacker);
109
110         unbind_button.set_sensitive (false);
111 }
112
113 void
114 KeyEditor::add_tab (string const & name, Bindings& bindings)
115 {
116         Tab* t = new Tab (*this, name, &bindings);
117
118         if (t->populate () == 0) {
119                 /* no bindings */
120                 delete t;
121                 return;
122         }
123
124         t->show_all ();
125         notebook.append_page (*t, name);
126 }
127
128
129 void
130 KeyEditor::remove_tab (string const &name)
131 {
132         guint npages = notebook.get_n_pages ();
133
134         for (guint n = 0; n < npages; ++n) {
135                 Widget* w = notebook.get_nth_page (n);
136                 Tab* tab = dynamic_cast<Tab*> (w);
137                 if (tab) {
138                         if (tab->name == name) {
139                                 notebook.remove_page (*w);
140                                 return;
141                         }
142                 }
143         }
144         cerr << "Removed " << name << endl;
145 }
146
147 void
148 KeyEditor::unbind ()
149 {
150         current_tab()->unbind ();
151 }
152
153 void
154 KeyEditor::page_change (GtkNotebookPage*, guint)
155 {
156         current_tab()->view.get_selection()->unselect_all ();
157         unbind_button.set_sensitive (false);
158 }
159
160 bool
161 KeyEditor::Tab::key_press_event (GdkEventKey* ev)
162 {
163         if (view.get_selection()->count_selected_rows() != 1) {
164                 return false;
165         }
166
167         if (!ev->is_modifier) {
168                 last_keyval = ev->keyval;
169         }
170
171         /* Don't let anything else handle the key press, because navigation
172          * keys will be used by GTK to change the selection/treeview cursor
173          * position
174          */
175
176         return true;
177 }
178
179 bool
180 KeyEditor::Tab::key_release_event (GdkEventKey* ev)
181 {
182         if (view.get_selection()->count_selected_rows() != 1) {
183                 return false;
184         }
185
186         if (last_keyval == 0) {
187                 return false;
188         }
189
190         owner.current_tab()->bind (ev, last_keyval);
191
192         last_keyval = 0;
193         return true;
194 }
195
196 KeyEditor::Tab::Tab (KeyEditor& ke, string const & str, Bindings* b)
197         : owner (ke)
198         , name (str)
199         , bindings (b)
200         , last_keyval (0)
201 {
202         data_model = TreeStore::create(columns);
203         populate ();
204
205         filter = TreeModelFilter::create(data_model);
206         filter->set_visible_func (sigc::mem_fun (*this, &Tab::visible_func));
207
208         sorted_filter = TreeModelSort::create(filter);
209
210         view.set_model (sorted_filter);
211         view.append_column (_("Action"), columns.name);
212         view.append_column (_("Shortcut"), columns.binding);
213         view.set_headers_visible (true);
214         view.set_headers_clickable (true);
215         view.get_selection()->set_mode (SELECTION_SINGLE);
216         view.set_reorderable (false);
217         view.set_size_request (500,300);
218         view.set_enable_search (false);
219         view.set_rules_hint (true);
220         view.set_name (X_("KeyEditorTree"));
221
222         view.signal_cursor_changed().connect (sigc::mem_fun (*this, &Tab::action_selected));
223         view.signal_key_press_event().connect (sigc::mem_fun (*this, &Tab::key_press_event), false);
224         view.signal_key_release_event().connect (sigc::mem_fun (*this, &Tab::key_release_event), false);
225
226         view.get_column(0)->set_sort_column (columns.name);
227         view.get_column(1)->set_sort_column (columns.binding);
228         data_model->set_sort_column (owner.sort_column,  owner.sort_type);
229         data_model->signal_sort_column_changed().connect (sigc::mem_fun (*this, &Tab::sort_column_changed));
230
231         signal_map().connect (sigc::mem_fun (*this, &Tab::tab_mapped));
232
233         scroller.add (view);
234         scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
235
236         set_spacing (6);
237         set_border_width (12);
238         pack_start (scroller);
239 }
240
241 void
242 KeyEditor::Tab::action_selected ()
243 {
244         if (view.get_selection()->count_selected_rows() == 0) {
245                 return;
246         }
247
248         TreeModel::const_iterator it = view.get_selection()->get_selected();
249
250         if (!it) {
251                 return;
252         }
253
254         if (!(*it)[columns.bindable]) {
255                 owner.unbind_button.set_sensitive (false);
256                 return;
257         }
258
259         const string& binding = (*it)[columns.binding];
260
261         if (!binding.empty()) {
262                 owner.unbind_button.set_sensitive (true);
263         }
264 }
265
266 void
267 KeyEditor::Tab::unbind ()
268 {
269         const std::string& action_path = (*view.get_selection()->get_selected())[columns.path];
270
271         TreeModel::iterator it = find_action_path (data_model->children().begin(), data_model->children().end(),  action_path);
272
273         if (!it || !(*it)[columns.bindable]) {
274                 return;
275         }
276
277         bindings->remove (Gtkmm2ext::Bindings::Press,  action_path , true);
278         (*it)[columns.binding] = string ();
279
280         owner.unbind_button.set_sensitive (false);
281 }
282
283 void
284 KeyEditor::Tab::bind (GdkEventKey* release_event, guint pressed_key)
285 {
286         const std::string& action_path = (*view.get_selection()->get_selected())[columns.path];
287         TreeModel::iterator it = find_action_path (data_model->children().begin(), data_model->children().end(),  action_path);
288
289         /* pressed key could be upper case if Shift was used. We want all
290            single keys stored as their lower-case version, so ensure this
291         */
292
293         pressed_key = gdk_keyval_to_lower (pressed_key);
294
295         if (!it || !(*it)[columns.bindable]) {
296                 return;
297         }
298
299         GdkModifierType mod = (GdkModifierType)(Keyboard::RelevantModifierKeyMask & release_event->state);
300         Gtkmm2ext::KeyboardKey new_binding (mod, pressed_key);
301
302         if (bindings->is_bound (new_binding, Gtkmm2ext::Bindings::Press)) {
303                 bindings_collision_dialog (owner);
304                 return;
305         }
306
307         bool result = bindings->replace (new_binding, Gtkmm2ext::Bindings::Press, action_path);
308
309         if (result) {
310                 (*it)[columns.binding] = gtk_accelerator_get_label (new_binding.key(), (GdkModifierType) new_binding.state());
311                 owner.unbind_button.set_sensitive (true);
312         }
313 }
314
315 uint32_t
316 KeyEditor::Tab::populate ()
317 {
318         vector<string> paths;
319         vector<string> labels;
320         vector<string> tooltips;
321         vector<string> keys;
322         vector<Glib::RefPtr<Action> > actions;
323         typedef std::map<string,TreeIter> NodeMap;
324         NodeMap nodes;
325         NodeMap::iterator r;
326
327         bindings->get_all_actions (paths, labels, tooltips, keys, actions);
328
329         vector<string>::iterator k;
330         vector<string>::iterator p;
331         vector<string>::iterator t;
332         vector<string>::iterator l;
333         vector<Glib::RefPtr<Action> >::iterator a;
334
335         data_model->clear ();
336
337         for (a = actions.begin(), l = labels.begin(), k = keys.begin(), p = paths.begin(), t = tooltips.begin(); l != labels.end(); ++k, ++p, ++t, ++l, ++a) {
338
339                 TreeModel::Row row;
340                 vector<string> parts;
341
342                 split (*p, parts, '/');
343
344                 string category = parts[1];
345                 string action_name = parts[2];
346
347                 if (action_name.empty()) {
348                         continue;
349                 }
350
351                 //kinda kludgy way to avoid displaying menu items as mappable
352                 if ((action_name.find ("Menu") == action_name.length() - 4) ||
353                     (action_name.find ("menu") == action_name.length() - 4) ||
354                     (action_name == _("RegionList"))) {
355                         continue;
356                 }
357
358                 if ((r = nodes.find (category)) == nodes.end()) {
359
360                         /* category/group is missing, so add it first */
361
362                         TreeIter rowp;
363                         TreeModel::Row parent;
364                         rowp = data_model->append();
365                         nodes[category] = rowp;
366                         parent = *(rowp);
367                         parent[columns.name] = category;
368                         parent[columns.bindable] = false;
369                         parent[columns.action] = *a;
370
371                         /* now set up the child row that we're about to fill
372                          * out with information
373                          */
374
375                         row = *(data_model->append (parent.children()));
376
377                 } else {
378
379                         /* category/group is present, so just add the child row */
380
381                         row = *(data_model->append ((*r->second)->children()));
382
383                 }
384
385                 /* add this action */
386
387                 /* use the "visible label" as the action name */
388
389                 if (l->empty ()) {
390                         /* no label, try using the tooltip instead */
391                         row[columns.name] = *t;
392                 } else {
393                         row[columns.name] = *l;
394                 }
395                 row[columns.path] = string_compose ("%1/%2", category, action_name);
396                 row[columns.bindable] = true;
397
398                 if (*k == ActionManager::unbound_string) {
399                         row[columns.binding] = string();
400                 } else {
401                         row[columns.binding] = *k;
402                 }
403                 row[columns.action] = *a;
404         }
405
406         return data_model->children().size();
407 }
408
409 void
410 KeyEditor::Tab::sort_column_changed ()
411 {
412         int column;
413         SortType type;
414         if (data_model->get_sort_column_id (column, type)) {
415                 owner.sort_column = column;
416                 owner.sort_type = type;
417         }
418 }
419
420 void
421 KeyEditor::Tab::tab_mapped ()
422 {
423         data_model->set_sort_column (owner.sort_column,  owner.sort_type);
424         filter->refilter ();
425 }
426
427 bool
428 KeyEditor::Tab::visible_func(const Gtk::TreeModel::const_iterator& iter) const
429 {
430         if (!iter) {
431                 return false;
432         }
433
434         // never filter when search string is empty or item is a category
435         if (owner.filter_string.empty () || !(*iter)[columns.bindable]) {
436                 return true;
437         }
438
439         // search name
440         std::string name = (*iter)[columns.name];
441         boost::to_lower (name);
442         if (name.find (owner.filter_string) != std::string::npos) {
443                 return true;
444         }
445
446         // search binding
447         std::string binding = (*iter)[columns.binding];
448         boost::to_lower (binding);
449         if (binding.find (owner.filter_string) != std::string::npos) {
450                 return true;
451         }
452
453         return false;
454 }
455
456 TreeModel::iterator
457 KeyEditor::Tab::find_action_path (TreeModel::const_iterator begin, TreeModel::const_iterator end, const std::string& action_path) const
458 {
459         if (!begin) {
460                 return end;
461         }
462
463         for (TreeModel::iterator it = begin; it != end; ++it) {
464                 if (it->children()) {
465                         TreeModel::iterator jt = find_action_path (it->children().begin(), it->children().end(), action_path);
466                         if (jt != it->children().end()) {
467                                 return jt;
468                         }
469                 }
470                 const std::string& path = (*it)[columns.path];
471                 if (action_path.compare(path) == 0) {
472                         return it;
473                 }
474         }
475         return end;
476 }
477
478 void
479 KeyEditor::reset ()
480 {
481         Keyboard::the_keyboard().reset_bindings ();
482
483         for (Tabs::iterator t = tabs.begin(); t != tabs.end(); ++t) {
484                 (*t)->view.get_selection()->unselect_all ();
485                 (*t)->populate ();
486         }
487 }
488
489 KeyEditor::Tab*
490 KeyEditor::current_tab ()
491 {
492         return dynamic_cast<Tab*> (notebook.get_nth_page (notebook.get_current_page()));
493 }
494
495 void
496 KeyEditor::search_string_updated (const std::string& filter)
497 {
498         filter_string = boost::to_lower_copy(filter);
499         KeyEditor::Tab* tab = current_tab ();
500         if (tab) {
501                 tab->filter->refilter ();
502         }
503 }