/
EventManager.cpp
830 lines (660 loc) · 20 KB
/
EventManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
#include "EventManager.h"
#include "imodule.h"
#include "iradiant.h"
#include "itextstream.h"
#include "icommandsystem.h"
#include "iselection.h"
#include <iostream>
#include <typeinfo>
#include <wx/wxprec.h>
#include <wx/toolbar.h>
#include "registry/registry.h"
#include "xmlutil/Node.h"
#include "wxutil/Modifier.h"
#include "Statement.h"
#include "Toggle.h"
#include "WidgetToggle.h"
#include "RegistryToggle.h"
#include "KeyEvent.h"
#include "SaveEventVisitor.h"
#include "MouseToolManager.h"
#include "debugging/debugging.h"
#include "module/StaticModule.h"
#include <iostream>
namespace ui
{
namespace
{
inline bool signatureIsEmptyOrOptional(const cmd::Signature& signature)
{
for (auto part : signature)
{
if ((part & cmd::ARGTYPE_OPTIONAL) == 0)
{
return false;
}
}
return true; // empty or is fully optional
}
}
// RegisterableModule implementation
const std::string& EventManager::getName() const
{
static std::string _name(MODULE_EVENTMANAGER);
return _name;
}
const StringSet& EventManager::getDependencies() const
{
static StringSet _dependencies;
if (_dependencies.empty())
{
_dependencies.insert(MODULE_XMLREGISTRY);
}
return _dependencies;
}
void EventManager::initialiseModule(const ApplicationContext& ctx)
{
rMessage() << getName() << "::initialiseModule called." << std::endl;
// Deactivate the empty event, so it's safe to return it as NullEvent
_emptyEvent->setEnabled(false);
_shortcutFilter.reset(new GlobalKeyEventFilter(*this));
rMessage() << getName() << " successfully initialised." << std::endl;
}
void EventManager::shutdownModule()
{
rMessage() << getName() << "::shutdownModule called" << std::endl;
_shortcutFilter.reset();
saveEventListToRegistry();
_accelerators.clear();
_events.clear();
}
// Constructor
EventManager::EventManager() :
_emptyEvent(new Event()),
_emptyAccelerator(Accelerator::CreateEmpty())
{}
#if 0
Accelerator& EventManager::addAccelerator(const std::string& key, const std::string& modifierStr)
{
unsigned int keyVal = Accelerator::getKeyCodeFromName(key);
unsigned int modifierFlags = wxutil::Modifier::GetStateFromModifierString(modifierStr);
// Add a new Accelerator to the list
_accelerators.emplace_back(std::make_shared<Accelerator>(keyVal, modifierFlags));
// return the reference to the last accelerator in the list
return *_accelerators.back();
}
#endif
#if 0
Accelerator& EventManager::addAccelerator(wxKeyEvent& ev)
{
int keyCode = ev.GetKeyCode();
unsigned int modifierFlags = wxutil::Modifier::GetStateForKeyEvent(ev);
// Create a new accelerator with the given arguments and add it
_accelerators.emplace_back(std::make_shared<Accelerator>(keyCode, modifierFlags, _emptyEvent));
// return the reference to the last accelerator in the list
return *_accelerators.back();
}
#endif
void EventManager::resetAcceleratorBindings()
{
// Select the stock mappings
std::string xPathQuery = "user/ui/input/shortcuts[@name='default']//shortcut";
xml::NodeList shortcutList = GlobalRegistry().findXPath(xPathQuery);
if (shortcutList.empty())
{
// No accelerator definitions found!
rWarning() << "EventManager: No default shortcut definitions found..." << std::endl;
return;
}
// Disconnect all accelerators from all events
for (EventMap::value_type& pair : _events)
{
pair.second->disconnectAccelerators();
}
_accelerators.clear();
rMessage() << "EventManager: Default shortcuts found in Registry: " << shortcutList.size() << std::endl;
loadAcceleratorFromList(shortcutList);
}
IEventPtr EventManager::findEvent(const std::string& name)
{
// Try to lookup the command
auto found = _events.find(name);
#if 0
if (found == _events.end())
{
// Try to look up a matching command in the CommandSystem
if (GlobalCommandSystem().commandExists(name))
{
auto signature = GlobalCommandSystem().getSignature(name);
if (signatureIsEmptyOrOptional(signature))
{
// Insert a new event wrapping this command
found = _events.emplace(name, std::make_shared<Statement>(name)).first;
}
}
}
#endif
// if nothing found, return the NullEvent
return found != _events.end() ? found->second : _emptyEvent;
}
IEventPtr EventManager::findEvent(wxKeyEvent& ev)
{
// Retrieve the accelerators for this eventkey
Accelerator& accel = findAccelerator(ev);
// Did we find any matching accelerators? If yes, take the first found accelerator
return accel.getEvent() ? accel.getEvent() : _emptyEvent;
}
std::string EventManager::getEventName(const IEventPtr& event)
{
// Try to lookup the given eventptr
for (const EventMap::value_type& pair : _events)
{
if (pair.second == event)
{
return pair.first;
}
}
return std::string();
}
std::string EventManager::getAcceleratorStr(const IEventPtr& event, bool forMenu)
{
IAccelerator& accelerator = findAccelerator(event);
return accelerator.getString(forMenu);
}
// Checks if the eventName is already registered and writes to rWarning, if so
bool EventManager::alreadyRegistered(const std::string& eventName)
{
// Try to find the command and see if it's already registered
IEventPtr foundEvent = findEvent(eventName);
if (foundEvent->empty())
{
return false;
}
rWarning() << "EventManager: Event " << eventName << " already registered!" << std::endl;
return true;
}
// Add the given command to the internal list
IEventPtr EventManager::addCommand(const std::string& name, const std::string& statement, bool reactOnKeyUp)
{
if (alreadyRegistered(name))
{
return _emptyEvent;
}
// Add the command to the list
IEventPtr event = std::make_shared<Statement>(statement, reactOnKeyUp);
_events[name] = event;
// Return the pointer to the newly created event
return event;
}
IEventPtr EventManager::addKeyEvent(const std::string& name, const KeyStateChangeCallback& keyStateChangeCallback)
{
if (alreadyRegistered(name))
{
return _emptyEvent;
}
IEventPtr event = std::make_shared<KeyEvent>(keyStateChangeCallback);
// Add the new keyevent to the list
_events[name] = event;
// Return the pointer to the newly created event
return event;
}
IEventPtr EventManager::addWidgetToggle(const std::string& name) {
if (alreadyRegistered(name))
{
return _emptyEvent;
}
IEventPtr event = std::make_shared<WidgetToggle>();
// Add the command to the list
_events[name] = event;
// Return the pointer to the newly created event
return event;
}
IEventPtr EventManager::addRegistryToggle(const std::string& name, const std::string& registryKey)
{
if (alreadyRegistered(name))
{
return _emptyEvent;
}
IEventPtr event = std::make_shared<RegistryToggle>(registryKey);
// Add the command to the list
_events[name] = event;
// Return the pointer to the newly created event
return event;
}
IEventPtr EventManager::addToggle(const std::string& name, const ToggleCallback& onToggled)
{
if (alreadyRegistered(name))
{
return _emptyEvent;
}
IEventPtr event = std::make_shared<Toggle>(onToggled);
// Add the command to the list
_events[name] = event;
// Return the pointer to the newly created event
return event;
}
void EventManager::setToggled(const std::string& name, const bool toggled)
{
// Check could be placed here by std::dynamic_pointer_cast
if (!findEvent(name)->setToggled(toggled))
{
rWarning() << "EventManager: Event " << name << " is not a Toggle." << std::endl;
}
}
void EventManager::registerMenuItem(const std::string& eventName, const ui::IMenuElementPtr& item)
{
auto result = _menuItems.emplace(eventName, ItemConnection());
result->second.item = item;
// Set the accelerator of this menu item
auto& accelerator = findAccelerator(eventName);
item->setAccelerator(accelerator.getString(true));
// Check if we have an event object corresponding to this event name
auto evt = findEvent(eventName);
if (!evt->empty())
{
evt->connectMenuItem(item);
}
else
{
// There's no special event object this item is connected to
// just wire up an execute() when this item is clicked
result->second.itemActivatedConn = item->signal_ItemActivated().connect(
[=]() { GlobalCommandSystem().execute(eventName); }
);
}
}
void EventManager::unregisterMenuItem(const std::string& eventName, const ui::IMenuElementPtr& item)
{
for (auto it = _menuItems.lower_bound(eventName);
it != _menuItems.end() && it != _menuItems.upper_bound(eventName); ++it)
{
if (it->second.item == item)
{
it->second.itemActivatedConn.disconnect();
_menuItems.erase(it);
break;
}
}
// Check if we have an event object corresponding to this event name
auto evt = findEvent(eventName);
if (!evt->empty())
{
evt->disconnectMenuItem(item);
}
}
Accelerator& EventManager::connectAccelerator(int keyCode, unsigned int modifierFlags, const std::string& command)
{
auto result = _accelerators.emplace(command, std::make_shared<Accelerator>(keyCode, modifierFlags));
Accelerator& accel = *result.first->second;
// There might be an event to associate
auto event = findEvent(command);
if (!event->empty())
{
accel.setEvent(event);
}
else
{
accel.setStatement(command);
}
setMenuItemAccelerator(command, accel.getString(true));
return *result.first->second;
#if 0
else
{
// Command NOT found
rWarning() << "EventManager: Unable to connect command: " << command << std::endl;
}
#endif
}
// Connects the given accelerator to the given command (identified by the string)
void EventManager::connectAccelerator(wxKeyEvent& keyEvent, const std::string& command)
{
int keyCode = keyEvent.GetKeyCode();
unsigned int modifierFlags = wxutil::Modifier::GetStateForKeyEvent(keyEvent);
connectAccelerator(keyCode, modifierFlags, command);
}
void EventManager::disconnectAccelerator(const std::string& command)
{
auto existing = _accelerators.find(command);
if (existing != _accelerators.end())
{
// Clear menu item accelerator string
setMenuItemAccelerator(command, std::string());
if (existing->second->getEvent())
{
existing->second->getEvent()->disconnectAccelerators();
existing->second->setEvent(_emptyEvent);
}
_accelerators.erase(existing);
}
#if 0
// Cycle through the accelerators and check for matches
for (const auto& accel : _accelerators)
{
if (accel->match(event))
{
// Connect the accelerator to the empty event (disable the accelerator)
event->disconnectAccelerators();
accel->setEvent(_emptyEvent);
accel->setKey(0);
accel->setModifiers(0);
}
}
IEventPtr event = findEvent(command);
if (!event->empty())
{
}
else
{
// Command NOT found
rWarning() << "EventManager: Unable to disconnect command: " << command << std::endl;
}
#endif
}
void EventManager::setMenuItemAccelerator(const std::string& command, const std::string& acceleratorStr)
{
auto foundMenuItem = _menuItems.find(command);
if (foundMenuItem != _menuItems.end())
{
foundMenuItem->second.item->setAccelerator(acceleratorStr);
}
}
void EventManager::disableEvent(const std::string& eventName)
{
findEvent(eventName)->setEnabled(false);
}
void EventManager::enableEvent(const std::string& eventName)
{
findEvent(eventName)->setEnabled(true);
}
void EventManager::renameEvent(const std::string& oldEventName, const std::string& newEventName)
{
auto existing = _events.find(oldEventName);
if (existing == _events.end())
{
rError() << "Cannot rename event, this name is not registered: " << oldEventName << std::endl;
}
// Re-insert the event using a new name
auto existingEvent = existing->second;
_events.erase(existing);
_events.insert(std::make_pair(newEventName, existingEvent));
}
void EventManager::removeEvent(const std::string& eventName)
{
// Try to lookup the command
EventMap::iterator i = _events.find(eventName);
if (i != _events.end())
{
// Remove all accelerators beforehand
disconnectAccelerator(eventName);
// Remove the event from the list
_events.erase(i);
}
}
void EventManager::disconnectToolbar(wxToolBar* toolbar)
{
std::for_each(_events.begin(), _events.end(), [&] (EventMap::value_type& pair)
{
for (std::size_t tool = 0; tool < toolbar->GetToolsCount(); tool++)
{
pair.second->disconnectToolItem(const_cast<wxToolBarToolBase*>(toolbar->GetToolByPos(static_cast<int>(tool))));
}
});
}
// Loads the default shortcuts from the registry
void EventManager::loadAccelerators()
{
// TODO
//// Register all custom statements as events too to make them shortcut-bindable
//// before going ahead
//GlobalCommandSystem().foreachStatement([&](const std::string& statementName)
//{
// addCommand(statementName, statementName, false);
//}, true); // custom statements only
xml::NodeList shortcutSets = GlobalRegistry().findXPath("user/ui/input//shortcuts");
// If we have two sets of shortcuts, don't select the stock ones
std::string xPathQuery = shortcutSets.size() > 1 ?
"user/ui/input/shortcuts[not(@name)]//shortcut" : // find all without name attribute
"user/ui/input/shortcuts//shortcut"; // find all shortcuts
xml::NodeList shortcutList = GlobalRegistry().findXPath(xPathQuery);
if (shortcutList.empty())
{
// No accelerator definitions found!
rWarning() << "EventManager: No shortcut definitions found..." << std::endl;
return;
}
rMessage() << "EventManager: Shortcuts found in Registry: " << shortcutList.size() << std::endl;
loadAcceleratorFromList(shortcutList);
}
void EventManager::loadAcceleratorFromList(const xml::NodeList& shortcutList)
{
for (const xml::Node& shortcutNode : shortcutList)
{
const std::string key = shortcutNode.getAttributeValue("key");
const std::string cmd = shortcutNode.getAttributeValue("command");
// Get the modifier string (e.g. "SHIFT+ALT")
const std::string modifierStr = shortcutNode.getAttributeValue("modifiers");
// Check for a non-empty key string
if (key.empty()) continue;
// Check for duplicate accelerator mappings
const auto& existingAccel = findAccelerator(key, modifierStr);
if (existingAccel.getStatement() == cmd)
{
rWarning() << "Accelerator " << existingAccel.getString(false) <<
" is already mapped to " << cmd << std::endl;
continue;
}
// Create the accelerator object
int keyVal = Accelerator::getKeyCodeFromName(key);
unsigned int modifierFlags = wxutil::Modifier::GetStateFromModifierString(modifierStr);
auto& accelerator = connectAccelerator(keyVal, modifierFlags, cmd);
// Update all registered menu items
for (const auto& item : _menuItems)
{
if (item.second.item->getEvent() == cmd)
{
item.second.item->setAccelerator(accelerator.getString(true));
}
}
// Try to lookup the command
IEventPtr event = findEvent(cmd);
// Check for valid command definitions
if (!event->empty())
{
// Connect the newly created accelerator to the command
event->connectAccelerator(accelerator);
accelerator.setEvent(event);
continue;
}
#if 1
// Second chance: look up a matching command
if (GlobalCommandSystem().commandExists(cmd))
{
auto signature = GlobalCommandSystem().getSignature(cmd);
if (signatureIsEmptyOrOptional(signature))
{
accelerator.setStatement(cmd);
continue;
}
}
#endif
rWarning() << "EventManager: Cannot load shortcut definition (command invalid): "
<< cmd << std::endl;
}
}
void EventManager::foreachEvent(IEventVisitor& eventVisitor)
{
// Cycle through the event and pass them to the visitor class
for (const auto& pair : _events)
{
auto& accel = findAccelerator(pair.second);
eventVisitor.visit(pair.first, accel);
}
}
// Tries to locate an accelerator, that is connected to the given command
Accelerator& EventManager::findAccelerator(const IEventPtr& event)
{
// Cycle through the accelerators and check for matches
for (const auto& pair : _accelerators)
{
if (pair.second->match(event))
{
// Return the reference to the found accelerator
return *pair.second;
}
}
// Return an empty accelerator if nothing is found
return _emptyAccelerator;
}
Accelerator& EventManager::findAccelerator(const std::string& commandName)
{
auto found = _accelerators.find(commandName);
if (found != _accelerators.end())
{
return *found->second;
}
return _emptyAccelerator;
#if 0
auto foundEvent = _events.find(commandName);
// Cycle through the accelerators and check for matches
for (const auto& accel : _accelerators)
{
if (accel->getStatement() == commandName)
{
// Return the reference to the found accelerator
return *accel;
}
// If we got an event wrapper, check if this accelerator is associated to it
if (foundEvent != _events.end() && accel->match(foundEvent->second))
{
return *accel;
}
}
// Return an empty accelerator if nothing is found
return _emptyAccelerator;
#endif
}
void EventManager::saveEventListToRegistry()
{
const std::string rootKey = "user/ui/input";
// The visitor class to save each event definition into the registry
// Note: the SaveEventVisitor automatically wipes all the existing shortcuts from the registry
SaveEventVisitor visitor(rootKey, *this);
foreachEvent(visitor);
}
Accelerator& EventManager::findAccelerator(const std::string& key, const std::string& modifierStr)
{
unsigned int keyVal = Accelerator::getKeyCodeFromName(key);
unsigned int modifierFlags = wxutil::Modifier::GetStateFromModifierString(modifierStr);
return findAccelerator(keyVal, modifierFlags);
}
bool EventManager::duplicateAccelerator(const std::string& key,
const std::string& modifiers,
const IEventPtr& event)
{
#if 0
Accelerator& accelerator = findAccelerator(key, modifiers);
for (const auto& accelerator : accelList)
{
// If one of the accelerators in the list matches the event, return true
if (accelerator->match(event))
{
return true;
}
}
#endif
return false;
}
Accelerator& EventManager::findAccelerator(unsigned int keyVal, unsigned int modifierFlags)
{
// Cycle through the accelerators and check for matches
for (const auto& pair : _accelerators)
{
if (pair.second->match(keyVal, modifierFlags))
{
// Add the pointer to the found accelerators
return *pair.second;
}
}
return _emptyAccelerator;
}
Accelerator& EventManager::findAccelerator(wxKeyEvent& ev)
{
int keyval = ev.GetKeyCode(); // is always uppercase
return findAccelerator(keyval, wxutil::Modifier::GetStateForKeyEvent(ev));
}
bool EventManager::handleKeyEvent(wxKeyEvent& keyEvent)
{
Accelerator& accelerator = findAccelerator(keyEvent);
const std::string& statement = accelerator.getStatement();
if (!statement.empty())
{
if (keyEvent.GetEventType() == wxEVT_KEY_DOWN)
{
GlobalCommandSystem().execute(statement);
}
return true;
}
auto ev = accelerator.getEvent();
if (ev)
{
if (keyEvent.GetEventType() == wxEVT_KEY_DOWN)
{
ev->keyDown();
}
else
{
ev->keyUp();
}
return true;
}
return false;
}
bool EventManager::isModifier(wxKeyEvent& ev)
{
int keyCode = ev.GetKeyCode();
return (keyCode == WXK_SHIFT || keyCode == WXK_CONTROL ||
keyCode == WXK_ALT || keyCode == WXK_WINDOWS_LEFT ||
keyCode == WXK_WINDOWS_MENU || keyCode == WXK_WINDOWS_RIGHT);
}
namespace
{
std::string getKeyString(wxKeyEvent& ev)
{
int keycode = ev.GetKeyCode();
std::string virtualKeyCodeName = Accelerator::getNameFromKeyCode(keycode);
if (!virtualKeyCodeName.empty())
{
return virtualKeyCodeName;
}
if (keycode > 0 && keycode < 32)
{
return wxString::Format("Ctrl-%c", (unsigned char)('A' + keycode - 1)).ToStdString();
}
if (keycode >= 32 && keycode < 128)
{
return wxString::Format("%c", (unsigned char)keycode).ToStdString();
}
return "unknown";
}
} // namespace
std::string EventManager::getEventStr(wxKeyEvent& ev)
{
std::string returnValue("");
// Don't react on modifiers only (no actual key like A, 2, U, etc.)
if (isModifier(ev))
{
return returnValue;
}
// Convert the key event to modifier flags
const unsigned int modifierFlags = wxutil::Modifier::GetStateForKeyEvent(ev);
// Construct the complete string
returnValue += wxutil::Modifier::GetLocalisedModifierString(modifierFlags);
returnValue += (returnValue != "") ? "-" : "";
returnValue += getKeyString(ev);
return returnValue;
}
// Static module instances
module::StaticModule<EventManager> eventManagerModule;
module::StaticModule<MouseToolManager> mouseToolManagerModule;
}