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 The 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#include <app_monitor.h>
34
35#include <wx/event.h>
36#include <wx/evtloop.h>
37#include <wx/clipbrd.h>
38#include <wx/app.h>
39
40#include <math/vector2wx.h>
41
42#include <view/view.h>
43#include <view/view_controls.h>
44#include <eda_base_frame.h>
45#include <tool/tool_base.h>
47#include <tool/tool_manager.h>
48#include <tool/action_menu.h>
49#include <tool/coroutine.h>
50#include <tool/action_manager.h>
51
53
56{
58 theTool( aTool )
59 {
60 clear();
61 }
62
63 TOOL_STATE( const TOOL_STATE& aState )
64 {
65 theTool = aState.theTool;
66 idle = aState.idle;
67 shutdown = aState.shutdown;
68 pendingWait = aState.pendingWait;
70 contextMenu = aState.contextMenu;
72 cofunc = aState.cofunc;
74 wakeupEvent = aState.wakeupEvent;
75 waitEvents = aState.waitEvents;
76 transitions = aState.transitions;
77 vcSettings = aState.vcSettings;
78 // do not copy stateStack
79 }
80
82 {
83 wxASSERT_MSG( stateStack.empty(), wxT( "StateStack not empty!" ) );
84 }
85
88
90 bool idle;
91
94
98
101
104
107
110
113
116
119
122 std::vector<TRANSITION> transitions;
123
126
128 {
129 theTool = aState.theTool;
130 idle = aState.idle;
131 shutdown = aState.shutdown;
132 pendingWait = aState.pendingWait;
134 contextMenu = aState.contextMenu;
136 cofunc = aState.cofunc;
137 initialEvent = aState.initialEvent;
138 wakeupEvent = aState.wakeupEvent;
139 waitEvents = aState.waitEvents;
140 transitions = aState.transitions;
141 vcSettings = aState.vcSettings;
142
143 // do not copy stateStack
144 return *this;
145 }
146
147 bool operator==( const TOOL_MANAGER::TOOL_STATE& aRhs ) const
148 {
149 return aRhs.theTool == theTool;
150 }
151
152 bool operator!=( const TOOL_MANAGER::TOOL_STATE& aRhs ) const
153 {
154 return aRhs.theTool != theTool;
155 }
156
161 void Push()
162 {
163 auto state = std::make_unique<TOOL_STATE>( *this );
164 stateStack.push( std::move( state ) );
165 clear();
166 }
167
174 bool Pop()
175 {
176 delete cofunc;
177
178 if( !stateStack.empty() )
179 {
180 *this = *stateStack.top().get();
181 stateStack.pop();
182 return true;
183 }
184
186 return false;
187 }
188
189private:
191 std::stack<std::unique_ptr<TOOL_STATE>> stateStack;
192
195 {
196 cofunc = nullptr;
197 shutdown = false;
198 pendingWait = false;
199 pendingContextMenu = false;
200 contextMenu = nullptr;
202 }
203
205 void clear()
206 {
207 idle = true;
209 vcSettings.Reset();
210 transitions.clear();
211 }
212};
213
214
216 m_model( nullptr ),
217 m_view( nullptr ),
218 m_viewControls( nullptr ),
219 m_frame( nullptr ),
220 m_settings( nullptr ),
222 m_menuActive( false ),
223 m_menuOwner( -1 ),
224 m_activeState( nullptr ),
225 m_shuttingDown( false )
226{
227 m_actionMgr = new ACTION_MANAGER( this );
228}
229
230
232{
233 std::map<TOOL_BASE*, TOOL_STATE*>::iterator it, it_end;
234
235 for( it = m_toolState.begin(), it_end = m_toolState.end(); it != it_end; ++it )
236 {
237 delete it->second->cofunc; // delete cofunction
238 delete it->second; // delete TOOL_STATE
239 delete it->first; // delete the tool itself
240 }
241
242 delete m_actionMgr;
243}
244
245
247{
248 wxASSERT_MSG( m_toolNameIndex.find( aTool->GetName() ) == m_toolNameIndex.end(),
249 wxT( "Adding two tools with the same name may result in unexpected behavior.") );
250 wxASSERT_MSG( m_toolIdIndex.find( aTool->GetId() ) == m_toolIdIndex.end(),
251 wxT( "Adding two tools with the same ID may result in unexpected behavior.") );
252 wxASSERT_MSG( m_toolTypes.find( typeid( *aTool ).name() ) == m_toolTypes.end(),
253 wxT( "Adding two tools of the same type may result in unexpected behavior.") );
254
255 wxLogTrace( kicadTraceToolStack,
256 wxS( "TOOL_MANAGER::RegisterTool: Registering tool %s with ID %d" ),
257 aTool->GetName(), aTool->GetId() );
258
259 m_toolOrder.push_back( aTool );
260
261 TOOL_STATE* st = new TOOL_STATE( aTool );
262
263 m_toolState[aTool] = st;
264 m_toolNameIndex[aTool->GetName()] = st;
265 m_toolIdIndex[aTool->GetId()] = st;
266 m_toolTypes[typeid( *aTool ).name()] = st->theTool;
267
268 aTool->attachManager( this );
269}
270
271
273{
274 TOOL_BASE* tool = FindTool( aToolId );
275
276 if( tool && tool->GetType() == INTERACTIVE )
277 return invokeTool( tool );
278
279 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::InvokeTool - no tool with ID %d" ),
280 aToolId );
281
282 return false; // there is no tool with the given id
283}
284
285
286bool TOOL_MANAGER::InvokeTool( const std::string& aToolName )
287{
288 TOOL_BASE* tool = FindTool( aToolName );
289
290 if( tool && tool->GetType() == INTERACTIVE )
291 return invokeTool( tool );
292
293 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::InvokeTool - no tool with name %s" ),
294 aToolName );
295
296 return false; // there is no tool with the given name
297}
298
299
300bool TOOL_MANAGER::doRunAction( const std::string& aActionName, bool aNow, const ki::any& aParam,
301 COMMIT* aCommit )
302{
303 TOOL_ACTION* action = m_actionMgr->FindAction( aActionName );
304
305 if( !action )
306 {
307 wxASSERT_MSG( false, wxString::Format( "Could not find action %s.", aActionName ) );
308 return false;
309 }
310
311 doRunAction( *action, aNow, aParam, aCommit );
312
313 return true;
314}
315
316
318{
319 if( m_viewControls )
320 return m_viewControls->GetMousePosition();
321 else
323}
324
325
327{
328 if( m_viewControls )
329 return m_viewControls->GetCursorPosition();
330 else
332}
333
334
335bool TOOL_MANAGER::doRunAction( const TOOL_ACTION& aAction, bool aNow, const ki::any& aParam,
336 COMMIT* aCommit, bool aFromAPI )
337{
338 if( m_shuttingDown )
339 return true;
340
341 bool retVal = false;
342 TOOL_EVENT event = aAction.MakeEvent();
343
344 if( event.Category() == TC_COMMAND )
346
347 // Allow to override the action parameter
348 if( aParam.has_value() )
349 event.SetParameter( aParam );
350
351 if( aNow )
352 {
353 TOOL_STATE* current = m_activeState;
354
355 // An event with a commit must be run synchronously
356 if( aCommit )
357 {
358 // We initialize the SYNCHRONOUS state to finished so that tools that don't have an
359 // event loop won't hang if someone forgets to set the state.
360 std::atomic<SYNCRONOUS_TOOL_STATE> synchronousControl = STS_FINISHED;
361
362 event.SetSynchronous( &synchronousControl );
363 event.SetCommit( aCommit );
364
365 processEvent( event );
366
367 while( synchronousControl == STS_RUNNING )
368 {
369 wxYield(); // Needed to honor mouse (and other) events during editing
370 wxMilliSleep( 1 ); // Needed to avoid 100% use of one cpu core.
371 // The sleeping time must be must be small to avoid
372 // noticeable lag in mouse and editing events
373 // (1 to 5 ms is a good value)
374 }
375
376 retVal = synchronousControl != STS_CANCELLED;
377 }
378 else
379 {
380 retVal = processEvent( event );
381 }
382
383 setActiveState( current );
384 UpdateUI( event );
385 }
386 else
387 {
388 // It is really dangerous to pass a commit (whose lifetime we can't guarantee) to
389 // deferred event processing. There is a possibility that user actions will get run
390 // in between, which might either affect the lifetime of the commit or push or pop
391 // other commits. However, we don't currently have a better solution for the API.
392 if( aCommit )
393 {
394 wxASSERT_MSG( aFromAPI, wxT( "Deferred actions have no way of guaranteeing the "
395 "lifetime of the COMMIT object" ) );
396 event.SetCommit( aCommit );
397 }
398
399 PostEvent( event );
400 }
401
402 return retVal;
403}
404
405
407{
409
410 processEvent( evt );
411}
412
413
414void TOOL_MANAGER::PrimeTool( const VECTOR2D& aPosition )
415{
416 int modifiers = 0;
417
418 /*
419 * Don't include any modifiers. They're part of the hotkey, not part of the resulting
420 * click.
421 *
422 * modifiers |= wxGetKeyState( WXK_SHIFT ) ? MD_SHIFT : 0;
423 * modifiers |= wxGetKeyState( WXK_CONTROL ) ? MD_CTRL : 0;
424 * modifiers |= wxGetKeyState( WXK_ALT ) ? MD_ALT : 0;
425 */
426
427 TOOL_EVENT evt( TC_MOUSE, TA_PRIME, BUT_LEFT | modifiers );
428 evt.SetMousePosition( aPosition );
429
430 PostEvent( evt );
431}
432
433
435{
436 // Horrific hack, but it's a crash bug. Don't let inter-frame commands stack up
437 // waiting to be processed.
438 if( aEvent.IsSimulator() && m_eventQueue.size() > 0 && m_eventQueue.back().IsSimulator() )
439 m_eventQueue.pop_back();
440
441 m_eventQueue.push_back( aEvent );
442}
443
444
445int TOOL_MANAGER::GetHotKey( const TOOL_ACTION& aAction ) const
446{
447 return m_actionMgr->GetHotKey( aAction );
448}
449
450
452{
453 wxASSERT( aTool != nullptr );
454
455 TOOL_EVENT evt( TC_COMMAND, TA_ACTIVATE, aTool->GetName() );
457 processEvent( evt );
458
459 if( TOOL_STATE* active = GetCurrentToolState() )
460 setActiveState( active );
461
462 return true;
463}
464
465
467{
468 wxASSERT( aTool != nullptr );
469
470 wxString msg = wxString::Format( wxS( "TOOL_MANAGER::runTool - running tool %s" ), aTool->GetName() );
471 APP_MONITOR::AddTransactionBreadcrumb( msg, "tool.run" );
472
473 if( !isRegistered( aTool ) )
474 {
475 wxASSERT_MSG( false, wxT( "You cannot run unregistered tools" ) );
476 return false;
477 }
478
479 TOOL_ID id = aTool->GetId();
480
481 wxLogTrace( kicadTraceToolStack, msg,
482 aTool->GetName() );
483
484 if( aTool->GetType() == INTERACTIVE )
485 static_cast<TOOL_INTERACTIVE*>( aTool )->resetTransitions();
486
487 // If the tool is already active, bring it to the top of the active tools stack
488 if( isActive( aTool ) && m_activeTools.size() > 1 )
489 {
490 auto it = std::find( m_activeTools.begin(), m_activeTools.end(), id );
491
492 if( it != m_activeTools.end() )
493 {
494 if( it != m_activeTools.begin() )
495 {
496 m_activeTools.erase( it );
497 m_activeTools.push_front( id );
498 }
499
500 return false;
501 }
502 }
503
506
507 // Add the tool on the front of the processing queue (it gets events first)
508 m_activeTools.push_front( id );
509
510 return true;
511}
512
513
515{
516 m_shuttingDown = true;
517
518 // Create a temporary list of tools to iterate over since when the tools shutdown
519 // they remove themselves from the list automatically (invalidating the iterator)
520 ID_LIST tmpList = m_activeTools;
521
522 // Make sure each tool knows that it is shutting down, so that loops get shut down
523 // at the dispatcher
524 for( auto id : tmpList )
525 {
526 if( m_toolIdIndex.count( id ) == 0 )
527 continue;
528
529 m_toolIdIndex[id]->shutdown = true;
530 }
531
532 for( auto id : tmpList )
533 {
534 ShutdownTool( id );
535 }
536}
537
538
540{
541 TOOL_BASE* tool = FindTool( aToolId );
542
543 if( tool && tool->GetType() == INTERACTIVE )
544 ShutdownTool( tool );
545
546 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::ShutdownTool - no tool with ID %d" ),
547 aToolId );
548}
549
550
551void TOOL_MANAGER::ShutdownTool( const std::string& aToolName )
552{
553 TOOL_BASE* tool = FindTool( aToolName );
554
555 if( tool && tool->GetType() == INTERACTIVE )
556 ShutdownTool( tool );
557
558 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::ShutdownTool - no tool with name %s" ),
559 aToolName );
560}
561
562
564{
565 wxASSERT( aTool != nullptr );
566
567 TOOL_ID id = aTool->GetId();
568
569 if( isActive( aTool ) )
570 {
571 TOOL_MANAGER::ID_LIST::iterator it = std::find( m_activeTools.begin(),
572 m_activeTools.end(), id );
573
574 TOOL_STATE* st = m_toolIdIndex[*it];
575
576 // the tool state handler is waiting for events (i.e. called Wait() method)
577 if( st && st->pendingWait )
578 {
579 // Wake up the tool and tell it to shutdown
580 st->shutdown = true;
581 st->pendingWait = false;
582 st->waitEvents.clear();
583
584 if( st->cofunc )
585 {
586 wxLogTrace( kicadTraceToolStack,
587 wxS( "TOOL_MANAGER::ShutdownTool - Shutting down tool %s" ),
588 st->theTool->GetName() );
589
590 setActiveState( st );
591 bool end = !st->cofunc->Resume();
592
593 if( end )
594 finishTool( st );
595 }
596 }
597 }
598}
599
600
602{
603 std::map<TOOL_ID, TOOL_STATE*>::const_iterator it = m_toolIdIndex.find( aId );
604
605 if( it != m_toolIdIndex.end() )
606 return it->second->theTool;
607
608 return nullptr;
609}
610
611
612TOOL_BASE* TOOL_MANAGER::FindTool( const std::string& aName ) const
613{
614 std::map<std::string, TOOL_STATE*>::const_iterator it = m_toolNameIndex.find( aName );
615
616 if( it != m_toolNameIndex.end() )
617 return it->second->theTool;
618
619 return nullptr;
620}
621
622
624{
625 // Deactivate the active tool, but do not run anything new
627 processEvent( evt );
628}
629
630
632{
633 if( aReason != TOOL_BASE::REDRAW )
635
636 for( auto& state : m_toolState )
637 {
638 TOOL_BASE* tool = state.first;
639
640 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::ResetTools: Resetting tool '%s'" ),
641 tool->GetName() );
642
643 setActiveState( state.second );
644 tool->Reset( aReason );
645
646 if( tool->GetType() == INTERACTIVE )
647 static_cast<TOOL_INTERACTIVE*>( tool )->resetTransitions();
648 }
649}
650
651
653{
654 for( auto it = m_toolOrder.begin(); it != m_toolOrder.end(); /* iter inside */ )
655 {
656 TOOL_BASE* tool = *it;
657 wxASSERT( m_toolState.count( tool ) );
658 TOOL_STATE* state = m_toolState[tool];
659 setActiveState( state );
660 ++it; // keep the iterator valid if the element is going to be erased
661
662 if( !tool->Init() )
663 {
664 wxLogTrace( kicadTraceToolStack,
665 wxS( "TOOL_MANAGER initialization of tool '%s' failed" ),
666 tool->GetName() );
667
668 // Unregister the tool
669 setActiveState( nullptr );
670 m_toolState.erase( tool );
671 m_toolNameIndex.erase( tool->GetName() );
672 m_toolIdIndex.erase( tool->GetId() );
673 m_toolTypes.erase( typeid( *tool ).name() );
674
675 delete state;
676 delete tool;
677 }
678 }
679
680 m_actionMgr->UpdateHotKeys( true );
681
683}
684
685
686int TOOL_MANAGER::GetPriority( int aToolId ) const
687{
688 int priority = 0;
689
690 for( TOOL_ID tool : m_activeTools )
691 {
692 if( tool == aToolId )
693 return priority;
694
695 ++priority;
696 }
697
698 return -1;
699}
700
701
703 const TOOL_EVENT_LIST& aConditions )
704{
705 TOOL_STATE* st = m_toolState[aTool];
706
707 st->transitions.emplace_back( TRANSITION( aConditions, aHandler ) );
708}
709
710
712{
713 m_toolState[aTool]->transitions.clear();
714}
715
716
717void TOOL_MANAGER::RunMainStack( TOOL_BASE* aTool, std::function<void()> aFunc )
718{
719 TOOL_STATE* st = m_toolState[aTool];
720 setActiveState( st );
721 wxCHECK( st->cofunc, /* void */ );
722 st->cofunc->RunMainStack( std::move( aFunc ) );
723}
724
725
727{
728 TOOL_STATE* st = m_toolState[aTool];
729
730 wxCHECK( !st->pendingWait, nullptr ); // everything collapses on two KiYield() in a row
731
732 // indicate to the manager that we are going to sleep and we shall be
733 // woken up when an event matching aConditions arrive
734 st->pendingWait = true;
735 st->waitEvents = aConditions;
736
737 wxCHECK( st->cofunc, nullptr );
738
739 // switch context back to event dispatcher loop
740 st->cofunc->KiYield();
741
742 // If the tool should shutdown, it gets a null event to break the loop
743 if( st->shutdown )
744 return nullptr;
745 else
746 return &st->wakeupEvent;
747}
748
749
751{
752 bool handled = false;
753
754 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::dispatchInternal - received event: %s" ),
755 aEvent.Format() );
756
757 auto it = m_activeTools.begin();
758
759 // iterate over active tool stack
760 while( it != m_activeTools.end() )
761 {
762 TOOL_STATE* st = m_toolIdIndex[*it];
763 bool increment = true;
764
765 // forward context menu events to the tool that created the menu
766 if( aEvent.IsChoiceMenu() )
767 {
768 if( *it != m_menuOwner )
769 {
770 ++it;
771 continue;
772 }
773 }
774
775 // If we're pendingWait then we had better have a cofunc to process the wait.
776 wxASSERT( !st || !st->pendingWait || st->cofunc );
777
778 // the tool state handler is waiting for events (i.e. called Wait() method)
779 if( st && st->cofunc && st->pendingWait && st->waitEvents.Matches( aEvent ) )
780 {
781 if( !aEvent.FirstResponder() )
782 aEvent.SetFirstResponder( st->theTool );
783
784 // got matching event? clear wait list and wake up the coroutine
785 st->wakeupEvent = aEvent;
786 st->pendingWait = false;
787 st->waitEvents.clear();
788
789 wxLogTrace( kicadTraceToolStack,
790 wxS( "TOOL_MANAGER::dispatchInternal - Waking tool %s for event: %s" ),
791 st->theTool->GetName(), aEvent.Format() );
792
793 setActiveState( st );
794 bool end = !st->cofunc->Resume();
795
796 if( end )
797 {
798 it = finishTool( st );
799 increment = false;
800 }
801
802 // If the tool did not request the event be passed to other tools, we're done
803 if( !st->wakeupEvent.PassEvent() )
804 {
805 wxLogTrace( kicadTraceToolStack,
806 wxS( "TOOL_MANAGER::dispatchInternal - tool %s stopped passing "
807 "event: %s" ),
808 st->theTool->GetName(), aEvent.Format() );
809
810 return true;
811 }
812 }
813
814 if( increment )
815 ++it;
816 }
817
818 for( const auto& state : m_toolState )
819 {
820 TOOL_STATE* st = state.second;
821 bool finished = false;
822
823 // no state handler in progress - check if there are any transitions (defined by
824 // Go() method that match the event.
825 if( !st->transitions.empty() )
826 {
827 for( const TRANSITION& tr : st->transitions )
828 {
829 if( tr.first.Matches( aEvent ) )
830 {
831 auto func_copy = tr.second;
832
833 if( !aEvent.FirstResponder() )
834 aEvent.SetFirstResponder( st->theTool );
835
836 // if there is already a context, then push it on the stack
837 // and transfer the previous view control settings to the new context
838 if( st->cofunc )
839 {
840 KIGFX::VC_SETTINGS viewControlSettings = st->vcSettings;
841 st->Push();
842 st->vcSettings = std::move( viewControlSettings );
843 }
844
845 st->cofunc = new COROUTINE<int, const TOOL_EVENT&>( std::move( func_copy ) );
846
847 wxLogTrace( kicadTraceToolStack,
848 wxS( "TOOL_MANAGER::dispatchInternal - Running tool %s for "
849 "event: %s" ),
850 st->theTool->GetName(), aEvent.Format() );
851
852 // got match? Run the handler.
853 setActiveState( st );
854 st->idle = false;
855 st->initialEvent = aEvent;
856 st->cofunc->Call( st->initialEvent );
857 handled = true;
858
859 if( !st->cofunc->Running() )
860 finishTool( st ); // The coroutine has finished immediately?
861
862 // if it is a message, continue processing
863 finished = !( aEvent.Category() == TC_MESSAGE );
864
865 // there is no point in further checking, as transitions got cleared
866 break;
867 }
868 }
869 }
870
871 if( finished )
872 break; // only the first tool gets the event
873 }
874
875 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::dispatchInternal - %s handle event: %s" ),
876 ( handled ? wxS( "Did" ) : wxS( "Did not" ) ), aEvent.Format() );
877
878 return handled;
879}
880
881
883{
884 if( aEvent.Action() == TA_KEY_PRESSED )
885 return m_actionMgr->RunHotKey( aEvent.Modifier() | aEvent.KeyCode() );
886
887 return false;
888}
889
890
892{
893 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::dispatchActivation - Received event: %s" ),
894 aEvent.Format() );
895
896 if( aEvent.IsActivate() )
897 {
898 auto tool = m_toolNameIndex.find( aEvent.getCommandStr() );
899
900 if( tool != m_toolNameIndex.end() )
901 {
902 wxLogTrace( kicadTraceToolStack,
903 wxS( "TOOL_MANAGER::dispatchActivation - Running tool %s for event: %s" ),
904 tool->second->theTool->GetName(), aEvent.Format() );
905
906 runTool( tool->second->theTool );
907 return true;
908 }
909 }
910
911 return false;
912}
913
914
916{
917 // Don't open context menus if we're inside a yielding event loop such as a progress dialog.
918 // Opening a popup menu during YieldFor creates a nested modal situation that can leave the
919 // menu stuck and unresponsive, potentially locking up the entire UI on some platforms.
920 if( wxEventLoopBase* loop = wxEventLoopBase::GetActive() )
921 {
922 if( loop->IsYielding() )
923 return;
924 }
925
926 for( TOOL_ID toolId : m_activeTools )
927 {
928 TOOL_STATE* st = m_toolIdIndex[toolId];
929
930 // the tool requested a context menu. The menu is activated on RMB click (CMENU_BUTTON mode)
931 // or immediately (CMENU_NOW) mode. The latter is used for clarification lists.
932 if( st->contextMenuTrigger == CMENU_OFF )
933 continue;
934
935 if( st->contextMenuTrigger == CMENU_BUTTON && !aEvent.IsClick( BUT_RIGHT ) )
936 break;
937
938 if( st->cofunc )
939 {
940 st->pendingWait = true;
942 }
943
944 // Store the menu pointer in case it is changed by the TOOL when handling menu events
945 ACTION_MENU* m = st->contextMenu;
946
947 if( st->contextMenuTrigger == CMENU_NOW )
949
950 // Store the cursor position, so the tools could execute actions
951 // using the point where the user has invoked a context menu
952 if( m_viewControls )
953 m_menuCursor = m_viewControls->GetCursorPosition();
954
955 // Save all tools cursor settings, as they will be overridden
956 for( const std::pair<const TOOL_ID, TOOL_STATE*>& idState : m_toolIdIndex )
957 {
958 TOOL_STATE* s = idState.second;
959 const auto& vc = s->vcSettings;
960
961 if( vc.m_forceCursorPosition )
962 m_cursorSettings[idState.first] = vc.m_forcedPosition;
963 else
964 m_cursorSettings[idState.first] = std::nullopt;
965 }
966
967 if( m_viewControls )
968 m_viewControls->ForceCursorPosition( true, m_menuCursor );
969
970 // Display a copy of menu
971 std::unique_ptr<ACTION_MENU> menu( m->Clone() );
972
973 m_menuOwner = toolId;
974 m_menuActive = true;
975
976 if( wxWindow* frame = dynamic_cast<wxWindow*>( m_frame ) )
977 frame->PopupMenu( menu.get() );
978
979 // Warp the cursor if a menu item was selected
980 if( menu->GetSelected() >= 0 )
981 {
983 m_viewControls->WarpMouseCursor( m_menuCursor, true, false );
984 }
985 // Otherwise notify the tool of a canceled menu
986 else
987 {
989 evt.SetHasPosition( false );
990 evt.SetParameter( m );
991 dispatchInternal( evt );
992 }
993
994 // Restore setting in case it was vetoed
996
997 // Notify the tools that menu has been closed
999 evt.SetHasPosition( false );
1000 evt.SetParameter( m );
1001 dispatchInternal( evt );
1002
1003 m_menuActive = false;
1004 m_menuOwner = -1;
1005
1006 // Restore cursor settings
1007 for( const std::pair<const TOOL_ID,
1008 std::optional<VECTOR2D>>& cursorSetting : m_cursorSettings )
1009 {
1010 auto it = m_toolIdIndex.find( cursorSetting.first );
1011 wxASSERT( it != m_toolIdIndex.end() );
1012
1013 if( it == m_toolIdIndex.end() )
1014 continue;
1015
1016 KIGFX::VC_SETTINGS& vc = it->second->vcSettings;
1017 vc.m_forceCursorPosition = (bool) cursorSetting.second;
1018 vc.m_forcedPosition = cursorSetting.second ? *cursorSetting.second : VECTOR2D( 0, 0 );
1019 }
1020
1021 m_cursorSettings.clear();
1022 break;
1023 }
1024}
1025
1026
1028{
1030 m_viewControls->WarpMouseCursor( m_menuCursor, true, false );
1031
1032 // Don't warp again when the menu is closed
1034}
1035
1036
1037TOOL_MANAGER::ID_LIST::iterator TOOL_MANAGER::finishTool( TOOL_STATE* aState )
1038{
1039 auto it = std::find( m_activeTools.begin(), m_activeTools.end(), aState->theTool->GetId() );
1040
1041 if( !aState->Pop() )
1042 {
1043 // Deactivate the tool if there are no other contexts saved on the stack
1044 if( it != m_activeTools.end() )
1045 it = m_activeTools.erase( it );
1046
1047 aState->idle = true;
1048 }
1049
1050 if( aState == m_activeState )
1051 setActiveState( nullptr );
1052
1053 return it;
1054}
1055
1056
1058{
1059 // Once the tool manager is shutting down, don't start
1060 // activating more tools
1061 if( m_shuttingDown )
1062 return true;
1063
1064 bool handled = processEvent( aEvent );
1065
1066 TOOL_STATE* activeTool = GetCurrentToolState();
1067
1068 if( activeTool )
1069 setActiveState( activeTool );
1070
1071 if( m_view && m_view->IsDirty() )
1072 {
1073#if defined( __WXMAC__ )
1074 wxTheApp->ProcessPendingEvents(); // required for updating brightening behind a popup menu
1075#endif
1076 }
1077
1078 UpdateUI( aEvent );
1079
1080 return handled;
1081}
1082
1083
1085 CONTEXT_MENU_TRIGGER aTrigger )
1086{
1087 TOOL_STATE* st = m_toolState[aTool];
1088
1089 st->contextMenu = aMenu;
1090 st->contextMenuTrigger = aTrigger;
1091}
1092
1093
1095{
1096 if( TOOL_STATE* active = GetCurrentToolState() )
1097 return active->vcSettings;
1098
1099 return m_viewControls->GetSettings();
1100}
1101
1102
1103TOOL_ID TOOL_MANAGER::MakeToolId( const std::string& aToolName )
1104{
1105 static int currentId;
1106
1107 return currentId++;
1108}
1109
1110
1112 KIGFX::VIEW_CONTROLS* aViewControls,
1113 APP_SETTINGS_BASE* aSettings, TOOLS_HOLDER* aFrame )
1114{
1115 m_model = aModel;
1116 m_view = aView;
1117 m_viewControls = aViewControls;
1118 m_frame = aFrame;
1119 m_settings = aSettings;
1120}
1121
1122
1124{
1125 if( !isRegistered( aTool ) )
1126 return false;
1127
1128 // Just check if the tool is on the active tools stack
1129 return alg::contains( m_activeTools, aTool->GetId() );
1130}
1131
1132
1134{
1135 aState->vcSettings = m_viewControls->GetSettings();
1136
1137 if( m_menuActive )
1138 {
1139 // Context menu is active, so the cursor settings are overridden (see DispatchContextMenu())
1140 auto it = m_cursorSettings.find( aState->theTool->GetId() );
1141
1142 if( it != m_cursorSettings.end() )
1143 {
1144 const KIGFX::VC_SETTINGS& curr = m_viewControls->GetSettings();
1145
1146 // Tool has overridden the cursor position, so store the new settings
1148 {
1149 if( !curr.m_forceCursorPosition )
1150 it->second = std::nullopt;
1151 else
1152 it->second = curr.m_forcedPosition;
1153 }
1154 else
1155 {
1156 std::optional<VECTOR2D> cursor = it->second;
1157
1158 if( cursor )
1159 {
1160 aState->vcSettings.m_forceCursorPosition = true;
1162 }
1163 else
1164 {
1165 aState->vcSettings.m_forceCursorPosition = false;
1166 }
1167 }
1168 }
1169 }
1170}
1171
1172
1174{
1175 m_viewControls->ApplySettings( aState->vcSettings );
1176}
1177
1178
1180{
1181 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::processEvent - %s" ), aEvent.Format() );
1182
1183 // First try to dispatch the action associated with the event if it is a key press event
1184 bool handled = DispatchHotKey( aEvent );
1185
1186 if( !handled )
1187 {
1188 TOOL_EVENT mod_event( aEvent );
1189
1190 // Only immediate actions get the position. Otherwise clear for tool activation
1191 if( GetToolHolder() && !GetToolHolder()->GetDoImmediateActions() )
1192 {
1193 // An tool-selection-event has no position
1194 if( !mod_event.getCommandStr().empty()
1195 && mod_event.getCommandStr() != GetToolHolder()->CurrentToolName()
1196 && !mod_event.ForceImmediate() )
1197 {
1198 mod_event.SetHasPosition( false );
1199 }
1200 }
1201
1202 // If the event is not handled through a hotkey activation, pass it to the currently
1203 // running tool loops
1204 handled |= dispatchInternal( mod_event );
1205 handled |= dispatchActivation( mod_event );
1206
1207 // Open the context menu if requested by a tool
1208 DispatchContextMenu( mod_event );
1209
1210 // Dispatch any remaining events in the event queue
1211 while( !m_eventQueue.empty() )
1212 {
1213 TOOL_EVENT event = m_eventQueue.front();
1214 m_eventQueue.pop_front();
1215 processEvent( event );
1216 }
1217 }
1218
1219 wxLogTrace( kicadTraceToolStack, wxS( "TOOL_MANAGER::processEvent - %s handle event: %s" ),
1220 ( handled ? "Did" : "Did not" ), aEvent.Format() );
1221
1222 return handled;
1223}
1224
1225
1227{
1230
1231 m_activeState = aState;
1232
1234 applyViewControls( aState );
1235}
1236
1237
1239{
1240 auto it = m_toolIdIndex.find( aId );
1241
1242 if( it == m_toolIdIndex.end() )
1243 return false;
1244
1245 return !it->second->idle;
1246}
1247
1248
1250{
1251 EDA_BASE_FRAME* frame = dynamic_cast<EDA_BASE_FRAME*>( GetToolHolder() );
1252
1253 if( frame )
1254 frame->UpdateStatusBar();
1255}
Manage TOOL_ACTION objects.
Define the structure of a menu based on ACTIONs.
Definition action_menu.h:47
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.
Represent a set of changes (additions, deletions or modifications) of a data model (e....
Definition commit.h:72
Implement a coroutine.
Definition coroutine.h:84
bool Call(ArgType aArg)
Start execution of a coroutine, passing args as its arguments.
Definition coroutine.h:286
void KiYield()
Stop execution of the coroutine and returns control to the caller.
Definition coroutine.h:249
bool Resume()
Resume execution of a previously yielded coroutine.
Definition coroutine.h:332
bool Running() const
Definition coroutine.h:381
void RunMainStack(std::function< void()> func)
Run a functor inside the application main stack context.
Definition coroutine.h:272
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:100
An interface for classes handling user events controlling the view behavior such as zooming,...
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition view.h:67
Represent a single user action.
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:62
A list of TOOL_EVENTs, with overloaded || operators allowing for concatenating TOOL_EVENTs with littl...
Definition tool_event.h:648
OPT_TOOL_EVENT Matches(const TOOL_EVENT &aEvent) const
Definition tool_event.h:687
Generic, UI-independent tool event.
Definition tool_event.h:171
bool PassEvent() const
These give a tool a method of informing the TOOL_MANAGER that a particular event should be passed on ...
Definition tool_event.h:255
TOOL_ACTIONS Action() const
Returns more specific information about the type of an event.
Definition tool_event.h:250
void SetMousePosition(const VECTOR2D &aP)
Definition tool_event.h:538
int KeyCode() const
Definition tool_event.h:376
TOOL_BASE * FirstResponder() const
Definition tool_event.h:268
bool IsActivate() const
Definition tool_event.h:345
void SetFirstResponder(TOOL_BASE *aTool)
Definition tool_event.h:269
bool IsSimulator() const
Indicate if the event is from the simulator.
void SetParameter(T aParam)
Set a non-standard parameter assigned to the event.
Definition tool_event.h:528
bool ForceImmediate() const
Returns if the action associated with this event should be treated as immediate regardless of the cur...
Definition tool_event.h:265
bool IsClick(int aButtonMask=BUT_ANY) const
TOOL_EVENT_CATEGORY Category() const
Return the category (eg. mouse/keyboard/action) of an event.
Definition tool_event.h:247
int Modifier(int aMask=MD_MODIFIER_MASK) const
Return information about key modifiers state (Ctrl, Alt, etc.).
Definition tool_event.h:366
void SetHasPosition(bool aHasPosition)
Definition tool_event.h:261
const std::string & getCommandStr() const
Definition tool_event.h:558
bool IsChoiceMenu() const
Definition tool_event.h:355
const std::string Format() const
Return information about event in form of a human-readable string.
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
Pointer to the state object corresponding to the currently executed tool.
void UpdateUI(const TOOL_EVENT &aEvent)
Update the status bar and synchronizes toolbars.
std::map< TOOL_ID, std::optional< VECTOR2D > > m_cursorSettings
Original cursor position, if overridden by the context menu handler.
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
Index of the registered tools to easily lookup by their type.
bool isRegistered(TOOL_BASE *aTool) const
Return information about a tool registration status.
APP_SETTINGS_BASE * m_settings
TOOL_STATE * GetCurrentToolState() const
Return the TOOL_STATE object representing the state of the active tool.
VECTOR2D GetCursorPosition() const
std::list< TOOL_EVENT > m_eventQueue
Queue that stores events to be processed at the end of the event processing cycle.
std::pair< TOOL_EVENT_LIST, TOOL_STATE_FUNC > TRANSITION
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' names.
TOOLS_HOLDER * m_frame
void CancelTool()
Send a cancel event to the tool currently at the top of the tool stack.
bool m_warpMouseAfterContextMenu
KIGFX::VIEW_CONTROLS * m_viewControls
void WarpAfterContextMenu()
Normally we warp the mouse after the context menu action runs.
ACTION_MANAGER * m_actionMgr
Instance of ACTION_MANAGER that handles TOOL_ACTIONs.
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
VECTOR2D GetMousePosition() const
bool processEvent(const TOOL_EVENT &aEvent)
Main function for event processing.
std::list< TOOL_ID > ID_LIST
ID_LIST::iterator finishTool(TOOL_STATE *aState)
Deactivate a tool and does the necessary clean up.
bool doRunAction(const TOOL_ACTION &aAction, bool aNow, const ki::any &aParam, COMMIT *aCommit, bool aFromAPI=false)
Helper function to actually run an action.
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 current states, associated by tools' ID numbers.
TOOL_ID m_menuOwner
Tool currently displaying a popup menu. It is negative when there is no menu displayed.
KIGFX::VIEW * m_view
void ClearTransitions(TOOL_BASE *aTool)
Clear the state transition map for a tool.
bool m_shuttingDown
True if the tool manager is shutting down (don't process additional events)
void saveViewControls(TOOL_STATE *aState)
Save the #VIEW_CONTROLS settings to the tool state object.
int GetHotKey(const TOOL_ACTION &aAction) const
Return the hot key associated with a given action or 0 if there is none.
bool m_menuActive
Flag indicating whether a context menu is currently displayed.
TOOL_STATE_MAP m_toolState
Index of registered tools current states, associated by tools' objects.
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
Stack of the active tools.
void ResetTools(TOOL_BASE::RESET_REASON aReason)
Reset all tools (i.e.
EDA_ITEM * m_model
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)
Generate 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.
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()
Initialize all registered tools.
VECTOR2D m_menuCursor
Right click context menu position.
void ShutdownAllTools()
Shutdown all tools with a currently registered event loop in this tool manager by waking them up with...
A type-safe container of any type.
Definition ki_any.h:93
bool has_value() const noexcept
Report whether there is a contained object or not.
Definition ki_any.h:312
Base window classes and related definitions.
const wxChar *const kicadTraceToolStack
Flag to enable tracing of the tool handling stack.
void AddTransactionBreadcrumb(const wxString &aMsg, const wxString &aCategory)
Add a transaction breadcrumb.
wxPoint GetMousePosition()
Returns the mouse position in screen coordinates.
Definition wxgtk/ui.cpp:721
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.
VECTOR2D m_forcedPosition
Forced cursor position (world coordinates).
bool m_forceCursorPosition
Is the forced cursor position enabled.
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.
void resetRuntimeState()
Resets runtime-only state that must not leak across tool activations.
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.
void clear()
Restores the initial state.
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
VECTOR2I end
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
@ TA_ANY
Definition tool_event.h:126
@ TA_CHOICE_MENU_CHOICE
Context menu choice.
Definition tool_event.h:98
@ TA_ACTIVATE
Tool activation event.
Definition tool_event.h:115
@ TA_CHOICE_MENU_CLOSED
Context menu is closed, no matter whether anything has been chosen or not.
Definition tool_event.h:101
@ TA_PRIME
Tool priming event (a special mouse click).
Definition tool_event.h:124
@ TA_KEY_PRESSED
Definition tool_event.h:76
@ TA_CANCEL_TOOL
Tool cancel event.
Definition tool_event.h:90
CONTEXT_MENU_TRIGGER
Defines when a context menu is opened.
Definition tool_event.h:154
@ CMENU_NOW
Right now (after TOOL_INTERACTIVE::SetContextMenu).
Definition tool_event.h:156
@ CMENU_OFF
Never.
Definition tool_event.h:157
@ CMENU_BUTTON
On the right button.
Definition tool_event.h:155
@ STS_CANCELLED
Definition tool_event.h:164
@ STS_FINISHED
Definition tool_event.h:163
@ STS_RUNNING
Definition tool_event.h:162
@ TC_ANY
Definition tool_event.h:60
@ TC_COMMAND
Definition tool_event.h:57
@ TC_MOUSE
Definition tool_event.h:55
@ TC_MESSAGE
Definition tool_event.h:58
@ BUT_LEFT
Definition tool_event.h:132
@ BUT_RIGHT
Definition tool_event.h:133
wxLogTrace helper definitions.
VECTOR2< double > VECTOR2D
Definition vector2d.h:686
VECTOR2D ToVECTOR2D(const wxPoint &aPoint)
Definition vector2wx.h:40