KiCad PCB EDA Suite
pcbnew.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 Jean-Pierre Charras, jp.charras at wanadoo.fr
5  * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
6  * Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, you may find one here:
20  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21  * or you may search the http://www.gnu.org website for the version 2 license,
22  * or you may write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25 
31 #ifdef KICAD_SCRIPTING
32  #include <python_scripting.h>
34 #endif
35 #include <fctsys.h>
36 #include <pgm_base.h>
37 #include <kiface_i.h>
38 #include <kiface_ids.h>
39 #include <confirm.h>
40 #include <macros.h>
41 #include <pcb_edit_frame.h>
42 #include <eda_dde.h>
43 #include <wx/file.h>
44 #include <wx/snglinst.h>
45 #include <gestfich.h>
46 #include <pcbnew.h>
47 #include <class_board.h>
48 #include <class_draw_panel_gal.h>
49 #include <fp_lib_table.h>
50 #include <footprint_edit_frame.h>
51 #include <footprint_viewer_frame.h>
52 #include <footprint_wizard_frame.h>
54 #include <footprint_info_impl.h>
55 #include <dialog_configure_paths.h>
56 #include "invoke_pcb_dialog.h"
58 
59 extern bool IsWxPythonLoaded();
60 
61 namespace PCB {
62 
63 static struct IFACE : public KIFACE_I
64 {
65  // Of course all are virtual overloads, implementations of the KIFACE.
66 
67  IFACE( const char* aName, KIWAY::FACE_T aType ) :
68  KIFACE_I( aName, aType )
69  {}
70 
71  bool OnKifaceStart( PGM_BASE* aProgram, int aCtlBits ) override;
72 
73  void OnKifaceEnd() override;
74 
75  wxWindow* CreateWindow( wxWindow* aParent, int aClassId, KIWAY* aKiway, int aCtlBits = 0 ) override
76  {
77  switch( aClassId )
78  {
79  case FRAME_PCB_EDITOR:
80  {
81  auto frame = new PCB_EDIT_FRAME( aKiway, aParent );
82 
83 #if defined( KICAD_SCRIPTING )
84  // give the scripting helpers access to our frame
85  ScriptingSetPcbEditFrame( frame );
86 #endif
87 
88  if( Kiface().IsSingle() )
89  {
90  // only run this under single_top, not under a project manager.
91  frame->CreateServer( KICAD_PCB_PORT_SERVICE_NUMBER );
92  }
93 
94  return frame;
95  }
96 
98  return new FOOTPRINT_EDIT_FRAME( aKiway, aParent,
100 
103  return new FOOTPRINT_VIEWER_FRAME( aKiway, aParent, FRAME_T( aClassId ) );
104 
106  return new FOOTPRINT_WIZARD_FRAME( aKiway, aParent, FRAME_T( aClassId ) );
107 
109  return dynamic_cast< wxWindow* >( FOOTPRINT_PREVIEW_PANEL::New( aKiway, aParent ) );
110 
112  {
113  DIALOG_CONFIGURE_PATHS dlg( aParent, aKiway->Prj().Get3DFilenameResolver() );
114 
115  if( dlg.ShowModal() == wxID_OK )
116  aKiway->CommonSettingsChanged( true );
117 
118  // Dialog has completed; nothing to return.
119  return nullptr;
120  }
121 
123  InvokePcbLibTableEditor( aKiway, aParent );
124  // Dialog has completed; nothing to return.
125  return nullptr;
126 
127  default:
128  return nullptr;
129  }
130  }
131 
140  void* IfaceOrAddress( int aDataId ) override
141  {
142  switch( aDataId )
143  {
144  // Return a pointer to the global instance of the footprint list.
146  return (void*) &GFootprintList;
147 
148  // Return a new FP_LIB_TABLE with the global table installed as a fallback.
150  return (void*) new FP_LIB_TABLE( &GFootprintTable );
151 
152  // Return a pointer to the global instance of the global footprint table.
154  return (void*) &GFootprintTable;
155 
156  default:
157  return nullptr;
158  }
159  }
160 
167  void SaveFileAs( const wxString& aProjectBasePath, const wxString& aSrcProjectName,
168  const wxString& aNewProjectBasePath, const wxString& aNewProjectName,
169  const wxString& aSrcFilePath, wxString& aErrors ) override;
170 
171 } kiface( "pcbnew", KIWAY::FACE_PCB );
172 
173 } // namespace
174 
175 using namespace PCB;
176 
177 
179 
180 
181 KIFACE_I& Kiface() { return kiface; }
182 
183 
184 // KIFACE_GETTER's actual spelling is a substitution macro found in kiway.h.
185 // KIFACE_GETTER will not have name mangling due to declaration in kiway.h.
186 MY_API( KIFACE* ) KIFACE_GETTER( int* aKIFACEversion, int aKiwayVersion, PGM_BASE* aProgram )
187 {
188  process = aProgram;
189  return &kiface;
190 }
191 
192 #if defined( BUILD_KIWAY_DLL )
193 PGM_BASE& Pgm()
194 {
195  wxASSERT( process ); // KIFACE_GETTER has already been called.
196  return *process;
197 }
198 
199 // Similar to PGM_BASE& Pgm(), but return nullptr when a *.ki_face is run from a python script.
201 {
202  return process;
203 }
204 
205 #endif
206 
207 
208 #if defined( KICAD_SCRIPTING )
209 static bool scriptingSetup()
210 {
211 
212 #if defined( __WINDOWS__ )
213  // If our python.exe (in kicad/bin) exists, force our kicad python environment
214  wxString kipython = FindKicadFile( "python.exe" );
215 
216  // we need only the path:
217  wxFileName fn( kipython );
218  kipython = fn.GetPath();
219 
220  // If our python install is existing inside kicad, use it
221  // Note: this is useful only when another python version is installed
222  if( wxDirExists( kipython ) )
223  {
224  // clear any PYTHONPATH and PYTHONHOME env var definition: the default
225  // values work fine inside Kicad:
226  wxSetEnv( wxT( "PYTHONPATH" ), wxEmptyString );
227  wxSetEnv( wxT( "PYTHONHOME" ), wxEmptyString );
228 
229  // Add our python executable path in first position:
230  wxString ppath;
231  wxGetEnv( wxT( "PATH" ), &ppath );
232 
233  kipython << wxT( ";" ) << ppath;
234  wxSetEnv( wxT( "PATH" ), kipython );
235  }
236 
237 #elif defined( __WXMAC__ )
238 
239  // Add default paths to PYTHONPATH
240  wxString pypath;
241 
242  // Bundle scripting folder (<kicad.app>/Contents/SharedSupport/scripting)
243  pypath += GetOSXKicadDataDir() + wxT( "/scripting" );
244 
245  // $(KICAD_PATH)/scripting/plugins is always added in kicadplugins.i
246  if( wxGetenv("KICAD_PATH") != NULL )
247  {
248  pypath += wxT( ":" ) + wxString( wxGetenv("KICAD_PATH") );
249  }
250 
251  // Bundle wxPython folder (<kicad.app>/Contents/Frameworks/python/site-packages)
252  pypath += wxT( ":" ) + Pgm().GetExecutablePath() +
253  wxT( "Contents/Frameworks/python/site-packages" );
254 
255  // Original content of $PYTHONPATH
256  if( wxGetenv( wxT( "PYTHONPATH" ) ) != NULL )
257  {
258  pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
259  }
260 
261  // set $PYTHONPATH
262  wxSetEnv( "PYTHONPATH", pypath );
263 
264 #else
265  wxString pypath;
266 
267  // PYTHON_DEST is the scripts install dir as determined by the build system.
268  pypath = Pgm().GetExecutablePath() + wxT( "../" PYTHON_DEST );
269 
270  if( !wxIsEmpty( wxGetenv( wxT( "PYTHONPATH" ) ) ) )
271  pypath = wxString( wxGetenv( wxT( "PYTHONPATH" ) ) ) + wxT( ":" ) + pypath;
272 
273  wxSetEnv( wxT( "PYTHONPATH" ), pypath );
274 
275 #endif
276 
278  {
279  wxLogError( "pcbnewInitPythonScripting() failed." );
280  return false;
281  }
282 
283  return true;
284 }
285 #endif // KICAD_SCRIPTING
286 
287 
289 {
290 #if defined( KICAD_SCRIPTING )
291  // Reload plugin list: reload Python plugins if they are newer than the already loaded,
292  // and load new plugins
293  char cmd[1024];
294 
295  snprintf( cmd, sizeof( cmd ), "pcbnew.LoadPlugins(\"%s\")", TO_UTF8( PyScriptingPath() ) );
296 
297  PyLOCK lock;
298 
299  // ReRun the Python method pcbnew.LoadPlugins (already called when starting Pcbnew)
300  int retv = PyRun_SimpleString( cmd );
301 
302  if( retv != 0 )
303  wxLogError( "Python error %d occurred running command:\n\n`%s`", retv, cmd );
304 #endif
305 }
306 
307 
312 
317 
318 
319 
320 bool IFACE::OnKifaceStart( PGM_BASE* aProgram, int aCtlBits )
321 {
322  // This is process-level-initialization, not project-level-initialization of the DSO.
323  // Do nothing in here pertinent to a project!
324 
325  start_common( aCtlBits );
326 
327  wxFileName fn = FP_LIB_TABLE::GetGlobalTableFileName();
328 
329  if( !fn.FileExists() )
330  {
331  DIALOG_GLOBAL_FP_LIB_TABLE_CONFIG fpDialog( NULL );
332 
333  fpDialog.ShowModal();
334  }
335  else
336  {
337  try
338  {
339  // The global table is not related to a specific project. All projects
340  // will use the same global table. So the KIFACE::OnKifaceStart() contract
341  // of avoiding anything project specific is not violated here.
343  return false;
344  }
345  catch( const IO_ERROR& ioe )
346  {
347  // if we are here, a incorrect global footprint library table was found.
348  // Incorrect global symbol library table is not a fatal error:
349  // the user just has to edit the (partially) loaded table.
350  wxString msg = _(
351  "An error occurred attempting to load the global footprint library table.\n"
352  "Please edit this global footprint library table in Preferences menu."
353  );
354 
355  DisplayErrorMessage( NULL, msg, ioe.What() );
356  }
357  }
358 
359 #if defined( KICAD_SCRIPTING )
360  scriptingSetup();
361 #endif
362 
363  return true;
364 }
365 
366 
368 {
369 #if defined( KICAD_SCRIPTING_WXPYTHON )
370  // Restore the thread state and tell Python to cleanup after itself.
371  // wxPython will do its own cleanup as part of that process.
372  // This should only be called if python was setup correctly.
373 
374  if( IsWxPythonLoaded() )
376 #endif
377 
378  end_common();
379 }
380 
381 
382 void IFACE::SaveFileAs( const wxString& aProjectBasePath, const wxString& aSrcProjectName,
383  const wxString& aNewProjectBasePath, const wxString& aNewProjectName,
384  const wxString& aSrcFilePath, wxString& aErrors )
385 {
386  wxFileName destFile( aSrcFilePath );
387  wxString destPath = destFile.GetPath();
388  wxString ext = destFile.GetExt();
389 
390  if( destPath.StartsWith( aProjectBasePath ) )
391  {
392  destPath.Replace( aProjectBasePath, aNewProjectBasePath, false );
393  destFile.SetPath( destPath );
394  }
395 
396  if( ext == "kicad_pcb" || ext == "kicad_pcb-bak" )
397  {
398  if( destFile.GetName() == aSrcProjectName )
399  destFile.SetName( aNewProjectName );
400 
401  CopyFile( aSrcFilePath, destFile.GetFullPath(), aErrors );
402  }
403  else if( ext == "brd" )
404  {
405  if( destFile.GetName() == aSrcProjectName )
406  destFile.SetName( aNewProjectName );
407 
408  CopyFile( aSrcFilePath, destFile.GetFullPath(), aErrors );
409  }
410  else if( ext == "mod" || ext == "kicad_mod" )
411  {
412  // Footprints are not project-specific. Keep their source names.
413  CopyFile( aSrcFilePath, destFile.GetFullPath(), aErrors );
414  }
415  else if( ext == "cmp" )
416  {
417  // JEY TODO
418  }
419  else if( ext == "rpt" )
420  {
421  // DRC must be the "gold standard". Since we can't gaurantee that there aren't
422  // any non-deterministic cases in the save-as algorithm, we don't want to certify
423  // the result with the source's DRC report. Therefore copy it under the old
424  // name.
425  CopyFile( aSrcFilePath, destFile.GetFullPath(), aErrors );
426  }
427  else if( destFile.GetName() == "fp-lib-table" )
428  {
429  try
430  {
431  FP_LIB_TABLE fpLibTable;
432  fpLibTable.Load( aSrcFilePath );
433 
434  for( unsigned i = 0; i < fpLibTable.GetCount(); i++ )
435  {
436  LIB_TABLE_ROW& row = fpLibTable.At( i );
437  wxString uri = row.GetFullURI();
438 
439  uri.Replace( "/" + aSrcProjectName + ".pretty", "/" + aNewProjectName + ".pretty" );
440 
441  row.SetFullURI( uri );
442  }
443 
444  fpLibTable.Save( destFile.GetFullPath() );
445  }
446  catch( ... )
447  {
448  wxString msg;
449 
450  if( !aErrors.empty() )
451  aErrors += "\n";
452 
453  msg.Printf( _( "Cannot copy file \"%s\"." ), destFile.GetFullPath() );
454  aErrors += msg;
455  }
456  }
457  else
458  {
459  wxFAIL_MSG( "Unexpected filetype for Pcbnew::SaveFileAs()" );
460  }
461 }
462 
Class FOOTPRINT_WIZARD_FRAME.
Class KIFACE_I is a KIFACE (I)mplementation, with some features useful for DSOs which implement a KIF...
Definition: kiface_i.h:37
#define KICAD_PCB_PORT_SERVICE_NUMBER
< Pcbnew listens on this port for commands from Eeschema
Definition: eda_dde.h:39
void SaveFileAs(const wxString &aProjectBasePath, const wxString &aSrcProjectName, const wxString &aNewProjectBasePath, const wxString &aNewProjectName, const wxString &aSrcFilePath, wxString &aErrors) override
Function SaveFileAs Saving a file under a different name is delegated to the various KIFACEs because ...
Definition: pcbnew.cpp:382
DDE server & client.
bool start_common(int aCtlBits)
Common things to do for a top program module, during OnKifaceStart().
Definition: kiface_i.cpp:90
Hold a record identifying a library accessed by the appropriate plug in object in the LIB_TABLE.
bool pcbnewInitPythonScripting(const char *aUserScriptingPath)
Initialize the python environment and publish the Pcbnew interface inside it.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:249
This file is part of the common library TODO brief description.
bool OnKifaceStart(PGM_BASE *aProgram, int aCtlBits) override
Function OnKifaceStart is called just once shortly after the DSO is loaded.
Definition: pcbnew.cpp:320
This file is part of the common library.
VTBL_ENTRY void CommonSettingsChanged(bool aEnvVarsChanged)
Function CommonSettingsChanged Calls CommonSettingsChanged() on all KIWAY_PLAYERs.
Definition: kiway.cpp:471
Class PGM_BASE keeps program (whole process) data for KiCad programs.
Definition: pgm_base.h:156
FRAME_T
Enum FRAME_T is the set of EDA_BASE_FRAME derivatives, typically stored in EDA_BASE_FRAME::m_Ident.
Definition: frame_type.h:34
VTBL_ENTRY PROJECT & Prj() const
Function Prj returns the PROJECT associated with this KIWAY.
Definition: kiway.cpp:171
unsigned GetCount() const
Get the number of rows contained in the table.
static PGM_BASE * process
Definition: pcbnew.cpp:178
Component library viewer main window.
MY_API(KIFACE *) KIFACE_GETTER(int *aKIFACEversion
void CopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
Function CopyFile.
Definition: gestfich.cpp:358
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:66
Return the global FP_LIB_TABLE.
Definition: kiface_ids.h:53
void ScriptingSetPcbEditFrame(PCB_EDIT_FRAME *aPcbEditFrame)
void pcbnewFinishPythonScripting()
not specified: a GAL engine must be set by the client
FP_LIB_TABLE GFootprintTable
The global footprint library table.
Definition: pcbnew.cpp:311
This file contains miscellaneous commonly used macros and functions.
IFACE(const char *aName, KIWAY::FACE_T aType)
Definition: pcbnew.cpp:67
const wxString GetFullURI(bool aSubstituted=false) const
Return the full location specifying URI for the LIB, either in original UI form or in environment var...
void InvokePcbLibTableEditor(KIWAY *aKiway, wxWindow *aCaller)
Function InvokePcbLibTableEditor shows the modal DIALOG_FP_LIB_TABLE for purposes of editing the glob...
void OnKifaceEnd() override
Function OnKifaceEnd is called just once just before the DSO is to be unloaded.
Definition: pcbnew.cpp:367
#define TO_UTF8(wxstring)
Macro TO_UTF8 converts a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: macros.h:48
wxString PyScriptingPath()
Find the Python scripting path.
wxWindow * CreateWindow(wxWindow *aParent, int aClassId, KIWAY *aKiway, int aCtlBits=0) override
Function CreateWindow creates a wxWindow for the current project.
Definition: pcbnew.cpp:75
bool IsWxPythonLoaded()
bool IsSingle() const
Function IsSingle is this KIFACE_I running under single_top?
Definition: kiface_i.h:115
int aKiwayVersion
Definition: pcbnew.cpp:186
virtual const wxString What() const
A composite of Problem() and Where()
Definition: exceptions.cpp:33
KIFACE * KIFACE_GETTER(int *aKIFACEversion, int aKIWAYversion, PGM_BASE *aProgram)
No name mangling. Each KIFACE (DSO/DLL) will implement this once.
static bool LoadGlobalTable(FP_LIB_TABLE &aTable)
Function LoadGlobalTable loads the global footprint library table into aTable.
void end_common()
Common things to do for a top program module, during OnKifaceEnd();.
Definition: kiface_i.cpp:100
PGM_BASE * PgmOrNull()
similat to PGM_BASE& Pgm(), but return a reference that can be nullptr when running a shared lib from...
Definition: cvpcb.cpp:110
static FOOTPRINT_PREVIEW_PANEL * New(KIWAY *aKiway, wxWindow *aParent)
Class KIWAY is a minimalistic software bus for communications between various DLLs/DSOs (DSOs) within...
Definition: kiway.h:274
pcbnew DSO
Definition: kiway.h:283
Return a new FP_LIB_TABLE with the global table installed as a fallback.
Definition: kiface_ids.h:46
void Load(const wxString &aFileName)
Load the library table using the path defined by aFileName aFallBackTable.
wxString FindKicadFile(const wxString &shortname)
Function FindKicadFile searches the executable file shortname in KiCad binary path and return full fi...
Definition: gestfich.cpp:112
#define _(s)
void * IfaceOrAddress(int aDataId) override
Function IfaceOrAddress return a pointer to the requested object.
Definition: pcbnew.cpp:140
PCB::IFACE KIFACE_I kiface("pcbnew", KIWAY::FACE_PCB)
FACE_T
Known KIFACE implementations.
Definition: kiway.h:280
void PythonPluginsReloadBase()
Helper function PythonPluginsReloadBase Reload Python plugins if they are newer than the already load...
Definition: pcbnew.cpp:288
void SetFullURI(const wxString &aFullURI)
Change the full URI for the library.
see class PGM_BASE
LIB_TABLE_ROW & At(unsigned aIndex)
Get the 'n'th LIB_TABLE_ROW object.
VTBL_ENTRY const wxString & GetExecutablePath() const
Definition: pgm_base.h:222
size_t i
Definition: json11.cpp:649
Class KIFACE is used by a participant in the KIWAY alchemy.
Definition: kiway.h:151
Class PCB_EDIT_FRAME is the main frame for Pcbnew.
void Save(const wxString &aFileName) const
Write this library table to aFileName in s-expression form.
KIFACE_I & Kiface()
Global KIFACE_I "get" accessor.
Definition: pcbnew.cpp:181
FOOTPRINT_LIST_IMPL GFootprintList
The global footprint info table.
Definition: pcbnew.cpp:316
Struct IO_ERROR is a class used to hold an error message and may be used when throwing exceptions con...
Definition: ki_exception.h:76
static wxString GetGlobalTableFileName()
Function GetGlobalTableFileName.
int PGM_BASE * aProgram
Definition: pcbnew.cpp:187
Return a pointer to the global instance of FOOTPRINT_LIST from pcbnew.
Definition: kiface_ids.h:39