KiCad PCB EDA Suite
Loading...
Searching...
No Matches
tool_manager.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2013-2023 CERN
5 * Copyright (C) 2019-2023 KiCad Developers, see AUTHORS.txt for contributors.
6 * @author Tomasz Wlostowski <[email protected]>
7 * @author Maciej Suminski <[email protected]>
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, you may find one here:
21 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
22 * or you may search the http://www.gnu.org website for the version 2 license,
23 * or you may write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25 */
26
27#include <core/kicad_algo.h>
28#include <optional>
29#include <map>
30#include <stack>
31#include <trace_helpers.h>
32#include <kiplatform/ui.h>
33
34#include <wx/event.h>
35#include <wx/clipbrd.h>
36#include <wx/app.h>
37
38#include <math/vector2wx.h>
39
40#include <view/view.h>
41#include <view/view_controls.h>
42#include <eda_base_frame.h>
43#include <tool/tool_base.h>
45#include <tool/tool_manager.h>
46#include <tool/action_menu.h>
47#include <tool/coroutine.h>
48#include <tool/action_manager.h>
49
51
54{
56 theTool( aTool )
57 {
58 clear();
59 }
60
61 TOOL_STATE( const TOOL_STATE& aState )
62 {
63 theTool = aState.theTool;
64 idle = aState.idle;
65 shutdown = aState.shutdown;
66 pendingWait = aState.pendingWait;
68 contextMenu = aState.contextMenu;
70 cofunc = aState.cofunc;
72 wakeupEvent = aState.wakeupEvent;
73 waitEvents = aState.waitEvents;
74 transitions = aState.transitions;
75 vcSettings = aState.vcSettings;
76 // do not copy stateStack
77 }
78
80 {
81 if( !stateStack.empty() )
82 wxFAIL;
83 }
84
87
89 bool idle;
90
93
97
100
103
106
109
112
115
118
121 std::vector<TRANSITION> transitions;
122
125
127 {
128 theTool = aState.theTool;
129 idle = aState.idle;
130 shutdown = aState.shutdown;
131 pendingWait = aState.pendingWait;
133 contextMenu = aState.contextMenu;
135 cofunc = aState.cofunc;
136 initialEvent = aState.initialEvent;
137 wakeupEvent = aState.wakeupEvent;
138 waitEvents = aState.waitEvents;
139 transitions = aState.transitions;
140 vcSettings = aState.vcSettings;
141 // do not copy stateStack
142 return *this;
143 }
144
145 bool operator==( const TOOL_MANAGER::TOOL_STATE& aRhs ) const
146 {
147 return aRhs.theTool == theTool;
148 }
149
150 bool operator!=( const TOOL_MANAGER::TOOL_STATE& aRhs ) const
151 {
152 return aRhs.theTool != theTool;
153 }
154
159 void Push()
160 {
161 auto state = std::make_unique<TOOL_STATE>( *this );
162 stateStack.push( std::move( state ) );
163 clear();
164 }
165
172 bool Pop()
173 {
174 delete cofunc;
175
176 if( !stateStack.empty() )
177 {
178 *this = *stateStack.top().get();
179 stateStack.pop();
180 return true;
181 }
182 else
183 {
184 cofunc = nullptr;
185 return false;
186 }
187 }
188
189private:
191 std::stack<std::unique_ptr<TOOL_STATE>> stateStack;
192
194 void clear()
195 {
196 idle = true;
197 shutdown = false;
198 pendingWait = false;
199 pendingContextMenu = false;
200 cofunc = nullptr;
201 contextMenu = nullptr;
204 transitions.clear();
205 }
206};
207
208
210 m_model( nullptr ),
211 m_view( nullptr ),
212 m_viewControls( nullptr ),
213 m_frame( nullptr ),
214 m_settings( nullptr ),
215 m_warpMouseAfterContextMenu( true ),
216 m_menuActive( false ),
217 m_menuOwner( -1 ),
218 m_activeState( nullptr ),
219 m_shuttingDown( false )
220{
221 m_actionMgr = new ACTION_MANAGER( this );
222}
223
224
226{
227 std::map<TOOL_BASE*, TOOL_STATE*>::iterator it, it_end;
228
229 for( it = m_toolState.begin(), it_end = m_toolState.end(); it != it_end; ++it )
230 {
231 delete it->second->cofunc; // delete cofunction
232 delete it->second; // delete TOOL_STATE
233 delete it->first; // delete the tool itself
234 }
235
236 delete m_actionMgr;
237}
238
239
241{
242 wxASSERT_MSG( m_toolNameIndex.find( aTool->GetName() ) == m_toolNameIndex.end(),
243 wxT( "Adding two tools with the same name may result in unexpected behavior.") );
244 wxASSERT_MSG( m_toolIdIndex.find( aTool->GetId() ) == m_toolIdIndex.end(),
245 wxT( "Adding two tools with the same ID may result in unexpected behavior.") );
246 wxASSERT_MSG( m_toolTypes.find( typeid( *aTool ).name() ) == m_toolTypes.end(),
247 wxT( "Adding two tools of the same type may result in unexpected behavior.") );
248
249 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::RegisterTool: Registering tool %s with ID %d" ),
250 aTool->GetName(), aTool->GetId() );
251
252 m_toolOrder.push_back( aTool );
253
254 TOOL_STATE* st = new TOOL_STATE( aTool );
255
256 m_toolState[aTool] = st;
257 m_toolNameIndex[aTool->GetName()] = st;
258 m_toolIdIndex[aTool->GetId()] = st;
259 m_toolTypes[typeid( *aTool ).name()] = st->theTool;
260
261 aTool->attachManager( this );
262}
263
264
266{
267 TOOL_BASE* tool = FindTool( aToolId );
268
269 if( tool && tool->GetType() == INTERACTIVE )
270 return invokeTool( tool );
271
272 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::InvokeTool - no tool with ID %d" ),
273 aToolId );
274
275 return false; // there is no tool with the given id
276}
277
278
279bool TOOL_MANAGER::InvokeTool( const std::string& aToolName )
280{
281 TOOL_BASE* tool = FindTool( aToolName );
282
283 if( tool && tool->GetType() == INTERACTIVE )
284 return invokeTool( tool );
285
286 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::InvokeTool - no tool with name %s" ),
287 aToolName );
288
289 return false; // there is no tool with the given name
290}
291
292
293bool TOOL_MANAGER::doRunAction( const std::string& aActionName, bool aNow, const std::any& aParam,
294 COMMIT* aCommit )
295{
296 TOOL_ACTION* action = m_actionMgr->FindAction( aActionName );
297
298 if( !action )
299 {
300 wxASSERT_MSG( false, wxString::Format( "Could not find action %s.", aActionName ) );
301 return false;
302 }
303
304 doRunAction( *action, aNow, aParam, aCommit );
305
306 return true;
307}
308
309
311{
312 if( m_viewControls )
314 else
316}
317
318
320{
321 if( m_viewControls )
323 else
325}
326
327
328bool TOOL_MANAGER::doRunAction( const TOOL_ACTION& aAction, bool aNow, const std::any& aParam,
329 COMMIT* aCommit )
330{
331 if( m_shuttingDown )
332 return true;
333
334 bool retVal = false;
335 TOOL_EVENT event = aAction.MakeEvent();
336
337 // We initialize the SYNCHRONOUS state to finished so that tools that don't have an event
338 // loop won't hang if someone forgets to set the state.
339 std::atomic<SYNCRONOUS_TOOL_STATE> synchronousControl = STS_FINISHED;
340
341 if( event.Category() == TC_COMMAND )
342 event.SetMousePosition( GetCursorPosition() );
343
344 // Allow to override the action parameter
345 if( aParam.has_value() )
346 event.SetParameter( aParam );
347
348 // Pass the commit (if any)
349 if( aCommit )
350 {
351 event.SetSynchronous( &synchronousControl );
352 event.SetCommit( aCommit );
353 }
354
355 if( aNow )
356 {
357 TOOL_STATE* current = m_activeState;
358
359 if( aCommit )
360 {
361 // An event with a commit must be run synchronously
362 processEvent( event );
363
364 while( synchronousControl == STS_RUNNING )
365 {
366 wxYield(); // Needed to honor mouse (and other) events during editing
367 wxMilliSleep( 1 ); // Needed to avoid 100% use of one cpu core.
368 // The sleeping time must be must be small to avoid
369 // noticeable lag in mouse and editing events
370 // (1 to 5 ms is a good value)
371 }
372
373 retVal = synchronousControl != STS_CANCELLED;
374 }
375 else
376 {
377 retVal = processEvent( event );
378 }
379
380 setActiveState( current );
381 UpdateUI( event );
382 }
383 else
384 {
385 PostEvent( event );
386 }
387
388 return retVal;
389}
390
391
393{
395
396 processEvent( evt );
397}
398
399
400void TOOL_MANAGER::PrimeTool( const VECTOR2D& aPosition )
401{
402 int modifiers = 0;
403
404 /*
405 * Don't include any modifiers. They're part of the hotkey, not part of the resulting
406 * click.
407 *
408 * modifiers |= wxGetKeyState( WXK_SHIFT ) ? MD_SHIFT : 0;
409 * modifiers |= wxGetKeyState( WXK_CONTROL ) ? MD_CTRL : 0;
410 * modifiers |= wxGetKeyState( WXK_ALT ) ? MD_ALT : 0;
411 */
412
413 TOOL_EVENT evt( TC_MOUSE, TA_PRIME, BUT_LEFT | modifiers );
414 evt.SetMousePosition( aPosition );
415
416 PostEvent( evt );
417}
418
419
421{
422 // Horrific hack, but it's a crash bug. Don't let inter-frame commands stack up
423 // waiting to be processed.
424 if( aEvent.IsSimulator() && m_eventQueue.size() > 0 && m_eventQueue.back().IsSimulator() )
425 m_eventQueue.pop_back();
426
427 m_eventQueue.push_back( aEvent );
428}
429
430
431int TOOL_MANAGER::GetHotKey( const TOOL_ACTION& aAction ) const
432{
433 return m_actionMgr->GetHotKey( aAction );
434}
435
436
438{
439 wxASSERT( aTool != nullptr );
440
441 TOOL_EVENT evt( TC_COMMAND, TA_ACTIVATE, aTool->GetName() );
443 processEvent( evt );
444
445 if( TOOL_STATE* active = GetCurrentToolState() )
446 setActiveState( active );
447
448 return true;
449}
450
451
453{
454 wxASSERT( aTool != nullptr );
455
456 if( !isRegistered( aTool ) )
457 {
458 wxASSERT_MSG( false, wxT( "You cannot run unregistered tools" ) );
459 return false;
460 }
461
462 TOOL_ID id = aTool->GetId();
463
464 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::runTool - running tool %s" ),
465 aTool->GetName() );
466
467 if( aTool->GetType() == INTERACTIVE )
468 static_cast<TOOL_INTERACTIVE*>( aTool )->resetTransitions();
469
470 // If the tool is already active, bring it to the top of the active tools stack
471 if( isActive( aTool ) && m_activeTools.size() > 1 )
472 {
473 auto it = std::find( m_activeTools.begin(), m_activeTools.end(), id );
474
475 if( it != m_activeTools.end() )
476 {
477 if( it != m_activeTools.begin() )
478 {
479 m_activeTools.erase( it );
480 m_activeTools.push_front( id );
481 }
482
483 return false;
484 }
485 }
486
489
490 // Add the tool on the front of the processing queue (it gets events first)
491 m_activeTools.push_front( id );
492
493 return true;
494}
495
496
498{
499 m_shuttingDown = true;
500
501 // Create a temporary list of tools to iterate over since when the tools shutdown
502 // they remove themselves from the list automatically (invalidating the iterator)
503 ID_LIST tmpList = m_activeTools;
504
505 // Make sure each tool knows that it is shutting down, so that loops get shut down
506 // at the dispatcher
507 for( auto id : tmpList )
508 {
509 if( m_toolIdIndex.count( id ) == 0 )
510 continue;
511
512 m_toolIdIndex[id]->shutdown = true;
513 }
514
515 for( auto id : tmpList )
516 {
517 ShutdownTool( id );
518 }
519}
520
521
523{
524 TOOL_BASE* tool = FindTool( aToolId );
525
526 if( tool && tool->GetType() == INTERACTIVE )
527 ShutdownTool( tool );
528
529 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::ShutdownTool - no tool with ID %d" ),
530 aToolId );
531}
532
533
534void TOOL_MANAGER::ShutdownTool( const std::string& aToolName )
535{
536 TOOL_BASE* tool = FindTool( aToolName );
537
538 if( tool && tool->GetType() == INTERACTIVE )
539 ShutdownTool( tool );
540
541 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::ShutdownTool - no tool with name %s" ),
542 aToolName );
543}
544
545
547{
548 wxASSERT( aTool != nullptr );
549
550 TOOL_ID id = aTool->GetId();
551
552 if( isActive( aTool ) )
553 {
554 TOOL_MANAGER::ID_LIST::iterator it = std::find( m_activeTools.begin(),
555 m_activeTools.end(), id );
556
557 TOOL_STATE* st = m_toolIdIndex[*it];
558
559 // the tool state handler is waiting for events (i.e. called Wait() method)
560 if( st && st->pendingWait )
561 {
562 // Wake up the tool and tell it to shutdown
563 st->shutdown = true;
564 st->pendingWait = false;
565 st->waitEvents.clear();
566
567 if( st->cofunc )
568 {
569 wxLogTrace( kicadTraceToolStack,
570 wxS( "TOOL_MANAGER::ShutdownTool - Shutting down tool %s" ),
571 st->theTool->GetName() );
572
573 setActiveState( st );
574 bool end = !st->cofunc->Resume();
575
576 if( end )
577 finishTool( st );
578 }
579 }
580 }
581}
582
583
585{
586 std::map<TOOL_ID, TOOL_STATE*>::const_iterator it = m_toolIdIndex.find( aId );
587
588 if( it != m_toolIdIndex.end() )
589 return it->second->theTool;
590
591 return nullptr;
592}
593
594
595TOOL_BASE* TOOL_MANAGER::FindTool( const std::string& aName ) const
596{
597 std::map<std::string, TOOL_STATE*>::const_iterator it = m_toolNameIndex.find( aName );
598
599 if( it != m_toolNameIndex.end() )
600 return it->second->theTool;
601
602 return nullptr;
603}
604
605
607{
608 // Deactivate the active tool, but do not run anything new
610 processEvent( evt );
611}
612
613
615{
616 if( aReason != TOOL_BASE::REDRAW )
618
619 for( auto& state : m_toolState )
620 {
621 TOOL_BASE* tool = state.first;
622
623 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::ResetTools: Resetting tool '%s'" ),
624 tool->GetName() );
625
626 setActiveState( state.second );
627 tool->Reset( aReason );
628
629 if( tool->GetType() == INTERACTIVE )
630 static_cast<TOOL_INTERACTIVE*>( tool )->resetTransitions();
631 }
632}
633
634
636{
637 for( auto it = m_toolOrder.begin(); it != m_toolOrder.end(); /* iter inside */ )
638 {
639 TOOL_BASE* tool = *it;
640 wxASSERT( m_toolState.count( tool ) );
641 TOOL_STATE* state = m_toolState[tool];
642 setActiveState( state );
643 ++it; // keep the iterator valid if the element is going to be erased
644
645 if( !tool->Init() )
646 {
647 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER initialization of tool '%s' failed" ),
648 tool->GetName() );
649
650 // Unregister the tool
651 setActiveState( nullptr );
652 m_toolState.erase( tool );
653 m_toolNameIndex.erase( tool->GetName() );
654 m_toolIdIndex.erase( tool->GetId() );
655 m_toolTypes.erase( typeid( *tool ).name() );
656
657 delete state;
658 delete tool;
659 }
660 }
661
662 m_actionMgr->UpdateHotKeys( true );
663
665}
666
667
668int TOOL_MANAGER::GetPriority( int aToolId ) const
669{
670 int priority = 0;
671
672 for( TOOL_ID tool : m_activeTools )
673 {
674 if( tool == aToolId )
675 return priority;
676
677 ++priority;
678 }
679
680 return -1;
681}
682
683
685 const TOOL_EVENT_LIST& aConditions )
686{
687 TOOL_STATE* st = m_toolState[aTool];
688
689 st->transitions.emplace_back( TRANSITION( aConditions, aHandler ) );
690}
691
692
694{
695 m_toolState[aTool]->transitions.clear();
696}
697
698
699void TOOL_MANAGER::RunMainStack( TOOL_BASE* aTool, std::function<void()> aFunc )
700{
701 TOOL_STATE* st = m_toolState[aTool];
702 setActiveState( st );
703 wxCHECK( st->cofunc, /* void */ );
704 st->cofunc->RunMainStack( std::move( aFunc ) );
705}
706
707
709{
710 TOOL_STATE* st = m_toolState[aTool];
711
712 wxCHECK( !st->pendingWait, nullptr ); // everything collapses on two KiYield() in a row
713
714 // indicate to the manager that we are going to sleep and we shall be
715 // woken up when an event matching aConditions arrive
716 st->pendingWait = true;
717 st->waitEvents = aConditions;
718
719 wxCHECK( st->cofunc, nullptr );
720
721 // switch context back to event dispatcher loop
722 st->cofunc->KiYield();
723
724 // If the tool should shutdown, it gets a null event to break the loop
725 if( st->shutdown )
726 return nullptr;
727 else
728 return &st->wakeupEvent;
729}
730
731
733{
734 bool handled = false;
735
736 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::dispatchInternal - received event: %s" ),
737 aEvent.Format() );
738
739 auto it = m_activeTools.begin();
740
741 // iterate over active tool stack
742 while( it != m_activeTools.end() )
743 {
744 TOOL_STATE* st = m_toolIdIndex[*it];
745 bool increment = true;
746
747 // forward context menu events to the tool that created the menu
748 if( aEvent.IsChoiceMenu() )
749 {
750 if( *it != m_menuOwner )
751 {
752 ++it;
753 continue;
754 }
755 }
756
757 // If we're pendingWait then we had better have a cofunc to process the wait.
758 wxASSERT( !st || !st->pendingWait || st->cofunc );
759
760 // the tool state handler is waiting for events (i.e. called Wait() method)
761 if( st && st->cofunc && st->pendingWait && st->waitEvents.Matches( aEvent ) )
762 {
763 if( !aEvent.FirstResponder() )
764 aEvent.SetFirstResponder( st->theTool );
765
766 // got matching event? clear wait list and wake up the coroutine
767 st->wakeupEvent = aEvent;
768 st->pendingWait = false;
769 st->waitEvents.clear();
770
771 wxLogTrace( kicadTraceToolStack,
772 wxS( "TOOL_MANAGER::dispatchInternal - Waking tool %s for event: %s" ),
773 st->theTool->GetName(), aEvent.Format() );
774
775 setActiveState( st );
776 bool end = !st->cofunc->Resume();
777
778 if( end )
779 {
780 it = finishTool( st );
781 increment = false;
782 }
783
784 // If the tool did not request the event be passed to other tools, we're done
785 if( !st->wakeupEvent.PassEvent() )
786 {
787 wxLogTrace( kicadTraceToolStack,
788 wxS( "TOOL_MANAGER::dispatchInternal - tool %s stopped passing event: %s" ),
789 st->theTool->GetName(), aEvent.Format() );
790
791 return true;
792 }
793 }
794
795 if( increment )
796 ++it;
797 }
798
799 for( const auto& state : m_toolState )
800 {
801 TOOL_STATE* st = state.second;
802 bool finished = false;
803
804 // no state handler in progress - check if there are any transitions (defined by
805 // Go() method that match the event.
806 if( !st->transitions.empty() )
807 {
808 for( const TRANSITION& tr : st->transitions )
809 {
810 if( tr.first.Matches( aEvent ) )
811 {
812 auto func_copy = tr.second;
813
814 if( !aEvent.FirstResponder() )
815 aEvent.SetFirstResponder( st->theTool );
816
817 // if there is already a context, then push it on the stack
818 // and transfer the previous view control settings to the new context
819 if( st->cofunc )
820 {
821 KIGFX::VC_SETTINGS viewControlSettings = st->vcSettings;
822 st->Push();
823 st->vcSettings = std::move( viewControlSettings );
824 }
825
826 st->cofunc = new COROUTINE<int, const TOOL_EVENT&>( std::move( func_copy ) );
827
828 wxLogTrace( kicadTraceToolStack,
829 wxS( "TOOL_MANAGER::dispatchInternal - Running tool %s for event: %s" ),
830 st->theTool->GetName(), aEvent.Format() );
831
832 // got match? Run the handler.
833 setActiveState( st );
834 st->idle = false;
835 st->initialEvent = aEvent;
836 st->cofunc->Call( st->initialEvent );
837 handled = true;
838
839 if( !st->cofunc->Running() )
840 finishTool( st ); // The coroutine has finished immediately?
841
842 // if it is a message, continue processing
843 finished = !( aEvent.Category() == TC_MESSAGE );
844
845 // there is no point in further checking, as transitions got cleared
846 break;
847 }
848 }
849 }
850
851 if( finished )
852 break; // only the first tool gets the event
853 }
854
855 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::dispatchInternal - %s handle event: %s" ),
856 ( handled ? wxS( "Did" ) : wxS( "Did not" ) ), aEvent.Format() );
857
858 return handled;
859}
860
861
863{
864 if( aEvent.Action() == TA_KEY_PRESSED )
865 return m_actionMgr->RunHotKey( aEvent.Modifier() | aEvent.KeyCode() );
866
867 return false;
868}
869
870
872{
873 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::dispatchActivation - Received event: %s" ),
874 aEvent.Format() );
875
876 if( aEvent.IsActivate() )
877 {
878 auto tool = m_toolNameIndex.find( aEvent.getCommandStr() );
879
880 if( tool != m_toolNameIndex.end() )
881 {
882 wxLogTrace( kicadTraceToolStack,
883 wxS( "TOOL_MANAGER::dispatchActivation - Running tool %s for event: %s" ),
884 tool->second->theTool->GetName(), aEvent.Format() );
885
886 runTool( tool->second->theTool );
887 return true;
888 }
889 }
890
891 return false;
892}
893
895{
896 for( TOOL_ID toolId : m_activeTools )
897 {
898 TOOL_STATE* st = m_toolIdIndex[toolId];
899
900 // the tool requested a context menu. The menu is activated on RMB click (CMENU_BUTTON mode)
901 // or immediately (CMENU_NOW) mode. The latter is used for clarification lists.
902 if( st->contextMenuTrigger == CMENU_OFF )
903 continue;
904
905 if( st->contextMenuTrigger == CMENU_BUTTON && !aEvent.IsClick( BUT_RIGHT ) )
906 break;
907
908 if( st->cofunc )
909 {
910 st->pendingWait = true;
912 }
913
914 // Store the menu pointer in case it is changed by the TOOL when handling menu events
915 ACTION_MENU* m = st->contextMenu;
916
917 if( st->contextMenuTrigger == CMENU_NOW )
919
920 // Store the cursor position, so the tools could execute actions
921 // using the point where the user has invoked a context menu
922 if( m_viewControls )
924
925 // Save all tools cursor settings, as they will be overridden
926 for( const std::pair<const TOOL_ID, TOOL_STATE*>& idState : m_toolIdIndex )
927 {
928 TOOL_STATE* s = idState.second;
929 const auto& vc = s->vcSettings;
930
931 if( vc.m_forceCursorPosition )
932 m_cursorSettings[idState.first] = vc.m_forcedPosition;
933 else
934 m_cursorSettings[idState.first] = std::nullopt;
935 }
936
937 if( m_viewControls )
939
940 // Display a copy of menu
941 std::unique_ptr<ACTION_MENU> menu( m->Clone() );
942
943 m_menuOwner = toolId;
944 m_menuActive = true;
945
946 if( wxWindow* frame = dynamic_cast<wxWindow*>( m_frame ) )
947 frame->PopupMenu( menu.get() );
948
949 // Warp the cursor if a menu item was selected
950 if( menu->GetSelected() >= 0 )
951 {
954 }
955 // Otherwise notify the tool of a cancelled menu
956 else
957 {
959 evt.SetHasPosition( false );
960 evt.SetParameter( m );
961 dispatchInternal( evt );
962 }
963
964 // Restore setting in case it was vetoed
966
967 // Notify the tools that menu has been closed
969 evt.SetHasPosition( false );
970 evt.SetParameter( m );
971 dispatchInternal( evt );
972
973 m_menuActive = false;
974 m_menuOwner = -1;
975
976 // Restore cursor settings
977 for( const std::pair<const TOOL_ID, std::optional<VECTOR2D>>& cursorSetting : m_cursorSettings )
978 {
979 auto it = m_toolIdIndex.find( cursorSetting.first );
980 wxASSERT( it != m_toolIdIndex.end() );
981
982 if( it == m_toolIdIndex.end() )
983 continue;
984
985 KIGFX::VC_SETTINGS& vc = it->second->vcSettings;
986 vc.m_forceCursorPosition = (bool) cursorSetting.second;
987 vc.m_forcedPosition = cursorSetting.second ? *cursorSetting.second : VECTOR2D( 0, 0 );
988 }
989
990 m_cursorSettings.clear();
991 break;
992 }
993}
994
995
996TOOL_MANAGER::ID_LIST::iterator TOOL_MANAGER::finishTool( TOOL_STATE* aState )
997{
998 auto it = std::find( m_activeTools.begin(), m_activeTools.end(), aState->theTool->GetId() );
999
1000 if( !aState->Pop() )
1001 {
1002 // Deactivate the tool if there are no other contexts saved on the stack
1003 if( it != m_activeTools.end() )
1004 it = m_activeTools.erase( it );
1005
1006 aState->idle = true;
1007 }
1008
1009 if( aState == m_activeState )
1010 setActiveState( nullptr );
1011
1012 return it;
1013}
1014
1015
1017{
1018 // Once the tool manager is shutting down, don't start
1019 // activating more tools
1020 if( m_shuttingDown )
1021 return true;
1022
1023 bool handled = processEvent( aEvent );
1024
1025 TOOL_STATE* activeTool = GetCurrentToolState();
1026
1027 if( activeTool )
1028 setActiveState( activeTool );
1029
1030 if( m_view && m_view->IsDirty() )
1031 {
1032#if defined( __WXMAC__ )
1033 wxTheApp->ProcessPendingEvents(); // required for updating brightening behind a popup menu
1034#endif
1035 }
1036
1037 UpdateUI( aEvent );
1038
1039 return handled;
1040}
1041
1042
1044 CONTEXT_MENU_TRIGGER aTrigger )
1045{
1046 TOOL_STATE* st = m_toolState[aTool];
1047
1048 st->contextMenu = aMenu;
1049 st->contextMenuTrigger = aTrigger;
1050}
1051
1052
1054{
1055 if( TOOL_STATE* active = GetCurrentToolState() )
1056 return active->vcSettings;
1057
1058 return m_viewControls->GetSettings();
1059}
1060
1061
1062TOOL_ID TOOL_MANAGER::MakeToolId( const std::string& aToolName )
1063{
1064 static int currentId;
1065
1066 return currentId++;
1067}
1068
1069
1071 KIGFX::VIEW_CONTROLS* aViewControls,
1072 APP_SETTINGS_BASE* aSettings, TOOLS_HOLDER* aFrame )
1073{
1074 m_model = aModel;
1075 m_view = aView;
1076 m_viewControls = aViewControls;
1077 m_frame = aFrame;
1078 m_settings = aSettings;
1079}
1080
1081
1083{
1084 if( !isRegistered( aTool ) )
1085 return false;
1086
1087 // Just check if the tool is on the active tools stack
1088 return alg::contains( m_activeTools, aTool->GetId() );
1089}
1090
1091
1093{
1095
1096 if( m_menuActive )
1097 {
1098 // Context menu is active, so the cursor settings are overridden (see DispatchContextMenu())
1099 auto it = m_cursorSettings.find( aState->theTool->GetId() );
1100
1101 if( it != m_cursorSettings.end() )
1102 {
1104
1105 // Tool has overridden the cursor position, so store the new settings
1107 {
1108 if( !curr.m_forceCursorPosition )
1109 it->second = std::nullopt;
1110 else
1111 it->second = curr.m_forcedPosition;
1112 }
1113 else
1114 {
1115 std::optional<VECTOR2D> cursor = it->second;
1116
1117 if( cursor )
1118 {
1119 aState->vcSettings.m_forceCursorPosition = true;
1121 }
1122 else
1123 {
1124 aState->vcSettings.m_forceCursorPosition = false;
1125 }
1126 }
1127 }
1128 }
1129}
1130
1131
1133{
1135}
1136
1137
1139{
1140 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::processEvent - %s" ), aEvent.Format() );
1141
1142 // First try to dispatch the action associated with the event if it is a key press event
1143 bool handled = DispatchHotKey( aEvent );
1144
1145 if( !handled )
1146 {
1147 TOOL_EVENT mod_event( aEvent );
1148
1149 // Only immediate actions get the position. Otherwise clear for tool activation
1150 if( GetToolHolder() && !GetToolHolder()->GetDoImmediateActions() )
1151 {
1152 // An tool-selection-event has no position
1153 if( !mod_event.getCommandStr().empty()
1154 && mod_event.getCommandStr() != GetToolHolder()->CurrentToolName()
1155 && !mod_event.ForceImmediate() )
1156 {
1157 mod_event.SetHasPosition( false );
1158 }
1159 }
1160
1161 // If the event is not handled through a hotkey activation, pass it to the currently
1162 // running tool loops
1163 handled |= dispatchInternal( mod_event );
1164 handled |= dispatchActivation( mod_event );
1165
1166 // Open the context menu if requested by a tool
1167 DispatchContextMenu( mod_event );
1168
1169 // Dispatch any remaining events in the event queue
1170 while( !m_eventQueue.empty() )
1171 {
1172 TOOL_EVENT event = m_eventQueue.front();
1173 m_eventQueue.pop_front();
1174 processEvent( event );
1175 }
1176 }
1177
1178 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::processEvent - %s handle event: %s" ),
1179 ( handled ? "Did" : "Did not" ), aEvent.Format() );
1180
1181 return handled;
1182}
1183
1184
1186{
1189
1190 m_activeState = aState;
1191
1193 applyViewControls( aState );
1194}
1195
1196
1198{
1199 auto it = m_toolIdIndex.find( aId );
1200
1201 if( it == m_toolIdIndex.end() )
1202 return false;
1203
1204 return !it->second->idle;
1205}
1206
1207
1209{
1210 EDA_BASE_FRAME* frame = dynamic_cast<EDA_BASE_FRAME*>( GetToolHolder() );
1211
1212 if( frame )
1213 frame->UpdateStatusBar();
1214}
Manage TOOL_ACTION objects.
bool RunHotKey(int aHotKey) const
Run an action associated with a hotkey (if there is one available).
TOOL_ACTION * FindAction(const std::string &aActionName) const
Find an action with a given name (if there is one available).
int GetHotKey(const TOOL_ACTION &aAction) const
Return the hot key associated with a given action or 0 if there is none.
void UpdateHotKeys(bool aFullUpdate)
Optionally read the hotkey config files and then rebuilds the internal hotkey maps.
Defines the structure of a menu based on ACTIONs.
Definition: action_menu.h:49
ACTION_MENU * Clone() const
Create a deep, recursive copy of this ACTION_MENU.
APP_SETTINGS_BASE is a settings class that should be derived for each standalone KiCad application.
Definition: app_settings.h:92
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition: commit.h:74
Implement a coroutine.
Definition: coroutine.h:84
bool Call(ArgType aArg)
Start execution of a coroutine, passing args as its arguments.
Definition: coroutine.h:272
void KiYield()
Stop execution of the coroutine and returns control to the caller.
Definition: coroutine.h:235
bool Resume()
Resume execution of a previously yielded coroutine.
Definition: coroutine.h:318
bool Running() const
Definition: coroutine.h:367
void RunMainStack(std::function< void()> func)
Run a functor inside the application main stack context.
Definition: coroutine.h:258
The base frame for deriving all KiCad main window classes.
virtual void UpdateStatusBar()
Update the status bar information.
A base class for most all the KiCad significant classes used in schematics and boards.
Definition: eda_item.h:89
An interface for classes handling user events controlling the view behavior such as zooming,...
virtual void ForceCursorPosition(bool aEnabled, const VECTOR2D &aPosition=VECTOR2D(0, 0))
Place the cursor immediately at a given point.
virtual void WarpMouseCursor(const VECTOR2D &aPosition, bool aWorldCoordinates=false, bool aWarpView=false)=0
If enabled (.
VECTOR2D GetCursorPosition() const
Return the current cursor position in world coordinates.
virtual VECTOR2D GetMousePosition(bool aWorldCoordinates=true) const =0
Return the current mouse pointer position.
void ApplySettings(const VC_SETTINGS &aSettings)
Load new settings from program common settings.
const VC_SETTINGS & GetSettings() const
Apply VIEW_CONTROLS settings from an object.
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition: view.h:68
bool IsDirty() const
Return true if any of the VIEW layers needs to be refreshened.
Definition: view.h:597
Represent a single user action.
Definition: tool_action.h:269
TOOL_EVENT MakeEvent() const
Return the event associated with the action (i.e.
Base abstract interface for all kinds of tools.
Definition: tool_base.h:66
virtual void Reset(RESET_REASON aReason)=0
Bring the tool to a known, initial state.
virtual bool Init()
Init() is called once upon a registration of the tool.
Definition: tool_base.h:92
const std::string & GetName() const
Return the name of the tool.
Definition: tool_base.h:136
TOOL_TYPE GetType() const
Return the type of the tool.
Definition: tool_base.h:111
RESET_REASON
Determine the reason of reset for a tool.
Definition: tool_base.h:78
@ REDRAW
Full drawing refresh.
Definition: tool_base.h:83
@ RUN
Tool is invoked after being inactive.
Definition: tool_base.h:79
TOOL_ID GetId() const
Return the unique identifier of the tool.
Definition: tool_base.h:123
void attachManager(TOOL_MANAGER *aManager)
Set the TOOL_MANAGER the tool will belong to.
Definition: tool_base.cpp:60
A list of TOOL_EVENTs, with overloaded || operators allowing for concatenating TOOL_EVENTs with littl...
Definition: tool_event.h:636
OPT_TOOL_EVENT Matches(const TOOL_EVENT &aEvent) const
Definition: tool_event.h:676
Generic, UI-independent tool event.
Definition: tool_event.h:167
bool PassEvent() const
Definition: tool_event.h:251
TOOL_ACTIONS Action() const
These give a tool a method of informing the TOOL_MANAGER that a particular event should be passed on ...
Definition: tool_event.h:246
void SetMousePosition(const VECTOR2D &aP)
Definition: tool_event.h:525
int KeyCode() const
Definition: tool_event.h:368
TOOL_BASE * FirstResponder() const
Definition: tool_event.h:264
bool IsActivate() const
Definition: tool_event.h:337
void SetFirstResponder(TOOL_BASE *aTool)
Controls whether the tool is first being pushed to the stack or being reactivated after a pause.
Definition: tool_event.h:265
bool IsSimulator() const
Indicate if the event is from the simulator.
Definition: tool_event.cpp:257
void SetParameter(T aParam)
Set a non-standard parameter assigned to the event.
Definition: tool_event.h:515
bool ForceImmediate() const
Definition: tool_event.h:261
bool IsClick(int aButtonMask=BUT_ANY) const
Definition: tool_event.cpp:209
TOOL_EVENT_CATEGORY Category() const
Returns more specific information about the type of an event.
Definition: tool_event.h:243
int Modifier(int aMask=MD_MODIFIER_MASK) const
Definition: tool_event.h:358
void SetHasPosition(bool aHasPosition)
Returns if the action associated with this event should be treated as immediate regardless of the cur...
Definition: tool_event.h:257
const std::string & getCommandStr() const
Definition: tool_event.h:545
bool IsChoiceMenu() const
Definition: tool_event.h:347
const std::string Format() const
Return information about event in form of a human-readable string.
Definition: tool_event.cpp:97
void applyViewControls(const TOOL_STATE *aState)
Apply #VIEW_CONTROLS settings stored in a #TOOL_STATE object.
int GetPriority(int aToolId) const
Return priority of a given tool.
bool ProcessEvent(const TOOL_EVENT &aEvent)
Propagate an event to tools that requested events of matching type(s).
TOOL_STATE * m_activeState
True if the tool manager is shutting down (don't process additional events)
Definition: tool_manager.h:676
void UpdateUI(const TOOL_EVENT &aEvent)
Update the status bar and synchronizes toolbars.
std::map< TOOL_ID, std::optional< VECTOR2D > > m_cursorSettings
Definition: tool_manager.h:653
void PostEvent(const TOOL_EVENT &aEvent)
Put an event to the event queue to be processed at the end of event processing cycle.
void ScheduleNextState(TOOL_BASE *aTool, TOOL_STATE_FUNC &aHandler, const TOOL_EVENT_LIST &aConditions)
Define a state transition.
std::map< const char *, TOOL_BASE * > m_toolTypes
Stack of the active tools.
Definition: tool_manager.h:644
bool isRegistered(TOOL_BASE *aTool) const
Return information about a tool registration status.
Definition: tool_manager.h:590
APP_SETTINGS_BASE * m_settings
Queue that stores events to be processed at the end of the event processing cycle.
Definition: tool_manager.h:659
TOOL_STATE * GetCurrentToolState() const
Return the #TOOL_STATE object representing the state of the active tool.
Definition: tool_manager.h:430
VECTOR2D GetCursorPosition() const
std::list< TOOL_EVENT > m_eventQueue
Right click context menu position.
Definition: tool_manager.h:662
std::pair< TOOL_EVENT_LIST, TOOL_STATE_FUNC > TRANSITION
Definition: tool_manager.h:535
void setActiveState(TOOL_STATE *aState)
Save the previous active state and sets a new one.
void DeactivateTool()
Deactivate the currently active tool.
bool dispatchInternal(TOOL_EVENT &aEvent)
Pass an event at first to the active tools, then to all others.
void PrimeTool(const VECTOR2D &aPosition)
"Prime" a tool by sending a cursor left-click event with the mouse position set to the passed in posi...
bool runTool(TOOL_BASE *aTool)
Make a tool active, so it can receive events and react to them.
bool InvokeTool(TOOL_ID aToolId)
Call a tool by sending a tool activation event to tool of given ID.
NAME_STATE_MAP m_toolNameIndex
Index of the registered tools current states, associated by tools' ID numbers.
Definition: tool_manager.h:638
TOOLS_HOLDER * m_frame
Definition: tool_manager.h:658
void CancelTool()
Send a cancel event to the tool currently at the top of the tool stack.
bool m_warpMouseAfterContextMenu
Flag indicating whether a context menu is currently displayed.
Definition: tool_manager.h:667
KIGFX::VIEW_CONTROLS * m_viewControls
Definition: tool_manager.h:657
bool doRunAction(const TOOL_ACTION &aAction, bool aNow, const std::any &aParam, COMMIT *aCommit)
Helper function to actually run an action.
ACTION_MANAGER * m_actionMgr
Original cursor position, if overridden by the context menu handler.
Definition: tool_manager.h:650
const KIGFX::VC_SETTINGS & GetCurrentToolVC() const
Return the view controls settings for the current tool or the general settings if there is no active ...
void RunMainStack(TOOL_BASE *aTool, std::function< void()> aFunc)
TOOLS_HOLDER * GetToolHolder() const
Definition: tool_manager.h:402
VECTOR2D GetMousePosition() const
bool processEvent(const TOOL_EVENT &aEvent)
Main function for event processing.
std::list< TOOL_ID > ID_LIST
Definition: tool_manager.h:75
ID_LIST::iterator finishTool(TOOL_STATE *aState)
Deactivate a tool and does the necessary clean up.
bool dispatchActivation(const TOOL_EVENT &aEvent)
Check if it is a valid activation event and invokes a proper tool.
ID_STATE_MAP m_toolIdIndex
Index of the registered tools to easily lookup by their type.
Definition: tool_manager.h:641
TOOL_ID m_menuOwner
Pointer to the state object corresponding to the currently executed tool.
Definition: tool_manager.h:673
KIGFX::VIEW * m_view
Definition: tool_manager.h:656
void ClearTransitions(TOOL_BASE *aTool)
Clear the state transition map for a tool.
bool m_shuttingDown
Definition: tool_manager.h:679
void saveViewControls(TOOL_STATE *aState)
Save the #VIEW_CONTROLS settings to the tool state object.
int GetHotKey(const TOOL_ACTION &aAction) const
bool m_menuActive
Tool currently displaying a popup menu. It is negative when there is no menu displayed.
Definition: tool_manager.h:670
TOOL_STATE_MAP m_toolState
Index of the registered tools current states, associated by tools' names.
Definition: tool_manager.h:635
void ShutdownTool(TOOL_BASE *aTool)
Shutdown the specified tool by waking it up with a null event to terminate the processing loop.
ID_LIST m_activeTools
Instance of ACTION_MANAGER that handles TOOL_ACTIONs.
Definition: tool_manager.h:647
void ResetTools(TOOL_BASE::RESET_REASON aReason)
Reset all tools (i.e.
EDA_ITEM * m_model
Definition: tool_manager.h:655
bool DispatchHotKey(const TOOL_EVENT &aEvent)
Handle specific events, that are intended for TOOL_MANAGER rather than tools.
static TOOL_ID MakeToolId(const std::string &aToolName)
Generates a unique ID from for a tool with given name.
bool invokeTool(TOOL_BASE *aTool)
Invoke a tool by sending a proper event (in contrary to runTool, which makes the tool run for real).
void DispatchContextMenu(const TOOL_EVENT &aEvent)
Handle context menu related events.
std::vector< TOOL_BASE * > m_toolOrder
< List of tools in the order they were registered
Definition: tool_manager.h:632
TOOL_BASE * FindTool(int aId) const
Search for a tool with given ID.
void ScheduleContextMenu(TOOL_BASE *aTool, ACTION_MENU *aMenu, CONTEXT_MENU_TRIGGER aTrigger)
Set behavior of the tool's context popup menu.
TOOL_EVENT * ScheduleWait(TOOL_BASE *aTool, const TOOL_EVENT_LIST &aConditions)
Pause execution of a given tool until one or more events matching aConditions arrives.
bool IsToolActive(TOOL_ID aId) const
Return true if a tool with given id is active (executing)
bool isActive(TOOL_BASE *aTool) const
Return information about a tool activation status.
void RegisterTool(TOOL_BASE *aTool)
Add a tool to the manager set and sets it up.
void SetEnvironment(EDA_ITEM *aModel, KIGFX::VIEW *aView, KIGFX::VIEW_CONTROLS *aViewControls, APP_SETTINGS_BASE *aSettings, TOOLS_HOLDER *aFrame)
Set the work environment (model, view, view controls and the parent window).
void InitTools()
Initializes all registered tools.
VECTOR2D m_menuCursor
Definition: tool_manager.h:665
void ShutdownAllTools()
Shutdown all tools with a currently registered event loop in this tool manager by waking them up with...
Base window classes and related definitions.
const wxChar *const kicadTraceToolStack
Flag to enable tracing of the tool handling stack.
wxPoint GetMousePosition()
Returns the mouse position in screen coordinates.
Definition: wxgtk/ui.cpp:620
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition: kicad_algo.h:100
Structure to keep VIEW_CONTROLS settings for easy store/restore operations.
Definition: view_controls.h:43
VECTOR2D m_forcedPosition
Is the forced cursor position enabled.
Definition: view_controls.h:56
void Reset()
Flag determining the cursor visibility.
bool m_forceCursorPosition
Should the cursor be locked within the parent window area.
Definition: view_controls.h:59
Struct describing the current execution state of a TOOL.
bool operator!=(const TOOL_MANAGER::TOOL_STATE &aRhs) const
bool Pop()
Restore state of the tool from stack.
bool pendingWait
Flag defining if the tool is waiting for any event (i.e.
bool pendingContextMenu
Is there a context menu being displayed.
void Push()
Store the current state of the tool on stack.
CONTEXT_MENU_TRIGGER contextMenuTrigger
Defines when the context menu is opened.
TOOL_EVENT initialEvent
The first event that triggered activation of the tool.
KIGFX::VC_SETTINGS vcSettings
VIEW_CONTROLS settings to preserve settings when the tools are switched.
TOOL_STATE(const TOOL_STATE &aState)
TOOL_STATE(TOOL_BASE *aTool)
ACTION_MENU * contextMenu
Context menu currently used by the tool.
bool idle
Is the tool active (pending execution) or disabled at the moment.
std::vector< TRANSITION > transitions
List of possible transitions (ie.
TOOL_EVENT_LIST waitEvents
List of events the tool is currently waiting for.
COROUTINE< int, const TOOL_EVENT & > * cofunc
Tool execution context.
bool shutdown
Should the tool shutdown during next execution.
std::stack< std::unique_ptr< TOOL_STATE > > stateStack
< Stack preserving previous states of a TOOL.
TOOL_BASE * theTool
The tool itself.
TOOL_EVENT wakeupEvent
The event that triggered the execution/wakeup of the tool after Wait() call.
TOOL_STATE & operator=(const TOOL_STATE &aState)
bool operator==(const TOOL_MANAGER::TOOL_STATE &aRhs) const
std::function< int(const TOOL_EVENT &)> TOOL_STATE_FUNC
Definition: tool_base.h:58
int TOOL_ID
Unique identifier for tools.
Definition: tool_base.h:56
@ INTERACTIVE
Tool that interacts with the user.
Definition: tool_base.h:49
CONTEXT_MENU_TRIGGER
Defines when a context menu is opened.
Definition: tool_event.h:150
@ CMENU_NOW
Definition: tool_event.h:152
@ CMENU_OFF
Definition: tool_event.h:153
@ CMENU_BUTTON
Definition: tool_event.h:151
@ TA_ANY
Definition: tool_event.h:125
@ TA_CHOICE_MENU_CHOICE
Definition: tool_event.h:97
@ TA_ACTIVATE
Definition: tool_event.h:114
@ TA_CHOICE_MENU_CLOSED
Definition: tool_event.h:100
@ TA_PRIME
Definition: tool_event.h:123
@ TA_KEY_PRESSED
Definition: tool_event.h:75
@ TA_CANCEL_TOOL
Definition: tool_event.h:89
@ TC_ANY
Definition: tool_event.h:59
@ TC_COMMAND
Definition: tool_event.h:56
@ TC_MOUSE
Definition: tool_event.h:54
@ TC_MESSAGE
Definition: tool_event.h:57
@ STS_CANCELLED
Definition: tool_event.h:160
@ STS_FINISHED
Definition: tool_event.h:159
@ STS_RUNNING
Definition: tool_event.h:158
@ BUT_LEFT
Definition: tool_event.h:131
@ BUT_RIGHT
Definition: tool_event.h:132
wxLogTrace helper definitions.
VECTOR2D ToVECTOR2D(const wxPoint &aPoint)
Definition: vector2wx.h:40