KiCad PCB EDA Suite
Loading...
Searching...
No Matches
kicad_cli.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) 2004-2015 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright The 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
25
26#include <wx/filename.h>
27#include <wx/log.h>
28#include <wx/stdpaths.h>
29#include <wx/wxcrtvararg.h> //for wxPrintf
30
31#include <kiway.h>
33#include <string_utils.h>
34#include <paths.h>
37#include <systemdirsappend.h>
38#include <trace_helpers.h>
39
40#include <cctype>
41#include <set>
42#include <stdexcept>
43
44#include "pgm_kicad.h"
45#include "kicad_manager_frame.h"
46
47#include <build_version.h>
48#include <kiplatform/app.h>
50#include <locale_io.h>
51
52#include "cli/command_jobset.h"
54#include "cli/command_pcb.h"
56#include "cli/command_pcb_drc.h"
78#include "cli/command_fp.h"
82#include "cli/command_sch.h"
83#include "cli/command_sch_erc.h"
86#include "cli/command_sym.h"
90#include "cli/command_version.h"
91#include "cli/exit_codes.h"
92
93// Add this header after all others, to avoid a collision name in a Windows header
94// on mingw.
95#include <wx/app.h>
96
97// a dummy to quiet linking with EDA_BASE_FRAME::config();
98#include <kiface_base.h>
99#include <thread_pool.h>
100
101
103{
104 // This function should never be called. It is only referenced from
105 // EDA_BASE_FRAME::config() and this is only provided to satisfy the linker,
106 // not to be actually called.
107 wxLogFatalError( wxT( "Unexpected call to Kiface() in kicad/kicad.cpp" ) );
108
109 throw std::logic_error( "Unexpected call to Kiface() in kicad/kicad.cpp" );
110}
111
112
114{
116
117 std::vector<COMMAND_ENTRY> subCommands;
118
119 COMMAND_ENTRY( CLI::COMMAND* aHandler ) : handler( aHandler ){};
120 COMMAND_ENTRY( CLI::COMMAND* aHandler, std::vector<COMMAND_ENTRY> aSub ) :
121 handler( aHandler ), subCommands( aSub ){};
122};
123
177
178
179// clang-format off
180static std::vector<COMMAND_ENTRY> commandStack = {
181 {
182 &jobsetCmd,
183 {
184 {
186 }
187 }
188 },
189 {
190 &fpCmd,
191 {
192 {
194 {
196 }
197 },
198 {
200 }
201 }
202 },
203 {
204 &pcbCmd,
205 {
206 {
207 &pcbDrcCmd
208 },
209 {
211 },
212 {
214 {
239 }
240 },
241 {
243 }
244 }
245 },
246 {
247 &schCmd,
248 {
249 {
250 &schErcCmd
251 },
252 {
254 {
263 }
264 },
265 {
267 }
268 }
269 },
270 {
271 &symCmd,
272 {
273 {
275 {
277 }
278 },
279 {
281 }
282 }
283 },
284 {
285 &versionCmd,
286 }
287};
288// clang-format on
289
290
291static void recurseArgParserBuild( argparse::ArgumentParser& aArgParser, COMMAND_ENTRY& aEntry )
292{
293 aArgParser.add_subparser( aEntry.handler->GetArgParser() );
294
295 for( COMMAND_ENTRY& subEntry : aEntry.subCommands )
296 {
297 recurseArgParserBuild( aEntry.handler->GetArgParser(), subEntry );
298 }
299}
300
301
302static COMMAND_ENTRY* recurseArgParserSubCommandUsed( argparse::ArgumentParser& aArgParser,
303 COMMAND_ENTRY& aEntry )
304{
305 COMMAND_ENTRY* cliCmd = nullptr;
306
307 if( aArgParser.is_subcommand_used( aEntry.handler->GetName() ) )
308 {
309 for( COMMAND_ENTRY& subentry : aEntry.subCommands )
310 {
311 cliCmd = recurseArgParserSubCommandUsed( aEntry.handler->GetArgParser(), subentry );
312 if( cliCmd )
313 break;
314 }
315
316 if(!cliCmd)
317 cliCmd = &aEntry;
318 }
319
320 return cliCmd;
321}
322
323
324static void printHelp( argparse::ArgumentParser& argParser )
325{
326 std::stringstream ss;
327 ss << argParser;
328 wxPrintf( From_UTF8( ss.str().c_str() ) );
329}
330
331
338static bool looksLikeNegativeVectorValue( const std::string& aValue )
339{
340 if( aValue.empty() || aValue[0] != '-' )
341 return false;
342
343 if( aValue.find( ',' ) == std::string::npos )
344 return false;
345
346 for( size_t i = 1; i < aValue.size(); ++i )
347 {
348 char c = aValue[i];
349
350 if( !std::isdigit( c ) && c != '.' && c != ',' && c != '-' && c != '+' )
351 return false;
352 }
353
354 return true;
355}
356
357
369static std::vector<std::string> preprocessArgs( int argc, char** argv )
370{
371 std::vector<std::string> result;
372
373 static const std::set<std::string> vectorArgs = {
374 "--rotate", "--pan", "--pivot"
375 };
376
377 for( int i = 0; i < argc; ++i )
378 {
379 std::string current( argv[i] );
380
381 if( vectorArgs.count( current ) && i + 1 < argc )
382 {
383 std::string next( argv[i + 1] );
384
386 {
387 result.push_back( current + "='" + next + "'" );
388 ++i;
389 continue;
390 }
391 }
392
393 result.push_back( current );
394 }
395
396 return result;
397}
398
399
401{
403 App().SetAppDisplayName( wxT( "kicad-cli" ) );
404
405#if defined( DEBUG )
406 wxString absoluteArgv0 = wxStandardPaths::Get().GetExecutablePath();
407
408 if( !wxIsAbsolutePath( absoluteArgv0 ) )
409 {
410 wxLogError( wxT( "No meaningful argv[0]" ) );
411 return false;
412 }
413#endif
414
415 if( !InitPgm( true, true) )
416 return false;
417
418 m_bm.InitSettings( new KICAD_SETTINGS );
421 m_bm.Init();
422
424
425 return true;
426}
427
428
430{
431 argparse::ArgumentParser argParser( std::string( "kicad-cli" ), GetMajorMinorVersion().ToStdString(),
432 argparse::default_arguments::none );
433
434 argParser.add_argument( "-v", ARG_VERSION )
435 .help( UTF8STDSTR( _( "prints version information and exits" ) ) )
436 .flag()
437 .nargs( 0 );
438
439 argParser.add_argument( ARG_HELP_SHORT, ARG_HELP )
440 .help( UTF8STDSTR( ARG_HELP_DESC ) )
441 .flag()
442 .nargs( 0 );
443
444 for( COMMAND_ENTRY& entry : commandStack )
445 {
446 recurseArgParserBuild( argParser, entry );
447 }
448
449 try
450 {
451 // Use the C locale to parse arguments
452 // Otherwise the decimal separator for the locale will be applied
453 LOCALE_IO dummy;
454
455 // Pre-process arguments to handle negative vector values (e.g., --rotate -45,0,45)
456 // which argparse would otherwise interpret as unknown options
457 std::vector<std::string> args = preprocessArgs( m_argcUtf8, m_argvUtf8 );
458 argParser.parse_args( args );
459 }
460 // std::runtime_error doesn't seem to be enough for the scan<>()
461 catch( const std::exception& err )
462 {
463 bool requestedHelp = false;
464
465 for( int i = 0; i < m_argcUtf8; ++i )
466 {
467 if( std::string arg( m_argvUtf8[i] ); arg == ARG_HELP_SHORT || arg == ARG_HELP )
468 {
469 requestedHelp = true;
470 break;
471 }
472 }
473
474 if( !requestedHelp )
475 wxPrintf( "%s\n", err.what() );
476
477 // find the correct argparser object to output the command usage info
478 COMMAND_ENTRY* cliCmd = nullptr;
479 for( COMMAND_ENTRY& entry : commandStack )
480 {
481 if( argParser.is_subcommand_used( entry.handler->GetName() ) )
482 {
483 cliCmd = recurseArgParserSubCommandUsed( argParser, entry );
484 }
485 }
486
487 // arg parser uses a stream overload for printing the help
488 // we want to intercept so we can wxString the utf8 contents
489 // because on windows our terminal codepage might not be utf8
490 if( cliCmd )
491 cliCmd->handler->PrintHelp();
492 else
493 {
494 printHelp( argParser );
495 }
496
497 return requestedHelp ? 0 : CLI::EXIT_CODES::ERR_ARGS;
498 }
499
500 if( argParser[ ARG_HELP ] == true )
501 {
502 std::stringstream ss;
503 ss << argParser;
504 wxPrintf( From_UTF8( ss.str().c_str() ) );
505
506 return 0;
507 }
508
509 CLI::COMMAND* cliCmd = nullptr;
510
511 // the version arg gets redirected to the version subcommand
512 if( argParser[ARG_VERSION] == true )
513 {
514 cliCmd = &versionCmd;
515 }
516
517 if( !cliCmd )
518 {
519 for( COMMAND_ENTRY& entry : commandStack )
520 {
521 if( argParser.is_subcommand_used( entry.handler->GetName() ) )
522 {
523 COMMAND_ENTRY* cmdSubEntry = recurseArgParserSubCommandUsed( argParser, entry );
524 if( cmdSubEntry != nullptr )
525 {
526 cliCmd = cmdSubEntry->handler;
527 break;
528 }
529 }
530 }
531 }
532
533 if( cliCmd )
534 {
535 int exitCode = cliCmd->Perform( Kiway );
536
537 if( exitCode != CLI::EXIT_CODES::AVOID_CLOSING )
538 {
539 return exitCode;
540 }
541 else
542 {
543 return 0;
544 }
545 }
546 else
547 {
548 printHelp( argParser );
549
551 }
552}
553
554
556{
557 // Abort and wait on any background jobs
558 GetKiCadThreadPool().purge();
559 GetKiCadThreadPool().wait();
560
562
564 {
566 m_settings_manager->Save();
567 }
568
569 // Destroy everything in PGM_KICAD,
570 // especially wxSingleInstanceCheckerImpl earlier than wxApp and earlier
571 // than static destruction would.
572 Destroy();
573}
574
575
576void PGM_KICAD::MacOpenFile( const wxString& aFileName )
577{
578#if defined( __WXMAC__ )
579 wxFAIL_MSG( "kicad-cli should not call MacOpenFile" );
580#endif
581}
582
583
585{
586 // unlike a normal destructor, this is designed to be called more
587 // than once safely:
588
589 m_bm.End();
590
592}
593
594
596
598
602struct APP_KICAD_CLI : public wxAppConsole
603{
604 APP_KICAD_CLI() : wxAppConsole()
605 {
606 SetPgm( &program );
607
608 // Init the environment each platform wants
610 }
611
612
613 bool OnInit() override
614 {
615 // Perform platform-specific init tasks
616 if( !KIPLATFORM::APP::Init() )
617 return false;
618
619#ifndef DEBUG
620 // Enable logging traces to the console in release build.
621 // This is usually disabled, but it can be useful for users to run to help
622 // debug issues and other problems.
623 if( wxGetEnv( wxS( "KICAD_ENABLE_WXTRACE" ), nullptr ) )
624 {
625 wxLog::EnableLogging( true );
626 wxLog::SetLogLevel( wxLOG_Trace );
627 }
628#endif
629
630 if( !program.OnPgmInit() )
631 {
632 program.OnPgmExit();
633 return false;
634 }
635
636 return true;
637 }
638
639 int OnExit() override
640 {
641 program.OnPgmExit();
642
643#if defined( __FreeBSD__ )
644 // Avoid wxLog crashing when used in destructors.
645 wxLog::EnableLogging( false );
646#endif
647
648 return wxAppConsole::OnExit();
649 }
650
651 int OnRun() override
652 {
653 try
654 {
655 return program.OnPgmRun();
656 }
657 catch( ... )
658 {
659 Pgm().HandleException( std::current_exception() );
660 }
661
662 return -1;
663 }
664
665 int FilterEvent( wxEvent& aEvent ) override
666 {
667 return Event_Skip;
668 }
669
670#if defined( DEBUG )
674 bool ProcessEvent( wxEvent& aEvent ) override
675 {
676 if( aEvent.GetEventType() == wxEVT_CHAR || aEvent.GetEventType() == wxEVT_CHAR_HOOK )
677 {
678 wxKeyEvent* keyEvent = static_cast<wxKeyEvent*>( &aEvent );
679
680 if( keyEvent )
681 {
682 wxLogTrace( kicadTraceKeyEvent, "APP_KICAD::ProcessEvent %s", dump( *keyEvent ) );
683 }
684 }
685
686 aEvent.Skip();
687 return false;
688 }
689
697 bool OnExceptionInMainLoop() override
698 {
699 try
700 {
701 throw;
702 }
703 catch( ... )
704 {
705 Pgm().HandleException( std::current_exception() );
706 }
707
708 return false; // continue on. Return false to abort program
709 }
710#endif
711};
712
713IMPLEMENT_APP_CONSOLE( APP_KICAD_CLI )
714
715
716// The C++ project manager supports one open PROJECT, so Prj() calls within
717// this link image need this function.
719{
720 return Kiway.Prj();
721}
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
argparse::ArgumentParser & GetArgParser()
Definition command.h:60
const std::string & GetName() const
Definition command.h:61
void PrintHelp()
Definition command.cpp:48
int Perform(KIWAY &aKiway)
Entry point to processing commands from args and doing work.
Definition command.cpp:56
A KIFACE implementation.
Definition kiface_base.h:39
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:294
void OnKiwayEnd()
Definition kiway.cpp:776
void LoadGlobalTables(std::initializer_list< LIBRARY_TABLE_TYPE > aTablesToLoad={})
(Re)loads the global library tables in the given list, or all tables if no list is given
virtual wxApp & App()
Return a bare naked wxApp which may come from wxPython, SINGLE_TOP, or kicad.exe.
Definition pgm_base.cpp:200
int m_argcUtf8
Definition pgm_base.h:452
std::unique_ptr< SETTINGS_MANAGER > m_settings_manager
Definition pgm_base.h:412
void Destroy()
Definition pgm_base.cpp:179
bool InitPgm(bool aHeadless=false, bool aSkipPyInit=false, bool aIsUnitTest=false)
Initialize this program.
Definition pgm_base.cpp:316
char ** m_argvUtf8
argv parameters converted to utf8 form because wxWidgets has opinions.
Definition pgm_base.h:450
void HandleException(std::exception_ptr aPtr, bool aUnhandled=false)
A exception handler to be used at the top level if exceptions bubble up that for.
Definition pgm_base.cpp:796
void BuildArgvUtf8()
Builds the UTF8 based argv variable.
Definition pgm_base.cpp:271
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:132
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:134
void SaveCommonSettings()
Save the program (process) settings subset which are stored .kicad_common.
Definition pgm_base.cpp:526
PGM_KICAD extends PGM_BASE to bring in FileHistory() and PdfBrowser() which were moved from EDA_APP i...
Definition pgm_kicad.h:42
bool OnPgmInit()
Definition kicad.cpp:93
void Destroy()
Definition kicad.cpp:442
void MacOpenFile(const wxString &aFileName) override
Specific to MacOSX (not used under Linux or Windows).
Definition kicad.cpp:429
void OnPgmExit()
Definition kicad.cpp:401
APP_SETTINGS_BASE * PgmSettings()
Definition pgm_kicad.h:59
int OnPgmRun()
Definition kicad.cpp:395
BIN_MOD m_bm
Definition pgm_kicad.h:72
Container for project specific data.
Definition project.h:65
T * RegisterSettings(T *aSettings, bool aLoadNow=true)
Take ownership of the pointer passed in.
void SetKiway(KIWAY *aKiway)
Associate this setting manager with the given Kiway.
#define ARG_HELP
Definition command.h:30
#define UTF8STDSTR(s)
Definition command.h:27
#define ARG_HELP_DESC
Definition command.h:32
#define ARG_VERSION
Definition command.h:29
#define ARG_HELP_SHORT
Definition command.h:31
#define _(s)
const wxChar *const kicadTraceKeyEvent
Flag to enable wxKeyEvent debug tracing.
PROJECT & Prj()
Definition kicad.cpp:637
static CLI::PCB_EXPORT_SVG_COMMAND exportPcbSvgCmd
static CLI::SCH_EXPORT_PLOT_COMMAND exportSchHpglCmd
static CLI::SCH_EXPORT_PLOT_COMMAND exportSchSvgCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbVrmlCmd
static CLI::PCB_EXPORT_STATS_COMMAND exportPcbStatsCmd
static CLI::PCB_EXPORT_DXF_COMMAND exportPcbDxfCmd
static CLI::SCH_ERC_COMMAND schErcCmd
static CLI::PCB_EXPORT_HPGL_COMMAND exportPcbHpglCmd
static CLI::PCB_DRC_COMMAND pcbDrcCmd
static CLI::PCB_EXPORT_GERBER_COMMAND exportPcbGerberCmd
static std::vector< std::string > preprocessArgs(int argc, char **argv)
Pre-process command line arguments to handle negative numeric values.
static CLI::FP_EXPORT_SVG_COMMAND fpExportSvgCmd
static CLI::PCB_EXPORT_COMMAND exportPcbCmd
static CLI::PCB_RENDER_COMMAND pcbRenderCmd
static bool looksLikeNegativeVectorValue(const std::string &aValue)
Check if a string looks like a numeric vector value that happens to start with a minus sign.
static CLI::SYM_UPGRADE_COMMAND symUpgradeCmd
static CLI::FP_EXPORT_COMMAND fpExportCmd
static CLI::SCH_EXPORT_PYTHONBOM_COMMAND exportSchPythonBomCmd
static CLI::FP_UPGRADE_COMMAND fpUpgradeCmd
static CLI::SCH_EXPORT_PLOT_COMMAND exportSchPdfCmd
static void printHelp(argparse::ArgumentParser &argParser)
static CLI::JOBSET_RUN_COMMAND jobsetRunCmd
static CLI::PCB_UPGRADE_COMMAND pcbUpgradeCmd
static CLI::PCB_EXPORT_POS_COMMAND exportPcbPosCmd
static CLI::PCB_EXPORT_PS_COMMAND exportPcbPsCmd
static CLI::SYM_COMMAND symCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbStepCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbPlyCmd
static CLI::PCB_EXPORT_GERBERS_COMMAND exportPcbGerbersCmd
static PGM_KICAD program
static CLI::SCH_EXPORT_BOM_COMMAND exportSchBomCmd
static CLI::PCB_EXPORT_IPCD356_COMMAND exportPcbIpcD356Cmd
static CLI::SCH_COMMAND schCmd
static CLI::PCB_COMMAND pcbCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcb3DPDFCmd
static std::vector< COMMAND_ENTRY > commandStack
static CLI::PCB_EXPORT_DRILL_COMMAND exportPcbDrillCmd
static CLI::PCB_EXPORT_IPC2581_COMMAND exportPcbIpc2581Cmd
static CLI::SCH_EXPORT_PLOT_COMMAND exportSchDxfCmd
static CLI::JOBSET_COMMAND jobsetCmd
static CLI::SYM_EXPORT_COMMAND symExportCmd
static CLI::SYM_EXPORT_SVG_COMMAND symExportSvgCmd
static COMMAND_ENTRY * recurseArgParserSubCommandUsed(argparse::ArgumentParser &aArgParser, COMMAND_ENTRY &aEntry)
static CLI::PCB_EXPORT_3D_COMMAND exportPcbU3DCmd
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
static CLI::PCB_EXPORT_ODB_COMMAND exportPcbOdbCmd
static CLI::VERSION_COMMAND versionCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbStlCmd
static CLI::PCB_EXPORT_PDF_COMMAND exportPcbPdfCmd
static CLI::SCH_UPGRADE_COMMAND schUpgradeCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbXaoCmd
static void recurseArgParserBuild(argparse::ArgumentParser &aArgParser, COMMAND_ENTRY &aEntry)
static CLI::SCH_EXPORT_NETLIST_COMMAND exportSchNetlistCmd
static CLI::SCH_EXPORT_PLOT_COMMAND exportSchPostscriptCmd
static CLI::PCB_EXPORT_GENCAD_COMMAND exportPcbGencadCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbStepzCmd
static CLI::FP_COMMAND fpCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbGlbCmd
static CLI::SCH_EXPORT_COMMAND exportSchCmd
static CLI::PCB_EXPORT_3D_COMMAND exportPcbBrepCmd
#define KFCTL_CPP_PROJECT_SUITE
Running under C++ project mgr, possibly with others.
Definition kiway.h:163
#define KFCTL_CLI
Running as CLI app.
Definition kiway.h:164
static const int ERR_ARGS
Definition exit_codes.h:31
static const int AVOID_CLOSING
Definition exit_codes.h:28
bool Init()
Perform application-specific initialization tasks.
Definition unix/app.cpp:40
void Init()
Perform environment initialization tasks.
void SetPgm(PGM_BASE *pgm)
PGM_BASE & Pgm()
The global program "get" accessor.
CITER next(CITER it)
Definition ptree.cpp:124
PGM_SINGLE_TOP program
KIWAY Kiway(KFCTL_STANDALONE)
std::vector< FAB_LAYER_COLOR > dummy
wxString From_UTF8(const char *cstring)
Not publicly visible because most of the action is in PGM_KICAD these days.
int OnExit() override
bool OnInit() override
int FilterEvent(wxEvent &aEvent) override
int OnRun() override
COMMAND_ENTRY(CLI::COMMAND *aHandler)
COMMAND_ENTRY(CLI::COMMAND *aHandler, std::vector< COMMAND_ENTRY > aSub)
CLI::COMMAND * handler
std::vector< COMMAND_ENTRY > subCommands
System directories search utilities.
wxString result
Test unit parsing edge cases and error handling.
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
wxString dump(const wxArrayString &aArray)
Debug helper for printing wxArrayString contents.
wxLogTrace helper definitions.