KiCad PCB EDA Suite
Loading...
Searching...
No Matches
command_import.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include "command_import.h"
21#include <cli/exit_codes.h>
22#include <jobs/job_pcb_import.h>
23#include <jobs/job_sch_import.h>
25#include <ki_exception.h>
26#include <pgm_base.h>
28#include <project.h>
30#include <reporter.h>
31#include <kiid.h>
32#include <string_utils.h>
33#include <macros.h>
35#include <wx/crt.h>
36#include <wx/filename.h>
37
38#include <string>
39#include <set>
40#include <vector>
41
42
43#define ARG_LAYER_MAP "--layer-map"
44
45
47{
48 m_argParser.add_description( UTF8STDSTR(
49 _( "Import non-KiCad board and/or schematic files into a new KiCad project" ) ) );
50
51 m_argParser.add_argument( ARG_INPUT )
52 .help( UTF8STDSTR( _( "Input file(s) to import; each is autodetected as a board or "
53 "schematic" ) ) )
54 .nargs( argparse::nargs_pattern::at_least_one )
55 .metavar( "INPUT_FILES" );
56
57 m_argParser.add_argument( "-o", ARG_OUTPUT )
58 .default_value( std::string() )
59 .help( UTF8STDSTR( _( "Output project path stem; produces <stem>.kicad_pro plus "
60 "imported board and/or schematic files beside it. Defaults to the first "
61 "input's name in the current directory." ) ) )
62 .metavar( "PROJECT" );
63
64 m_argParser.add_argument( ARG_LAYER_MAP )
65 .default_value( std::string( "" ) )
66 .help( UTF8STDSTR( _( "JSON file mapping source layer names to KiCad layer names for "
67 "imported boards; unmapped layers use the automatic best-guess" ) ) )
68 .metavar( "FILE" );
69}
70
71
73{
74 std::vector<std::string> rawInputs = m_argParser.get<std::vector<std::string>>( ARG_INPUT );
75 wxString outputArg = From_UTF8( m_argParser.get<std::string>( ARG_OUTPUT ).c_str() );
76
77 if( rawInputs.empty() )
78 {
79 wxFprintf( stderr, _( "At least one input file is required\n" ) );
81 }
82
83 std::vector<wxString> inputFiles;
84
85 for( const std::string& raw : rawInputs )
86 inputFiles.push_back( From_UTF8( raw.c_str() ) );
87
88 std::map<wxString, wxString> layerMap;
89 wxString layerMapFile = From_UTF8( m_argParser.get<std::string>( ARG_LAYER_MAP ).c_str() );
90
91 if( !layerMapFile.IsEmpty() )
92 {
93 wxString error;
94
95 if( !LoadLayerMapFile( layerMapFile, layerMap, error ) )
96 {
97 wxFprintf( stderr, wxS( "%s\n" ), error );
99 }
100 }
101
102 wxFileName projectFn;
103
104 if( !outputArg.IsEmpty() )
105 {
106 projectFn.Assign( outputArg );
107 }
108 else
109 {
110 wxFileName firstInput( inputFiles.front() );
111 projectFn.AssignDir( wxFileName::GetCwd() );
112 projectFn.SetName( firstInput.GetName() );
113 }
114
115 projectFn.SetExt( FILEEXT::ProjectFileExtension );
116 projectFn.MakeAbsolute();
117
118 if( !projectFn.DirExists()
119 && !wxFileName::Mkdir( projectFn.GetPath(), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
120 {
121 wxFprintf( stderr, _( "Could not create output directory: %s\n" ), projectFn.GetPath() );
123 }
124
125 wxString stem = projectFn.GetName();
126 wxString dir = projectFn.GetPath();
127
128 wxFileName boardFn( dir, stem, FILEEXT::KiCadPcbFileExtension );
129 wxFileName schFn( dir, stem, FILEEXT::KiCadSchematicFileExtension );
130
131 // LoadProject returns false for a not-yet-existing file but still registers a fully-defaulted
132 // active project, so success is signalled by GetProject() returning it.
134
135 mgr.LoadProject( projectFn.GetFullPath(), true );
136
137 PROJECT* project = mgr.GetProject( projectFn.GetFullPath() );
138
139 if( !project )
140 {
141 wxFprintf( stderr, _( "Could not create project: %s\n" ), projectFn.GetFullPath() );
143 }
145
146 bool haveBoard = false;
147 bool haveSch = false;
148 std::vector<FILE_INFO_PAIR> boards;
149 int retCode = EXIT_CODES::SUCCESS;
150
151 std::map<wxString, wxString> netNameMap;
152 wxString boardInput;
153
154 // Preserve board-first format detection, but defer loading until the schematic supplies its names.
155 for( const wxString& input : inputFiles )
156 {
157 if( !haveBoard )
158 {
159 JOB_PCB_IMPORT probe;
160 probe.m_inputFile = input;
161 probe.m_probeOnly = true;
162
163 int pcbResult = aKiway.ProcessJob( KIWAY::FACE_PCB, &probe, &reporter );
164
165 if( pcbResult == EXIT_CODES::SUCCESS )
166 {
167 const auto& sourcePcbs = probe.m_projectBoards;
168
169 if( !sourcePcbs.empty() )
170 {
171 const bool hasMultipleBoards = sourcePcbs.size() > 1;
172 std::set<wxString> usedBoardNames;
173
174 for( const auto& [pcbId, sourceName] : sourcePcbs )
175 {
176 wxFileName outputFn = boardFn;
177
178 if( hasMultipleBoards )
179 {
180 wxString boardName = EscapeString( sourceName, CTX_FILENAME );
181
182 if( boardName.empty() )
183 boardName = pcbId;
184
185 wxString uniqueBoardName = boardName;
186 unsigned duplicate = 2;
187
188 while( !usedBoardNames.insert( uniqueBoardName ).second )
189 {
190 uniqueBoardName = wxString::Format( wxS( "%s-%u" ), boardName, duplicate );
191 ++duplicate;
192 }
193
194 outputFn.SetName( uniqueBoardName );
195 }
196
197 JOB_PCB_IMPORT pcbJob;
198 pcbJob.m_inputFile = input;
199 pcbJob.m_importPcbId = pcbId;
200 pcbJob.m_isPartOfMultiBoardProject = hasMultipleBoards;
201 pcbJob.SetConfiguredOutputPath( outputFn.GetFullPath() );
202
203 pcbResult = aKiway.ProcessJob( KIWAY::FACE_PCB, &pcbJob, &reporter );
204
205 if( pcbResult != EXIT_CODES::SUCCESS )
206 {
207 retCode = pcbResult;
208 break;
209 }
210
211 boards.emplace_back( KIID(), outputFn.GetFullName() );
212 haveBoard = true;
213 }
214
215 if( retCode != EXIT_CODES::SUCCESS )
216 break;
217
218 continue;
219 }
220
221 boards.emplace_back( KIID(), boardFn.GetFullName() );
222 haveBoard = true;
223 boardInput = input;
224 continue;
225 }
226 else if( pcbResult != EXIT_CODES::ERR_UNKNOWN_FILE_FORMAT )
227 {
228 retCode = pcbResult;
229 break;
230 }
231 }
232
233 if( !haveSch )
234 {
235 JOB_SCH_IMPORT schJob;
236 schJob.m_inputFile = input;
238 schJob.SetConfiguredOutputPath( schFn.GetFullPath() );
239
240 int schResult = aKiway.ProcessJob( KIWAY::FACE_SCH, &schJob, &reporter );
241
242 if( schResult == EXIT_CODES::SUCCESS )
243 {
244 haveSch = true;
245 netNameMap = std::move( schJob.m_netNameMap );
246 continue;
247 }
248 else if( schResult != EXIT_CODES::ERR_UNKNOWN_FILE_FORMAT )
249 {
250 retCode = schResult;
251 break;
252 }
253 }
254
255 if( haveBoard && haveSch )
256 {
257 wxFprintf( stderr, _( "Could not import '%s': a board and a schematic have already "
258 "been imported for this project\n" ), input );
259 }
260 else
261 {
262 wxFprintf( stderr, _( "No board or schematic importer recognizes the file: %s\n" ), input );
263 }
264
266 break;
267 }
268
269 if( retCode == EXIT_CODES::SUCCESS && !boardInput.empty() )
270 {
271 JOB_PCB_IMPORT pcbJob;
272 pcbJob.m_inputFile = boardInput;
274 pcbJob.m_layerMap = layerMap;
275 pcbJob.m_netNameMap = std::move( netNameMap );
276 pcbJob.SetConfiguredOutputPath( boardFn.GetFullPath() );
277 retCode = aKiway.ProcessJob( KIWAY::FACE_PCB, &pcbJob, &reporter );
278 }
279
280 if( retCode == EXIT_CODES::SUCCESS && !haveBoard && !haveSch )
281 {
282 wxFprintf( stderr, _( "No inputs could be imported\n" ) );
284 }
285
286 if( retCode == EXIT_CODES::SUCCESS && project )
287 {
288 // The schematic handler already registered any sheets; link the board here.
289 if( haveBoard )
290 {
291 std::vector<FILE_INFO_PAIR>& projectBoards = project->GetProjectFile().GetBoards();
292 projectBoards = boards;
293 }
294
295 if( mgr.SaveProject( projectFn.GetFullPath() ) )
296 {
297 reporter.Report( wxString::Format( _( "Created project '%s'\n" ),
298 projectFn.GetFullPath() ),
300 }
301 else
302 {
303 wxFprintf( stderr, _( "Failed to write project file: %s\n" ),
304 projectFn.GetFullPath() );
306 }
307 }
308
309 mgr.UnloadProject( project, false );
310
311 return retCode;
312}
argparse::ArgumentParser m_argParser
Definition command.h:113
COMMAND(const std::string &aName)
Define a new COMMAND instance.
Definition command.cpp:30
int doPerform(KIWAY &aKiway) override
The internal handler that should be overloaded to implement command specific processing and work.
static CLI_REPORTER & GetInstance()
Definition reporter.cpp:261
Job to import a non-KiCad PCB file to KiCad format.
wxString m_importPcbId
EasyEDA Pro PCB document identifier selected by project-level import.
std::map< wxString, wxString > m_layerMap
Explicit overrides from source layer name to KiCad layer name (canonical board-file name,...
std::map< wxString, wxString > m_netNameMap
bool m_isPartOfMultiBoardProject
Avoid promoting an individual board's source settings into shared project settings.
std::vector< std::pair< wxString, wxString > > m_projectBoards
PCB document identifier and source name pairs found during a probe.
wxString m_inputFile
Job to import a non-KiCad schematic file to KiCad format.
wxString m_inputFile
std::map< wxString, wxString > m_netNameMap
void SetConfiguredOutputPath(const wxString &aPath)
Sets the configured output path for the job, this path is always saved to file.
Definition job.cpp:157
Definition kiid.h:46
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
int ProcessJob(KIWAY::FACE_T aFace, JOB *aJob, REPORTER *aReporter=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr)
Definition kiway.cpp:740
@ FACE_SCH
eeschema DSO
Definition kiway.h:355
@ FACE_PCB
pcbnew DSO
Definition kiway.h:356
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:123
Container for project specific data.
Definition project.h:63
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Load a project or sets up a new project with a specified path.
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
#define ARG_OUTPUT
Definition command.h:33
#define ARG_INPUT
Definition command.h:34
#define UTF8STDSTR(s)
Definition command.h:27
#define ARG_LAYER_MAP
#define _(s)
static const std::string ProjectFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string KiCadPcbFileExtension
static wxString From_UTF8(const char *cstring)
Convert a UTF8 encoded C string to a wxString for all wxWidgets build modes.
Definition idf_helpers.h:44
bool LoadLayerMapFile(const wxString &aFile, std::map< wxString, wxString > &aMap, wxString &aError)
Load an explicit layer-mapping file into aMap.
This file contains miscellaneous commonly used macros and functions.
static const int ERR_ARGS
Definition exit_codes.h:31
static const int ERR_INVALID_INPUT_FILE
Definition exit_codes.h:33
static const int SUCCESS
Definition exit_codes.h:29
static const int ERR_INVALID_OUTPUT_CONFLICT
Definition exit_codes.h:34
static const int ERR_UNKNOWN_FILE_FORMAT
No plugin for the requested face recognized the input file format.
Definition exit_codes.h:42
static const int ERR_UNKNOWN
Definition exit_codes.h:32
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
@ RPT_SEVERITY_INFO
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_FILENAME
IbisParser parser & reporter
Definition of file extensions used in Kicad.