KiCad PCB EDA Suite
pcbnew_scripting_helpers.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) 2012 NBEE Embedded Systems, Miguel Angel Ajo <miguelangel@nbee.es>
5  * Copyright (C) 1992-2017 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
30 #include <Python.h>
31 #undef HAVE_CLOCK_GETTIME // macro is defined in Python.h and causes redefine warning
32 
34 
35 #include <action_plugin.h>
36 #include <board.h>
37 #include <board_design_settings.h>
38 #include <pcb_marker.h>
39 #include <cstdlib>
40 #include <drc/drc_engine.h>
41 #include <drc/drc_item.h>
42 #include <fp_lib_table.h>
43 #include <io_mgr.h>
44 #include <kicad_string.h>
45 #include <macros.h>
47 #include <project.h>
51 #include <locale_io.h>
52 #include <wx/app.h>
53 
54 
56 
58 
59 
61 {
62  if( s_PcbEditFrame )
63  return s_PcbEditFrame->GetBoard();
64  else
65  return NULL;
66 }
67 
68 
70 {
71  s_PcbEditFrame = aPcbEditFrame;
72 }
73 
74 
75 BOARD* LoadBoard( wxString& aFileName )
76 {
77  if( aFileName.EndsWith( KiCadPcbFileExtension ) )
78  return LoadBoard( aFileName, IO_MGR::KICAD_SEXP );
79  else if( aFileName.EndsWith( LegacyPcbFileExtension ) )
80  return LoadBoard( aFileName, IO_MGR::LEGACY );
81 
82  // as fall back for any other kind use the legacy format
83  return LoadBoard( aFileName, IO_MGR::LEGACY );
84 }
85 
86 
88 {
89  if( !s_SettingsManager )
90  {
91  // Ensure wx system settings stuff is available
92  static_cast<void>( wxTheApp );
93  s_SettingsManager = new SETTINGS_MANAGER( true );
94  }
95 
96  return s_SettingsManager;
97 }
98 
99 
101 {
103 
104  if( !project )
105  {
108  }
109 
110  return project;
111 }
112 
113 
114 BOARD* LoadBoard( wxString& aFileName, IO_MGR::PCB_FILE_T aFormat )
115 {
116  wxFileName pro = aFileName;
117  pro.SetExt( ProjectFileExtension );
118  pro.MakeAbsolute();
119  wxString projectPath = pro.GetFullPath();
120 
121  // Ensure the "C" locale is temporary set, before reading any file
122  // It also avoid wxWidget alerts about locale issues, later, when using Python 3
124 
125  PROJECT* project = GetSettingsManager()->GetProject( projectPath );
126 
127  if( !project )
128  {
129  GetSettingsManager()->LoadProject( projectPath );
130  project = GetSettingsManager()->GetProject( projectPath );
131  }
132 
133  // Board cannot be loaded without a project, so create the default project
134  if( !project )
136 
137  BOARD* brd = IO_MGR::Load( aFormat, aFileName );
138 
139  if( brd )
140  {
141  brd->SetProject( project );
142 
143  // Move legacy view settings to local project settings
144  if( !brd->m_LegacyVisibleLayers.test( Rescue ) )
145  project->GetLocalSettings().m_VisibleLayers = brd->m_LegacyVisibleLayers;
146 
148  project->GetLocalSettings().m_VisibleItems = brd->m_LegacyVisibleItems;
149 
151  bds.m_DRCEngine = std::make_shared<DRC_ENGINE>( brd, &bds );
152 
153  try
154  {
155  wxFileName rules = pro;
156  rules.SetExt( DesignRulesFileExtension );
157  bds.m_DRCEngine->InitEngine( rules );
158  }
159  catch( ... )
160  {
161  // Best efforts...
162  }
163 
164  for( PCB_MARKER* marker : brd->ResolveDRCExclusions() )
165  brd->Add( marker );
166 
167  brd->BuildConnectivity();
168  brd->BuildListOfNets();
170  }
171 
172  return brd;
173 }
174 
175 
177 {
178  BOARD* brd = new BOARD();
179 
180  brd->SetProject( GetDefaultProject() );
181 
182  return brd;
183 }
184 
185 
186 bool SaveBoard( wxString& aFileName, BOARD* aBoard, IO_MGR::PCB_FILE_T aFormat )
187 {
188  aBoard->BuildConnectivity();
190 
191  IO_MGR::Save( aFormat, aFileName, aBoard, NULL );
192 
193  wxFileName pro = aFileName;
194  pro.SetExt( ProjectFileExtension );
195  pro.MakeAbsolute();
196  wxString projectPath = pro.GetFullPath();
197 
198  GetSettingsManager()->SaveProject( pro.GetFullPath() );
199 
200  return true;
201 }
202 
203 
204 bool SaveBoard( wxString& aFileName, BOARD* aBoard )
205 {
206  return SaveBoard( aFileName, aBoard, IO_MGR::KICAD_SEXP );
207 }
208 
209 
211 {
212  BOARD* board = GetBoard();
213 
214  if( !board )
215  return nullptr;
216 
217  PROJECT* project = board->GetProject();
218 
219  if( !project )
220  return nullptr;
221 
222  return project->PcbFootprintLibs();
223 }
224 
225 
226 wxArrayString GetFootprintLibraries()
227 {
228  wxArrayString footprintLibraryNames;
229 
231 
232  if( !tbl )
233  return footprintLibraryNames;
234 
235  for( const wxString& name : tbl->GetLogicalLibs() )
236  footprintLibraryNames.Add( name );
237 
238  return footprintLibraryNames;
239 }
240 
241 
242 wxArrayString GetFootprints( const wxString& aNickName )
243 {
244  wxArrayString footprintNames;
245 
247 
248  if( !tbl )
249  return footprintNames;
250 
251  tbl->FootprintEnumerate( footprintNames, aNickName, true );
252 
253  return footprintNames;
254 }
255 
256 
257 bool ExportSpecctraDSN( wxString& aFullFilename )
258 {
259  if( s_PcbEditFrame )
260  {
261  bool ok = s_PcbEditFrame->ExportSpecctraFile( aFullFilename );
262  return ok;
263  }
264  else
265  {
266  return false;
267  }
268 }
269 
270 bool ExportVRML( const wxString& aFullFileName, double aMMtoWRMLunit,
271  bool aExport3DFiles, bool aUseRelativePaths,
272  const wxString& a3D_Subdir,
273  double aXRef, double aYRef )
274 {
275  if( s_PcbEditFrame )
276  {
277  bool ok = s_PcbEditFrame->ExportVRML_File( aFullFileName, aMMtoWRMLunit,
278  aExport3DFiles, aUseRelativePaths,
279  a3D_Subdir, aXRef, aYRef );
280  return ok;
281  }
282  else
283  {
284  return false;
285  }
286 }
287 
288 bool ImportSpecctraSES( wxString& aFullFilename )
289 {
290  if( s_PcbEditFrame )
291  {
292  bool ok = s_PcbEditFrame->ImportSpecctraSession( aFullFilename );
293  return ok;
294  }
295  else
296  {
297  return false;
298  }
299 }
300 
301 
302 bool ExportFootprintsToLibrary( bool aStoreInNewLib, const wxString& aLibName, wxString* aLibPath )
303 {
304  if( s_PcbEditFrame )
305  {
306  s_PcbEditFrame->ExportFootprintsToLibrary( aStoreInNewLib, aLibName, aLibPath );
307  return true;
308  }
309  else
310  {
311  return false;
312  }
313 }
314 
315 void Refresh()
316 {
317  if( s_PcbEditFrame )
318  {
319  auto board = s_PcbEditFrame->GetBoard();
320  board->BuildConnectivity();
321 
322  // Re-init everything: this is the easy way to do that
325  }
326 }
327 
328 
330 {
331  if( s_PcbEditFrame )
333 }
334 
335 
337 {
338  if( s_PcbEditFrame )
339  return static_cast<int>( s_PcbEditFrame->GetUserUnits() );
340 
341  return -1;
342 }
343 
344 
346 {
348 }
349 
350 
351 bool WriteDRCReport( BOARD* aBoard, const wxString& aFileName, EDA_UNITS aUnits,
352  bool aReportAllTrackErrors )
353 {
354  wxCHECK( aBoard, false );
355 
356  BOARD_DESIGN_SETTINGS& bds = aBoard->GetDesignSettings();
357  std::shared_ptr<DRC_ENGINE> engine = bds.m_DRCEngine;
358 
359  if( !engine )
360  {
361  bds.m_DRCEngine = std::make_shared<DRC_ENGINE>( aBoard, &bds );
362  engine = bds.m_DRCEngine;
363  }
364 
365  wxCHECK( engine, false );
366 
367  wxFileName fn = aBoard->GetFileName();
368  fn.SetExt( DesignRulesFileExtension );
369  wxString drcRulesPath = s_SettingsManager->Prj().AbsolutePath( fn.GetFullName() );
370 
371  try
372  {
373  engine->InitEngine( drcRulesPath );
374  }
375  catch( PARSE_ERROR& )
376  {
377  return false;
378  }
379 
380  std::vector<std::shared_ptr<DRC_ITEM>> footprints;
381  std::vector<std::shared_ptr<DRC_ITEM>> unconnected;
382  std::vector<std::shared_ptr<DRC_ITEM>> violations;
383 
384  engine->SetProgressReporter( nullptr );
385 
386  engine->SetViolationHandler(
387  [&]( const std::shared_ptr<DRC_ITEM>& aItem, wxPoint aPos )
388  {
389  if( aItem->GetErrorCode() == DRCE_MISSING_FOOTPRINT
390  || aItem->GetErrorCode() == DRCE_DUPLICATE_FOOTPRINT
391  || aItem->GetErrorCode() == DRCE_EXTRA_FOOTPRINT
392  || aItem->GetErrorCode() == DRCE_NET_CONFLICT )
393  {
394  footprints.push_back( aItem );
395  }
396  else if( aItem->GetErrorCode() == DRCE_UNCONNECTED_ITEMS )
397  {
398  unconnected.push_back( aItem );
399  }
400  else
401  {
402  violations.push_back( aItem );
403  }
404  } );
405 
406  engine->RunTests( aUnits, aReportAllTrackErrors, false );
407  engine->ClearViolationHandler();
408 
409  // TODO: Unify this with DIALOG_DRC::writeReport
410 
411  FILE* fp = wxFopen( aFileName, wxT( "w" ) );
412 
413  if( fp == nullptr )
414  return false;
415 
416  std::map<KIID, EDA_ITEM*> itemMap;
417  aBoard->FillItemMap( itemMap );
418 
419  fprintf( fp, "** Drc report for %s **\n", TO_UTF8( aBoard->GetFileName() ) );
420 
421  wxDateTime now = wxDateTime::Now();
422 
423  fprintf( fp, "** Created on %s **\n", TO_UTF8( now.Format( wxT( "%F %T" ) ) ) );
424 
425  fprintf( fp, "\n** Found %d DRC violations **\n", static_cast<int>( violations.size() ) );
426 
427  for( const std::shared_ptr<DRC_ITEM>& item : violations )
428  {
429  SEVERITY severity = bds.GetSeverity( item->GetErrorCode() );
430  fprintf( fp, "%s", TO_UTF8( item->ShowReport( aUnits, severity, itemMap ) ) );
431  }
432 
433  fprintf( fp, "\n** Found %d unconnected pads **\n", static_cast<int>( unconnected.size() ) );
434 
435  for( const std::shared_ptr<DRC_ITEM>& item : unconnected )
436  {
437  SEVERITY severity = bds.GetSeverity( item->GetErrorCode() );
438  fprintf( fp, "%s", TO_UTF8( item->ShowReport( aUnits, severity, itemMap ) ) );
439  }
440 
441  fprintf( fp, "\n** Found %d Footprint errors **\n", static_cast<int>( footprints.size() ) );
442 
443  for( const std::shared_ptr<DRC_ITEM>& item : footprints )
444  {
445  SEVERITY severity = bds.GetSeverity( item->GetErrorCode() );
446  fprintf( fp, "%s", TO_UTF8( item->ShowReport( aUnits, severity, itemMap ) ) );
447  }
448 
449  fprintf( fp, "\n** End of Report **\n" );
450  fclose( fp );
451 
452  return true;
453 }
void UpdateUserInterface()
Update the layer manager and other widgets from the board setup (layer and items visibility,...
BOARD * LoadBoard(wxString &aFileName)
bool WriteDRCReport(BOARD *aBoard, const wxString &aFileName, EDA_UNITS aUnits, bool aReportAllTrackErrors)
Runs the DRC check on the given board and writes the results to a report file.
void BuildListOfNets()
Definition: board.h:663
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
static bool IsActionRunning()
Container for project specific data.
Definition: project.h:62
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:40
int GetUserUnits()
Returns the currently selected user unit value for the interface.
const std::string ProjectFileExtension
const std::string LegacyPcbFileExtension
SEVERITY
Definition: ui_common.h:83
void ActivateGalCanvas() override
Set the #m_Pcb member in such as way as to ensure deleting any previous BOARD.
PCB_DRAW_PANEL_GAL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
const std::string DesignRulesFileExtension
bool ExportFootprintsToLibrary(bool aStoreInNewLib, const wxString &aLibName, wxString *aLibPath)
Function ExportFootprintsToLibrary Save footprints in a library:
wxArrayString GetFootprints(const wxString &aNickName)
will get the names of all of the footprints available in a footprint library
PROJECT * GetProject() const
Definition: board.h:360
This is the end of the layers used for visibility bit masks in Pcbnew.
const std::string KiCadPcbFileExtension
void ScriptingSetPcbEditFrame(PCB_EDIT_FRAME *aPcbEditFrame)
bool ExportVRML_File(const wxString &aFullFileName, double aMMtoWRMLunit, bool aExport3DFiles, bool aUseRelativePaths, const wxString &a3D_Subdir, double aXRef, double aYRef)
Create the file(s) exporting current BOARD to a VRML file.
const wxString & GetFileName() const
Definition: board.h:228
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:588
virtual const wxString AbsolutePath(const wxString &aFileName) const
Fix up aFileName if it is relative to the project's directory to be an absolute path and filename.
Definition: project.cpp:271
This file contains miscellaneous commonly used macros and functions.
void ExportFootprintsToLibrary(bool aStoreInNewLib, const wxString &aLibName=wxEmptyString, wxString *aLibPath=NULL)
Save footprints in a library:
bool IsActionRunning()
Are we currently in an action plugin?
wxArrayString GetFootprintLibraries()
will get the nicknames of all of the footprint libraries configured in pcbnew in both the project and...
static LIB_SYMBOL * dummy()
Used to draw a dummy shape when a LIB_SYMBOL is not found in library.
Definition: sch_symbol.cpp:70
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:96
void FootprintEnumerate(wxArrayString &aFootprintNames, const wxString &aNickname, bool aBestEfforts)
Return a list of footprint names contained within the library given by aNickname.
void SynchronizeNetsAndNetClasses()
Copy NETCLASS info to each NET, based on NET membership in a NETCLASS.
Definition: board.cpp:1488
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT) override
Adds an item to the container.
Definition: board.cpp:606
std::vector< PCB_MARKER * > ResolveDRCExclusions()
Rebuild DRC markers from the serialized data in BOARD_DESIGN_SETTINGS.
Definition: board.cpp:206
#define NULL
void Refresh()
Update the board display after modifying it by a python script (note: it is automatically called by a...
#define GAL_LAYER_INDEX(x)
Use this macro to convert a GAL layer to a 0-indexed offset from LAYER_VIAS.
static SETTINGS_MANAGER * s_SettingsManager
bool ImportSpecctraSES(wxString &aFullFilename)
will import a specctra *.ses file and use it to relocate MODULEs and to replace all vias and tracks i...
Definition of file extensions used in Kicad.
SEVERITY GetSeverity(int aDRCErrorCode)
void BuildConnectivity()
Build or rebuild the board connectivity database for the board, especially the list of connected item...
Definition: board.cpp:136
void UpdateUserInterface()
Update the layer manager and other widgets from the board setup (layer and items visibility,...
FP_LIB_TABLE * GetFootprintLibraryTable()
bool ExportSpecctraDSN(wxString &aFullFilename)
will export the current BOARD to a specctra dsn file.
SETTINGS_MANAGER * GetSettingsManager()
PROJECT * GetDefaultProject()
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=NULL) override
Update the board display after modifying it by a python script (note: it is automatically called by a...
static BOARD * Load(PCB_FILE_T aFileType, const wxString &aFileName, BOARD *aAppendToMe=nullptr, const PROPERTIES *aProperties=nullptr, PROJECT *aProject=nullptr)
Find the requested PLUGIN and if found, calls the PLUGIN::Load() function on it using the arguments p...
Definition: io_mgr.cpp:158
BOARD * GetBoard()
EDA_UNITS
Definition: eda_units.h:38
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Loads a project or sets up a new project with a specified path.
void SetProject(PROJECT *aProject)
Link a board to a given project.
Definition: board.cpp:142
bool ImportSpecctraSession(const wxString &aFullFilename)
Import a specctra *.ses file and use it to relocate MODULEs and to replace all vias and tracks in an ...
bool SaveBoard(wxString &aFileName, BOARD *aBoard, IO_MGR::PCB_FILE_T aFormat)
A filename or source description, a problem input line, a line number, a byte offset,...
Definition: ki_exception.h:118
Class PCBNEW_ACTION_PLUGINS.
Legacy Pcbnew file formats prior to s-expression.
Definition: io_mgr.h:54
const char * name
Definition: DXF_plotter.cpp:59
bool ExportVRML(const wxString &aFullFileName, double aMMtoWRMLunit, bool aExport3DFiles, bool aUseRelativePaths, const wxString &a3D_Subdir, double aXRef, double aYRef)
will export the current BOARD to a VRML (wrl) file.
static void Save(PCB_FILE_T aFileType, const wxString &aFileName, BOARD *aBoard, const PROPERTIES *aProperties=nullptr)
Write either a full aBoard to a storage file in a format that this implementation knows about,...
Definition: io_mgr.cpp:173
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
bool SaveProject(const wxString &aFullPath=wxEmptyString)
Saves a loaded project.
The main frame for Pcbnew.
BOARD * CreateEmptyBoard()
Constructs a default BOARD with a tempoary (no filename) project.
BOARD * GetBoard() const
PCB_FILE_T
The set of file types that the IO_MGR knows about, and for which there has been a plugin written.
Definition: io_mgr.h:52
void FillItemMap(std::map< KIID, EDA_ITEM * > &aMap)
Definition: board.cpp:946
LSET m_LegacyVisibleLayers
Visibility settings stored in board prior to 6.0, only used for loading legacy files.
Definition: board.h:264
std::shared_ptr< DRC_ENGINE > m_DRCEngine
PROJECT * GetProject(const wxString &aFullPath) const
Retrieves a loaded project by name.
EDA_UNITS GetUserUnits() const
Return the user units currently in use.
static PCB_EDIT_FRAME * s_PcbEditFrame
std::vector< wxString > GetLogicalLibs()
Return the logical library names, all of them that are pertinent to a look up done on this LIB_TABLE.
bool ExportSpecctraFile(const wxString &aFullFilename)
Export the current BOARD to a specctra dsn file.
S-expression Pcbnew file format.
Definition: io_mgr.h:55
Container for design settings for a BOARD object.
GAL_SET m_LegacyVisibleItems
Definition: board.h:265