Un-bunch the bunched-up Keybindings editor widgets.
[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 #include <fstream>
26 #include <sstream>
27
28 #include <boost/algorithm/string.hpp>
29
30 #include <glib.h>
31 #include <glib/gstdio.h>
32
33 #include <gtkmm/stock.h>
34 #include <gtkmm/label.h>
35 #include <gtkmm/accelkey.h>
36 #include <gtkmm/accelmap.h>
37 #include <gtkmm/uimanager.h>
38
39 #include "gtkmm2ext/bindings.h"
40 #include "gtkmm2ext/utils.h"
41
42 #include "pbd/error.h"
43 #include "pbd/openuri.h"
44 #include "pbd/strsplit.h"
45
46 #include "ardour/filesystem_paths.h"
47 #include "ardour/profile.h"
48
49 #include "actions.h"
50 #include "keyboard.h"
51 #include "keyeditor.h"
52
53 #include "pbd/i18n.h"
54
55 using namespace std;
56 using namespace Gtk;
57 using namespace Gdk;
58 using namespace PBD;
59
60 using Gtkmm2ext::Keyboard;
61 using Gtkmm2ext::Bindings;
62
63 sigc::signal<void> KeyEditor::UpdateBindings;
64
65 void bindings_collision_dialog (Gtk::Window& parent)
66 {
67         ArdourDialog dialog (parent, _("Colliding keybindings"), true);
68         Label label (_("The key sequence is already bound. Please remove the other binding first."));
69
70         dialog.get_vbox()->pack_start (label, true, true);
71         dialog.add_button (_("Ok"), Gtk::RESPONSE_ACCEPT);
72         dialog.show_all ();
73         dialog.run();
74 }
75
76 KeyEditor::KeyEditor ()
77         : ArdourWindow (_("Key Bindings"))
78         , unbind_button (_("Remove shortcut"))
79         , unbind_box (BUTTONBOX_END)
80         , filter_entry (_("Search..."), true)
81         , filter_string("")
82         , sort_column(0)
83         , sort_type(Gtk::SORT_ASCENDING)
84 {
85
86         notebook.signal_switch_page ().connect (sigc::mem_fun (*this, &KeyEditor::page_change));
87
88         vpacker.pack_start (notebook, true, true);
89
90         Glib::RefPtr<Gdk::Pixbuf> icon = ARDOUR_UI_UTILS::get_icon ("search");
91         filter_entry.set_icon_from_pixbuf (icon);
92         filter_entry.set_icon_tooltip_text (_("Click to reset search string"));
93         filter_entry.signal_search_string_updated ().connect (sigc::mem_fun (*this, &KeyEditor::search_string_updated));
94         vpacker.pack_start (filter_entry, false, false);
95
96         Label* hint = manage (new Label (_("To remove a shortcut, select an action then press this: ")));
97         hint->show ();
98         unbind_box.pack_start (*hint, false, true);
99         unbind_box.pack_start (unbind_button, false, false);
100         unbind_button.signal_clicked().connect (sigc::mem_fun (*this, &KeyEditor::unbind));
101
102         vpacker.set_spacing (4);
103         vpacker.pack_start (unbind_box, false, false);
104         unbind_box.show ();
105         unbind_button.show ();
106
107         reset_button.add (reset_label);
108         reset_label.set_markup (string_compose ("  <span size=\"large\" weight=\"bold\">%1</span>  ", _("Reset Bindings to Defaults")));
109
110         print_button.add (print_label);
111         print_label.set_markup (string_compose ("  <span size=\"large\" weight=\"bold\">%1</span>  ", _("Print Bindings (to your web browser)")));
112
113         print_button.signal_clicked().connect (sigc::mem_fun (*this, &KeyEditor::print));
114
115         reset_box.pack_start (reset_button, true, false);
116         reset_box.pack_start (print_button, true, false);
117         reset_box.show ();
118         reset_button.show ();
119         reset_label.show ();
120         print_button.show ();
121         reset_button.signal_clicked().connect (sigc::mem_fun (*this, &KeyEditor::reset));
122         vpacker.pack_start (*(manage (new  HSeparator())), true, true, 5);
123         vpacker.pack_start (reset_box, false, false);
124
125         add (vpacker);
126
127         unbind_button.set_sensitive (false);
128         _refresh_connection = UpdateBindings.connect (sigc::mem_fun (*this, &KeyEditor::refresh));
129 }
130
131 void
132 KeyEditor::add_tab (string const & name, Bindings& bindings)
133 {
134         Tab* t = new Tab (*this, name, &bindings);
135
136         if (t->populate () == 0) {
137                 /* no bindings */
138                 delete t;
139                 return;
140         }
141
142         tabs.push_back (t);
143         t->show_all ();
144         notebook.append_page (*t, name);
145 }
146
147
148 void
149 KeyEditor::remove_tab (string const &name)
150 {
151         guint npages = notebook.get_n_pages ();
152
153         for (guint n = 0; n < npages; ++n) {
154                 Widget* w = notebook.get_nth_page (n);
155                 Tab* tab = dynamic_cast<Tab*> (w);
156                 if (tab) {
157                         if (tab->name == name) {
158                                 notebook.remove_page (*w);
159                                 return;
160                         }
161                 }
162         }
163         cerr << "Removed " << name << endl;
164 }
165
166 void
167 KeyEditor::unbind ()
168 {
169         current_tab()->unbind ();
170 }
171
172 void
173 KeyEditor::page_change (GtkNotebookPage*, guint)
174 {
175         current_tab()->view.get_selection()->unselect_all ();
176         unbind_button.set_sensitive (false);
177 }
178
179 bool
180 KeyEditor::Tab::key_press_event (GdkEventKey* ev)
181 {
182         if (view.get_selection()->count_selected_rows() != 1) {
183                 return false;
184         }
185
186         if (!ev->is_modifier) {
187                 last_keyval = ev->keyval;
188         }
189
190         /* Don't let anything else handle the key press, because navigation
191          * keys will be used by GTK to change the selection/treeview cursor
192          * position
193          */
194
195         return true;
196 }
197
198 bool
199 KeyEditor::Tab::key_release_event (GdkEventKey* ev)
200 {
201         if (view.get_selection()->count_selected_rows() != 1) {
202                 return false;
203         }
204
205         if (last_keyval == 0) {
206                 return false;
207         }
208
209         owner.current_tab()->bind (ev, last_keyval);
210
211         last_keyval = 0;
212         return true;
213 }
214
215 KeyEditor::Tab::Tab (KeyEditor& ke, string const & str, Bindings* b)
216         : owner (ke)
217         , name (str)
218         , bindings (b)
219         , last_keyval (0)
220 {
221         data_model = TreeStore::create(columns);
222         populate ();
223
224         filter = TreeModelFilter::create(data_model);
225         filter->set_visible_func (sigc::mem_fun (*this, &Tab::visible_func));
226
227         sorted_filter = TreeModelSort::create(filter);
228
229         view.set_model (sorted_filter);
230         view.append_column (_("Action"), columns.name);
231         view.append_column (_("Shortcut"), columns.binding);
232         view.set_headers_visible (true);
233         view.set_headers_clickable (true);
234         view.get_selection()->set_mode (SELECTION_SINGLE);
235         view.set_reorderable (false);
236         view.set_size_request (500,300);
237         view.set_enable_search (false);
238         view.set_rules_hint (true);
239         view.set_name (X_("KeyEditorTree"));
240
241         view.signal_cursor_changed().connect (sigc::mem_fun (*this, &Tab::action_selected));
242         view.signal_key_press_event().connect (sigc::mem_fun (*this, &Tab::key_press_event), false);
243         view.signal_key_release_event().connect (sigc::mem_fun (*this, &Tab::key_release_event), false);
244
245         view.get_column(0)->set_sort_column (columns.name);
246         view.get_column(1)->set_sort_column (columns.binding);
247         data_model->set_sort_column (owner.sort_column,  owner.sort_type);
248         data_model->signal_sort_column_changed().connect (sigc::mem_fun (*this, &Tab::sort_column_changed));
249
250         signal_map().connect (sigc::mem_fun (*this, &Tab::tab_mapped));
251
252         scroller.add (view);
253         scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
254
255         set_spacing (6);
256         set_border_width (12);
257         pack_start (scroller);
258 }
259
260 void
261 KeyEditor::Tab::action_selected ()
262 {
263         if (view.get_selection()->count_selected_rows() == 0) {
264                 return;
265         }
266
267         TreeModel::const_iterator it = view.get_selection()->get_selected();
268
269         if (!it) {
270                 return;
271         }
272
273         if (!(*it)[columns.bindable]) {
274                 owner.unbind_button.set_sensitive (false);
275                 return;
276         }
277
278         const string& binding = (*it)[columns.binding];
279
280         if (!binding.empty()) {
281                 owner.unbind_button.set_sensitive (true);
282         }
283 }
284
285 void
286 KeyEditor::Tab::unbind ()
287 {
288         const std::string& action_path = (*view.get_selection()->get_selected())[columns.path];
289
290         TreeModel::iterator it = find_action_path (data_model->children().begin(), data_model->children().end(),  action_path);
291
292         if (!it || !(*it)[columns.bindable]) {
293                 return;
294         }
295
296         bindings->remove (Gtkmm2ext::Bindings::Press,  action_path , true);
297         (*it)[columns.binding] = string ();
298
299         owner.unbind_button.set_sensitive (false);
300 }
301
302 void
303 KeyEditor::Tab::bind (GdkEventKey* release_event, guint pressed_key)
304 {
305         const std::string& action_path = (*view.get_selection()->get_selected())[columns.path];
306         TreeModel::iterator it = find_action_path (data_model->children().begin(), data_model->children().end(),  action_path);
307
308         /* pressed key could be upper case if Shift was used. We want all
309            single keys stored as their lower-case version, so ensure this
310         */
311
312         pressed_key = gdk_keyval_to_lower (pressed_key);
313
314         if (!it || !(*it)[columns.bindable]) {
315                 return;
316         }
317
318         GdkModifierType mod = (GdkModifierType)(Keyboard::RelevantModifierKeyMask & release_event->state);
319         Gtkmm2ext::KeyboardKey new_binding (mod, pressed_key);
320
321         if (bindings->is_bound (new_binding, Gtkmm2ext::Bindings::Press)) {
322                 bindings_collision_dialog (owner);
323                 return;
324         }
325
326         bool result = bindings->replace (new_binding, Gtkmm2ext::Bindings::Press, action_path);
327
328         if (result) {
329                 (*it)[columns.binding] = gtk_accelerator_get_label (new_binding.key(), (GdkModifierType) new_binding.state());
330                 owner.unbind_button.set_sensitive (true);
331         }
332 }
333
334 uint32_t
335 KeyEditor::Tab::populate ()
336 {
337         vector<string> paths;
338         vector<string> labels;
339         vector<string> tooltips;
340         vector<string> keys;
341         vector<Glib::RefPtr<Action> > actions;
342         typedef std::map<string,TreeIter> NodeMap;
343         NodeMap nodes;
344         NodeMap::iterator r;
345
346         bindings->get_all_actions (paths, labels, tooltips, keys, actions);
347
348         vector<string>::iterator k;
349         vector<string>::iterator p;
350         vector<string>::iterator t;
351         vector<string>::iterator l;
352         vector<Glib::RefPtr<Action> >::iterator a;
353
354         data_model->clear ();
355
356         for (a = actions.begin(), l = labels.begin(), k = keys.begin(), p = paths.begin(), t = tooltips.begin(); l != labels.end(); ++k, ++p, ++t, ++l, ++a) {
357
358                 TreeModel::Row row;
359                 vector<string> parts;
360
361                 split (*p, parts, '/');
362
363                 string category = parts[1];
364                 string action_name = parts[2];
365
366                 if (action_name.empty()) {
367                         continue;
368                 }
369
370                 //kinda kludgy way to avoid displaying menu items as mappable
371                 if ((action_name.find ("Menu") == action_name.length() - 4) ||
372                     (action_name.find ("menu") == action_name.length() - 4) ||
373                     (action_name == _("RegionList"))) {
374                         continue;
375                 }
376
377                 if ((r = nodes.find (category)) == nodes.end()) {
378
379                         /* category/group is missing, so add it first */
380
381                         TreeIter rowp;
382                         TreeModel::Row parent;
383                         rowp = data_model->append();
384                         nodes[category] = rowp;
385                         parent = *(rowp);
386                         parent[columns.name] = category;
387                         parent[columns.bindable] = false;
388                         parent[columns.action] = *a;
389
390                         /* now set up the child row that we're about to fill
391                          * out with information
392                          */
393
394                         row = *(data_model->append (parent.children()));
395
396                 } else {
397
398                         /* category/group is present, so just add the child row */
399
400                         row = *(data_model->append ((*r->second)->children()));
401
402                 }
403
404                 /* add this action */
405
406                 /* use the "visible label" as the action name */
407
408                 if (l->empty ()) {
409                         /* no label, try using the tooltip instead */
410                         row[columns.name] = *t;
411                 } else {
412                         row[columns.name] = *l;
413                 }
414                 row[columns.path] = string_compose ("%1/%2", category, action_name);
415                 row[columns.bindable] = true;
416
417                 if (*k == ActionManager::unbound_string) {
418                         row[columns.binding] = string();
419                 } else {
420                         row[columns.binding] = *k;
421                 }
422                 row[columns.action] = *a;
423         }
424
425         return data_model->children().size();
426 }
427
428 void
429 KeyEditor::Tab::sort_column_changed ()
430 {
431         int column;
432         SortType type;
433         if (data_model->get_sort_column_id (column, type)) {
434                 owner.sort_column = column;
435                 owner.sort_type = type;
436         }
437 }
438
439 void
440 KeyEditor::Tab::tab_mapped ()
441 {
442         data_model->set_sort_column (owner.sort_column,  owner.sort_type);
443         filter->refilter ();
444 }
445
446 bool
447 KeyEditor::Tab::visible_func(const Gtk::TreeModel::const_iterator& iter) const
448 {
449         if (!iter) {
450                 return false;
451         }
452
453         // never filter when search string is empty or item is a category
454         if (owner.filter_string.empty () || !(*iter)[columns.bindable]) {
455                 return true;
456         }
457
458         // search name
459         std::string name = (*iter)[columns.name];
460         boost::to_lower (name);
461         if (name.find (owner.filter_string) != std::string::npos) {
462                 return true;
463         }
464
465         // search binding
466         std::string binding = (*iter)[columns.binding];
467         boost::to_lower (binding);
468         if (binding.find (owner.filter_string) != std::string::npos) {
469                 return true;
470         }
471
472         return false;
473 }
474
475 TreeModel::iterator
476 KeyEditor::Tab::find_action_path (TreeModel::const_iterator begin, TreeModel::const_iterator end, const std::string& action_path) const
477 {
478         if (!begin) {
479                 return end;
480         }
481
482         for (TreeModel::iterator it = begin; it != end; ++it) {
483                 if (it->children()) {
484                         TreeModel::iterator jt = find_action_path (it->children().begin(), it->children().end(), action_path);
485                         if (jt != it->children().end()) {
486                                 return jt;
487                         }
488                 }
489                 const std::string& path = (*it)[columns.path];
490                 if (action_path.compare(path) == 0) {
491                         return it;
492                 }
493         }
494         return end;
495 }
496
497 void
498 KeyEditor::reset ()
499 {
500         Keyboard::the_keyboard().reset_bindings ();
501         refresh ();
502 }
503
504 void
505 KeyEditor::refresh ()
506 {
507         for (Tabs::iterator t = tabs.begin(); t != tabs.end(); ++t) {
508                 (*t)->view.get_selection()->unselect_all ();
509                 (*t)->populate ();
510         }
511 }
512
513 KeyEditor::Tab*
514 KeyEditor::current_tab ()
515 {
516         return dynamic_cast<Tab*> (notebook.get_nth_page (notebook.get_current_page()));
517 }
518
519 void
520 KeyEditor::search_string_updated (const std::string& filter)
521 {
522         filter_string = boost::to_lower_copy(filter);
523         KeyEditor::Tab* tab = current_tab ();
524         if (tab) {
525                 tab->filter->refilter ();
526         }
527 }
528
529 void
530 KeyEditor::print () const
531 {
532         stringstream sstr;
533         Bindings::save_all_bindings_as_html (sstr);
534
535         if (sstr.str().empty()) {
536                 return;
537         }
538
539
540         gchar* file_name;
541         GError *err = NULL;
542         gint fd;
543
544         if ((fd = g_file_open_tmp ("akprintXXXXXX.html", &file_name, &err)) < 0) {
545                 if (err) {
546                         error << string_compose (_("Could not open temporary file to print bindings (%1)"), err->message) << endmsg;
547                         g_error_free (err);
548                 }
549                 return;
550         }
551
552 #ifdef PLATFORM_WINDOWS
553         ::close (fd);
554 #endif
555
556         err = NULL;
557
558         if (!g_file_set_contents (file_name, sstr.str().c_str(), sstr.str().size(), &err)) {
559 #ifndef PLATFORM_WINDOWS
560                 ::close (fd);
561 #endif
562                 g_unlink (file_name);
563                 if (err) {
564                         error << string_compose (_("Could not save bindings to file (%1)"), err->message) << endmsg;
565                         g_error_free (err);
566                 }
567                 return;
568         }
569
570 #ifndef PLATFORM_WINDOWS
571         ::close (fd);
572 #endif
573
574         PBD::open_uri (string_compose ("file:///%1", file_name));
575 }