KiCad PCB EDA Suite
sim_plot_frame.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) 2016 CERN
5  * Copyright (C) 2016-2018 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 3
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  * https://www.gnu.org/licenses/gpl-3.0.html
22  * or you may search the http://www.gnu.org website for the version 3 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 <wx/stc/stc.h>
28 
29 #include <sch_edit_frame.h>
30 #include <eeschema_id.h>
31 #include <kiway.h>
32 #include <confirm.h>
33 #include <bitmaps.h>
35 #include <widgets/tuner_slider.h>
38 #include <pgm_base.h>
39 #include "sim_plot_frame.h"
40 #include "sim_plot_panel.h"
41 #include "spice_simulator.h"
42 #include "spice_reporter.h"
43 #include <menus_helpers.h>
44 #include <tool/tool_manager.h>
45 #include <tools/ee_actions.h>
46 
48 {
49  int res = (int) aFirst | (int) aSecond;
50 
51  return (SIM_PLOT_TYPE) res;
52 }
53 
54 
56 {
57 public:
59  : m_parent( aParent )
60  {
61  }
62 
63  REPORTER& Report( const wxString& aText, SEVERITY aSeverity = RPT_UNDEFINED ) override
64  {
65  wxCommandEvent* event = new wxCommandEvent( EVT_SIM_REPORT );
66  event->SetString( aText );
67  wxQueueEvent( m_parent, event );
68  return *this;
69  }
70 
71  bool HasMessage() const override
72  {
73  return false; // Technically "indeterminate" rather than false.
74  }
75 
76  void OnSimStateChange( SPICE_SIMULATOR* aObject, SIM_STATE aNewState ) override
77  {
78  wxCommandEvent* event = NULL;
79 
80  switch( aNewState )
81  {
82  case SIM_IDLE:
83  event = new wxCommandEvent( EVT_SIM_FINISHED );
84  break;
85 
86  case SIM_RUNNING:
87  event = new wxCommandEvent( EVT_SIM_STARTED );
88  break;
89 
90  default:
91  wxFAIL;
92  return;
93  }
94 
95  wxQueueEvent( m_parent, event );
96  }
97 
98 private:
100 };
101 
102 
103 TRACE_DESC::TRACE_DESC( const NETLIST_EXPORTER_PSPICE_SIM& aExporter, const wxString& aName,
104  SIM_PLOT_TYPE aType, const wxString& aParam )
105  : m_name( aName ), m_type( aType ), m_param( aParam )
106 {
107  // Title generation
108  m_title = wxString::Format( "%s(%s)", aParam, aName );
109 
110  if( aType & SPT_AC_MAG )
111  m_title += " (mag)";
112  else if( aType & SPT_AC_PHASE )
113  m_title += " (phase)";
114 }
115 
116 // Store the path of saved workbooks during the session
118 
119 SIM_PLOT_FRAME::SIM_PLOT_FRAME( KIWAY* aKiway, wxWindow* aParent )
120  : SIM_PLOT_FRAME_BASE( aParent ), m_lastSimPlot( nullptr )
121 {
122  SetKiway( this, aKiway );
123  m_signalsIconColorList = NULL;
124 
126 
127  if( m_schematicFrame == NULL )
128  throw std::runtime_error( "There is no schematic window" );
129 
130  // Give an icon
131  wxIcon icon;
132  icon.CopyFromBitmap( KiBitmap( simulator_xpm ) );
133  SetIcon( icon );
134 
135  // Gives a minimal size
136  SetSizeHints( 500, 400, -1, -1, -1, -1 );
137 
138  // Get the previous size and position of windows:
139  LoadSettings( config() );
140 
141  // Give icons to menuitems
143 
145 
146  if( !m_simulator )
147  {
148  throw std::runtime_error( "Could not create simulator instance" );
149  return;
150  }
151 
152  m_simulator->Init();
153 
154  if( m_savedWorkbooksPath.IsEmpty() )
155  {
157  }
158 
159  m_reporter = new SIM_THREAD_REPORTER( this );
160  m_simulator->SetReporter( m_reporter );
161 
163 
164  Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( SIM_PLOT_FRAME::onClose ), NULL, this );
165  Connect( EVT_SIM_UPDATE, wxCommandEventHandler( SIM_PLOT_FRAME::onSimUpdate ), NULL, this );
166  Connect( EVT_SIM_REPORT, wxCommandEventHandler( SIM_PLOT_FRAME::onSimReport ), NULL, this );
167  Connect( EVT_SIM_STARTED, wxCommandEventHandler( SIM_PLOT_FRAME::onSimStarted ), NULL, this );
168  Connect( EVT_SIM_FINISHED, wxCommandEventHandler( SIM_PLOT_FRAME::onSimFinished ), NULL, this );
169  Connect( EVT_SIM_CURSOR_UPDATE, wxCommandEventHandler( SIM_PLOT_FRAME::onCursorUpdate ), NULL, this );
170 
171  // Toolbar buttons
172  m_toolSimulate = m_toolBar->AddTool( ID_SIM_RUN, _( "Run/Stop Simulation" ),
173  KiBitmap( sim_run_xpm ), _( "Run Simulation" ), wxITEM_NORMAL );
174  m_toolAddSignals = m_toolBar->AddTool( ID_SIM_ADD_SIGNALS, _( "Add Signals" ),
175  KiBitmap( sim_add_signal_xpm ), _( "Add signals to plot" ), wxITEM_NORMAL );
176  m_toolProbe = m_toolBar->AddTool( ID_SIM_PROBE, _( "Probe" ),
177  KiBitmap( sim_probe_xpm ), _( "Probe signals on the schematic" ), wxITEM_NORMAL );
178  m_toolTune = m_toolBar->AddTool( ID_SIM_TUNE, _( "Tune" ),
179  KiBitmap( sim_tune_xpm ), _( "Tune component values" ), wxITEM_NORMAL );
180  m_toolSettings = m_toolBar->AddTool( wxID_ANY, _( "Settings" ),
181  KiBitmap( sim_settings_xpm ), _( "Simulation settings" ), wxITEM_NORMAL );
182 
183  Connect( m_toolSimulate->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
184  wxCommandEventHandler( SIM_PLOT_FRAME::onSimulate ), NULL, this );
185  Connect( m_toolAddSignals->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
186  wxCommandEventHandler( SIM_PLOT_FRAME::onAddSignal ), NULL, this );
187  Connect( m_toolProbe->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
188  wxCommandEventHandler( SIM_PLOT_FRAME::onProbe ), NULL, this );
189  Connect( m_toolTune->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
190  wxCommandEventHandler( SIM_PLOT_FRAME::onTune ), NULL, this );
191  Connect( m_toolSettings->GetId(), wxEVT_COMMAND_TOOL_CLICKED,
192  wxCommandEventHandler( SIM_PLOT_FRAME::onSettings ), NULL, this );
193 
194  // Bind toolbar buttons event to existing menu event handlers, so they behave the same
195  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onSimulate, this, m_runSimulation->GetId() );
196  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onAddSignal, this, m_addSignals->GetId() );
197  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onProbe, this, m_probeSignals->GetId() );
198  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onTune, this, m_tuneValue->GetId() );
199  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onShowNetlist, this, m_showNetlist->GetId() );
200  Bind( wxEVT_COMMAND_MENU_SELECTED, &SIM_PLOT_FRAME::onSettings, this, m_settings->GetId() );
201 
202  m_toolBar->Realize();
203  m_plotNotebook->SetPageText( 0, _( "Welcome!" ) );
204 
205  // the settings dialog will be created later, on demand.
206  // if created in the ctor, for some obscure reason, there is an issue
207  // on Windows: when open it, the simulator frame is sent to the background.
208  // instead of being behind the dialog frame (as it does)
209  m_settingsDlg = NULL;
210 
211  // resize the subwindows size. At least on Windows, calling wxSafeYield before
212  // resizing the subwindows forces the wxSplitWindows size events automatically generated
213  // by wxWidgets to be executed before our resize code.
214  // Otherwise, the changes made by setSubWindowsSashSize are overwritten by one these
215  // events
216  wxSafeYield();
218 }
219 
220 
222 {
223  m_simulator->SetReporter( nullptr );
224  delete m_reporter;
225  delete m_signalsIconColorList;
226 
227  if( m_settingsDlg )
228  m_settingsDlg->Destroy();
229 }
230 
231 #define PLOT_PANEL_WIDTH_ENTRY "SimPlotPanelWidth"
232 #define PLOT_PANEL_HEIGHT_ENTRY "SimPlotPanelHeight"
233 #define SIGNALS_PANEL_HEIGHT_ENTRY "SimSignalPanelHeight"
234 #define CURSORS_PANEL_HEIGHT_ENTRY "SimCursorsPanelHeight"
235 
236 void SIM_PLOT_FRAME::SaveSettings( wxConfigBase* aCfg )
237 {
238  // Save main frame size and position:
240 
241  // Save subwindows sizes
242  aCfg->Write( PLOT_PANEL_WIDTH_ENTRY, m_splitterLeftRight->GetSashPosition() );
243  aCfg->Write( PLOT_PANEL_HEIGHT_ENTRY, m_splitterPlotAndConsole->GetSashPosition() );
244  aCfg->Write( SIGNALS_PANEL_HEIGHT_ENTRY, m_splitterSignals->GetSashPosition() );
245  aCfg->Write( CURSORS_PANEL_HEIGHT_ENTRY, m_splitterTuneValues->GetSashPosition() );
246 }
247 
248 
249 void SIM_PLOT_FRAME::LoadSettings( wxConfigBase* aCfg )
250 {
251  // Read main frame size and position:
253  SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y );
254 
255  // Read subwindows sizes (should be > 0 )
260 }
261 
262 
263 // A small helper struct to handle bitmaps initialisation in menus
265 {
266  int m_MenuId;
267  BITMAP_DEF m_Bitmap;
268 };
269 
270 
272 {
273  // Give icons to menuitems of the main menubar
274  BM_MENU_INIT_ITEM bm_list[]
275  {
276  // File menu:
277  { wxID_NEW, simulator_xpm },
278  { wxID_OPEN,directory_browser_xpm },
279  { wxID_SAVE, directory_xpm},
280  { ID_SAVE_AS_IMAGE, export_xpm},
281  { ID_SAVE_AS_CSV, export_xpm},
282  { wxID_CLOSE, exit_xpm},
283 
284  // simulator menu:
285  { ID_MENU_RUN_SIM, sim_run_xpm},
286  { ID_MENU_ADD_SIGNAL, sim_add_signal_xpm},
287  { ID_MENU_PROBE_SIGNALS, sim_probe_xpm},
288  { ID_MENU_TUNE_SIGNALS, sim_tune_xpm},
289  { ID_MENU_SHOW_NETLIST, netlist_xpm},
290  { ID_MENU_SET_SIMUL, sim_settings_xpm},
291 
292  // View menu
293  { wxID_ZOOM_IN, zoom_in_xpm},
294  { wxID_ZOOM_OUT, zoom_out_xpm},
295  { wxID_ZOOM_FIT, zoom_fit_in_page_xpm},
296  { ID_MENU_SHOW_GRID, grid_xpm},
298 
299  { 0, nullptr } // Sentinel
300  };
301 
302  // wxMenuItems are already created and attached to the m_mainMenu wxMenuBar.
303  // A problem is the fact setting bitmaps in wxMenuItems after they are attached
304  // to a wxMenu do not work in all cases.
305  // So the trick is:
306  // Remove the wxMenuItem from its wxMenu
307  // Set the bitmap
308  // Insert the modified wxMenuItem to its previous place
309  for( int ii = 0; bm_list[ii].m_MenuId; ++ii )
310  {
311  wxMenuItem* item = m_mainMenu->FindItem( bm_list[ii].m_MenuId );
312 
313  if( !item || !bm_list[ii].m_Bitmap)
314  continue;
315 
316  wxMenu* menu = item->GetMenu();
317  // Calculate the initial index of item inside the wxMenu parent
318  wxMenuItemList& mlist = menu->GetMenuItems();
319  int mpos = mlist.IndexOf( item );
320 
321  if( mpos >= 0 ) // Should be always the case
322  {
323  // Modify the bitmap
324  menu->Remove( item );
325  AddBitmapToMenuItem( item, KiBitmap( bm_list[ii].m_Bitmap ) );
326  // Insert item to its the initial index
327  menu->Insert( mpos, item );
328  }
329  }
330 }
331 
332 
334 {
337 
340 
343 
346 }
347 
348 
350 {
351  STRING_FORMATTER formatter;
352  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
353 
354  if( !m_settingsDlg )
355  m_settingsDlg = new DIALOG_SIM_SETTINGS( this );
356 
357  m_simConsole->Clear();
359 
360  if( plotPanel )
361  m_exporter->SetSimCommand( m_plots[plotPanel].m_simCommand );
362 
363  if( !m_exporter->Format( &formatter, m_settingsDlg->GetNetlistOptions() ) )
364  {
365  DisplayError( this, _( "There were errors during netlist export, aborted." ) );
366  return;
367  }
368 
369  if( m_exporter->GetSimType() == ST_UNKNOWN )
370  {
371  DisplayInfoMessage( this, _( "You need to select the simulation settings first." ) );
372  return;
373  }
374 
375  m_simulator->LoadNetlist( formatter.GetString() );
376  updateTuners();
377  applyTuners();
378  m_simulator->Run();
379 }
380 
381 
383 {
384  m_simulator->Stop();
385 }
386 
387 
389 {
390  return m_simulator ? m_simulator->IsRunning() : false;
391 }
392 
393 
395 {
396  SIM_PLOT_PANEL* plotPanel = new SIM_PLOT_PANEL( aSimType, m_plotNotebook, wxID_ANY );
397 
398  if( m_welcomePanel )
399  {
400  m_plotNotebook->DeletePage( 0 );
401  m_welcomePanel = nullptr;
402  }
403 
404  m_plotNotebook->AddPage( plotPanel, wxString::Format( _( "Plot%u" ),
405  (unsigned int) m_plotNotebook->GetPageCount() + 1 ), true );
406 
407  m_plots[plotPanel] = PLOT_INFO();
408 
409  return plotPanel;
410 }
411 
412 
413 void SIM_PLOT_FRAME::AddVoltagePlot( const wxString& aNetName )
414 {
415  addPlot( aNetName, SPT_VOLTAGE, "V" );
416 }
417 
418 
419 void SIM_PLOT_FRAME::AddCurrentPlot( const wxString& aDeviceName, const wxString& aParam )
420 {
421  addPlot( aDeviceName, SPT_CURRENT, aParam );
422 }
423 
424 
426 {
427  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
428 
429  if( !plotPanel )
430  return;
431 
432  // For now limit the tuner tool to RLC components
433  char primitiveType = NETLIST_EXPORTER_PSPICE::GetSpiceField( SF_PRIMITIVE, aComponent, 0 )[0];
434 
435  if( primitiveType != SP_RESISTOR && primitiveType != SP_CAPACITOR && primitiveType != SP_INDUCTOR )
436  return;
437 
438  const wxString componentName = aComponent->GetField( REFERENCE )->GetText();
439 
440  // Do not add multiple instances for the same component
441  auto tunerIt = std::find_if( m_tuners.begin(), m_tuners.end(), [&]( const TUNER_SLIDER* t )
442  {
443  return t->GetComponentName() == componentName;
444  }
445  );
446 
447  if( tunerIt != m_tuners.end() )
448  return; // We already have it
449 
450  try
451  {
452  TUNER_SLIDER* tuner = new TUNER_SLIDER( this, m_tunePanel, aComponent );
453  m_tuneSizer->Add( tuner );
454  m_tuners.push_back( tuner );
455  m_tunePanel->Layout();
456  }
457  catch( const KI_PARAM_ERROR& e )
458  {
459  // Sorry, no bonus
460  DisplayError( nullptr, e.What() );
461  }
462 }
463 
464 
465 void SIM_PLOT_FRAME::RemoveTuner( TUNER_SLIDER* aTuner, bool aErase )
466 {
467  if( aErase )
468  m_tuners.remove( aTuner );
469 
470  aTuner->Destroy();
471  m_tunePanel->Layout();
472 }
473 
474 
476 {
477  wxWindow* curPage = m_plotNotebook->GetCurrentPage();
478 
479  return ( curPage == m_welcomePanel ) ? nullptr : static_cast<SIM_PLOT_PANEL*>( curPage );
480 }
481 
482 
484 {
485  return m_exporter.get();
486 }
487 
488 
489 void SIM_PLOT_FRAME::addPlot( const wxString& aName, SIM_PLOT_TYPE aType, const wxString& aParam )
490 {
491  SIM_TYPE simType = m_exporter->GetSimType();
492 
493  if( !SIM_PLOT_PANEL::IsPlottable( simType ) )
494  return; // TODO else write out in console?
495 
496  // Create a new plot if the current one displays a different type
497  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
498 
499  if( !plotPanel || plotPanel->GetType() != simType )
500  plotPanel = NewPlotPanel( simType );
501 
502  TRACE_DESC descriptor( *m_exporter, aName, aType, aParam );
503 
504  bool updated = false;
505  SIM_PLOT_TYPE xAxisType = GetXAxisType( simType );
506 
507  if( xAxisType == SPT_LIN_FREQUENCY || xAxisType == SPT_LOG_FREQUENCY )
508  {
509  int baseType = descriptor.GetType() & ~( SPT_AC_MAG | SPT_AC_PHASE );
510 
511  // Add two plots: magnitude & phase
512  TRACE_DESC mag_desc( *m_exporter, descriptor, (SIM_PLOT_TYPE)( baseType | SPT_AC_MAG ) );
513  TRACE_DESC phase_desc( *m_exporter, descriptor, (SIM_PLOT_TYPE)( baseType | SPT_AC_PHASE ) );
514 
515  updated |= updatePlot( mag_desc, plotPanel );
516  updated |= updatePlot( phase_desc, plotPanel );
517  }
518  else
519  {
520  updated = updatePlot( descriptor, plotPanel );
521  }
522 
523  if( updated )
524  {
526  }
527 }
528 
529 
530 void SIM_PLOT_FRAME::removePlot( const wxString& aPlotName, bool aErase )
531 {
532  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
533 
534  if( !plotPanel )
535  return;
536 
537  if( aErase )
538  {
539  auto& traceMap = m_plots[plotPanel].m_traces;
540  auto traceIt = traceMap.find( aPlotName );
541  wxASSERT( traceIt != traceMap.end() );
542  traceMap.erase( traceIt );
543  }
544 
545  wxASSERT( plotPanel->TraceShown( aPlotName ) );
546  plotPanel->DeleteTrace( aPlotName );
547  plotPanel->Fit();
548 
550  updateCursors();
551 }
552 
553 
555 {
557 }
558 
559 
560 bool SIM_PLOT_FRAME::updatePlot( const TRACE_DESC& aDescriptor, SIM_PLOT_PANEL* aPanel )
561 {
562  SIM_TYPE simType = m_exporter->GetSimType();
563  wxString spiceVector = m_exporter->GetSpiceVector( aDescriptor.GetName(),
564  aDescriptor.GetType(), aDescriptor.GetParam() );
565 
566  if( !SIM_PLOT_PANEL::IsPlottable( simType ) )
567  {
568  // There is no plot to be shown
569  m_simulator->Command( wxString::Format( "print %s", spiceVector ).ToStdString() );
570 
571  return false;
572  }
573 
574  // First, handle the x axis
575  wxString xAxisName( m_simulator->GetXAxis( simType ) );
576 
577  if( xAxisName.IsEmpty() )
578  return false;
579 
580  auto data_x = m_simulator->GetMagPlot( (const char*) xAxisName.c_str() );
581  unsigned int size = data_x.size();
582 
583  if( data_x.empty() )
584  return false;
585 
586  SIM_PLOT_TYPE plotType = aDescriptor.GetType();
587  std::vector<double> data_y;
588 
589  // Now, Y axis data
590  switch( m_exporter->GetSimType() )
591  {
592  case ST_AC:
593  {
594  wxASSERT_MSG( !( ( plotType & SPT_AC_MAG ) && ( plotType & SPT_AC_PHASE ) ),
595  "Cannot set both AC_PHASE and AC_MAG bits" );
596 
597  if( plotType & SPT_AC_MAG )
598  data_y = m_simulator->GetMagPlot( (const char*) spiceVector.c_str() );
599  else if( plotType & SPT_AC_PHASE )
600  data_y = m_simulator->GetPhasePlot( (const char*) spiceVector.c_str() );
601  else
602  wxASSERT_MSG( false, "Plot type missing AC_PHASE or AC_MAG bit" );
603  }
604  break;
605 
606  case ST_NOISE:
607  case ST_DC:
608  case ST_TRANSIENT:
609  {
610  data_y = m_simulator->GetMagPlot( (const char*) spiceVector.c_str() );
611  }
612  break;
613 
614  default:
615  wxASSERT_MSG( false, "Unhandled plot type" );
616  return false;
617  }
618 
619  if( data_y.size() != size )
620  return false;
621 
622  // If we did a two-source DC analysis, we need to split the resulting vector and add traces
623  // for each input step
624  SPICE_DC_PARAMS source1, source2;
625 
626  if( m_exporter->GetSimType() == ST_DC &&
627  m_exporter->ParseDCCommand( m_exporter->GetUsedSimCommand(), &source1, &source2 ) )
628  {
629  if( !source2.m_source.IsEmpty() )
630  {
631  // Source 1 is the inner loop, so lets add traces for each Source 2 (outer loop) step
632  SPICE_VALUE v = source2.m_vstart;
633  wxString name;
634 
635  size_t offset = 0;
636  size_t outer = ( size_t )( ( source2.m_vend - v ) / source2.m_vincrement ).ToDouble();
637  size_t inner = data_x.size() / ( outer + 1 );
638 
639  wxASSERT( data_x.size() % ( outer + 1 ) == 0 );
640 
641  for( size_t idx = 0; idx <= outer; idx++ )
642  {
643  name = wxString::Format( "%s (%s = %s V)", aDescriptor.GetTitle(),
644  source2.m_source, v.ToString() );
645 
646  std::vector<double> sub_x( data_x.begin() + offset,
647  data_x.begin() + offset + inner );
648  std::vector<double> sub_y( data_y.begin() + offset,
649  data_y.begin() + offset + inner );
650 
651  if( aPanel->AddTrace( name, inner,
652  sub_x.data(), sub_y.data(), aDescriptor.GetType() ) )
653  {
654  m_plots[aPanel].m_traces.insert( std::make_pair( name, aDescriptor ) );
655  }
656 
657  v = v + source2.m_vincrement;
658  offset += inner;
659  }
660 
661  return true;
662  }
663  }
664 
665  if( aPanel->AddTrace( aDescriptor.GetTitle(), size,
666  data_x.data(), data_y.data(), aDescriptor.GetType() ) )
667  {
668  m_plots[aPanel].m_traces.insert( std::make_pair( aDescriptor.GetTitle(), aDescriptor ) );
669  }
670 
671  return true;
672 }
673 
674 
676 {
677  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
678 
679  if( !plotPanel )
680  return;
681 
682  m_signals->ClearAll();
683 
684  wxSize size = m_signals->GetClientSize();
685  m_signals->AppendColumn( _( "Signal" ), wxLIST_FORMAT_LEFT, size.x );
686 
687  // Build an image list, to show the color of the corresponding trace
688  // in the plot panel
689  // This image list is used for trace and cursor lists
690  wxMemoryDC bmDC;
691  const int isize = bmDC.GetCharHeight();
692 
693  if( m_signalsIconColorList == NULL )
694  m_signalsIconColorList = new wxImageList( isize, isize, false );
695  else
696  m_signalsIconColorList->RemoveAll();
697 
698  for( const auto& trace : CurrentPlot()->GetTraces() )
699  {
700  wxBitmap bitmap( isize, isize );
701  bmDC.SelectObject( bitmap );
702  wxColour tcolor = trace.second->GetTraceColour();
703 
704  wxColour bgColor = m_signals->wxWindow::GetBackgroundColour();
705  bmDC.SetPen( wxPen( bgColor ) );
706  bmDC.SetBrush( wxBrush( bgColor ) );
707  bmDC.DrawRectangle( 0, 0, isize, isize ); // because bmDC.Clear() does not work in wxGTK
708 
709  bmDC.SetPen( wxPen( tcolor ) );
710  bmDC.SetBrush( wxBrush( tcolor ) );
711  bmDC.DrawRectangle( 0, isize / 4 + 1, isize, isize / 2 );
712 
713  bmDC.SelectObject( wxNullBitmap ); // Needed to initialize bitmap
714 
715  bitmap.SetMask( new wxMask( bitmap, *wxBLACK ) );
716  m_signalsIconColorList->Add( bitmap );
717  }
718 
719  if( bmDC.IsOk() )
720  {
721  bmDC.SetBrush( wxNullBrush );
722  bmDC.SetPen( wxNullPen );
723  }
724 
725  m_signals->SetImageList( m_signalsIconColorList, wxIMAGE_LIST_SMALL );
726 
727  // Fill the signals listctrl. Keep the order of names and
728  // the order of icon color identical, because the icons
729  // are also used in cursor list, and the color index is
730  // calculated from the trace name index
731  int imgidx = 0;
732 
733  for( const auto& trace : m_plots[plotPanel].m_traces )
734  {
735  m_signals->InsertItem( imgidx, trace.first, imgidx );
736  imgidx++;
737  }
738 }
739 
740 
742 {
743  wxQueueEvent( this, new wxCommandEvent( EVT_SIM_CURSOR_UPDATE ) );
744 }
745 
746 
748 {
749  const auto& spiceItems = m_exporter->GetSpiceItems();
750 
751  for( auto it = m_tuners.begin(); it != m_tuners.end(); /* iteration inside the loop */ )
752  {
753  const wxString& ref = (*it)->GetComponentName();
754 
755  if( std::find_if( spiceItems.begin(), spiceItems.end(), [&]( const SPICE_ITEM& item )
756  {
757  return item.m_refName == ref;
758  }) == spiceItems.end() )
759  {
760  // The component does not exist anymore, remove the associated tuner
761  TUNER_SLIDER* tuner = *it;
762  it = m_tuners.erase( it );
763  RemoveTuner( tuner, false );
764  }
765  else
766  {
767  ++it;
768  }
769  }
770 }
771 
772 
774 {
775  for( auto& tuner : m_tuners )
776  {
778  std::string command( "alter @" + tuner->GetSpiceName()
779  + "=" + tuner->GetValue().ToSpiceString() );
780 
781  m_simulator->Command( command );
782  }
783 }
784 
785 
786 bool SIM_PLOT_FRAME::loadWorkbook( const wxString& aPath )
787 {
788  m_plots.clear();
789  m_plotNotebook->DeleteAllPages();
790 
791  wxTextFile file( aPath );
792 
793  if( !file.Open() )
794  return false;
795 
796  long plotsCount;
797 
798  if( !file.GetFirstLine().ToLong( &plotsCount ) ) // GetFirstLine instead of GetNextLine
799  return false;
800 
801  for( long i = 0; i < plotsCount; ++i )
802  {
803  long plotType, tracesCount;
804 
805  if( !file.GetNextLine().ToLong( &plotType ) )
806  return false;
807 
808  SIM_PLOT_PANEL* plotPanel = NewPlotPanel( (SIM_TYPE) plotType );
809  m_plots[plotPanel].m_simCommand = file.GetNextLine();
810  StartSimulation();
811 
812  // Perform simulation, so plots can be added with values
813  do
814  {
815  wxThread::This()->Sleep( 50 );
816  }
817  while( IsSimulationRunning() );
818 
819  if( !file.GetNextLine().ToLong( &tracesCount ) )
820  return false;
821 
822  for( long j = 0; j < tracesCount; ++j )
823  {
824  long traceType;
825  wxString name, param;
826 
827  if( !file.GetNextLine().ToLong( &traceType ) )
828  return false;
829 
830  name = file.GetNextLine();
831  param = file.GetNextLine();
832 
833  if( name.IsEmpty() || param.IsEmpty() )
834  return false;
835 
836  addPlot( name, (SIM_PLOT_TYPE) traceType, param );
837  }
838  }
839 
840  return true;
841 }
842 
843 
844 bool SIM_PLOT_FRAME::saveWorkbook( const wxString& aPath )
845 {
846 
847  wxString savePath = aPath;
848 
849  if( !savePath.Lower().EndsWith(".wbk"))
850  {
851  savePath += ".wbk";
852  };
853 
854 
855  wxTextFile file( savePath );
856 
857  if( file.Exists() )
858  {
859  if( !file.Open() )
860  return false;
861 
862  file.Clear();
863  }
864  else
865  {
866  file.Create();
867  }
868 
869  file.AddLine( wxString::Format( "%lu", m_plots.size() ) );
870 
871  for( const auto& plot : m_plots )
872  {
873  file.AddLine( wxString::Format( "%d", plot.first->GetType() ) );
874  file.AddLine( plot.second.m_simCommand );
875  file.AddLine( wxString::Format( "%lu", plot.second.m_traces.size() ) );
876 
877  for( const auto& trace : plot.second.m_traces )
878  {
879  file.AddLine( wxString::Format( "%d", trace.second.GetType() ) );
880  file.AddLine( trace.second.GetName() );
881  file.AddLine( trace.second.GetParam() );
882  }
883  }
884 
885  bool res = file.Write();
886  file.Close();
887 
888  return res;
889 }
890 
891 
893 {
894  switch( aType )
895  {
896  case ST_AC:
897  return SPT_LIN_FREQUENCY;
899 
900  case ST_DC:
901  return SPT_SWEEP;
902 
903  case ST_TRANSIENT:
904  return SPT_TIME;
905 
906  default:
907  wxASSERT_MSG( false, "Unhandled simulation type" );
908  return (SIM_PLOT_TYPE) 0;
909  }
910 }
911 
912 
913 void SIM_PLOT_FRAME::menuNewPlot( wxCommandEvent& aEvent )
914 {
915  SIM_TYPE type = m_exporter->GetSimType();
916 
917  if( SIM_PLOT_PANEL::IsPlottable( type ) )
918  {
919  SIM_PLOT_PANEL* prevPlot = CurrentPlot();
920  SIM_PLOT_PANEL* newPlot = NewPlotPanel( type );
921 
922  // If the previous plot had the same type, copy the simulation command
923  if( prevPlot )
924  m_plots[newPlot].m_simCommand = m_plots[prevPlot].m_simCommand;
925  }
926 }
927 
928 
929 void SIM_PLOT_FRAME::menuOpenWorkbook( wxCommandEvent& event )
930 {
931  wxFileDialog openDlg( this, _( "Open simulation workbook" ), m_savedWorkbooksPath, "",
932  WorkbookFileWildcard(), wxFD_OPEN | wxFD_FILE_MUST_EXIST );
933 
934  if( openDlg.ShowModal() == wxID_CANCEL )
935  return;
936 
937  m_savedWorkbooksPath = openDlg.GetDirectory();
938 
939  if( !loadWorkbook( openDlg.GetPath() ) )
940  DisplayError( this, _( "There was an error while opening the workbook file" ) );
941 }
942 
943 
944 void SIM_PLOT_FRAME::menuSaveWorkbook( wxCommandEvent& event )
945 {
946  if( !CurrentPlot() )
947  return;
948 
949  wxFileDialog saveDlg( this, _( "Save Simulation Workbook" ), m_savedWorkbooksPath, "",
950  WorkbookFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
951 
952  if( saveDlg.ShowModal() == wxID_CANCEL )
953  return;
954 
955  m_savedWorkbooksPath = saveDlg.GetDirectory();
956 
957  if( !saveWorkbook( saveDlg.GetPath() ) )
958  DisplayError( this, _( "There was an error while saving the workbook file" ) );
959 }
960 
961 
962 void SIM_PLOT_FRAME::menuSaveImage( wxCommandEvent& event )
963 {
964  if( !CurrentPlot() )
965  return;
966 
967  wxFileDialog saveDlg( this, _( "Save Plot as Image" ), "", "",
968  PngFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
969 
970  if( saveDlg.ShowModal() == wxID_CANCEL )
971  return;
972 
973  CurrentPlot()->SaveScreenshot( saveDlg.GetPath(), wxBITMAP_TYPE_PNG );
974 }
975 
976 
977 void SIM_PLOT_FRAME::menuSaveCsv( wxCommandEvent& event )
978 {
979  if( !CurrentPlot() )
980  return;
981 
982  const wxChar SEPARATOR = ';';
983 
984  wxFileDialog saveDlg( this, _( "Save Plot Data" ), "", "",
985  CsvFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
986 
987  if( saveDlg.ShowModal() == wxID_CANCEL )
988  return;
989 
990  wxFile out( saveDlg.GetPath(), wxFile::write );
991  bool timeWritten = false;
992 
993  for( const auto& t : CurrentPlot()->GetTraces() )
994  {
995  const TRACE* trace = t.second;
996 
997  if( !timeWritten )
998  {
999  out.Write( wxString::Format( "Time%c", SEPARATOR ) );
1000 
1001  for( double v : trace->GetDataX() )
1002  out.Write( wxString::Format( "%f%c", v, SEPARATOR ) );
1003 
1004  out.Write( "\r\n" );
1005  timeWritten = true;
1006  }
1007 
1008  out.Write( wxString::Format( "%s%c", t.first, SEPARATOR ) );
1009 
1010  for( double v : trace->GetDataY() )
1011  out.Write( wxString::Format( "%f%c", v, SEPARATOR ) );
1012 
1013  out.Write( "\r\n" );
1014  }
1015 
1016  out.Close();
1017 }
1018 
1019 
1020 void SIM_PLOT_FRAME::menuZoomIn( wxCommandEvent& event )
1021 {
1022  if( CurrentPlot() )
1023  CurrentPlot()->ZoomIn();
1024 }
1025 
1026 
1027 void SIM_PLOT_FRAME::menuZoomOut( wxCommandEvent& event )
1028 {
1029  if( CurrentPlot() )
1030  CurrentPlot()->ZoomOut();
1031 }
1032 
1033 
1034 void SIM_PLOT_FRAME::menuZoomFit( wxCommandEvent& event )
1035 {
1036  if( CurrentPlot() )
1037  CurrentPlot()->Fit();
1038 }
1039 
1040 
1041 void SIM_PLOT_FRAME::menuShowGrid( wxCommandEvent& event )
1042 {
1043  SIM_PLOT_PANEL* plot = CurrentPlot();
1044 
1045  if( plot )
1046  plot->ShowGrid( !plot->IsGridShown() );
1047 }
1048 
1049 
1050 void SIM_PLOT_FRAME::menuShowGridUpdate( wxUpdateUIEvent& event )
1051 {
1052  SIM_PLOT_PANEL* plot = CurrentPlot();
1053 
1054  event.Check( plot ? plot->IsGridShown() : false );
1055 }
1056 
1057 
1058 void SIM_PLOT_FRAME::menuShowLegend( wxCommandEvent& event )
1059 {
1060  SIM_PLOT_PANEL* plot = CurrentPlot();
1061 
1062  if( plot )
1063  plot->ShowLegend( !plot->IsLegendShown() );
1064 }
1065 
1066 
1067 void SIM_PLOT_FRAME::menuShowLegendUpdate( wxUpdateUIEvent& event )
1068 {
1069  SIM_PLOT_PANEL* plot = CurrentPlot();
1070  event.Check( plot ? plot->IsLegendShown() : false );
1071 }
1072 
1073 
1074 void SIM_PLOT_FRAME::onPlotClose( wxAuiNotebookEvent& event )
1075 {
1076  int idx = event.GetSelection();
1077 
1078  if( idx == wxNOT_FOUND )
1079  return;
1080 
1081  SIM_PLOT_PANEL* plotPanel = dynamic_cast<SIM_PLOT_PANEL*>( m_plotNotebook->GetPage( idx ) );
1082 
1083  if( !plotPanel )
1084  return;
1085 
1086  m_plots.erase( plotPanel );
1087  updateSignalList();
1088  updateCursors();
1089 }
1090 
1091 
1092 void SIM_PLOT_FRAME::onPlotChanged( wxAuiNotebookEvent& event )
1093 {
1094  updateSignalList();
1095  updateCursors();
1096 }
1097 
1098 
1099 void SIM_PLOT_FRAME::onSignalDblClick( wxMouseEvent& event )
1100 {
1101  // Remove signal from the plot panel when double clicked
1102  long idx = m_signals->GetFocusedItem();
1103 
1104  if( idx != wxNOT_FOUND )
1105  removePlot( m_signals->GetItemText( idx, 0 ) );
1106 }
1107 
1108 
1109 void SIM_PLOT_FRAME::onSignalRClick( wxListEvent& event )
1110 {
1111  int idx = event.GetIndex();
1112 
1113  if( idx != wxNOT_FOUND )
1114  m_signals->Select( idx );
1115 
1116  idx = m_signals->GetFirstSelected();
1117 
1118  if( idx != wxNOT_FOUND )
1119  {
1120  const wxString& netName = m_signals->GetItemText( idx, 0 );
1121  SIGNAL_CONTEXT_MENU ctxMenu( netName, this );
1122  m_signals->PopupMenu( &ctxMenu );
1123  }
1124 }
1125 
1126 
1127 void SIM_PLOT_FRAME::onSimulate( wxCommandEvent& event )
1128 {
1129  if( IsSimulationRunning() )
1130  StopSimulation();
1131  else
1132  StartSimulation();
1133 }
1134 
1135 
1136 void SIM_PLOT_FRAME::onSettings( wxCommandEvent& event )
1137 {
1138  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1139 
1140  // Initial processing is required to e.g. display a list of power sources
1142 
1143  if( !m_exporter->ProcessNetlist( NET_ALL_FLAGS ) )
1144  {
1145  DisplayError( this, _( "There were errors during netlist export, aborted." ) );
1146  return;
1147  }
1148 
1149  if( !m_settingsDlg )
1150  m_settingsDlg = new DIALOG_SIM_SETTINGS( this );
1151 
1152  if( plotPanel )
1153  m_settingsDlg->SetSimCommand( m_plots[plotPanel].m_simCommand );
1154 
1156 
1157  if( m_settingsDlg->ShowModal() == wxID_OK )
1158  {
1159  wxString newCommand = m_settingsDlg->GetSimCommand();
1160  SIM_TYPE newSimType = NETLIST_EXPORTER_PSPICE_SIM::CommandToSimType( newCommand );
1161 
1162  // If it is a new simulation type, open a new plot
1163  if( !plotPanel || ( plotPanel && plotPanel->GetType() != newSimType ) )
1164  {
1165  plotPanel = NewPlotPanel( newSimType );
1166  }
1167 
1168  m_plots[plotPanel].m_simCommand = newCommand;
1169  }
1170 }
1171 
1172 
1173 void SIM_PLOT_FRAME::onAddSignal( wxCommandEvent& event )
1174 {
1175  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1176 
1177  if( !plotPanel || !m_exporter || plotPanel->GetType() != m_exporter->GetSimType() )
1178  {
1179  DisplayInfoMessage( this, _( "You need to run simulation first." ) );
1180  return;
1181  }
1182 
1183  DIALOG_SIGNAL_LIST dialog( this, m_exporter.get() );
1184  dialog.ShowModal();
1185 }
1186 
1187 
1188 void SIM_PLOT_FRAME::onProbe( wxCommandEvent& event )
1189 {
1190  if( m_schematicFrame == NULL )
1191  return;
1192 
1194  m_schematicFrame->Raise();
1195 }
1196 
1197 
1198 void SIM_PLOT_FRAME::onTune( wxCommandEvent& event )
1199 {
1200  if( m_schematicFrame == NULL )
1201  return;
1202 
1204  m_schematicFrame->Raise();
1205 }
1206 
1207 void SIM_PLOT_FRAME::onShowNetlist( wxCommandEvent& event )
1208 {
1209  class NETLIST_VIEW_DIALOG : public wxDialog
1210  {
1211  public:
1212  enum
1213  {
1214  MARGIN_LINE_NUMBERS
1215  };
1216 
1217  void onClose( wxCloseEvent& evt )
1218  {
1219  EndModal( GetReturnCode() );
1220  }
1221 
1222  NETLIST_VIEW_DIALOG(wxWindow* parent, wxString source) :
1223  wxDialog(parent, wxID_ANY, "SPICE Netlist",
1224  wxDefaultPosition, wxSize(1500,900),
1225  wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
1226  {
1227  wxStyledTextCtrl* text = new wxStyledTextCtrl( this, wxID_ANY );
1228 
1229  text->SetMarginWidth( MARGIN_LINE_NUMBERS, 50 );
1230  text->StyleSetForeground( wxSTC_STYLE_LINENUMBER, wxColour( 75, 75, 75 ) );
1231  text->StyleSetBackground( wxSTC_STYLE_LINENUMBER, wxColour( 220, 220, 220 ) );
1232  text->SetMarginType( MARGIN_LINE_NUMBERS, wxSTC_MARGIN_NUMBER );
1233 
1234  text->SetWrapMode( wxSTC_WRAP_WORD );
1235 
1236  text->SetText( source );
1237 
1238  text->StyleClearAll();
1239  text->SetLexer( wxSTC_LEX_SPICE );
1240 
1241  wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL );
1242  sizer->Add( text, 1, wxEXPAND );
1243  SetSizer( sizer );
1244 
1245  Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( NETLIST_VIEW_DIALOG::onClose ), NULL,
1246  this );
1247  }
1248  };
1249 
1250  if( m_schematicFrame == NULL || m_simulator == NULL )
1251  return;
1252 
1253  NETLIST_VIEW_DIALOG dlg( this, m_simulator->GetNetlist() );
1254  dlg.ShowModal();
1255 }
1256 
1257 
1258 void SIM_PLOT_FRAME::onClose( wxCloseEvent& aEvent )
1259 {
1260  SaveSettings( config() );
1261 
1262  if( IsSimulationRunning() )
1263  m_simulator->Stop();
1264 
1265  Destroy();
1266 }
1267 
1268 
1269 void SIM_PLOT_FRAME::onCursorUpdate( wxCommandEvent& event )
1270 {
1271  wxSize size = m_cursors->GetClientSize();
1272  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1273  m_cursors->ClearAll();
1274 
1275  if( !plotPanel )
1276  return;
1277 
1279  m_cursors->SetImageList(m_signalsIconColorList, wxIMAGE_LIST_SMALL);
1280 
1281  // Fill the signals listctrl
1282  m_cursors->AppendColumn( _( "Signal" ), wxLIST_FORMAT_LEFT, size.x / 2 );
1283  const long X_COL = m_cursors->AppendColumn( plotPanel->GetLabelX(), wxLIST_FORMAT_LEFT, size.x / 4 );
1284 
1285  wxString labelY1 = plotPanel->GetLabelY1();
1286  wxString labelY2 = plotPanel->GetLabelY2();
1287  wxString labelY;
1288 
1289  if( !labelY2.IsEmpty() )
1290  labelY = labelY1 + " / " + labelY2;
1291  else
1292  labelY = labelY1;
1293 
1294  const long Y_COL = m_cursors->AppendColumn( labelY, wxLIST_FORMAT_LEFT, size.x / 4 );
1295 
1296  // Update cursor values
1297  int itemidx = 0;
1298  for( const auto& trace : plotPanel->GetTraces() )
1299  {
1300  if( CURSOR* cursor = trace.second->GetCursor() )
1301  {
1302  // Find the right icon color in list.
1303  // It is the icon used in m_signals list for the same trace
1304  long iconColor = m_signals->FindItem( -1, trace.first );
1305 
1306  const wxRealPoint coords = cursor->GetCoords();
1307  long idx = m_cursors->InsertItem( itemidx++, trace.first, iconColor );
1308  m_cursors->SetItem( idx, X_COL, SPICE_VALUE( coords.x ).ToSpiceString() );
1309  m_cursors->SetItem( idx, Y_COL, SPICE_VALUE( coords.y ).ToSpiceString() );
1310  }
1311  }
1312 }
1313 
1314 
1315 void SIM_PLOT_FRAME::onSimStarted( wxCommandEvent& aEvent )
1316 {
1317  m_toolBar->SetToolNormalBitmap( ID_SIM_RUN, KiBitmap( sim_stop_xpm ) );
1318  SetCursor( wxCURSOR_ARROWWAIT );
1319 }
1320 
1321 
1322 void SIM_PLOT_FRAME::onSimFinished( wxCommandEvent& aEvent )
1323 {
1324  m_toolBar->SetToolNormalBitmap( ID_SIM_RUN, KiBitmap( sim_run_xpm ) );
1325  SetCursor( wxCURSOR_ARROW );
1326 
1327  SIM_TYPE simType = m_exporter->GetSimType();
1328 
1329  if( simType == ST_UNKNOWN )
1330  return;
1331 
1332  SIM_PLOT_PANEL* plotPanel = CurrentPlot();
1333 
1334  if( !plotPanel || plotPanel->GetType() != simType )
1335  plotPanel = NewPlotPanel( simType );
1336 
1337  if( IsSimulationRunning() )
1338  return;
1339 
1340  // If there are any signals plotted, update them
1341  if( SIM_PLOT_PANEL::IsPlottable( simType ) )
1342  {
1343  TRACE_MAP& traceMap = m_plots[plotPanel].m_traces;
1344 
1345  for( auto it = traceMap.begin(); it != traceMap.end(); /* iteration occurs in the loop */)
1346  {
1347  if( !updatePlot( it->second, plotPanel ) )
1348  {
1349  removePlot( it->first, false );
1350  it = traceMap.erase( it ); // remove a plot that does not exist anymore
1351  }
1352  else
1353  {
1354  ++it;
1355  }
1356  }
1357 
1358  updateSignalList();
1359  plotPanel->UpdateAll();
1360  plotPanel->ResetScales();
1361  }
1362  else
1363  {
1365  for( const auto& net : m_exporter->GetNetIndexMap() )
1366  {
1367  int node = net.second;
1368 
1369  if( node > 0 )
1370  m_simulator->Command( wxString::Format( "print v(%d)", node ).ToStdString() );
1371  }
1372  }
1373 }
1374 
1375 
1376 void SIM_PLOT_FRAME::onSimUpdate( wxCommandEvent& aEvent )
1377 {
1378  if( IsSimulationRunning() )
1379  StopSimulation();
1380 
1381  if( CurrentPlot() != m_lastSimPlot )
1382  {
1383  // We need to rerun simulation, as the simulator currently stores
1384  // results for another plot
1385  StartSimulation();
1386  }
1387  else
1388  {
1389  // Incremental update
1390  m_simConsole->Clear();
1391  // Do not export netlist, it is already stored in the simulator
1392  applyTuners();
1393  m_simulator->Run();
1394  }
1395 }
1396 
1397 
1398 void SIM_PLOT_FRAME::onSimReport( wxCommandEvent& aEvent )
1399 {
1400  m_simConsole->AppendText( aEvent.GetString() + "\n" );
1401  m_simConsole->SetInsertionPointEnd();
1402 }
1403 
1404 
1406  SIM_PLOT_FRAME* aPlotFrame )
1407  : m_signal( aSignal ), m_plotFrame( aPlotFrame )
1408 {
1410 
1411  AddMenuItem( this, HIDE_SIGNAL, _( "Hide Signal" ),
1412  _( "Erase the signal from plot screen" ),
1413  KiBitmap( delete_xpm ) );
1414 
1415  TRACE* trace = plot->GetTrace( m_signal );
1416 
1417  if( trace->HasCursor() )
1418  AddMenuItem( this, HIDE_CURSOR, _( "Hide Cursor" ), KiBitmap( pcb_target_xpm ) );
1419  else
1420  AddMenuItem( this, SHOW_CURSOR, _( "Show Cursor" ), KiBitmap( pcb_target_xpm ) );
1421 
1422  Connect( wxEVT_COMMAND_MENU_SELECTED, wxMenuEventHandler( SIGNAL_CONTEXT_MENU::onMenuEvent ), NULL, this );
1423 }
1424 
1425 
1427 {
1428  SIM_PLOT_PANEL* plot = m_plotFrame->CurrentPlot();
1429 
1430  switch( aEvent.GetId() )
1431  {
1432  case HIDE_SIGNAL:
1433  m_plotFrame->removePlot( m_signal );
1434  break;
1435 
1436  case SHOW_CURSOR:
1437  plot->EnableCursor( m_signal, true );
1438  break;
1439 
1440  case HIDE_CURSOR:
1441  plot->EnableCursor( m_signal, false );
1442  break;
1443  }
1444 }
1445 
1446 wxDEFINE_EVENT( EVT_SIM_UPDATE, wxCommandEvent );
1447 wxDEFINE_EVENT( EVT_SIM_REPORT, wxCommandEvent );
1448 
1449 wxDEFINE_EVENT( EVT_SIM_STARTED, wxCommandEvent );
1450 wxDEFINE_EVENT( EVT_SIM_FINISHED, wxCommandEvent );
void onAddSignal(wxCommandEvent &event)
#define ID_MENU_PROBE_SIGNALS
#define ID_SAVE_AS_IMAGE
void ZoomOut(const wxPoint &centerPoint=wxDefaultPosition)
Zoom out current view and refresh display.
Definition: mathplot.cpp:2295
bool IsLegendShown() const
bool saveWorkbook(const wxString &aPath)
Saves plot settings to a file.
wxString ToSpiceString() const
Returns string value in Spice format (e.g.
void SetKiway(wxWindow *aDest, KIWAY *aKiway)
Function SetKiway.
wxToolBarToolBase * m_toolProbe
void LoadSettings(wxConfigBase *aCfg) override
Load common frame parameters from a configuration file.
void setIconsForMenuItems()
Give icons to menuitems of the main menubar.
void onSimStarted(wxCommandEvent &aEvent)
KIWAY & Kiway() const
Function Kiway returns a reference to the KIWAY that this object has an opportunity to participate in...
Definition: kiway_holder.h:56
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
NETLIST_OBJECT_LIST * BuildNetListBase(bool updateStatusText=true)
Create a flat list which stores all connected objects.
void RemoveTuner(TUNER_SLIDER *aTuner, bool aErase=true)
Removes an existing tuner.
wxImageList * m_signalsIconColorList
imagelists uset to add a small coloured icon to signal names and cursors name, the same color as the ...
SIM_PLOT_TYPE operator|(SIM_PLOT_TYPE aFirst, SIM_PLOT_TYPE aSecond)
void onPlotChanged(wxAuiNotebookEvent &event) override
SIM_PLOT_FRAME * m_parent
void onSignalDblClick(wxMouseEvent &event) override
bool SetSimCommand(const wxString &aCommand)
This file is part of the common library.
wxSplitterWindow * m_splitterSignals
const wxString & GetTitle() const
bool HasCursor() const
wxMenuItem * AddMenuItem(wxMenu *aMenu, int aId, const wxString &aText, const wxBitmap &aImage, wxItemKind aType=wxITEM_NORMAL)
Function AddMenuItem is an inline helper function to create and insert a menu item with an icon into ...
Definition: bitmap.cpp:251
#define SIGNALS_PANEL_HEIGHT_ENTRY
void ShowLegend(bool aEnable)
int m_splitterPlotAndConsoleSashPosition
void menuZoomFit(wxCommandEvent &event) override
Structure to represent a schematic component in the Spice simulation.
virtual void SaveSettings(wxConfigBase *aCfg)
Saves common frame parameters to a configuration data file.
const std::vector< double > & GetDataX() const
static bool IsPlottable(SIM_TYPE aSimType)
std::list< TUNER_SLIDER * > m_tuners
List of currently displayed tuners
SIM_PLOT_TYPE GetType() const
wxString m_title
Title displayed in the signal list/plot legend
Class SIM_PLOT_FRAME_BASE.
bool IsGridShown() const
bool RunAction(const std::string &aActionName, bool aNow=false, T aParam=NULL)
Function RunAction() Runs the specified action.
Definition: tool_manager.h:109
void menuNewPlot(wxCommandEvent &aEvent) override
void applyTuners()
Applies component values specified using tunder sliders to the current netlist.
void AddVoltagePlot(const wxString &aNetName)
Adds a voltage plot for a given net name.
virtual wxConfigBase * config()
Returns the wxConfigBase used in SaveSettings(), and is overloaded in KICAD_MANAGER_FRAME.
void AddCurrentPlot(const wxString &aDeviceName, const wxString &aParam)
Adds a current plot for a particular device.
Trace descriptor class
Schematic editor (Eeschema) main window.
wxString CsvFileWildcard()
void onSimUpdate(wxCommandEvent &aEvent)
void menuOpenWorkbook(wxCommandEvent &event) override
void menuShowGrid(wxCommandEvent &event) override
void menuZoomIn(wxCommandEvent &event) override
Class REPORTER is a pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:61
void menuZoomOut(wxCommandEvent &event) override
SIM_THREAD_REPORTER * m_reporter
void OnSimStateChange(SPICE_SIMULATOR *aObject, SIM_STATE aNewState) override
std::shared_ptr< SPICE_SIMULATOR > m_simulator
bool updatePlot(const TRACE_DESC &aDescriptor, SIM_PLOT_PANEL *aPanel)
Updates plot in a particular SIM_PLOT_PANEL.
TRACE * GetTrace(const wxString &aName) const
#define ID_SAVE_AS_CSV
VTBL_ENTRY const wxString GetProjectPath() const
Function GetProjectPath returns the full path of the project.
Definition: project.cpp:102
Field Reference of part, i.e. "IC21".
wxString GetLabelY1() const
void updateCursors()
Updates the cursor values list.
wxSplitterWindow * m_splitterTuneValues
static SIM_TYPE CommandToSimType(const wxString &aCmd)
Returns simulation type basing on a simulation command directive.
SIM_PLOT_TYPE GetXAxisType(SIM_TYPE aType) const
Returns X axis for a given simulation type.
void menuSaveCsv(wxCommandEvent &event) override
void onPlotClose(wxAuiNotebookEvent &event) override
const wxString & GetParam() const
wxAuiNotebook * m_plotNotebook
SCH_EDIT_FRAME * m_schematicFrame
SCH_FIELD * GetField(int aFieldNdx) const
Returns a field in this symbol.
bool DeleteTrace(const wxString &aName)
void UpdateAll()
Refresh display.
Definition: mathplot.cpp:2803
void EnableCursor(const wxString &aName, bool aEnable)
Toggles cursor for a particular trace.
SIM_STATE
const wxString & GetSimCommand() const
void setSubWindowsSashSize()
wxBitmap KiBitmap(BITMAP_DEF aBitmap)
Construct a wxBitmap from a memory record, held in a BITMAP_DEF.
Definition: bitmap.cpp:79
#define PLOT_PANEL_WIDTH_ENTRY
wxString ToString() const
Returns string value as when converting double to string (e.g.
SEVERITY
Severity of the reported messages.
Definition: reporter.h:74
std::map< SIM_PLOT_PANEL *, PLOT_INFO > m_plots
Map of plot panels and associated data
SIM_PLOT_PANEL * m_lastSimPlot
Panel that was used as the most recent one for simulations
wxString GetLabelX() const
void AddBitmapToMenuItem(wxMenuItem *aMenu, const wxBitmap &aImage)
Add a bitmap to a menuitem.
Definition: bitmap.cpp:223
VTBL_ENTRY KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=NULL)
Function Player returns the KIWAY_PLAYER* given a FRAME_T.
Definition: kiway.cpp:321
#define ID_MENU_SHOW_NETLIST
wxString GetLabelY2() const
static TOOL_ACTION simTune
Definition: ee_actions.h:199
Helper class to handle Spice way of expressing values (e.g. 10.5 Meg)
Definition: spice_value.h:32
wxSplitterWindow * m_splitterLeftRight
void ZoomIn(const wxPoint &centerPoint=wxDefaultPosition)
Zoom into current view and refresh display.
Definition: mathplot.cpp:2238
#define CURSORS_PANEL_HEIGHT_ENTRY
wxMenuItem * m_runSimulation
#define ID_MENU_TUNE_SIGNALS
void onSimReport(wxCommandEvent &aEvent)
PROJECT & Prj() const
Function Prj returns a reference to the PROJECT "associated with" this KIWAY.
SIM_TYPE
Possible simulation types
Definition: sim_types.h:29
virtual void LoadSettings(wxConfigBase *aCfg)
Load common frame parameters from a configuration file.
void onSimFinished(wxCommandEvent &aEvent)
Interface to receive simulation updates from SPICE_SIMULATOR class.
bool AddTrace(const wxString &aName, int aPoints, const double *aX, const double *aY, SIM_PLOT_TYPE aFlags)
Definition of file extensions used in Kicad.
void onShowNetlist(wxCommandEvent &event)
SIM_THREAD_REPORTER(SIM_PLOT_FRAME *aParent)
void menuShowLegendUpdate(wxUpdateUIEvent &event) override
Class KIWAY is a minimalistic software bus for communications between various DLLs/DSOs (DSOs) within...
Definition: kiway.h:258
wxToolBarToolBase * m_toolAddSignals
Subclass of SIM_PLOT_FRAME_BASE, which is generated by wxFormBuilder.
int m_splitterTuneValuesSashPosition
static std::shared_ptr< SPICE_SIMULATOR > CreateInstance(const std::string &aName)
Creates a simulator instance of particular type (currently only ngspice is handled)
TRACE_DESC(const NETLIST_EXPORTER_PSPICE_SIM &aExporter, const wxString &aName, SIM_PLOT_TYPE aType, const wxString &aParam)
const std::string & GetString()
Definition: richio.h:475
void onSignalRClick(wxListEvent &event) override
void ResetScales()
Resets scale ranges to fit the current traces
bool IsSimulationRunning()
#define ID_MENU_SHOW_LEGEND
void menuShowLegend(wxCommandEvent &event) override
#define PLOT_PANEL_HEIGHT_ENTRY
void ShowGrid(bool aEnable)
#define _(s)
void onTune(wxCommandEvent &event)
wxToolBarToolBase * m_toolSimulate
void menuSaveImage(wxCommandEvent &event) override
#define ID_MENU_SET_SIMUL
wxString PngFileWildcard()
Implementing SIM_PLOT_FRAME_BASE.
bool loadWorkbook(const wxString &aPath)
Loads plot settings from a file.
void SetNetlistExporter(NETLIST_EXPORTER_PSPICE_SIM *aExporter)
static wxString m_savedWorkbooksPath
A string to store the path of saved workbooks during a session
void onCursorUpdate(wxCommandEvent &aEvent)
DIALOG_SIM_SETTINGS * m_settingsDlg
void Fit() override
Set view to fit global bounding box of all plot layers and refresh display.
Definition: mathplot.cpp:1995
const wxString & GetName() const
const wxString What() const
Definition: ki_exception.h:58
#define ID_MENU_ADD_SIGNAL
std::unique_ptr< NETLIST_EXPORTER_PSPICE_SIM > m_exporter
void updateNetlistExporter()
Reloads the current schematic for the netlist exporter.
see class PGM_BASE
void onSimulate(wxCommandEvent &event)
const char * name
Definition: DXF_plotter.cpp:61
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
SIGNAL_CONTEXT_MENU(const wxString &aSignal, SIM_PLOT_FRAME *aPlotFrame)
void onProbe(wxCommandEvent &event)
#define ID_MENU_SHOW_GRID
void updateSignalList()
Updates the list of currently plotted signals.
size_t i
Definition: json11.cpp:597
static wxString GetSpiceField(SPICE_FIELD aField, SCH_COMPONENT *aComponent, unsigned aCtl)
Retrieves either the requested field value or the default value.
Class SCH_COMPONENT describes a real schematic component.
Definition: sch_component.h:73
int m_splitterSignalsSashPosition
SIM_PLOT_PANEL * CurrentPlot() const
Returns the currently opened plot panel (or NULL if there is none).
std::map< wxString, TRACE_DESC > TRACE_MAP
wxDEFINE_EVENT(EVT_SIM_UPDATE, wxCommandEvent)
bool Destroy() override
Our version of Destroy() which is virtual from wxWidgets.
SIM_TYPE GetType() const
const std::vector< double > & GetDataY() const
int m_splitterLeftRightSashPosition
static TOOL_ACTION simProbe
Definition: ee_actions.h:198
const NETLIST_EXPORTER_PSPICE_SIM * GetExporter() const
Returns the netlist exporter object used for simulations.
void removePlot(const wxString &aPlotName, bool aErase=true)
Removes a plot with a specific title.
void SaveSettings(wxConfigBase *aCfg) override
Saves common frame parameters to a configuration data file.
Custom widget to handle quick component values modification and simulation on the fly.
Definition: tuner_slider.h:40
void AddTuner(SCH_COMPONENT *aComponent)
Adds a tuner for a component.
wxString WorkbookFileWildcard()
bool SaveScreenshot(const wxString &filename, wxBitmapType type=wxBITMAP_TYPE_BMP, wxSize imageSize=wxDefaultSize, bool fit=false)
Draw the window on a wxBitmap, then save it to a file.
Definition: mathplot.cpp:3033
const std::map< wxString, TRACE * > & GetTraces() const
wxSplitterWindow * m_splitterPlotAndConsole
void menuShowGridUpdate(wxUpdateUIEvent &event) override
bool HasMessage() const override
Function HasMessage Returns true if the reporter client is non-empty.
static const char * text_xpm[]
void menuSaveWorkbook(wxCommandEvent &event) override
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition: confirm.cpp:276
Class STRING_FORMATTER implements OUTPUTFORMATTER to a memory buffer.
Definition: richio.h:445
SIM_PLOT_TYPE
Possible plot types
Definition: sim_types.h:35
REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_UNDEFINED) override
Function Report is a pure virtual function to override in the derived object.
#define ID_MENU_RUN_SIM
void DisplayError(wxWindow *parent, const wxString &text, int displaytime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:243
void addPlot(const wxString &aName, SIM_PLOT_TYPE aType, const wxString &aParam)
Adds a new plot to the current panel.
virtual const wxString & GetText() const
Function GetText returns the string associated with the text object.
Definition: eda_text.h:124
void onSettings(wxCommandEvent &event)
void onClose(wxCloseEvent &aEvent)
wxToolBarToolBase * m_toolTune
void onMenuEvent(wxMenuEvent &aEvent)
SIM_PLOT_PANEL * NewPlotPanel(SIM_TYPE aSimType)
Creates a new plot panel for a given simulation type and adds it to the main notebook.
bool TraceShown(const wxString &aName) const
Cursor attached to a trace to follow its values:
Special netlist exporter flavor that allows one to override simulation commands.
void updateTuners()
Filters out tuners for components that do not exist anymore.
class KI_PARAM_ERROR is a class used to hold a translatable error message and may be used when throwi...
Definition: ki_exception.h:45
wxToolBarToolBase * m_toolSettings
SIM_PLOT_FRAME(KIWAY *aKiway, wxWindow *aParent)
Constructor.