Move pcbnew swig

Separates the python scripts into those using swig and those needed for
other scripting
This commit is contained in:
Seth Hillbrand
2021-06-01 20:18:24 +00:00
parent bf1437899e
commit adf885b667
40 changed files with 36 additions and 34 deletions
@@ -0,0 +1,155 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2021 KiCad Developers, see CHANGELOG.TXT for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/gpl-3.0.html
* or you may search the http://www.gnu.org website for the version 3 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "pcb_scripting_tool.h"
#include <action_plugin.h>
#include <gestfich.h>
#include <kiface_ids.h>
#include <kiway.h>
#include <python_scripting.h>
#include <tools/pcb_actions.h>
#include <pybind11/eval.h>
#include <Python.h>
#include <wx/string.h>
using initfunc = PyObject* (*)(void);
SCRIPTING_TOOL::SCRIPTING_TOOL() :
PCB_TOOL_BASE( "pcbnew.ScriptingTool" )
{}
SCRIPTING_TOOL::~SCRIPTING_TOOL()
{}
void SCRIPTING_TOOL::Reset( RESET_REASON aReason )
{
}
bool SCRIPTING_TOOL::Init()
{
PyLOCK lock;
PyObject* mod_name = PyUnicode_FromString( "_pcbnew" );
if( PyObject* existing_mod = PyImport_GetModule( mod_name ) )
{
Py_DecRef( existing_mod );
}
else
{
KIFACE* kiface = frame()->Kiway().KiFACE( KIWAY::FACE_PCB );
initfunc pcbnew_init = reinterpret_cast<initfunc>( kiface->IfaceOrAddress( KIFACE_SCRIPTING_LEGACY ) );
PyImport_AddModule( "_pcbnew" );
PyObject* mod = pcbnew_init();
PyObject* sys_mod = PyImport_GetModuleDict();
PyDict_SetItemString( sys_mod, "_pcbnew", mod );
Py_DECREF( mod );
}
Py_DecRef( mod_name );
// Load pcbnew inside Python and load all the user plugins and package-based plugins
{
using namespace pybind11::literals;
auto locals = pybind11::dict( "sys_path"_a = TO_UTF8( SCRIPTING::PyScriptingPath( false ) ),
"user_path"_a = TO_UTF8( SCRIPTING::PyScriptingPath( true ) ) );
pybind11::exec( R"(
import sys
import pcbnew
pcbnew.LoadPlugins( sys_path, user_path )
)", pybind11::globals(), locals );
}
return true;
}
int SCRIPTING_TOOL::reloadPlugins( const TOOL_EVENT& aEvent )
{
if( !m_isFootprintEditor )
// Reload Python plugins if they are newer than the already loaded, and load new plugins
// Remove all action plugins so that we don't keep references to old versions
ACTION_PLUGINS::UnloadAll();
{
PyLOCK lock;
using namespace pybind11::literals;
auto locals = pybind11::dict( "sys_path"_a = SCRIPTING::PyScriptingPath( false ),
"user_path"_a = SCRIPTING::PyScriptingPath( true ) );
pybind11::exec( R"(
import sys
import pcbnew
pcbnew.LoadPlugins( sys_path, user_path )
)", pybind11::globals(), locals );
}
if( !m_isFootprintEditor )
{
// Action plugins can be modified, therefore the plugins menu must be updated:
frame()->ReCreateMenuBar();
// Recreate top toolbar to add action plugin buttons
frame()->ReCreateHToolbar();
}
return 0;
}
int SCRIPTING_TOOL::showPluginFolder( const TOOL_EVENT& aEvent )
{
#ifdef __WXMAC__
wxString msg;
// Quote in case there are spaces in the path.
msg.Printf( "open \"%s\"", SCRIPTING::PyPluginsPath( true ) );
system( msg.c_str() );
#else
wxString pypath( SCRIPTING::PyPluginsPath( true ) );
// Quote in case there are spaces in the path.
AddDelimiterString( pypath );
wxLaunchDefaultApplication( pypath );
#endif
return 0;
}
void SCRIPTING_TOOL::setTransitions()
{
Go( &SCRIPTING_TOOL::reloadPlugins, PCB_ACTIONS::pluginsReload.MakeEvent() );
Go( &SCRIPTING_TOOL::showPluginFolder, PCB_ACTIONS::pluginsShowFolder.MakeEvent() );
}
@@ -0,0 +1,61 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2021 KiCad Developers, see CHANGELOG.TXT for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/gpl-3.0.html
* or you may search the http://www.gnu.org website for the version 3 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef PCBNEW_PCB_SCRIPTING_TOOL_H_
#define PCBNEW_PCB_SCRIPTING_TOOL_H_
#include <tools/pcb_tool_base.h>
class ACTION_MENU;
/**
* Tool relating to pads and pad settings.
*/
class SCRIPTING_TOOL : public PCB_TOOL_BASE
{
public:
SCRIPTING_TOOL();
~SCRIPTING_TOOL();
///< React to model/view changes
void Reset( RESET_REASON aReason ) override;
///< Basic initialization
bool Init() override;
private:
///< Reload Python plugins and reset toolbar (if in pcbnew)
int reloadPlugins( const TOOL_EVENT& aEvent );
///< Open the user's plugin folder in the system browser
int showPluginFolder( const TOOL_EVENT& aEvent );
///< Bind handlers to corresponding TOOL_ACTIONs.
void setTransitions() override;
};
#endif /* PCBNEW_PCB_SCRIPTING_TOOL_H_ */
@@ -0,0 +1,472 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2017-2021 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "pcbnew_action_plugins.h"
#include <bitmaps.h>
#include <board.h>
#include <footprint.h>
#include <track.h>
#include <zone.h>
#include <menus_helpers.h>
#include <pcbnew_settings.h>
#include <tool/action_menu.h>
#include <tool/action_toolbar.h>
#include "../../scripting/python_scripting.h"
PYTHON_ACTION_PLUGIN::PYTHON_ACTION_PLUGIN( PyObject* aAction )
{
PyLOCK lock;
m_PyAction = aAction;
Py_XINCREF( aAction );
}
PYTHON_ACTION_PLUGIN::~PYTHON_ACTION_PLUGIN()
{
PyLOCK lock;
Py_XDECREF( m_PyAction );
}
PyObject* PYTHON_ACTION_PLUGIN::CallMethod( const char* aMethod, PyObject* aArglist )
{
PyLOCK lock;
PyErr_Clear();
// pFunc is a new reference to the desired method
PyObject* pFunc = PyObject_GetAttrString( m_PyAction, aMethod );
if( pFunc && PyCallable_Check( pFunc ) )
{
PyObject* result = PyObject_CallObject( pFunc, aArglist );
if( PyErr_Occurred() )
{
wxMessageBox( PyErrStringWithTraceback(),
_( "Exception on python action plugin code" ),
wxICON_ERROR | wxOK );
}
if( result )
{
Py_XDECREF( pFunc );
return result;
}
}
else
{
wxString msg = wxString::Format( _( "Method \"%s\" not found, or not callable" ), aMethod );
wxMessageBox( msg, _( "Unknown Method" ), wxICON_ERROR | wxOK );
}
if( pFunc )
{
Py_XDECREF( pFunc );
}
return NULL;
}
wxString PYTHON_ACTION_PLUGIN::CallRetStrMethod( const char* aMethod, PyObject* aArglist )
{
wxString ret;
PyLOCK lock;
PyObject* result = CallMethod( aMethod, aArglist );
ret = PyStringToWx( result );
Py_XDECREF( result );
return ret;
}
wxString PYTHON_ACTION_PLUGIN::GetCategoryName()
{
PyLOCK lock;
return CallRetStrMethod( "GetCategoryName" );
}
wxString PYTHON_ACTION_PLUGIN::GetName()
{
PyLOCK lock;
return CallRetStrMethod( "GetName" );
}
wxString PYTHON_ACTION_PLUGIN::GetDescription()
{
PyLOCK lock;
return CallRetStrMethod( "GetDescription" );
}
bool PYTHON_ACTION_PLUGIN::GetShowToolbarButton()
{
PyLOCK lock;
PyObject* result = CallMethod( "GetShowToolbarButton");
return PyObject_IsTrue(result);
}
wxString PYTHON_ACTION_PLUGIN::GetIconFileName( bool aDark )
{
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", static_cast<int>( aDark ) );
wxString result = CallRetStrMethod( "GetIconFileName", arglist );
Py_DECREF( arglist );
return result;
}
wxString PYTHON_ACTION_PLUGIN::GetPluginPath()
{
PyLOCK lock;
return CallRetStrMethod( "GetPluginPath" );
}
void PYTHON_ACTION_PLUGIN::Run()
{
PyLOCK lock;
CallMethod( "Run" );
}
void* PYTHON_ACTION_PLUGIN::GetObject()
{
return (void*) m_PyAction;
}
void PYTHON_ACTION_PLUGINS::register_action( PyObject* aPyAction )
{
PYTHON_ACTION_PLUGIN* fw = new PYTHON_ACTION_PLUGIN( aPyAction );
fw->register_action();
}
void PYTHON_ACTION_PLUGINS::deregister_action( PyObject* aPyAction )
{
// deregister also destroys the previously created "PYTHON_ACTION_PLUGIN object"
ACTION_PLUGINS::deregister_object( (void*) aPyAction );
}
void PCB_EDIT_FRAME::OnActionPluginMenu( wxCommandEvent& aEvent )
{
ACTION_PLUGIN* actionPlugin = ACTION_PLUGINS::GetActionByMenu( aEvent.GetId() );
if( actionPlugin )
RunActionPlugin( actionPlugin );
}
void PCB_EDIT_FRAME::OnActionPluginButton( wxCommandEvent& aEvent )
{
ACTION_PLUGIN* actionPlugin = ACTION_PLUGINS::GetActionByButton( aEvent.GetId() );
if( actionPlugin )
RunActionPlugin( actionPlugin );
}
void PCB_EDIT_FRAME::RunActionPlugin( ACTION_PLUGIN* aActionPlugin )
{
PICKED_ITEMS_LIST itemsList;
BOARD* currentPcb = GetBoard();
bool fromEmpty = false;
// Append tracks:
for( TRACK* item : currentPcb->Tracks() )
{
ITEM_PICKER picker( nullptr, item, UNDO_REDO::CHANGED );
itemsList.PushItem( picker );
}
// Append footprints:
for( FOOTPRINT* item : currentPcb->Footprints() )
{
ITEM_PICKER picker( nullptr, item, UNDO_REDO::CHANGED );
itemsList.PushItem( picker );
}
// Append drawings
for( BOARD_ITEM* item : currentPcb->Drawings() )
{
ITEM_PICKER picker( nullptr, item, UNDO_REDO::CHANGED );
itemsList.PushItem( picker );
}
// Append zones outlines
for( ZONE* zone : currentPcb->Zones() )
{
ITEM_PICKER picker( nullptr, zone, UNDO_REDO::CHANGED );
itemsList.PushItem( picker );
}
if( itemsList.GetCount() > 0 )
SaveCopyInUndoList( itemsList, UNDO_REDO::CHANGED );
else
fromEmpty = true;
itemsList.ClearItemsList();
BOARD_COMMIT commit( this );
// Execute plugin itself...
ACTION_PLUGINS::SetActionRunning( true );
aActionPlugin->Run();
ACTION_PLUGINS::SetActionRunning( false );
// Get back the undo buffer to fix some modifications
PICKED_ITEMS_LIST* oldBuffer = NULL;
if( fromEmpty )
{
oldBuffer = new PICKED_ITEMS_LIST();
}
else
{
oldBuffer = PopCommandFromUndoList();
wxASSERT( oldBuffer );
}
// Try do discover what was modified
PICKED_ITEMS_LIST deletedItemsList;
// The list of existing items after running the action script
std::set<BOARD_ITEM*> currItemList;
// Append tracks:
for( TRACK* item : currentPcb->Tracks() )
currItemList.insert( item );
// Append footprints:
for( FOOTPRINT* item : currentPcb->Footprints() )
currItemList.insert( item );
// Append drawings
for( BOARD_ITEM* item : currentPcb->Drawings() )
currItemList.insert( item );
// Append zones outlines
for( ZONE* zone : currentPcb->Zones() )
currItemList.insert( zone );
// Found deleted items
for( unsigned int i = 0; i < oldBuffer->GetCount(); i++ )
{
BOARD_ITEM* item = (BOARD_ITEM*) oldBuffer->GetPickedItem( i );
ITEM_PICKER picker( nullptr, item, UNDO_REDO::DELETED );
wxASSERT( item );
if( currItemList.find( item ) == currItemList.end() )
{
deletedItemsList.PushItem( picker );
commit.Removed( item );
}
}
// Mark deleted elements in undolist
for( unsigned int i = 0; i < deletedItemsList.GetCount(); i++ )
{
oldBuffer->PushItem( deletedItemsList.GetItemWrapper( i ) );
}
// Find new footprints
for( FOOTPRINT* item : currentPcb->Footprints() )
{
if( !oldBuffer->ContainsItem( item ) )
{
ITEM_PICKER picker( nullptr, item, UNDO_REDO::NEWITEM );
oldBuffer->PushItem( picker );
commit.Added( item );
}
}
for( TRACK* item : currentPcb->Tracks() )
{
if( !oldBuffer->ContainsItem( item ) )
{
ITEM_PICKER picker( nullptr, item, UNDO_REDO::NEWITEM );
oldBuffer->PushItem( picker );
commit.Added( item );
}
}
for( BOARD_ITEM* item : currentPcb->Drawings() )
{
if( !oldBuffer->ContainsItem( item ) )
{
ITEM_PICKER picker( nullptr, item, UNDO_REDO::NEWITEM );
oldBuffer->PushItem( picker );
commit.Added( item );
}
}
for( ZONE* zone : currentPcb->Zones() )
{
if( !oldBuffer->ContainsItem( zone ) )
{
ITEM_PICKER picker( nullptr, zone, UNDO_REDO::NEWITEM );
oldBuffer->PushItem( picker );
commit.Added( zone );
}
}
if( oldBuffer->GetCount() )
{
OnModify();
PushCommandToUndoList( oldBuffer );
}
else
{
delete oldBuffer;
}
commit.Push( _( "Apply action script" ) );
ActivateGalCanvas();
}
void PCB_EDIT_FRAME::buildActionPluginMenus( ACTION_MENU* actionMenu )
{
if( !actionMenu ) // Should not occur.
return;
for( int ii = 0; ii < ACTION_PLUGINS::GetActionsCount(); ii++ )
{
wxMenuItem* item;
ACTION_PLUGIN* ap = ACTION_PLUGINS::GetAction( ii );
const wxBitmap& bitmap = ap->iconBitmap.IsOk() ? ap->iconBitmap : KiBitmap( BITMAPS::puzzle_piece );
item = AddMenuItem( actionMenu, wxID_ANY, ap->GetName(), ap->GetDescription(), bitmap );
Connect( item->GetId(), wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler( PCB_EDIT_FRAME::OnActionPluginMenu ) );
ACTION_PLUGINS::SetActionMenu( ii, item->GetId() );
}
}
void PCB_EDIT_FRAME::AddActionPluginTools()
{
bool need_separator = true;
const std::vector<ACTION_PLUGIN*>& orderedPlugins = GetOrderedActionPlugins();
for( ACTION_PLUGIN* ap : orderedPlugins )
{
if( GetActionPluginButtonVisible( ap->GetPluginPath(), ap->GetShowToolbarButton() ) )
{
if( need_separator )
{
m_mainToolBar->AddScaledSeparator( this );
need_separator = false;
}
// Add button
wxBitmap bitmap;
if ( ap->iconBitmap.IsOk() )
bitmap = KiScaledBitmap( ap->iconBitmap, this );
else
bitmap = KiScaledBitmap( BITMAPS::puzzle_piece, this );
wxAuiToolBarItem* button = m_mainToolBar->AddTool(
wxID_ANY, wxEmptyString, bitmap, ap->GetName() );
Connect( button->GetId(), wxEVT_COMMAND_MENU_SELECTED,
wxCommandEventHandler( PCB_EDIT_FRAME::OnActionPluginButton ) );
// Link action plugin to button
ACTION_PLUGINS::SetActionButton( ap, button->GetId() );
}
}
}
std::vector<ACTION_PLUGIN*> PCB_EDIT_FRAME::GetOrderedActionPlugins()
{
std::vector<ACTION_PLUGIN*> plugins;
std::vector<ACTION_PLUGIN*> orderedPlugins;
for( int i = 0; i < ACTION_PLUGINS::GetActionsCount(); i++ )
plugins.push_back( ACTION_PLUGINS::GetAction( i ) );
// First add plugins that have entries in settings
for( const auto& pair : m_settings->m_VisibleActionPlugins )
{
auto loc = std::find_if( plugins.begin(), plugins.end(),
[pair] ( ACTION_PLUGIN* plugin )
{
return plugin->GetPluginPath() == pair.first;
} );
if( loc != plugins.end() )
{
orderedPlugins.push_back( *loc );
plugins.erase( loc );
}
}
// Now append new plugins that have not been configured yet
for( auto remaining_plugin : plugins )
orderedPlugins.push_back( remaining_plugin );
return orderedPlugins;
}
bool PCB_EDIT_FRAME::GetActionPluginButtonVisible( const wxString& aPluginPath, bool aPluginDefault )
{
auto& settings = m_settings->m_VisibleActionPlugins;
for( const auto& entry : settings )
{
if( entry.first == aPluginPath )
return entry.second;
}
// Plugin is not in settings, return default.
return aPluginDefault;
}
@@ -0,0 +1,69 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2017 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file pcbnew_action_plugins.h
* @brief Class PCBNEW_ACTION_PLUGINS
*/
#ifndef PCBNEW_ACTION_PLUGINS_H
#define PCBNEW_ACTION_PLUGINS_H
#undef HAVE_CLOCK_GETTIME // macro is defined in Python.h and causes redefine warning
#include <Python.h>
#undef HAVE_CLOCK_GETTIME
#include <vector>
#include <action_plugin.h>
class PYTHON_ACTION_PLUGIN : public ACTION_PLUGIN
{
PyObject* m_PyAction;
PyObject* CallMethod( const char* aMethod,
PyObject* aArglist = NULL );
wxString CallRetStrMethod( const char* aMethod,
PyObject* aArglist = NULL );
public:
PYTHON_ACTION_PLUGIN( PyObject* action );
~PYTHON_ACTION_PLUGIN();
wxString GetCategoryName() override;
wxString GetName() override;
wxString GetDescription() override;
bool GetShowToolbarButton() override;
wxString GetIconFileName( bool aDark ) override;
wxString GetPluginPath() override;
void Run() override;
void* GetObject() override;
};
class PYTHON_ACTION_PLUGINS
{
public:
static void register_action( PyObject* aPyAction );
static void deregister_action( PyObject* aPyAction );
};
#endif /* PCBNEW_ACTION_PLUGINS_H */
@@ -0,0 +1,381 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2013 NBEE Embedded Systems SL, Miguel Angel Ajo <[email protected]>
* Copyright (C) 2016-2021 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file pcbnew_footprint_wizards.cpp
* @brief Class and PYTHON_FOOTPRINT_WIZARD_LIST and PYTHON_FOOTPRINT_WIZARD_LIST
*/
#include "pcbnew_footprint_wizards.h"
#include <cstdio>
#include <macros.h>
#include "../../scripting/python_scripting.h"
PYTHON_FOOTPRINT_WIZARD::PYTHON_FOOTPRINT_WIZARD( PyObject* aWizard )
{
PyLOCK lock;
m_PyWizard = aWizard;
Py_XINCREF( aWizard );
}
PYTHON_FOOTPRINT_WIZARD::~PYTHON_FOOTPRINT_WIZARD()
{
PyLOCK lock;
Py_XDECREF( m_PyWizard );
}
PyObject* PYTHON_FOOTPRINT_WIZARD::CallMethod( const char* aMethod, PyObject* aArglist )
{
PyLOCK lock;
PyErr_Clear();
// pFunc is a new reference to the desired method
PyObject* pFunc = PyObject_GetAttrString( m_PyWizard, aMethod );
if( pFunc && PyCallable_Check( pFunc ) )
{
PyObject* result = PyObject_CallObject( pFunc, aArglist );
if( PyErr_Occurred() )
{
#if 1 // defined(DEBUG)
wxMessageBox( PyErrStringWithTraceback(),
_( "Exception on python footprint wizard code" ),
wxICON_ERROR | wxOK );
#endif
}
if( result )
{
Py_XDECREF( pFunc );
return result;
}
}
else
{
wxString msg = wxString::Format(_( "Method \"%s\" not found, or not callable" ), aMethod );
wxMessageBox( msg, _( "Unknown Method" ), wxICON_ERROR | wxOK );
}
if( pFunc )
{
Py_XDECREF( pFunc );
}
return NULL;
}
wxString PYTHON_FOOTPRINT_WIZARD::CallRetStrMethod( const char* aMethod, PyObject* aArglist )
{
wxString ret;
PyLOCK lock;
PyObject* result = CallMethod( aMethod, aArglist );
if( result == Py_None )
{
Py_DECREF( result );
return ret;
}
ret = PyStringToWx( result );
Py_XDECREF( result );
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::CallRetArrayStrMethod( const char* aMethod,
PyObject* aArglist )
{
wxArrayString ret;
wxString str_item;
PyLOCK lock;
PyObject* result = CallMethod( aMethod, aArglist );
if( result )
{
if( !PyList_Check( result ) )
{
Py_DECREF( result );
ret.Add( wxT(
"PYTHON_FOOTPRINT_WIZARD::CallRetArrayStrMethod, result is not a list" ),
1 );
return ret;
}
ret = PyArrayStringToWx( result );
Py_DECREF( result );
}
return ret;
}
wxString PYTHON_FOOTPRINT_WIZARD::GetName()
{
PyLOCK lock;
return CallRetStrMethod( "GetName" );
}
wxString PYTHON_FOOTPRINT_WIZARD::GetImage()
{
PyLOCK lock;
return CallRetStrMethod( "GetImage" );
}
wxString PYTHON_FOOTPRINT_WIZARD::GetDescription()
{
PyLOCK lock;
return CallRetStrMethod( "GetDescription" );
}
int PYTHON_FOOTPRINT_WIZARD::GetNumParameterPages()
{
int ret = 0;
PyLOCK lock;
// Time to call the callback
PyObject* result = CallMethod( "GetNumParameterPages", NULL );
if( result )
{
if( !PyLong_Check( result ) )
return -1;
ret = PyLong_AsLong( result );
Py_DECREF( result );
}
return ret;
}
wxString PYTHON_FOOTPRINT_WIZARD::GetParameterPageName( int aPage )
{
wxString ret;
PyLOCK lock;
// Time to call the callback
PyObject* arglist = Py_BuildValue( "(i)", aPage );
PyObject* result = CallMethod( "GetParameterPageName", arglist );
Py_DECREF( arglist );
if( result == Py_None )
{
Py_DECREF( result );
return ret;
}
ret = PyStringToWx( result );
Py_XDECREF( result );
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::GetParameterNames( int aPage )
{
wxArrayString ret;
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", aPage );
ret = CallRetArrayStrMethod( "GetParameterNames", arglist );
Py_DECREF( arglist );
for( unsigned i = 0; i < ret.GetCount(); i++ )
{
wxString rest;
wxString item = ret[i];
if( item.StartsWith( wxT( "*" ), &rest ) )
{
ret[i] = rest;
}
}
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::GetParameterTypes( int aPage )
{
wxArrayString ret;
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", aPage );
ret = CallRetArrayStrMethod( "GetParameterTypes", arglist );
Py_DECREF( arglist );
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::GetParameterValues( int aPage )
{
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", aPage );
wxArrayString ret = CallRetArrayStrMethod( "GetParameterValues", arglist );
Py_DECREF( arglist );
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::GetParameterErrors( int aPage )
{
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", aPage );
wxArrayString ret = CallRetArrayStrMethod( "GetParameterErrors", arglist );
Py_DECREF( arglist );
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::GetParameterHints( int aPage )
{
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", aPage );
wxArrayString ret = CallRetArrayStrMethod( "GetParameterHints", arglist );
Py_DECREF( arglist );
return ret;
}
wxArrayString PYTHON_FOOTPRINT_WIZARD::GetParameterDesignators( int aPage )
{
PyLOCK lock;
PyObject* arglist = Py_BuildValue( "(i)", aPage );
wxArrayString ret = CallRetArrayStrMethod( "GetParameterDesignators", arglist );
Py_DECREF( arglist );
return ret;
}
wxString PYTHON_FOOTPRINT_WIZARD::SetParameterValues( int aPage, wxArrayString& aValues )
{
int len = aValues.size();
PyLOCK lock;
PyObject* py_list = PyList_New( len );
for( int i = 0; i < len; i++ )
{
wxString& str = aValues[i];
PyObject* py_str = PyUnicode_FromString( (const char*) str.mb_str() );
PyList_SetItem( py_list, i, py_str );
}
PyObject* arglist;
arglist = Py_BuildValue( "(i,O)", aPage, py_list );
wxString res = CallRetStrMethod( "SetParameterValues", arglist );
Py_DECREF( arglist );
return res;
}
void PYTHON_FOOTPRINT_WIZARD::ResetParameters()
{
PyLOCK lock;
CallMethod( "ResetWizard", NULL );
}
// this is a SWIG function declaration -from footprint.i
FOOTPRINT* PyFootprint_to_FOOTPRINT( PyObject* obj0 );
FOOTPRINT* PYTHON_FOOTPRINT_WIZARD::GetFootprint( wxString * aMessages )
{
PyLOCK lock;
PyObject* result = CallMethod( "GetFootprint", NULL );
if( aMessages )
*aMessages = CallRetStrMethod( "GetBuildMessages", NULL );
if( !result )
return NULL;
PyObject* obj = PyObject_GetAttrString( result, "this" );
if( PyErr_Occurred() )
{
PyErr_Print();
PyErr_Clear();
}
FOOTPRINT* footprint = PyFootprint_to_FOOTPRINT( obj );
return footprint;
}
void* PYTHON_FOOTPRINT_WIZARD::GetObject()
{
return (void*) m_PyWizard;
}
void PYTHON_FOOTPRINT_WIZARD_LIST::register_wizard( PyObject* aPyWizard )
{
PYTHON_FOOTPRINT_WIZARD* fw = new PYTHON_FOOTPRINT_WIZARD( aPyWizard );
fw->register_wizard();
}
void PYTHON_FOOTPRINT_WIZARD_LIST::deregister_wizard( PyObject* aPyWizard )
{
// deregister also destroyes the previously created "PYTHON_FOOTPRINT_WIZARD object"
FOOTPRINT_WIZARD_LIST::deregister_object( (void*) aPyWizard );
}
@@ -0,0 +1,79 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2013 NBEE Embedded Systems SL, Miguel Angel Ajo <[email protected]>
* Copyright (C) 2016 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file pcbnew_footprint_wizards.h
* @brief Class PCBNEW_FOOTPRINT_WIZARDS
*/
#ifndef PCBNEW_FOOTPRINT_WIZARDS_H
#define PCBNEW_FOOTPRINT_WIZARDS_H
#undef HAVE_CLOCK_GETTIME // macro is defined in Python.h and causes redefine warning
#include <Python.h>
#undef HAVE_CLOCK_GETTIME
#include <vector>
#include <footprint_wizard.h>
class PYTHON_FOOTPRINT_WIZARD : public FOOTPRINT_WIZARD
{
PyObject* m_PyWizard;
PyObject* CallMethod( const char* aMethod, PyObject* aArglist = NULL );
wxString CallRetStrMethod( const char* aMethod, PyObject* aArglist = NULL );
wxArrayString CallRetArrayStrMethod( const char* aMethod, PyObject* aArglist = NULL );
public:
PYTHON_FOOTPRINT_WIZARD( PyObject* wizard );
~PYTHON_FOOTPRINT_WIZARD();
wxString GetName() override;
wxString GetImage() override;
wxString GetDescription() override;
int GetNumParameterPages() override;
wxString GetParameterPageName( int aPage ) override;
wxArrayString GetParameterNames( int aPage ) override;
wxArrayString GetParameterTypes( int aPage ) override;
wxArrayString GetParameterValues( int aPage ) override;
wxArrayString GetParameterErrors( int aPage ) override;
// must return an empty string or an error description:
wxString SetParameterValues( int aPage, wxArrayString& aValues ) override;
FOOTPRINT* GetFootprint( wxString * aMessages ) override;
void* GetObject() override;
wxArrayString GetParameterHints( int aPage ) override;
wxArrayString GetParameterDesignators( int aPage = 0) override;
void ResetParameters() override;
};
class PYTHON_FOOTPRINT_WIZARD_LIST
{
public:
static void register_wizard( PyObject* aPyWizard );
static void deregister_wizard( PyObject* aPyWizard );
};
#endif /* PCBNEW_FOOTPRINT_WIZARDS_H */
@@ -0,0 +1,157 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2012 NBEE Embedded Systems, Miguel Angel Ajo <[email protected]>
* Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file python_scripting.cpp
* @brief methods to add scripting capabilities inside pcbnew
*/
#include "../../scripting/python_scripting.h"
#include <cstdlib>
#include <cstring>
#include <Python.h>
#include <sstream>
#include <eda_base_frame.h>
#include <gal/color4d.h>
#include <trace_helpers.h>
#include <kicad_string.h>
#include <paths.h>
#include <pgm_base.h>
#include <settings/settings_manager.h>
#include <kiplatform/environment.h>
#include <wx/app.h>
#include <config.h>
/**
* Run a python method from the pcbnew module.
*
* @param aMethodName is the name of the method (like "pcbnew.myfunction" )
* @param aNames will contain the returned string
*/
static void pcbnewRunPythonMethodWithReturnedString( const char* aMethodName, wxString& aNames )
{
aNames.Clear();
PyLOCK lock;
PyErr_Clear();
PyObject* builtins = PyImport_ImportModule( "pcbnew" );
wxASSERT( builtins );
if( !builtins ) // Something is wrong in pcbnew.py module (incorrect version?)
return;
PyObject* globals = PyDict_New();
PyDict_SetItemString( globals, "pcbnew", builtins );
Py_DECREF( builtins );
// Build the python code
char cmd[1024];
snprintf( cmd, sizeof(cmd), "result = %s()", aMethodName );
// Execute the python code and get the returned data
PyObject* localDict = PyDict_New();
PyObject* pobj = PyRun_String( cmd, Py_file_input, globals, localDict);
Py_DECREF( globals );
if( pobj )
{
PyObject* str = PyDict_GetItemString(localDict, "result" );
const char* str_res = NULL;
if(str)
{
PyObject* temp_bytes = PyUnicode_AsEncodedString( str, "UTF-8", "strict" );
if( temp_bytes != NULL )
{
str_res = PyBytes_AS_STRING( temp_bytes );
aNames = FROM_UTF8( str_res );
Py_DECREF( temp_bytes );
}
else
{
wxLogMessage( "cannot encode unicode python string" );
}
}
else
{
aNames = wxString();
}
Py_DECREF( pobj );
}
Py_DECREF( localDict );
if( PyErr_Occurred() )
wxLogMessage( PyErrStringWithTraceback() );
}
void pcbnewGetUnloadableScriptNames( wxString& aNames )
{
pcbnewRunPythonMethodWithReturnedString( "pcbnew.GetUnLoadableWizards", aNames );
}
void pcbnewGetScriptsSearchPaths( wxString& aNames )
{
pcbnewRunPythonMethodWithReturnedString( "pcbnew.GetWizardsSearchPaths", aNames );
}
void pcbnewGetWizardsBackTrace( wxString& aTrace )
{
pcbnewRunPythonMethodWithReturnedString( "pcbnew.GetWizardsBackTrace", aTrace );
// Filter message before displaying them
// a trace starts by "Traceback" and is followed by 2 useless lines
// for our purpose
wxArrayString traces;
wxStringSplit( aTrace, traces, '\n' );
// Build the filtered message (remove useless lines)
aTrace.Clear();
for( unsigned ii = 0; ii < traces.Count(); ++ii )
{
if( traces[ii].Contains( "Traceback" ) )
{
ii += 2; // Skip this line and next lines which are related to pcbnew.py module
if( !aTrace.IsEmpty() ) // Add separator for the next trace block
aTrace << "\n**********************************\n";
}
else
aTrace += traces[ii] + "\n";
}
}
@@ -0,0 +1,52 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef __PYTHON_SCRIPTING_H
#define __PYTHON_SCRIPTING_H
#include <wx/string.h>
/**
* Collect the list of python scripts which could not be loaded.
*
* @param aNames is a wxString which will contain the filenames (separated by '\n')
*/
void pcbnewGetUnloadableScriptNames( wxString& aNames );
/**
* Collect the list of paths where python scripts are searched.
*
* @param aNames is a wxString which will contain the paths (separated by '\n')
*/
void pcbnewGetScriptsSearchPaths( wxString& aNames );
/**
* Return the backtrace of errors (if any) when wizard python scripts are loaded.
*
* @param aNames is a wxString which will contain the trace
*/
void pcbnewGetWizardsBackTrace( wxString& aNames );
#endif // __PYTHON_SCRIPTING_H
@@ -0,0 +1,452 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2012 NBEE Embedded Systems, Miguel Angel Ajo <[email protected]>
* Copyright (C) 1992-2017 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file pcbnew_scripting_helpers.cpp
* @brief Scripting helper functions for pcbnew functionality
*/
#include <Python.h>
#undef HAVE_CLOCK_GETTIME // macro is defined in Python.h and causes redefine warning
#include "pcbnew_scripting_helpers.h"
#include <action_plugin.h>
#include <board.h>
#include <pcb_marker.h>
#include <cstdlib>
#include <drc/drc_engine.h>
#include <drc/drc_item.h>
#include <fp_lib_table.h>
#include <io_mgr.h>
#include <kicad_string.h>
#include <macros.h>
#include <pcbnew_scripting_helpers.h>
#include <project.h>
#include <settings/settings_manager.h>
#include <project/project_local_settings.h>
#include <wildcards_and_files_ext.h>
#include <locale_io.h>
#include <wx/app.h>
static PCB_EDIT_FRAME* s_PcbEditFrame = NULL;
static SETTINGS_MANAGER* s_SettingsManager = nullptr;
BOARD* GetBoard()
{
if( s_PcbEditFrame )
return s_PcbEditFrame->GetBoard();
else
return NULL;
}
void ScriptingSetPcbEditFrame( PCB_EDIT_FRAME* aPcbEditFrame )
{
s_PcbEditFrame = aPcbEditFrame;
}
BOARD* LoadBoard( wxString& aFileName )
{
if( aFileName.EndsWith( KiCadPcbFileExtension ) )
return LoadBoard( aFileName, IO_MGR::KICAD_SEXP );
else if( aFileName.EndsWith( LegacyPcbFileExtension ) )
return LoadBoard( aFileName, IO_MGR::LEGACY );
// as fall back for any other kind use the legacy format
return LoadBoard( aFileName, IO_MGR::LEGACY );
}
SETTINGS_MANAGER* GetSettingsManager()
{
if( !s_SettingsManager )
{
// Ensure wx system settings stuff is available
static_cast<void>( wxTheApp );
s_SettingsManager = new SETTINGS_MANAGER( true );
}
return s_SettingsManager;
}
PROJECT* GetDefaultProject()
{
PROJECT* project = GetSettingsManager()->GetProject( "" );
if( !project )
{
GetSettingsManager()->LoadProject( "" );
project = GetSettingsManager()->GetProject( "" );
}
return project;
}
BOARD* LoadBoard( wxString& aFileName, IO_MGR::PCB_FILE_T aFormat )
{
wxFileName pro = aFileName;
pro.SetExt( ProjectFileExtension );
pro.MakeAbsolute();
wxString projectPath = pro.GetFullPath();
// Ensure the "C" locale is temporary set, before reading any file
// It also avoid wxWidget alerts about locale issues, later, when using Python 3
LOCALE_IO dummy;
PROJECT* project = GetSettingsManager()->GetProject( projectPath );
if( !project )
{
GetSettingsManager()->LoadProject( projectPath );
project = GetSettingsManager()->GetProject( projectPath );
}
// Board cannot be loaded without a project, so create the default project
if( !project )
project = GetDefaultProject();
BOARD* brd = IO_MGR::Load( aFormat, aFileName );
if( brd )
{
brd->SetProject( project );
// Move legacy view settings to local project settings
if( !brd->m_LegacyVisibleLayers.test( Rescue ) )
project->GetLocalSettings().m_VisibleLayers = brd->m_LegacyVisibleLayers;
if( !brd->m_LegacyVisibleItems.test( GAL_LAYER_INDEX( GAL_LAYER_ID_BITMASK_END ) ) )
project->GetLocalSettings().m_VisibleItems = brd->m_LegacyVisibleItems;
BOARD_DESIGN_SETTINGS& bds = brd->GetDesignSettings();
bds.m_DRCEngine = std::make_shared<DRC_ENGINE>( brd, &bds );
try
{
wxFileName rules = pro;
rules.SetExt( DesignRulesFileExtension );
bds.m_DRCEngine->InitEngine( rules );
}
catch( ... )
{
// Best efforts...
}
for( PCB_MARKER* marker : brd->ResolveDRCExclusions() )
brd->Add( marker );
brd->BuildConnectivity();
brd->BuildListOfNets();
brd->SynchronizeNetsAndNetClasses();
}
return brd;
}
BOARD* CreateEmptyBoard()
{
BOARD* brd = new BOARD();
brd->SetProject( GetDefaultProject() );
return brd;
}
bool SaveBoard( wxString& aFileName, BOARD* aBoard, IO_MGR::PCB_FILE_T aFormat )
{
aBoard->BuildConnectivity();
aBoard->SynchronizeNetsAndNetClasses();
IO_MGR::Save( aFormat, aFileName, aBoard, NULL );
wxFileName pro = aFileName;
pro.SetExt( ProjectFileExtension );
pro.MakeAbsolute();
wxString projectPath = pro.GetFullPath();
GetSettingsManager()->SaveProject( pro.GetFullPath() );
return true;
}
bool SaveBoard( wxString& aFileName, BOARD* aBoard )
{
return SaveBoard( aFileName, aBoard, IO_MGR::KICAD_SEXP );
}
FP_LIB_TABLE* GetFootprintLibraryTable()
{
BOARD* board = GetBoard();
if( !board )
return nullptr;
PROJECT* project = board->GetProject();
if( !project )
return nullptr;
return project->PcbFootprintLibs();
}
wxArrayString GetFootprintLibraries()
{
wxArrayString footprintLibraryNames;
FP_LIB_TABLE* tbl = GetFootprintLibraryTable();
if( !tbl )
return footprintLibraryNames;
for( const wxString& name : tbl->GetLogicalLibs() )
footprintLibraryNames.Add( name );
return footprintLibraryNames;
}
wxArrayString GetFootprints( const wxString& aNickName )
{
wxArrayString footprintNames;
FP_LIB_TABLE* tbl = GetFootprintLibraryTable();
if( !tbl )
return footprintNames;
tbl->FootprintEnumerate( footprintNames, aNickName, true );
return footprintNames;
}
bool ExportSpecctraDSN( wxString& aFullFilename )
{
if( s_PcbEditFrame )
{
bool ok = s_PcbEditFrame->ExportSpecctraFile( aFullFilename );
return ok;
}
else
{
return false;
}
}
bool ExportVRML( const wxString& aFullFileName, double aMMtoWRMLunit,
bool aExport3DFiles, bool aUseRelativePaths,
const wxString& a3D_Subdir,
double aXRef, double aYRef )
{
if( s_PcbEditFrame )
{
bool ok = s_PcbEditFrame->ExportVRML_File( aFullFileName, aMMtoWRMLunit,
aExport3DFiles, aUseRelativePaths,
a3D_Subdir, aXRef, aYRef );
return ok;
}
else
{
return false;
}
}
bool ImportSpecctraSES( wxString& aFullFilename )
{
if( s_PcbEditFrame )
{
bool ok = s_PcbEditFrame->ImportSpecctraSession( aFullFilename );
return ok;
}
else
{
return false;
}
}
bool ExportFootprintsToLibrary( bool aStoreInNewLib, const wxString& aLibName, wxString* aLibPath )
{
if( s_PcbEditFrame )
{
s_PcbEditFrame->ExportFootprintsToLibrary( aStoreInNewLib, aLibName, aLibPath );
return true;
}
else
{
return false;
}
}
void Refresh()
{
if( s_PcbEditFrame )
{
auto board = s_PcbEditFrame->GetBoard();
board->BuildConnectivity();
// Re-init everything: this is the easy way to do that
s_PcbEditFrame->ActivateGalCanvas();
s_PcbEditFrame->GetCanvas()->Refresh();
}
}
void UpdateUserInterface()
{
if( s_PcbEditFrame )
s_PcbEditFrame->UpdateUserInterface();
}
int GetUserUnits()
{
if( s_PcbEditFrame )
return static_cast<int>( s_PcbEditFrame->GetUserUnits() );
return -1;
}
bool IsActionRunning()
{
return ACTION_PLUGINS::IsActionRunning();
}
bool WriteDRCReport( BOARD* aBoard, const wxString& aFileName, EDA_UNITS aUnits,
bool aReportAllTrackErrors )
{
wxCHECK( aBoard, false );
BOARD_DESIGN_SETTINGS& bds = aBoard->GetDesignSettings();
std::shared_ptr<DRC_ENGINE> engine = bds.m_DRCEngine;
if( !engine )
{
bds.m_DRCEngine = std::make_shared<DRC_ENGINE>( aBoard, &bds );
engine = bds.m_DRCEngine;
}
wxCHECK( engine, false );
wxFileName fn = aBoard->GetFileName();
fn.SetExt( DesignRulesFileExtension );
wxString drcRulesPath = s_SettingsManager->Prj().AbsolutePath( fn.GetFullName() );
try
{
engine->InitEngine( drcRulesPath );
}
catch( PARSE_ERROR& )
{
return false;
}
std::vector<std::shared_ptr<DRC_ITEM>> footprints;
std::vector<std::shared_ptr<DRC_ITEM>> unconnected;
std::vector<std::shared_ptr<DRC_ITEM>> violations;
engine->SetProgressReporter( nullptr );
engine->SetViolationHandler(
[&]( const std::shared_ptr<DRC_ITEM>& aItem, wxPoint aPos )
{
if( aItem->GetErrorCode() == DRCE_MISSING_FOOTPRINT
|| aItem->GetErrorCode() == DRCE_DUPLICATE_FOOTPRINT
|| aItem->GetErrorCode() == DRCE_EXTRA_FOOTPRINT
|| aItem->GetErrorCode() == DRCE_NET_CONFLICT )
{
footprints.push_back( aItem );
}
else if( aItem->GetErrorCode() == DRCE_UNCONNECTED_ITEMS )
{
unconnected.push_back( aItem );
}
else
{
violations.push_back( aItem );
}
} );
engine->RunTests( aUnits, aReportAllTrackErrors, false );
engine->ClearViolationHandler();
// TODO: Unify this with DIALOG_DRC::writeReport
FILE* fp = wxFopen( aFileName, wxT( "w" ) );
if( fp == nullptr )
return false;
std::map<KIID, EDA_ITEM*> itemMap;
aBoard->FillItemMap( itemMap );
fprintf( fp, "** Drc report for %s **\n", TO_UTF8( aBoard->GetFileName() ) );
wxDateTime now = wxDateTime::Now();
fprintf( fp, "** Created on %s **\n", TO_UTF8( now.Format( wxT( "%F %T" ) ) ) );
fprintf( fp, "\n** Found %d DRC violations **\n", static_cast<int>( violations.size() ) );
for( const std::shared_ptr<DRC_ITEM>& item : violations )
{
SEVERITY severity = bds.GetSeverity( item->GetErrorCode() );
fprintf( fp, "%s", TO_UTF8( item->ShowReport( aUnits, severity, itemMap ) ) );
}
fprintf( fp, "\n** Found %d unconnected pads **\n", static_cast<int>( unconnected.size() ) );
for( const std::shared_ptr<DRC_ITEM>& item : unconnected )
{
SEVERITY severity = bds.GetSeverity( item->GetErrorCode() );
fprintf( fp, "%s", TO_UTF8( item->ShowReport( aUnits, severity, itemMap ) ) );
}
fprintf( fp, "\n** Found %d Footprint errors **\n", static_cast<int>( footprints.size() ) );
for( const std::shared_ptr<DRC_ITEM>& item : footprints )
{
SEVERITY severity = bds.GetSeverity( item->GetErrorCode() );
fprintf( fp, "%s", TO_UTF8( item->ShowReport( aUnits, severity, itemMap ) ) );
}
fprintf( fp, "\n** End of Report **\n" );
fclose( fp );
return true;
}
@@ -0,0 +1,163 @@
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2013 NBEE Embedded Systems SL, Miguel Angel Ajo <[email protected]>
* Copyright (C) 2013-2017 KiCad Developers, see AUTHORS.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef __PCBNEW_SCRIPTING_HELPERS_H
#define __PCBNEW_SCRIPTING_HELPERS_H
#include <pcb_edit_frame.h>
#include <io_mgr.h>
/* we could be including all these methods as static in a class, but
* we want plain pcbnew.<method_name> access from python
*/
#ifndef SWIG
void ScriptingSetPcbEditFrame( PCB_EDIT_FRAME* aPCBEdaFrame );
#endif
// For Python scripts: return the current board.
BOARD* GetBoard();
BOARD* LoadBoard( wxString& aFileName, IO_MGR::PCB_FILE_T aFormat );
// Default LoadBoard() to load .kicad_pcb files:.
BOARD* LoadBoard( wxString& aFileName );
SETTINGS_MANAGER* GetSettingsManager();
/**
* Constructs a default BOARD with a tempoary (no filename) project
* @return the created board
*/
BOARD* CreateEmptyBoard();
// Boards can be saved only as .kicad_pcb file format,
// so no option to choose the file format.
bool SaveBoard( wxString& aFileName, BOARD* aBoard );
/**
* will get the nicknames of all of the footprint libraries configured in
* pcbnew in both the project and global library tables
* @return the list of footprint library nicknames, empty on error
*/
wxArrayString GetFootprintLibraries();
/**
* will get the names of all of the footprints available in a footprint library
* @param aNickName is the nickname specifying which footprint library to fetch
* from
* @return the list of footprint names, empty on error
*/
wxArrayString GetFootprints( const wxString& aNickName );
/**
* will export the current BOARD to a specctra dsn file.
* See http://www.autotraxeda.com/docs/SPECCTRA/SPECCTRA.pdf for the
* specification.
* @return true if OK
*/
bool ExportSpecctraDSN( wxString& aFullFilename );
/**
* will export the current BOARD to a VRML (wrl) file.
* See ExportVRML_File in pcb_edit_frame.h for detailed documentation.
* @return true if OK
*/
bool ExportVRML( const wxString& aFullFileName, double aMMtoWRMLunit,
bool aExport3DFiles, bool aUseRelativePaths,
const wxString& a3D_Subdir,
double aXRef, double aYRef );
/**
* will import a specctra *.ses file and use it to relocate MODULEs and
* to replace all vias and tracks in an existing and loaded BOARD.
* See http://www.autotraxeda.com/docs/SPECCTRA/SPECCTRA.pdf for the
* specification.
* @return true if OK
*/
bool ImportSpecctraSES( wxString& aFullFilename );
/**
* Function ExportFootprintsToLibrary
* Save footprints in a library:
* @param aStoreInNewLib:
* true : save footprints in a existing lib. Existing footprints will be kept
* or updated.
* This lib should be in fp lib table, and is type is .pretty
* false: save footprints in a new lib. It it is an existing lib,
* previous footprints will be removed
*
* @param aLibName:
* optional library name to create, stops dialog call.
* must be called with aStoreInNewLib as true
*/
bool ExportFootprintsToLibrary( bool aStoreInNewLib, const wxString& aLibName = wxEmptyString,
wxString* aLibPath = NULL );
/**
* Update the board display after modifying it by a python script
* (note: it is automatically called by action plugins, after running the plugin,
* so call this function is usually not needed inside action plugins
*
* Could be deprecated because modifying a board (especially deleting items) outside
* a action plugin can crash Pcbnew.
*/
void Refresh();
/**
* Update the layer manager and other widgets from the board setup
* (layer and items visibility, colors ...)
* (note: it is automatically called by action plugins, after running the plugin,
* so call this function is usually not needed inside action plugins
*/
void UpdateUserInterface();
/**
* Returns the currently selected user unit value for the interface
* @return 0 = Inches, 1=mm, -1 if the frame isn't set
*/
int GetUserUnits();
/**
* Are we currently in an action plugin?
*/
bool IsActionRunning();
/**
* Runs the DRC check on the given board and writes the results to a report file.
* Requires that the project for the board be loaded, and note that unlike the DRC dialog
* this does not attempt to fill zones, so zones must be valid before calling.
*
* @param aBoard is a valid loaded board
* @param aFileName is the full path and name of the report file to write
* @param aUnits is the units to use in the report
* @param aReportAllTrackErrors controls whether all errors or just the first error is reported
* for each track
* @return true if successful, false if not
*/
bool WriteDRCReport( BOARD* aBoard, const wxString& aFileName, EDA_UNITS aUnits,
bool aReportAllTrackErrors );
#endif // __PCBNEW_SCRIPTING_HELPERS_H