KiCad PCB EDA Suite
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-2018 CERN
5  * Copyright (C) 2019 KiCad Developers, see AUTHORS.txt for contributors.
6  * @author Tomasz Wlostowski <tomasz.wlostowski@cern.ch>
7  * @author Maciej Suminski <maciej.suminski@cern.ch>
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 <algorithm>
28 #include <core/optional.h>
29 #include <map>
30 #include <stack>
31 #include <trace_helpers.h>
32 
33 #include <wx/event.h>
34 #include <wx/clipbrd.h>
35 
36 #include <view/view.h>
37 #include <eda_base_frame.h>
38 #include <tool/tool_base.h>
39 #include <tool/tool_interactive.h>
40 #include <tool/tool_manager.h>
41 #include <tool/action_menu.h>
42 #include <tool/coroutine.h>
43 #include <tool/action_manager.h>
44 
45 #include <class_draw_panel_gal.h>
46 
49 {
50  TOOL_STATE( TOOL_BASE* aTool ) :
51  theTool( aTool )
52  {
53  clear();
54  }
55 
56  TOOL_STATE( const TOOL_STATE& aState )
57  {
58  theTool = aState.theTool;
59  idle = aState.idle;
60  pendingWait = aState.pendingWait;
62  contextMenu = aState.contextMenu;
64  cofunc = aState.cofunc;
65  wakeupEvent = aState.wakeupEvent;
66  waitEvents = aState.waitEvents;
67  transitions = aState.transitions;
68  vcSettings = aState.vcSettings;
69  // do not copy stateStack
70  }
71 
73  {
74  if( !stateStack.empty() )
75  wxFAIL;
76  }
77 
80 
82  bool idle;
83 
87 
90 
93 
96 
99 
102 
105 
108  std::vector<TRANSITION> transitions;
109 
112 
113  TOOL_STATE& operator=( const TOOL_STATE& aState )
114  {
115  theTool = aState.theTool;
116  idle = aState.idle;
117  pendingWait = aState.pendingWait;
119  contextMenu = aState.contextMenu;
121  cofunc = aState.cofunc;
122  wakeupEvent = aState.wakeupEvent;
123  waitEvents = aState.waitEvents;
124  transitions = aState.transitions;
125  vcSettings = aState.vcSettings;
126  // do not copy stateStack
127  return *this;
128  }
129 
130  bool operator==( const TOOL_MANAGER::TOOL_STATE& aRhs ) const
131  {
132  return aRhs.theTool == this->theTool;
133  }
134 
135  bool operator!=( const TOOL_MANAGER::TOOL_STATE& aRhs ) const
136  {
137  return aRhs.theTool != this->theTool;
138  }
139 
145  void Push()
146  {
147  auto state = std::make_unique<TOOL_STATE>( *this );
148  stateStack.push( std::move( state ) );
149  clear();
150  }
151 
158  bool Pop()
159  {
160  delete cofunc;
161 
162  if( !stateStack.empty() )
163  {
164  *this = *stateStack.top().get();
165  stateStack.pop();
166  return true;
167  }
168  else
169  {
170  cofunc = NULL;
171  return false;
172  }
173  }
174 
175 private:
177  std::stack<std::unique_ptr<TOOL_STATE>> stateStack;
178 
180  void clear()
181  {
182  idle = true;
183  pendingWait = false;
184  pendingContextMenu = false;
185  cofunc = NULL;
186  contextMenu = NULL;
188  vcSettings.Reset();
189  transitions.clear();
190  }
191 };
192 
193 
195  m_model( NULL ),
196  m_view( NULL ),
197  m_viewControls( NULL ),
198  m_frame( NULL ),
199  m_warpMouseAfterContextMenu( true ),
200  m_menuActive( false ),
201  m_menuOwner( -1 ),
202  m_activeState( nullptr )
203 {
204  m_actionMgr = new ACTION_MANAGER( this );
205 }
206 
207 
209 {
210  std::map<TOOL_BASE*, TOOL_STATE*>::iterator it, it_end;
211 
212  for( it = m_toolState.begin(), it_end = m_toolState.end(); it != it_end; ++it )
213  {
214  delete it->second->cofunc; // delete cofunction
215  delete it->second; // delete TOOL_STATE
216  delete it->first; // delete the tool itself
217  }
218 
219  delete m_actionMgr;
220 }
221 
222 
224 {
225  wxASSERT_MSG( m_toolNameIndex.find( aTool->GetName() ) == m_toolNameIndex.end(),
226  wxT( "Adding two tools with the same name may result in unexpected behaviour.") );
227  wxASSERT_MSG( m_toolIdIndex.find( aTool->GetId() ) == m_toolIdIndex.end(),
228  wxT( "Adding two tools with the same ID may result in unexpected behaviour.") );
229  wxASSERT_MSG( m_toolTypes.find( typeid( *aTool ).name() ) == m_toolTypes.end(),
230  wxT( "Adding two tools of the same type may result in unexpected behaviour.") );
231 
232  TOOL_STATE* st = new TOOL_STATE( aTool );
233 
234  m_toolState[aTool] = st;
235  m_toolNameIndex[aTool->GetName()] = st;
236  m_toolIdIndex[aTool->GetId()] = st;
237  m_toolTypes[typeid( *aTool ).name()] = st->theTool;
238 
239  aTool->attachManager( this );
240 }
241 
242 
244 {
245  TOOL_BASE* tool = FindTool( aToolId );
246 
247  if( tool && tool->GetType() == INTERACTIVE )
248  return invokeTool( tool );
249 
250  return false; // there is no tool with the given id
251 }
252 
253 
254 bool TOOL_MANAGER::InvokeTool( const std::string& aToolName )
255 {
256  TOOL_BASE* tool = FindTool( aToolName );
257 
258  if( tool && tool->GetType() == INTERACTIVE )
259  return invokeTool( tool );
260 
261  return false; // there is no tool with the given name
262 }
263 
264 
265 bool TOOL_MANAGER::RunAction( const std::string& aActionName, bool aNow, void* aParam )
266 {
267  TOOL_ACTION* action = m_actionMgr->FindAction( aActionName );
268 
269  if( !action )
270  {
271  wxASSERT_MSG( false, wxString::Format( wxT( "Could not find action %s." ), aActionName ) );
272  return false;
273  }
274 
275  RunAction( *action, aNow, aParam );
276 
277  return false;
278 }
279 
280 
281 bool TOOL_MANAGER::RunAction( const TOOL_ACTION& aAction, bool aNow, void* aParam )
282 {
283  bool handled = false;
284  TOOL_EVENT event = aAction.MakeEvent();
285 
286  // Allow to override the action parameter
287  if( aParam )
288  event.SetParameter( aParam );
289 
290  if( aNow )
291  {
292  TOOL_STATE* current = m_activeState;
293  handled = processEvent( event );
294  setActiveState( current );
295  UpdateUI( event );
296  }
297  else
298  {
299  PostEvent( event );
300  }
301 
302  return handled;
303 }
304 
305 
306 const std::map<std::string, TOOL_ACTION*>& TOOL_MANAGER::GetActions()
307 {
308  return m_actionMgr->GetActions();
309 }
310 
311 
313 {
314  return m_actionMgr->GetHotKey( aAction );
315 }
316 
317 
319 {
320  wxASSERT( aTool != NULL );
321 
322  TOOL_EVENT evt( TC_COMMAND, TA_ACTIVATE, aTool->GetName() );
323  processEvent( evt );
324 
325  if( TOOL_STATE* active = GetCurrentToolState() )
326  setActiveState( active );
327 
328  return true;
329 }
330 
331 
333 {
334  TOOL_BASE* tool = FindTool( aToolId );
335 
336  if( tool && tool->GetType() == INTERACTIVE )
337  return runTool( tool );
338 
339  return false; // there is no tool with the given id
340 }
341 
342 
343 bool TOOL_MANAGER::runTool( const std::string& aToolName )
344 {
345  TOOL_BASE* tool = FindTool( aToolName );
346 
347  if( tool && tool->GetType() == INTERACTIVE )
348  return runTool( tool );
349 
350  return false; // there is no tool with the given name
351 }
352 
353 
355 {
356  wxASSERT( aTool != NULL );
357 
358  if( !isRegistered( aTool ) )
359  {
360  wxASSERT_MSG( false, wxT( "You cannot run unregistered tools" ) );
361  return false;
362  }
363 
364  TOOL_ID id = aTool->GetId();
365 
366  if( aTool->GetType() == INTERACTIVE )
367  static_cast<TOOL_INTERACTIVE*>( aTool )->resetTransitions();
368 
369  // If the tool is already active, bring it to the top of the active tools stack
370  if( isActive( aTool ) && m_activeTools.size() > 1 )
371  {
372  auto it = std::find( m_activeTools.begin(), m_activeTools.end(), id );
373 
374  if( it != m_activeTools.end() )
375  {
376  if( it != m_activeTools.begin() )
377  {
378  m_activeTools.erase( it );
379  m_activeTools.push_front( id );
380  }
381 
382  return false;
383  }
384  }
385 
387  aTool->Reset( TOOL_INTERACTIVE::RUN );
388 
389  // Add the tool on the front of the processing queue (it gets events first)
390  m_activeTools.push_front( id );
391 
392  return true;
393 }
394 
395 
397 {
398  std::map<TOOL_ID, TOOL_STATE*>::const_iterator it = m_toolIdIndex.find( aId );
399 
400  if( it != m_toolIdIndex.end() )
401  return it->second->theTool;
402 
403  return NULL;
404 }
405 
406 
407 TOOL_BASE* TOOL_MANAGER::FindTool( const std::string& aName ) const
408 {
409  std::map<std::string, TOOL_STATE*>::const_iterator it = m_toolNameIndex.find( aName );
410 
411  if( it != m_toolNameIndex.end() )
412  return it->second->theTool;
413 
414  return NULL;
415 }
416 
417 
419 {
420  // Deactivate the active tool, but do not run anything new
422  processEvent( evt );
423 }
424 
425 
427 {
428  DeactivateTool();
429 
430  for( auto& state : m_toolState )
431  {
432  TOOL_BASE* tool = state.first;
433  setActiveState( state.second );
434  tool->Reset( aReason );
435 
436  if( tool->GetType() == INTERACTIVE )
437  static_cast<TOOL_INTERACTIVE*>( tool )->resetTransitions();
438  }
439 }
440 
441 
443 {
444  for( auto it = m_toolState.begin(); it != m_toolState.end(); /* iteration in the loop */ )
445  {
446  TOOL_BASE* tool = it->first;
447  TOOL_STATE* state = it->second;
448  setActiveState( state );
449  ++it; // keep the iterator valid if the element is going to be erased
450 
451  if( !tool->Init() )
452  {
453  wxMessageBox( wxString::Format( "Initialization of tool \"%s\" failed",
454  tool->GetName() ) );
455 
456  // Unregister the tool
457  setActiveState( nullptr );
458  m_toolState.erase( tool );
459  m_toolNameIndex.erase( tool->GetName() );
460  m_toolIdIndex.erase( tool->GetId() );
461  m_toolTypes.erase( typeid( *tool ).name() );
462 
463  delete state;
464  delete tool;
465  }
466  }
467 
468  m_actionMgr->UpdateHotKeys( true );
469 
471 }
472 
473 
474 int TOOL_MANAGER::GetPriority( int aToolId ) const
475 {
476  int priority = 0;
477 
478  for( TOOL_ID tool : m_activeTools )
479  {
480  if( tool == aToolId )
481  return priority;
482 
483  ++priority;
484  }
485 
486  return -1;
487 }
488 
489 
491  const TOOL_EVENT_LIST& aConditions )
492 {
493  TOOL_STATE* st = m_toolState[aTool];
494 
495  st->transitions.emplace_back( TRANSITION( aConditions, aHandler ) );
496 }
497 
498 
500 {
501  m_toolState[aTool]->transitions.clear();
502 }
503 
504 
505 void TOOL_MANAGER::RunMainStack( TOOL_BASE* aTool, std::function<void()> aFunc )
506 {
507  TOOL_STATE* st = m_toolState[aTool];
508  setActiveState( st );
509  st->cofunc->RunMainStack( std::move( aFunc ) );
510 }
511 
512 
514 {
515  TOOL_STATE* st = m_toolState[aTool];
516 
517  wxASSERT( !st->pendingWait ); // everything collapses on two KiYield() in a row
518 
519  // indicate to the manager that we are going to sleep and we shall be
520  // woken up when an event matching aConditions arrive
521  st->pendingWait = true;
522  st->waitEvents = aConditions;
523 
524  // switch context back to event dispatcher loop
525  st->cofunc->KiYield();
526 
527  return &st->wakeupEvent;
528 }
529 
530 
532 {
533  bool handled = false;
534 
535  wxLogTrace( kicadTraceToolStack, "TOOL_MANAGER::dispatchInternal %s", aEvent.Format() );
536 
537  // iterate over active tool stack
538  for( auto it = m_activeTools.begin(); it != m_activeTools.end(); ++it )
539  {
540  TOOL_STATE* st = m_toolIdIndex[*it];
541 
542  // forward context menu events to the tool that created the menu
543  if( aEvent.IsChoiceMenu() )
544  {
545  if( *it != m_menuOwner )
546  continue;
547  }
548 
549  // the tool state handler is waiting for events (i.e. called Wait() method)
550  if( st && st->pendingWait )
551  {
552  if( st->waitEvents.Matches( aEvent ) )
553  {
554  if( !aEvent.FirstResponder() )
555  const_cast<TOOL_EVENT*>( &aEvent )->SetFirstResponder( st->theTool );
556 
557  // got matching event? clear wait list and wake up the coroutine
558  st->wakeupEvent = aEvent;
559  st->pendingWait = false;
560  st->waitEvents.clear();
561 
562  if( st->cofunc )
563  {
564  wxLogTrace( kicadTraceToolStack,
565  "TOOL_MANAGER::dispatchInternal Waking tool %s for event: %s",
566  st->theTool->GetName(), aEvent.Format() );
567 
568  setActiveState( st );
569  bool end = !st->cofunc->Resume();
570 
571  if( end )
572  it = finishTool( st );
573  }
574 
575  // If the tool did not request the event be passed to other tools, we're done
576  if( !st->wakeupEvent.PassEvent() )
577  {
578  wxLogTrace( kicadTraceToolStack,
579  "TOOL_MANAGER::dispatchInternal %s stopped passing event: %s",
580  st->theTool->GetName(), aEvent.Format() );
581 
582  handled = true;
583  break;
584  }
585  }
586  }
587  }
588 
589  for( auto& state : m_toolState )
590  {
591  TOOL_STATE* st = state.second;
592  bool finished = false;
593 
594  // no state handler in progress - check if there are any transitions (defined by
595  // Go() method that match the event.
596  if( !st->transitions.empty() )
597  {
598  for( TRANSITION& tr : st->transitions )
599  {
600  if( tr.first.Matches( aEvent ) )
601  {
602  auto func_copy = tr.second;
603 
604  if( !aEvent.FirstResponder() )
605  const_cast<TOOL_EVENT*>( &aEvent )->SetFirstResponder( st->theTool );
606 
607  // if there is already a context, then push it on the stack
608  // and transfer the previous view control settings to the new context
609  if( st->cofunc )
610  {
611  auto vc = st->vcSettings;
612  st->Push();
613  st->vcSettings = vc;
614  }
615 
616  st->cofunc = new COROUTINE<int, const TOOL_EVENT&>( std::move( func_copy ) );
617 
618  // as the state changes, the transition table has to be set up again
619  st->transitions.clear();
620 
621  wxLogTrace( kicadTraceToolStack,
622  "TOOL_MANAGER::dispatchInternal Running tool %s for event: %s",
623  st->theTool->GetName(), aEvent.Format() );
624 
625  // got match? Run the handler.
626  setActiveState( st );
627  st->idle = false;
628  st->cofunc->Call( aEvent );
629  handled = true;
630 
631  if( !st->cofunc->Running() )
632  finishTool( st ); // The couroutine has finished immediately?
633 
634  // if it is a message, continue processing
635  finished = !( aEvent.Category() == TC_MESSAGE );
636 
637  // there is no point in further checking, as transitions got cleared
638  break;
639  }
640  }
641  }
642 
643  if( finished )
644  break; // only the first tool gets the event
645  }
646 
647  wxLogTrace( kicadTraceToolStack, "TOOL_MANAGER::dispatchInternal handled: %s %s",
648  ( handled ? "true" : "false" ), aEvent.Format() );
649 
650  return handled;
651 }
652 
653 
655 {
656  if( aEvent.Action() == TA_KEY_PRESSED )
657  return m_actionMgr->RunHotKey( aEvent.Modifier() | aEvent.KeyCode() );
658 
659  return false;
660 }
661 
662 
664 {
665  wxLogTrace( kicadTraceToolStack, "TOOL_MANAGER::dispatchActivation %s", aEvent.Format() );
666  if( aEvent.IsActivate() )
667  {
668  wxString cmdStr( *aEvent.GetCommandStr() );
669 
670  auto tool = m_toolNameIndex.find( *aEvent.GetCommandStr() );
671 
672  if( tool != m_toolNameIndex.end() )
673  {
674  wxLogTrace( kicadTraceToolStack,
675  "TOOL_MANAGER::dispatchActivation Running tool %s for event: %s",
676  tool->second->theTool->GetName(), aEvent.Format() );
677 
678  runTool( tool->second->theTool );
679  return true;
680  }
681  }
682 
683  return false;
684 }
685 
687 {
688  for( TOOL_ID toolId : m_activeTools )
689  {
690  TOOL_STATE* st = m_toolIdIndex[toolId];
691 
692  // the tool requested a context menu. The menu is activated on RMB click (CMENU_BUTTON mode)
693  // or immediately (CMENU_NOW) mode. The latter is used for clarification lists.
694  if( st->contextMenuTrigger == CMENU_OFF )
695  continue;
696 
697  if( st->contextMenuTrigger == CMENU_BUTTON && !aEvent.IsClick( BUT_RIGHT ) )
698  break;
699 
700  st->pendingWait = true;
702 
703  // Store the menu pointer in case it is changed by the TOOL when handling menu events
704  ACTION_MENU* m = st->contextMenu;
705 
706  if( st->contextMenuTrigger == CMENU_NOW )
708 
709  // Store the cursor position, so the tools could execute actions
710  // using the point where the user has invoked a context menu
712 
713  // Save all tools cursor settings, as they will be overridden
714  for( auto idState : m_toolIdIndex )
715  {
716  TOOL_STATE* s = idState.second;
717  const auto& vc = s->vcSettings;
718 
719  if( vc.m_forceCursorPosition )
720  m_cursorSettings[idState.first] = vc.m_forcedPosition;
721  else
722  m_cursorSettings[idState.first] = NULLOPT;
723  }
724 
726 
727  // Display a copy of menu
728  std::unique_ptr<ACTION_MENU> menu( m->Clone() );
729 
730  m_menuOwner = toolId;
731  m_menuActive = true;
732 
733  auto frame = dynamic_cast<wxFrame*>( m_frame );
734 
735  if( frame )
736  frame->PopupMenu( menu.get() );
737 
738  // Warp the cursor if a menu item was selected
739  if( menu->GetSelected() >= 0 && m_warpMouseAfterContextMenu )
740  m_viewControls->WarpCursor( m_menuCursor, true, false );
741  // Otherwise notify the tool of a cancelled menu
742  else
743  {
745  evt.SetParameter( m );
746  dispatchInternal( evt );
747  }
748 
749  // Restore setting in case it was vetoed
751 
752  // Notify the tools that menu has been closed
754  evt.SetParameter( m );
755  dispatchInternal( evt );
756 
757  m_menuActive = false;
758  m_menuOwner = -1;
759 
760  // Restore cursor settings
761  for( auto cursorSetting : m_cursorSettings )
762  {
763  auto it = m_toolIdIndex.find( cursorSetting.first );
764  wxASSERT( it != m_toolIdIndex.end() );
765 
766  if( it == m_toolIdIndex.end() )
767  continue;
768 
769  KIGFX::VC_SETTINGS& vc = it->second->vcSettings;
770  vc.m_forceCursorPosition = (bool) cursorSetting.second;
771  vc.m_forcedPosition = cursorSetting.second ? *cursorSetting.second : VECTOR2D( 0, 0 );
772  }
773 
774  m_cursorSettings.clear();
775  break;
776  }
777 }
778 
779 
780 TOOL_MANAGER::ID_LIST::iterator TOOL_MANAGER::finishTool( TOOL_STATE* aState )
781 {
782  auto it = std::find( m_activeTools.begin(), m_activeTools.end(), aState->theTool->GetId() );
783 
784  if( !aState->Pop() )
785  {
786  // Deactivate the tool if there are no other contexts saved on the stack
787  if( it != m_activeTools.end() )
788  it = m_activeTools.erase( it );
789 
790  aState->idle = true;
791  }
792 
793  if( aState == m_activeState )
794  setActiveState( nullptr );
795 
796  // Set transitions to be ready for future TOOL_EVENTs
797  TOOL_BASE* tool = aState->theTool;
798 
799  if( tool->GetType() == INTERACTIVE )
800  static_cast<TOOL_INTERACTIVE*>( tool )->resetTransitions();
801 
802  return --it;
803 }
804 
805 
807 {
808  bool handled = processEvent( aEvent );
809 
810  TOOL_STATE* activeTool = GetCurrentToolState();
811 
812  if( activeTool )
813  setActiveState( activeTool );
814 
815  if( m_view && m_view->IsDirty() )
816  {
818 
819 #if defined( __WXMAC__ ) || defined( __WINDOWS__ )
820  wxTheApp->ProcessPendingEvents(); // required for updating brightening behind a popup menu
821 #endif
822  }
823 
824  UpdateUI( aEvent );
825 
826  return handled;
827 }
828 
829 
831  CONTEXT_MENU_TRIGGER aTrigger )
832 {
833  TOOL_STATE* st = m_toolState[aTool];
834 
835  st->contextMenu = aMenu;
836  st->contextMenuTrigger = aTrigger;
837 }
838 
839 
840 bool TOOL_MANAGER::SaveClipboard( const std::string& aText )
841 {
842  if( wxTheClipboard->Open() )
843  {
844  wxTheClipboard->SetData( new wxTextDataObject( wxString( aText.c_str(), wxConvUTF8 ) ) );
845  wxTheClipboard->Close();
846 
847  return true;
848  }
849 
850  return false;
851 }
852 
853 
854 std::string TOOL_MANAGER::GetClipboard() const
855 {
856  std::string result;
857 
858  if( wxTheClipboard->Open() )
859  {
860  if( wxTheClipboard->IsSupported( wxDF_TEXT ) )
861  {
862  wxTextDataObject data;
863  wxTheClipboard->GetData( data );
864 
865  result = data.GetText().mb_str();
866  }
867 
868  wxTheClipboard->Close();
869  }
870 
871  return result;
872 }
873 
874 
876 {
877  if( TOOL_STATE* active = GetCurrentToolState() )
878  return active->vcSettings;
879 
880  return m_viewControls->GetSettings();
881 }
882 
883 
884 TOOL_ID TOOL_MANAGER::MakeToolId( const std::string& aToolName )
885 {
886  static int currentId;
887 
888  return currentId++;
889 }
890 
891 
893  KIGFX::VIEW_CONTROLS* aViewControls, EDA_BASE_FRAME* aFrame )
894 {
895  m_model = aModel;
896  m_view = aView;
897  m_viewControls = aViewControls;
898  m_frame = aFrame;
899 }
900 
901 
903 {
904  if( !isRegistered( aTool ) )
905  return false;
906 
907  // Just check if the tool is on the active tools stack
908  return std::find( m_activeTools.begin(), m_activeTools.end(), aTool->GetId() ) != m_activeTools.end();
909 }
910 
911 
913 {
915 
916  if( m_menuActive )
917  {
918  // Context menu is active, so the cursor settings are overridden (see DispatchContextMenu())
919  auto it = m_cursorSettings.find( aState->theTool->GetId() );
920 
921  if( it != m_cursorSettings.end() )
922  {
924 
925  // Tool has overridden the cursor position, so store the new settings
927  {
928  if( !curr.m_forceCursorPosition )
929  it->second = NULLOPT;
930  else
931  it->second = curr.m_forcedPosition;
932  }
933  else
934  {
935  OPT<VECTOR2D> cursor = it->second;
936 
937  if( cursor )
938  {
939  aState->vcSettings.m_forceCursorPosition = true;
940  aState->vcSettings.m_forcedPosition = *cursor;
941  }
942  else
943  {
944  aState->vcSettings.m_forceCursorPosition = false;
945  }
946  }
947  }
948  }
949 }
950 
951 
953 {
955 }
956 
957 
959 {
960  wxLogTrace( kicadTraceToolStack, "TOOL_MANAGER::processEvent %s", aEvent.Format() );
961 
962  // First try to dispatch the action associated with the event if it is a key press event
963  bool handled = dispatchHotKey( aEvent );
964 
965  if( !handled )
966  {
967  // If the event is not handled through a hotkey activation, pass it to the currently
968  // running tool loops
969  handled |= dispatchInternal( aEvent );
970  handled |= dispatchActivation( aEvent );
971 
972  // Open the context menu if requested by a tool
973  DispatchContextMenu( aEvent );
974 
975  // Dispatch any remaining events in the event queue
976  while( !m_eventQueue.empty() )
977  {
978  TOOL_EVENT event = m_eventQueue.front();
979  m_eventQueue.pop_front();
980  processEvent( event );
981  }
982  }
983 
984  wxLogTrace( kicadTraceToolStack, "TOOL_MANAGER::processEvent handled: %s %s",
985  ( handled ? "true" : "false" ), aEvent.Format() );
986 
987  return handled;
988 }
989 
990 
992 {
995 
996  m_activeState = aState;
997 
999  applyViewControls( aState );
1000 }
1001 
1002 
1004 {
1005  auto it = m_toolIdIndex.find( aId );
1006  return !it->second->idle;
1007 }
1008 
1009 
1010 void TOOL_MANAGER::UpdateUI( const TOOL_EVENT& aEvent )
1011 {
1012  EDA_BASE_FRAME* frame = GetEditFrame();
1013 
1014  if( frame )
1015  {
1016  frame->UpdateStatusBar();
1017 
1018  if( !aEvent.IsMotion() && !aEvent.IsDrag() )
1019  frame->SyncToolbars();
1020  }
1021 }
void RunMainStack(std::function< void()> func)
Function RunMainStack()
Definition: coroutine.h:204
bool m_menuActive
Flag indicating whether a context menu is currently displayed.
Definition: tool_manager.h:536
void DispatchContextMenu(const TOOL_EVENT &aEvent)
Function DispatchContextMenu() Handles context menu related events.
TOOL_TYPE GetType() const
Function GetType() Returns the type of the tool.
Definition: tool_base.h:110
VECTOR2D m_menuCursor
Right click context menu position.
Definition: tool_manager.h:531
void UpdateUI(const TOOL_EVENT &aEvent)
Updates the status bar and synchronizes toolbars.
virtual bool Init()
Function Init() Init() is called once upon a registration of the tool.
Definition: tool_base.h:92
void Reset()
Restores the default settings
TOOL_STATE(TOOL_BASE *aTool)
TOOL_STATE & operator=(const TOOL_STATE &aState)
int GetHotKey(const TOOL_ACTION &aAction)
const std::string Format() const
Function Format() Returns information about event in form of a human-readable string.
Definition: tool_event.cpp:69
TOOL_BASE * theTool
The tool itself.
ACTION_MANAGER * m_actionMgr
Instance of ACTION_MANAGER that handles TOOL_ACTIONs.
Definition: tool_manager.h:517
EDA_BASE_FRAME * GetEditFrame() const
Definition: tool_manager.h:256
bool processEvent(const TOOL_EVENT &aEvent)
Main function for event processing.
static TOOL_ID MakeToolId(const std::string &aToolName)
Generates a unique ID from for a tool with given name.
int GetPriority(int aToolId) const
Returns priority of a given tool.
std::vector< TRANSITION > transitions
List of possible transitions (ie.
Class ACTION_MENU.
Definition: action_menu.h:43
ID_STATE_MAP m_toolIdIndex
Index of the registered tools current states, associated by tools' ID numbers.
Definition: tool_manager.h:508
void ScheduleNextState(TOOL_BASE *aTool, TOOL_STATE_FUNC &aHandler, const TOOL_EVENT_LIST &aConditions)
Defines a state transition - the events that cause a given handler method in the tool to be called.
OPT< const TOOL_EVENT & > Matches(const TOOL_EVENT &aEvent) const
Definition: tool_event.h:581
bool SaveClipboard(const std::string &aText)
Stores an information to the system clipboard.
bool Call(ArgType aArg)
Function Call()
Definition: coroutine.h:218
TOOL_ACTIONS Action() const
Returns more specific information about the type of an event.
Definition: tool_event.h:247
void ApplySettings(const VC_SETTINGS &aSettings)
Applies VIEW_CONTROLS settings from an object
KIGFX::VC_SETTINGS vcSettings
VIEW_CONTROLS settings to preserve settings when the tools are switched.
TOOL_ID GetId() const
Function GetId() Returns the unique identifier of the tool.
Definition: tool_base.h:121
bool IsClick(int aButtonMask=BUT_ANY) const
Definition: tool_event.cpp:174
std::map< TOOL_ID, OPT< VECTOR2D > > m_cursorSettings
Original cursor position, if overridden by the context menu handler.
Definition: tool_manager.h:520
Tool is invoked after being inactive.
Definition: tool_base.h:81
ID_LIST::iterator finishTool(TOOL_STATE *aState)
Function finishTool() Deactivates a tool and does the necessary clean up.
bool dispatchActivation(const TOOL_EVENT &aEvent)
Function dispatchActivation() Checks if it is a valid activation event and invokes a proper tool.
bool IsMotion() const
Definition: tool_event.h:303
VECTOR2D m_forcedPosition
Forced cursor position (world coordinates)
Definition: view_controls.h:58
ACTION_MENU * contextMenu
Context menu currently used by the tool.
bool RunAction(const std::string &aActionName, bool aNow=false, T aParam=NULL)
Function RunAction() Runs the specified action.
Definition: tool_manager.h:109
bool operator==(const TOOL_MANAGER::TOOL_STATE &aRhs) const
void UpdateHotKeys(bool aFullUpdate)
Function UpdateHotKeys() Optionally reads the hotkey config files and then rebuilds the internal hotk...
TOOL_EVENT_CATEGORY Category() const
Returns the category (eg. mouse/keyboard/action) of an event..
Definition: tool_event.h:244
void attachManager(TOOL_MANAGER *aManager)
Function attachManager()
Definition: tool_base.cpp:60
Class ACTION_MANAGER.
TOOL_BASE * FindTool(int aId) const
Function FindTool() Searches for a tool with given ID.
TOOL_EVENT * ScheduleWait(TOOL_BASE *aTool, const TOOL_EVENT_LIST &aConditions)
Pauses execution of a given tool until one or more events matching aConditions arrives.
void applyViewControls(TOOL_STATE *aState)
Function applyViewControls() Applies VIEW_CONTROLS settings stored in a TOOL_STATE object.
void Push()
Function Push() Stores the current state of the tool on stack.
bool runTool(TOOL_ID aToolId)
Function runTool() Makes a tool active, so it can receive events and react to them.
void DeactivateTool()
Function DeactivateTool() Deactivates the currently active tool.
bool InvokeTool(TOOL_ID aToolId)
Function InvokeTool() Calls a tool by sending a tool activation event to tool of given ID.
virtual void SyncToolbars()
Update the toolbars (mostly settings/check buttons/checkboxes) with the current controller state.
const std::map< std::string, TOOL_ACTION * > & GetActions()
Get a list of currently-registered actions mapped by their name.
TOOL_ACTION * FindAction(const std::string &aActionName) const
Function FindAction() Finds an action with a given name (if there is one available).
const VC_SETTINGS & GetSettings() const
Returns the current VIEW_CONTROLS settings
EDA_BASE_FRAME * m_frame
Definition: tool_manager.h:525
virtual void UpdateStatusBar()
Update the status bar information.
bool RunHotKey(int aHotKey) const
Function RunHotKey() Runs an action associated with a hotkey (if there is one available).
EDA_ITEM * m_model
Definition: tool_manager.h:522
bool pendingWait
Flag defining if the tool is waiting for any event (i.e.
void SetParameter(T aParam)
Function SetParameter() Sets a non-standard parameter assigned to the event.
Definition: tool_event.h:445
virtual void Reset(RESET_REASON aReason)=0
Function Reset() Brings the tool to a known, initial state.
bool pendingContextMenu
Is there a context menu being displayed.
NAME_STATE_MAP m_toolNameIndex
Index of the registered tools current states, associated by tools' names.
Definition: tool_manager.h:505
int TOOL_ID
Unique identifier for tools.
Definition: tool_base.h:56
virtual void WarpCursor(const VECTOR2D &aPosition, bool aWorldCoordinates=false, bool aWarpView=false)=0
Function WarpCursor() If enabled (.
Class TOOL_EVENT_LIST.
Definition: tool_event.h:556
Tool that interacts with the user
Definition: tool_base.h:49
bool IsDrag(int aButtonMask=BUT_ANY) const
Definition: tool_event.h:293
const auto NULLOPT
Definition: optional.h:9
bool m_forceCursorPosition
Is the forced cursor position enabled
Definition: view_controls.h:61
TOOL_ID m_menuOwner
Tool currently displaying a popup menu. It is negative when there is no menu displayed.
Definition: tool_manager.h:539
const std::map< std::string, TOOL_ACTION * > & GetActions()
bool dispatchHotKey(const TOOL_EVENT &aEvent)
Function dispatchStandardEvents() Handles specific events, that are intended for TOOL_MANAGER rather ...
void setActiveState(TOOL_STATE *aState)
Saves the previous active state and sets a new one.
bool ProcessEvent(const TOOL_EVENT &aEvent)
Propagates an event to tools that requested events of matching type(s).
CONTEXT_MENU_TRIGGER
Defines when a context menu is opened.
Definition: tool_event.h:156
int GetHotKey(const TOOL_ACTION &aAction) const
Function GetHotKey() Returns the hot key associated with a given action or 0 if there is none.
Class TOOL_EVENT.
Definition: tool_event.h:168
bool idle
Is the tool active (pending execution) or disabled at the moment.
std::stack< std::unique_ptr< TOOL_STATE > > stateStack
Stack preserving previous states of a TOOL.
bool operator!=(const TOOL_MANAGER::TOOL_STATE &aRhs) const
const KIGFX::VC_SETTINGS & GetCurrentToolVC() const
Returns the view controls settings for the current tool or the general settings if there is no active...
Base window classes and related definitions.
Structure to keep VIEW_CONTROLS settings for easy store/restore operations
Definition: view_controls.h:44
void ResetTools(TOOL_BASE::RESET_REASON aReason)
Function ResetTools() Resets all tools (i.e.
Class VIEW_CONTROLS is an interface for classes handling user events controlling the view behaviour (...
wxLogTrace helper definitions.
ACTION_MENU * Clone() const
Creates a deep, recursive copy of this ACTION_MENU.
virtual void ForceCursorPosition(bool aEnabled, const VECTOR2D &aPosition=VECTOR2D(0, 0))
Function ForceCursorPosition() Places the cursor immediately at a given point.
Struct describing the current execution state of a TOOL.
KIGFX::VIEW_CONTROLS * m_viewControls
Definition: tool_manager.h:524
bool Resume()
Function Resume()
Definition: coroutine.h:252
std::function< int(const TOOL_EVENT &)> TOOL_STATE_FUNC
Definition: tool_base.h:58
TOOL_STATE * GetCurrentToolState() const
Returns the TOOL_STATE object representing the state of the active tool.
Definition: tool_manager.h:285
bool isActive(TOOL_BASE *aTool)
Function isActive() Returns information about a tool activation status.
KIGFX::VIEW * m_view
Definition: tool_manager.h:523
void RunMainStack(TOOL_BASE *aTool, std::function< void()> aFunc)
TOOL_EVENT wakeupEvent
The event that triggered the execution/wakeup of the tool after Wait() call.
int Modifier(int aMask=MD_MODIFIER_MASK) const
Returns information about key modifiers state (Ctrl, Alt, etc.)
Definition: tool_event.h:334
bool m_warpMouseAfterContextMenu
Definition: tool_manager.h:533
bool isRegistered(TOOL_BASE *aTool) const
Function isRegistered() Returns information about a tool registration status.
Definition: tool_manager.h:463
OPT< std::string > GetCommandStr() const
Definition: tool_event.h:455
bool IsActivate() const
Definition: tool_event.h:318
std::list< TOOL_EVENT > m_eventQueue
Queue that stores events to be processed at the end of the event processing cycle.
Definition: tool_manager.h:528
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:252
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, CPTREE &aTree)
Function Format outputs a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition: ptree.cpp:205
bool Pop()
Function Pop() Restores state of the tool from stack.
TOOL_STATE * m_activeState
Pointer to the state object corresponding to the currently executed tool.
Definition: tool_manager.h:542
COROUTINE< int, const TOOL_EVENT & > * cofunc
Tool execution context.
Class TOOL_BASE.
Definition: tool_base.h:67
The base frame for deriving all KiCad main window classes.
Class TOOL_ACTION.
Definition: tool_action.h:46
std::string GetClipboard() const
Returns the information currently stored in the system clipboard.
bool IsChoiceMenu() const
Definition: tool_event.h:328
TOOL_EVENT MakeEvent() const
Function MakeEvent() Returns the event associated with the action (i.e.
Definition: tool_action.h:107
Class EDA_ITEM is a base class for most all the KiCad significant classes, used in schematics and boa...
Definition: base_struct.h:163
void SetEnvironment(EDA_ITEM *aModel, KIGFX::VIEW *aView, KIGFX::VIEW_CONTROLS *aViewControls, EDA_BASE_FRAME *aFrame)
Sets the work environment (model, view, view controls and the parent window).
RESET_REASON
Determines the reason of reset for a tool
Definition: tool_base.h:79
const wxChar *const kicadTraceToolStack
Flag to enable tracing of the tool handling stack.
boost::optional< T > OPT
Definition: optional.h:7
bool Running() const
Function Running()
Definition: coroutine.h:293
CONTEXT_MENU_TRIGGER contextMenuTrigger
Defines when the context menu is opened.
TOOL_BASE * FirstResponder() const
Definition: tool_event.h:260
void InitTools()
Function InitTools() Initializes all registered tools.
bool IsToolActive(TOOL_ID aId) const
Function IsToolActive() Returns true if a tool with given id is active (executing)
const std::string & GetName() const
Function GetName() Returns the name of the tool.
Definition: tool_base.h:132
Class VIEW.
Definition: view.h:61
void ClearTransitions(TOOL_BASE *aTool)
Clears the state transition map for a tool.
int KeyCode() const
Definition: tool_event.h:339
ID_LIST m_activeTools
Stack of the active tools.
Definition: tool_manager.h:514
TOOL_EVENT_LIST waitEvents
List of events the tool is currently waiting for.
void clear()
Restores the initial state.
void PostEvent(const TOOL_EVENT &aEvent)
Puts an event to the event queue to be processed at the end of event processing cycle.
Definition: tool_manager.h:228
TOOL_STATE_MAP m_toolState
Index of registered tools current states, associated by tools' objects.
Definition: tool_manager.h:502
void ScheduleContextMenu(TOOL_BASE *aTool, ACTION_MENU *aMenu, CONTEXT_MENU_TRIGGER aTrigger)
Sets behaviour of the tool's context popup menu.
TOOL_STATE(const TOOL_STATE &aState)
void saveViewControls(TOOL_STATE *aState)
Function saveViewControls() Saves the VIEW_CONTROLS settings to the tool state object.
bool invokeTool(TOOL_BASE *aTool)
Function invokeTool() Invokes a tool by sending a proper event (in contrary to runTool,...
bool IsDirty() const
Function IsDirty() Returns true if any of the VIEW layers needs to be refreshened.
Definition: view.h:557
VECTOR2D GetCursorPosition() const
Returns the current cursor position in world coordinates.
void RegisterTool(TOOL_BASE *aTool)
Function RegisterTool() Adds a tool to the manager set and sets it up.
bool dispatchInternal(const TOOL_EVENT &aEvent)
Function dispatchInternal Passes an event at first to the active tools, then to all others.
void KiYield()
Function KiYield()
Definition: coroutine.h:169
std::pair< TOOL_EVENT_LIST, TOOL_STATE_FUNC > TRANSITION
Definition: tool_manager.h:384
virtual void RefreshCanvas()
Notification to refresh the drawing canvas (if any).
std::map< const char *, TOOL_BASE * > m_toolTypes
Index of the registered tools to easily lookup by their type.
Definition: tool_manager.h:511