]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/commands.cpp
Merge branch 'master' into master-merge
[xonotic/netradiant.git] / radiant / commands.cpp
1 /*
2    Copyright (C) 2001-2006, William Joseph.
3    All Rights Reserved.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant 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    GtkRadiant 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    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include "commands.h"
23
24 #include "gtk/gtk.h"
25 #include "debugging/debugging.h"
26 #include "warnings.h"
27
28 #include <map>
29 #include "string/string.h"
30 #include "versionlib.h"
31 #include "gtkutil/messagebox.h"
32 #include "gtkmisc.h"
33
34 typedef std::pair<Accelerator, int> ShortcutValue; // accelerator, isRegistered
35 typedef std::map<CopiedString, ShortcutValue> Shortcuts;
36
37 void Shortcuts_foreach( Shortcuts& shortcuts, CommandVisitor& visitor ){
38         for ( Shortcuts::iterator i = shortcuts.begin(); i != shortcuts.end(); ++i )
39         {
40                 visitor.visit( ( *i ).first.c_str(), ( *i ).second.first );
41         }
42 }
43
44 Shortcuts g_shortcuts;
45
46 const Accelerator& GlobalShortcuts_insert( const char* name, const Accelerator& accelerator ){
47         return ( *g_shortcuts.insert( Shortcuts::value_type( name, ShortcutValue( accelerator, false ) ) ).first ).second.first;
48 }
49
50 void GlobalShortcuts_foreach( CommandVisitor& visitor ){
51         Shortcuts_foreach( g_shortcuts, visitor );
52 }
53
54 void GlobalShortcuts_register( const char* name, int type ){
55         Shortcuts::iterator i = g_shortcuts.find( name );
56         if ( i != g_shortcuts.end() ) {
57                 ( *i ).second.second = type;
58         }
59 }
60
61 void GlobalShortcuts_reportUnregistered(){
62         for ( Shortcuts::iterator i = g_shortcuts.begin(); i != g_shortcuts.end(); ++i )
63         {
64                 if ( ( *i ).second.first.key != 0 && !( *i ).second.second ) {
65                         globalOutputStream() << "shortcut not registered: " << ( *i ).first.c_str() << "\n";
66                 }
67         }
68 }
69
70 typedef std::map<CopiedString, Command> Commands;
71
72 Commands g_commands;
73
74 void GlobalCommands_insert( const char* name, const Callback<void()>& callback, const Accelerator& accelerator ){
75         bool added = g_commands.insert( Commands::value_type( name, Command( callback, GlobalShortcuts_insert( name, accelerator ) ) ) ).second;
76         ASSERT_MESSAGE( added, "command already registered: " << makeQuoted( name ) );
77 }
78
79 const Command& GlobalCommands_find( const char* command ){
80         Commands::iterator i = g_commands.find( command );
81         ASSERT_MESSAGE( i != g_commands.end(), "failed to lookup command " << makeQuoted( command ) );
82         return ( *i ).second;
83 }
84
85 typedef std::map<CopiedString, Toggle> Toggles;
86
87
88 Toggles g_toggles;
89
90 void GlobalToggles_insert( const char* name, const Callback<void()>& callback, const Callback<void(const Callback<void(bool)> &)>& exportCallback, const Accelerator& accelerator ){
91         bool added = g_toggles.insert( Toggles::value_type( name, Toggle( callback, GlobalShortcuts_insert( name, accelerator ), exportCallback ) ) ).second;
92         ASSERT_MESSAGE( added, "toggle already registered: " << makeQuoted( name ) );
93 }
94 const Toggle& GlobalToggles_find( const char* name ){
95         Toggles::iterator i = g_toggles.find( name );
96         ASSERT_MESSAGE( i != g_toggles.end(), "failed to lookup toggle " << makeQuoted( name ) );
97         return ( *i ).second;
98 }
99
100 typedef std::map<CopiedString, KeyEvent> KeyEvents;
101
102
103 KeyEvents g_keyEvents;
104
105 void GlobalKeyEvents_insert( const char* name, const Accelerator& accelerator, const Callback<void()>& keyDown, const Callback<void()>& keyUp ){
106         bool added = g_keyEvents.insert( KeyEvents::value_type( name, KeyEvent( GlobalShortcuts_insert( name, accelerator ), keyDown, keyUp ) ) ).second;
107         ASSERT_MESSAGE( added, "command already registered: " << makeQuoted( name ) );
108 }
109 const KeyEvent& GlobalKeyEvents_find( const char* name ){
110         KeyEvents::iterator i = g_keyEvents.find( name );
111         ASSERT_MESSAGE( i != g_keyEvents.end(), "failed to lookup keyEvent " << makeQuoted( name ) );
112         return ( *i ).second;
113 }
114
115
116 void disconnect_accelerator( const char *name ){
117         Shortcuts::iterator i = g_shortcuts.find( name );
118         if ( i != g_shortcuts.end() ) {
119                 switch ( ( *i ).second.second )
120                 {
121                 case 1:
122                         // command
123                         command_disconnect_accelerator( name );
124                         break;
125                 case 2:
126                         // toggle
127                         toggle_remove_accelerator( name );
128                         break;
129                 }
130         }
131 }
132
133 void connect_accelerator( const char *name ){
134         Shortcuts::iterator i = g_shortcuts.find( name );
135         if ( i != g_shortcuts.end() ) {
136                 switch ( ( *i ).second.second )
137                 {
138                 case 1:
139                         // command
140                         command_connect_accelerator( name );
141                         break;
142                 case 2:
143                         // toggle
144                         toggle_add_accelerator( name );
145                         break;
146                 }
147         }
148 }
149
150
151 #include <uilib/uilib.h>
152 #include <gdk/gdkkeysyms.h>
153
154 #include "gtkutil/dialog.h"
155 #include "mainframe.h"
156
157 #include "stream/textfilestream.h"
158 #include "stream/stringstream.h"
159
160
161 struct command_list_dialog_t : public ModalDialog
162 {
163         command_list_dialog_t()
164                 : m_close_button( *this, eIDCANCEL ), m_list( ui::null ), m_command_iter(), m_model( ui::null ), m_waiting_for_key( false ){
165         }
166         ModalDialogButton m_close_button;
167
168         ui::TreeView m_list;
169         GtkTreeIter m_command_iter;
170         ui::TreeModel m_model;
171         bool m_waiting_for_key;
172 };
173
174 void accelerator_clear_button_clicked( ui::Button btn, gpointer dialogptr ){
175         command_list_dialog_t &dialog = *(command_list_dialog_t *) dialogptr;
176
177         if ( dialog.m_waiting_for_key ) {
178                 // just unhighlight, user wanted to cancel
179                 dialog.m_waiting_for_key = false;
180                 gtk_list_store_set( ui::ListStore::from( dialog.m_model ), &dialog.m_command_iter, 2, false, -1 );
181                 gtk_widget_set_sensitive( dialog.m_list , true );
182                 dialog.m_model = ui::TreeModel(ui::null);
183                 return;
184         }
185
186         auto sel = gtk_tree_view_get_selection( dialog.m_list );
187         GtkTreeModel *model;
188         GtkTreeIter iter;
189         if ( !gtk_tree_selection_get_selected( sel, &model, &iter ) ) {
190                 return;
191         }
192
193         GValue val;
194         memset( &val, 0, sizeof( val ) );
195         gtk_tree_model_get_value(model, &iter, 0, &val );
196         const char *commandName = g_value_get_string( &val );;
197
198         // clear the ACTUAL accelerator too!
199         disconnect_accelerator( commandName );
200
201         Shortcuts::iterator thisShortcutIterator = g_shortcuts.find( commandName );
202         if ( thisShortcutIterator == g_shortcuts.end() ) {
203                 return;
204         }
205         thisShortcutIterator->second.first = accelerator_null();
206
207         gtk_list_store_set( ui::ListStore::from( model ), &iter, 1, "", -1 );
208
209         g_value_unset( &val );
210 }
211
212 void accelerator_edit_button_clicked( ui::Button btn, gpointer dialogptr ){
213         command_list_dialog_t &dialog = *(command_list_dialog_t *) dialogptr;
214
215         // 1. find selected row
216         auto sel = gtk_tree_view_get_selection( dialog.m_list );
217         GtkTreeModel *model;
218         GtkTreeIter iter;
219         if ( !gtk_tree_selection_get_selected( sel, &model, &iter ) ) {
220                 return;
221         }
222         if ( dialog.m_waiting_for_key ) {
223                 // unhighlight highlit
224                 dialog.m_waiting_for_key = false;
225                 gtk_list_store_set( GTK_LIST_STORE( dialog.m_model ), &dialog.m_command_iter, 2, false, -1 );
226         }
227         dialog.m_command_iter = iter;
228         dialog.m_model = ui::TreeModel::from(model);
229
230         // 2. disallow changing the row
231         //gtk_widget_set_sensitive(dialog.m_list, false);
232
233         // 3. highlight the row
234         gtk_list_store_set( ui::ListStore::from( model ), &iter, 2, true, -1 );
235
236         // 4. grab keyboard focus
237         dialog.m_waiting_for_key = true;
238 }
239
240 gboolean accelerator_tree_butt_press( GtkWidget* widget, GdkEventButton* event, gpointer dialogptr ){
241         if ( event->type == GDK_2BUTTON_PRESS && event->button == 1 ) {
242                 accelerator_edit_button_clicked( ui::Button( ui::null ), dialogptr );
243                 return TRUE;
244         }
245         return FALSE;
246 }
247
248 bool accelerator_window_key_press( ui::Window widget, GdkEventKey *event, gpointer dialogptr ){
249         command_list_dialog_t &dialog = *(command_list_dialog_t *) dialogptr;
250
251         if ( !dialog.m_waiting_for_key ) {
252                 return false;
253         }
254
255 #if 0
256         if ( event->is_modifier ) {
257                 return false;
258         }
259 #else
260         switch ( event->keyval )
261         {
262         case GDK_KEY_Shift_L:
263         case GDK_KEY_Shift_R:
264         case GDK_KEY_Control_L:
265         case GDK_KEY_Control_R:
266         case GDK_KEY_Caps_Lock:
267         case GDK_KEY_Shift_Lock:
268         case GDK_KEY_Meta_L:
269         case GDK_KEY_Meta_R:
270         case GDK_KEY_Alt_L:
271         case GDK_KEY_Alt_R:
272         case GDK_KEY_Super_L:
273         case GDK_KEY_Super_R:
274         case GDK_KEY_Hyper_L:
275         case GDK_KEY_Hyper_R:
276                 return false;
277         }
278 #endif
279
280         dialog.m_waiting_for_key = false;
281
282         // 7. find the name of the accelerator
283         GValue val;
284         memset( &val, 0, sizeof( val ) );
285         gtk_tree_model_get_value(dialog.m_model, &dialog.m_command_iter, 0, &val );
286         const char *commandName = g_value_get_string( &val );;
287         Shortcuts::iterator thisShortcutIterator = g_shortcuts.find( commandName );
288         if ( thisShortcutIterator == g_shortcuts.end() ) {
289                 gtk_list_store_set( ui::ListStore::from( dialog.m_model ), &dialog.m_command_iter, 2, false, -1 );
290                 gtk_widget_set_sensitive( dialog.m_list , true );
291                 return true;
292         }
293
294         // 8. build an Accelerator
295         Accelerator newAccel( event->keyval, (GdkModifierType) event->state );
296
297         // 8. verify the key is still free, show a dialog to ask what to do if not
298         class VerifyAcceleratorNotTaken : public CommandVisitor
299         {
300         const char *commandName;
301         const Accelerator &newAccel;
302         ui::Widget widget;
303         ui::TreeModel model;
304 public:
305         bool allow;
306         VerifyAcceleratorNotTaken( const char *name, const Accelerator &accelerator, ui::Widget w, ui::TreeModel m ) : commandName( name ), newAccel( accelerator ), widget( w ), model( m ), allow( true ){
307         }
308         void visit( const char* name, Accelerator& accelerator ){
309                 if ( !strcmp( name, commandName ) ) {
310                         return;
311                 }
312                 if ( !allow ) {
313                         return;
314                 }
315                 if ( accelerator.key == 0 ) {
316                         return;
317                 }
318                 if ( accelerator == newAccel ) {
319                         StringOutputStream msg;
320                         msg << "The command " << name << " is already assigned to the key " << accelerator << ".\n\n"
321                                 << "Do you want to unassign " << name << " first?";
322                         auto r = ui::alert( widget.window(), msg.c_str(), "Key already used", ui::alert_type::YESNOCANCEL );
323                         if ( r == ui::alert_response::YES ) {
324                                 // clear the ACTUAL accelerator too!
325                                 disconnect_accelerator( name );
326                                 // delete the modifier
327                                 accelerator = accelerator_null();
328                                 // empty the cell of the key binds dialog
329                                 GtkTreeIter i;
330                                 if ( gtk_tree_model_get_iter_first(model, &i ) ) {
331                                         for (;; )
332                                         {
333                                                 GValue val;
334                                                 memset( &val, 0, sizeof( val ) );
335                                                 gtk_tree_model_get_value(model, &i, 0, &val );
336                                                 const char *thisName = g_value_get_string( &val );;
337                                                 if ( !strcmp( thisName, name ) ) {
338                                                         gtk_list_store_set( ui::ListStore::from( model ), &i, 1, "", -1 );
339                                                 }
340                                                 g_value_unset( &val );
341                                                 if ( !gtk_tree_model_iter_next(model, &i ) ) {
342                                                         break;
343                                                 }
344                                         }
345                                 }
346                         }
347                         else if ( r == ui::alert_response::CANCEL ) {
348                                 // aborted
349                                 allow = false;
350                         }
351                 }
352         }
353         } verify_visitor( commandName, newAccel, widget, dialog.m_model );
354         GlobalShortcuts_foreach( verify_visitor );
355
356         gtk_list_store_set( ui::ListStore::from( dialog.m_model ), &dialog.m_command_iter, 2, false, -1 );
357         gtk_widget_set_sensitive( dialog.m_list , true );
358
359         if ( verify_visitor.allow ) {
360                 // clear the ACTUAL accelerator first
361                 disconnect_accelerator( commandName );
362
363                 thisShortcutIterator->second.first = newAccel;
364
365                 // write into the cell
366                 StringOutputStream modifiers;
367                 modifiers << newAccel;
368                 gtk_list_store_set( ui::ListStore::from( dialog.m_model ), &dialog.m_command_iter, 1, modifiers.c_str(), -1 );
369
370                 // set the ACTUAL accelerator too!
371                 connect_accelerator( commandName );
372         }
373
374         g_value_unset( &val );
375
376         dialog.m_model = ui::TreeModel(ui::null);
377
378         return true;
379 }
380
381 /*
382     GtkTreeIter row;
383     GValue val;
384     if(!model) {g_error("Unable to get model from cell renderer");}
385     gtk_tree_model_get_iter_from_string(model, &row, path_string);
386
387     gtk_tree_model_get_value(model, &row, 0, &val);
388     const char *name = g_value_get_string(&val);
389     Shortcuts::iterator i = g_shortcuts.find(name);
390     if(i != g_shortcuts.end())
391     {
392         accelerator_parse(i->second.first, new_text);
393         StringOutputStream modifiers;
394         modifiers << i->second.first;
395         gtk_list_store_set(ui::ListStore::from(model), &row, 1, modifiers.c_str(), -1);
396     }
397    };
398  */
399
400 void DoCommandListDlg(){
401         command_list_dialog_t dialog;
402
403         ui::Window window = MainFrame_getWindow().create_modal_dialog_window("Mapped Commands", dialog, -1, 400);
404         window.on_key_press([](ui::Widget widget, GdkEventKey *event, gpointer dialogptr) {
405                 return accelerator_window_key_press(ui::Window::from(widget), event, dialogptr);
406         }, &dialog);
407
408         auto accel = ui::AccelGroup(ui::New);
409         window.add_accel_group( accel );
410
411         auto hbox = create_dialog_hbox( 4, 4 );
412         window.add(hbox);
413
414         {
415                 auto scr = create_scrolled_window( ui::Policy::NEVER, ui::Policy::AUTOMATIC );
416                 hbox.pack_start( scr, TRUE, TRUE, 0 );
417
418                 {
419                         auto store = ui::ListStore::from(gtk_list_store_new( 4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_INT ));
420
421                         auto view = ui::TreeView(ui::TreeModel::from(store._handle));
422                         dialog.m_list = view;
423
424                         //gtk_tree_view_set_enable_search( GTK_TREE_VIEW( view ), false ); // annoying
425
426                         g_signal_connect( G_OBJECT( view ), "button_press_event", G_CALLBACK( accelerator_tree_butt_press ), &dialog );
427
428                         {
429                                 auto renderer = ui::CellRendererText(ui::New);
430                                 auto column = ui::TreeViewColumn( "Command", renderer, {{"text", 0}, {"weight-set", 2}, {"weight", 3}} );
431                                 gtk_tree_view_append_column(view, column );
432                         }
433
434                         {
435                                 auto renderer = ui::CellRendererText(ui::New);
436                                 auto column = ui::TreeViewColumn( "Key", renderer, {{"text", 1}, {"weight-set", 2}, {"weight", 3}} );
437                                 gtk_tree_view_append_column(view, column );
438                         }
439
440                         view.show();
441                         scr.add(view);
442
443                         {
444                                 // Initialize dialog
445                                 StringOutputStream path( 256 );
446                                 path << SettingsPath_get() << "commandlist.txt";
447                                 globalOutputStream() << "Writing the command list to " << path.c_str() << "\n";
448                                 class BuildCommandList : public CommandVisitor
449                                 {
450                                 TextFileOutputStream m_commandList;
451                                 ui::ListStore m_store;
452 public:
453                                 BuildCommandList( const char* filename, ui::ListStore store ) : m_commandList( filename ), m_store( store ){
454                                 }
455                                 void visit( const char* name, Accelerator& accelerator ){
456                                         StringOutputStream modifiers;
457                                         modifiers << accelerator;
458
459                                         m_store.append(0, name, 1, modifiers.c_str(), 2, false, 3, 800);
460
461                                         if ( !m_commandList.failed() ) {
462                                                 int l = strlen( name );
463                                                 m_commandList << name;
464                                                 while ( l++ < 25 )
465                                                         m_commandList << ' ';
466                                                 m_commandList << modifiers.c_str() << '\n';
467                                         }
468                                 }
469                                 } visitor( path.c_str(), store );
470
471                                 GlobalShortcuts_foreach( visitor );
472                         }
473
474                         store.unref();
475                 }
476         }
477
478         auto vbox = create_dialog_vbox( 4 );
479         hbox.pack_start( vbox, TRUE, TRUE, 0 );
480         {
481                 auto editbutton = create_dialog_button( "Edit", (GCallback) accelerator_edit_button_clicked, &dialog );
482                 vbox.pack_start( editbutton, FALSE, FALSE, 0 );
483
484                 auto clearbutton = create_dialog_button( "Clear", (GCallback) accelerator_clear_button_clicked, &dialog );
485                 vbox.pack_start( clearbutton, FALSE, FALSE, 0 );
486
487                 ui::Widget spacer = ui::Image(ui::New);
488                 spacer.show();
489                 vbox.pack_start( spacer, TRUE, TRUE, 0 );
490
491                 auto button = create_modal_dialog_button( "Close", dialog.m_close_button );
492                 vbox.pack_start( button, FALSE, FALSE, 0 );
493                 widget_make_default( button );
494                 gtk_widget_grab_default( button  );
495                 gtk_widget_add_accelerator( button , "clicked", accel, GDK_KEY_Return, (GdkModifierType)0, (GtkAccelFlags)0 );
496                 gtk_widget_add_accelerator( button , "clicked", accel, GDK_KEY_Escape, (GdkModifierType)0, (GtkAccelFlags)0 );
497         }
498
499         modal_dialog_show( window, dialog );
500         window.destroy();
501 }
502
503 #include "profile/profile.h"
504
505 const char* const COMMANDS_VERSION = "1.0-gtk-accelnames";
506
507 void SaveCommandMap( const char* path ){
508         StringOutputStream strINI( 256 );
509         strINI << path << "shortcuts.ini";
510
511         TextFileOutputStream file( strINI.c_str() );
512         if ( !file.failed() ) {
513                 file << "[Version]\n";
514                 file << "number=" << COMMANDS_VERSION << "\n";
515                 file << "\n";
516                 file << "[Commands]\n";
517                 class WriteCommandMap : public CommandVisitor
518                 {
519                 TextFileOutputStream& m_file;
520 public:
521                 WriteCommandMap( TextFileOutputStream& file ) : m_file( file ){
522                 }
523                 void visit( const char* name, Accelerator& accelerator ){
524                         m_file << name << "=";
525
526                         const char* key = gtk_accelerator_name( accelerator.key, accelerator.modifiers );
527                         m_file << key;
528                         m_file << "\n";
529                 }
530                 } visitor( file );
531                 GlobalShortcuts_foreach( visitor );
532         }
533 }
534
535 const char* stringrange_find( const char* first, const char* last, char c ){
536         const char* p = strchr( first, '+' );
537         if ( p == 0 ) {
538                 return last;
539         }
540         return p;
541 }
542
543 class ReadCommandMap : public CommandVisitor
544 {
545 const char* m_filename;
546 std::size_t m_count;
547 public:
548 ReadCommandMap( const char* filename ) : m_filename( filename ), m_count( 0 ){
549 }
550 void visit( const char* name, Accelerator& accelerator ){
551         char value[1024];
552         if ( read_var( m_filename, "Commands", name, value ) ) {
553                 if ( string_empty( value ) ) {
554                         accelerator.key = 0;
555                         accelerator.modifiers = (GdkModifierType)0;
556                         return;
557                 }
558
559                 gtk_accelerator_parse( value, &accelerator.key, &accelerator.modifiers );
560                 accelerator = accelerator; // fix modifiers
561
562                 if ( accelerator.key != 0 ) {
563                         ++m_count;
564                 }
565                 else
566                 {
567                         globalOutputStream() << "WARNING: failed to parse user command " << makeQuoted( name ) << ": unknown key " << makeQuoted( value ) << "\n";
568                 }
569         }
570 }
571 std::size_t count() const {
572         return m_count;
573 }
574 };
575
576 void LoadCommandMap( const char* path ){
577         StringOutputStream strINI( 256 );
578         strINI << path << "shortcuts.ini";
579
580         FILE* f = fopen( strINI.c_str(), "r" );
581         if ( f != 0 ) {
582                 fclose( f );
583                 globalOutputStream() << "loading custom shortcuts list from " << makeQuoted( strINI.c_str() ) << "\n";
584
585                 Version version = version_parse( COMMANDS_VERSION );
586                 Version dataVersion = { 0, 0 };
587
588                 {
589                         char value[1024];
590                         if ( read_var( strINI.c_str(), "Version", "number", value ) ) {
591                                 dataVersion = version_parse( value );
592                         }
593                 }
594
595                 if ( version_compatible( version, dataVersion ) ) {
596                         globalOutputStream() << "commands import: data version " << dataVersion << " is compatible with code version " << version << "\n";
597                         ReadCommandMap visitor( strINI.c_str() );
598                         GlobalShortcuts_foreach( visitor );
599                         globalOutputStream() << "parsed " << Unsigned( visitor.count() ) << " custom shortcuts\n";
600                 }
601                 else
602                 {
603                         globalOutputStream() << "commands import: data version " << dataVersion << " is not compatible with code version " << version << "\n";
604                 }
605         }
606         else
607         {
608                 globalOutputStream() << "failed to load custom shortcuts from " << makeQuoted( strINI.c_str() ) << "\n";
609         }
610 }