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#ifdef KICAD_IPC_API
95#endif
96
97// Add this header after all others, to avoid a collision name in a Windows header
98// on mingw.
99#include <wx/app.h>
100
101// a dummy to quiet linking with EDA_BASE_FRAME::config();
102#include <kiface_base.h>
103#include <thread_pool.h>
104
105
107{
108 // This function should never be called. It is only referenced from
109 // EDA_BASE_FRAME::config() and this is only provided to satisfy the linker,
110 // not to be actually called.
111 wxLogFatalError( wxT( "Unexpected call to Kiface() in kicad/kicad.cpp" ) );
112
113 throw std::logic_error( "Unexpected call to Kiface() in kicad/kicad.cpp" );
114}
115
116
118{
120
121 std::vector<COMMAND_ENTRY> subCommands;
122
123 COMMAND_ENTRY( CLI::COMMAND* aHandler ) : handler( aHandler ){};
124 COMMAND_ENTRY( CLI::COMMAND* aHandler, std::vector<COMMAND_ENTRY> aSub ) :
125 handler( aHandler ), subCommands( aSub ){};
126};
127
181
182#ifdef KICAD_IPC_API
183static CLI::API_SERVER_COMMAND apiServerCmd{};
184#endif
185
186// clang-format off
187static std::vector<COMMAND_ENTRY> commandStack = {
188 {
189 &jobsetCmd,
190 {
191 {
193 }
194 }
195 },
196 {
197 &fpCmd,
198 {
199 {
201 {
203 }
204 },
205 {
207 }
208 }
209 },
210 {
211 &pcbCmd,
212 {
213 {
214 &pcbDrcCmd
215 },
216 {
218 },
219 {
221 },
222 {
224 {
248 }
249 },
250 {
252 }
253 }
254 },
255 {
256 &schCmd,
257 {
258 {
259 &schErcCmd
260 },
261 {
263 {
272 }
273 },
274 {
276 }
277 }
278 },
279 {
280 &symCmd,
281 {
282 {
284 {
286 }
287 },
288 {
290 }
291 }
292 },
293 {
294 &versionCmd,
295 }
296#ifdef KICAD_IPC_API
297 ,
298 {
299 &apiServerCmd,
300 }
301#endif
302};
303// clang-format on
304
305
306static void recurseArgParserBuild( argparse::ArgumentParser& aArgParser, COMMAND_ENTRY& aEntry )
307{
308 aArgParser.add_subparser( aEntry.handler->GetArgParser() );
309
310 for( COMMAND_ENTRY& subEntry : aEntry.subCommands )
311 {
312 recurseArgParserBuild( aEntry.handler->GetArgParser(), subEntry );
313 }
314}
315
316
317static COMMAND_ENTRY* recurseArgParserSubCommandUsed( argparse::ArgumentParser& aArgParser,
318 COMMAND_ENTRY& aEntry )
319{
320 COMMAND_ENTRY* cliCmd = nullptr;
321
322 if( aArgParser.is_subcommand_used( aEntry.handler->GetName() ) )
323 {
324 for( COMMAND_ENTRY& subentry : aEntry.subCommands )
325 {
326 cliCmd = recurseArgParserSubCommandUsed( aEntry.handler->GetArgParser(), subentry );
327 if( cliCmd )
328 break;
329 }
330
331 if(!cliCmd)
332 cliCmd = &aEntry;
333 }
334
335 return cliCmd;
336}
337
338
339static void printHelp( argparse::ArgumentParser& argParser )
340{
341 std::stringstream ss;
342 ss << argParser;
343 wxPrintf( From_UTF8( ss.str().c_str() ) );
344}
345
346
353static bool looksLikeNegativeVectorValue( const std::string& aValue )
354{
355 if( aValue.empty() || aValue[0] != '-' )
356 return false;
357
358 if( aValue.find( ',' ) == std::string::npos )
359 return false;
360
361 for( size_t i = 1; i < aValue.size(); ++i )
362 {
363 char c = aValue[i];
364
365 if( !std::isdigit( c ) && c != '.' && c != ',' && c != '-' && c != '+' )
366 return false;
367 }
368
369 return true;
370}
371
372
384static std::vector<std::string> preprocessArgs( int argc, char** argv )
385{
386 std::vector<std::string> result;
387
388 static const std::set<std::string> vectorArgs = {
389 "--rotate", "--pan", "--pivot"
390 };
391
392 for( int i = 0; i < argc; ++i )
393 {
394 std::string current( argv[i] );
395
396 if( vectorArgs.count( current ) && i + 1 < argc )
397 {
398 std::string next( argv[i + 1] );
399
401 {
402 result.push_back( current + "='" + next + "'" );
403 ++i;
404 continue;
405 }
406 }
407
408 result.push_back( current );
409 }
410
411 return result;
412}
413
414
416{
418 App().SetAppDisplayName( wxT( "kicad-cli" ) );
419
420#if defined( DEBUG )
421 wxString absoluteArgv0 = wxStandardPaths::Get().GetExecutablePath();
422
423 if( !wxIsAbsolutePath( absoluteArgv0 ) )
424 {
425 wxLogError( wxT( "No meaningful argv[0]" ) );
426 return false;
427 }
428#endif
429
430 if( !InitPgm( true ) )
431 return false;
432
433 m_bm.InitSettings( new KICAD_SETTINGS );
436 m_bm.Init();
437
439
440 return true;
441}
442
443
445{
446 argparse::ArgumentParser argParser( std::string( "kicad-cli" ), GetMajorMinorVersion().ToStdString(),
447 argparse::default_arguments::none );
448
449 argParser.add_argument( "-v", ARG_VERSION )
450 .help( UTF8STDSTR( _( "prints version information and exits" ) ) )
451 .flag()
452 .nargs( 0 );
453
454 argParser.add_argument( ARG_HELP_SHORT, ARG_HELP )
455 .help( UTF8STDSTR( ARG_HELP_DESC ) )
456 .flag()
457 .nargs( 0 );
458
459 for( COMMAND_ENTRY& entry : commandStack )
460 {
461 recurseArgParserBuild( argParser, entry );
462 }
463
464 try
465 {
466 // Use the C locale to parse arguments
467 // Otherwise the decimal separator for the locale will be applied
468 LOCALE_IO dummy;
469
470 // Pre-process arguments to handle negative vector values (e.g., --rotate -45,0,45)
471 // which argparse would otherwise interpret as unknown options
472 std::vector<std::string> args = preprocessArgs( m_argcUtf8, m_argvUtf8 );
473 argParser.parse_args( args );
474 }
475 // std::runtime_error doesn't seem to be enough for the scan<>()
476 catch( const std::exception& err )
477 {
478 bool requestedHelp = false;
479
480 for( int i = 0; i < m_argcUtf8; ++i )
481 {
482 if( std::string arg( m_argvUtf8[i] ); arg == ARG_HELP_SHORT || arg == ARG_HELP )
483 {
484 requestedHelp = true;
485 break;
486 }
487 }
488
489 if( !requestedHelp )
490 wxPrintf( "%s\n", err.what() );
491
492 // find the correct argparser object to output the command usage info
493 COMMAND_ENTRY* cliCmd = nullptr;
494 for( COMMAND_ENTRY& entry : commandStack )
495 {
496 if( argParser.is_subcommand_used( entry.handler->GetName() ) )
497 {
498 cliCmd = recurseArgParserSubCommandUsed( argParser, entry );
499 }
500 }
501
502 // arg parser uses a stream overload for printing the help
503 // we want to intercept so we can wxString the utf8 contents
504 // because on windows our terminal codepage might not be utf8
505 if( cliCmd )
506 cliCmd->handler->PrintHelp();
507 else
508 {
509 printHelp( argParser );
510 }
511
512 return requestedHelp ? 0 : CLI::EXIT_CODES::ERR_ARGS;
513 }
514
515 if( argParser[ ARG_HELP ] == true )
516 {
517 std::stringstream ss;
518 ss << argParser;
519 wxPrintf( From_UTF8( ss.str().c_str() ) );
520
521 return 0;
522 }
523
524 CLI::COMMAND* cliCmd = nullptr;
525
526 // the version arg gets redirected to the version subcommand
527 if( argParser[ARG_VERSION] == true )
528 {
529 cliCmd = &versionCmd;
530 }
531
532 if( !cliCmd )
533 {
534 for( COMMAND_ENTRY& entry : commandStack )
535 {
536 if( argParser.is_subcommand_used( entry.handler->GetName() ) )
537 {
538 COMMAND_ENTRY* cmdSubEntry = recurseArgParserSubCommandUsed( argParser, entry );
539 if( cmdSubEntry != nullptr )
540 {
541 cliCmd = cmdSubEntry->handler;
542 break;
543 }
544 }
545 }
546 }
547
548 if( cliCmd )
549 {
550 int exitCode = cliCmd->Perform( Kiway );
551
552 if( exitCode != CLI::EXIT_CODES::AVOID_CLOSING )
553 {
554 return exitCode;
555 }
556 else
557 {
558 return 0;
559 }
560 }
561 else
562 {
563 printHelp( argParser );
564
566 }
567}
568
569
571{
572 // Abort and wait on any background jobs
573 GetKiCadThreadPool().purge();
574 GetKiCadThreadPool().wait();
575
577
579 {
581 m_settings_manager->Save();
582 }
583
584 // Destroy everything in PGM_KICAD,
585 // especially wxSingleInstanceCheckerImpl earlier than wxApp and earlier
586 // than static destruction would.
587 Destroy();
588}
589
590
591void PGM_KICAD::MacOpenFile( const wxString& aFileName )
592{
593#if defined( __WXMAC__ )
594 wxFAIL_MSG( "kicad-cli should not call MacOpenFile" );
595#endif
596}
597
598
600{
601 // unlike a normal destructor, this is designed to be called more
602 // than once safely:
603
604 m_bm.End();
605
607}
608
609
611
613
617struct APP_KICAD_CLI : public wxAppConsole
618{
619 APP_KICAD_CLI() : wxAppConsole()
620 {
621 SetPgm( &program );
622
623 // Init the environment each platform wants
625 }
626
627
628 bool OnInit() override
629 {
630 // Perform platform-specific init tasks
631 if( !KIPLATFORM::APP::Init() )
632 return false;
633
634#ifndef DEBUG
635 // Enable logging traces to the console in release build.
636 // This is usually disabled, but it can be useful for users to run to help
637 // debug issues and other problems.
638 if( wxGetEnv( wxS( "KICAD_ENABLE_WXTRACE" ), nullptr ) )
639 {
640 wxLog::EnableLogging( true );
641 wxLog::SetLogLevel( wxLOG_Trace );
642 }
643#endif
644
645 if( !program.OnPgmInit() )
646 {
647 program.OnPgmExit();
648 return false;
649 }
650
651 return true;
652 }
653
654 int OnExit() override
655 {
656 program.OnPgmExit();
657
658#if defined( __FreeBSD__ )
659 // Avoid wxLog crashing when used in destructors.
660 wxLog::EnableLogging( false );
661#endif
662
663 return wxAppConsole::OnExit();
664 }
665
666 int OnRun() override
667 {
668 try
669 {
670 return program.OnPgmRun();
671 }
672 catch( ... )
673 {
674 Pgm().HandleException( std::current_exception() );
675 }
676
677 return -1;
678 }
679
680 int FilterEvent( wxEvent& aEvent ) override
681 {
682 return Event_Skip;
683 }
684
685#if defined( DEBUG )
689 bool ProcessEvent( wxEvent& aEvent ) override
690 {
691 if( aEvent.GetEventType() == wxEVT_CHAR || aEvent.GetEventType() == wxEVT_CHAR_HOOK )
692 {
693 wxKeyEvent* keyEvent = static_cast<wxKeyEvent*>( &aEvent );
694
695 if( keyEvent )
696 {
697 wxLogTrace( kicadTraceKeyEvent, "APP_KICAD::ProcessEvent %s", dump( *keyEvent ) );
698 }
699 }
700
701 aEvent.Skip();
702 return false;
703 }
704
712 bool OnExceptionInMainLoop() override
713 {
714 try
715 {
716 throw;
717 }
718 catch( ... )
719 {
720 Pgm().HandleException( std::current_exception() );
721 }
722
723 return false; // continue on. Return false to abort program
724 }
725#endif
726};
727
728IMPLEMENT_APP_CONSOLE( APP_KICAD_CLI )
729
730
731// The C++ project manager supports one open PROJECT, so Prj() calls within
732// this link image need this function.
734{
735 return Kiway.Prj();
736}
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:47
int Perform(KIWAY &aKiway)
Entry point to processing commands from args and doing work.
Definition command.cpp:55
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:315
void OnKiwayEnd()
Definition kiway.cpp:813
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:211
int m_argcUtf8
Definition pgm_base.h:449
std::unique_ptr< SETTINGS_MANAGER > m_settings_manager
Definition pgm_base.h:411
void Destroy()
Definition pgm_base.cpp:190
char ** m_argvUtf8
argv parameters converted to utf8 form because wxWidgets has opinions.
Definition pgm_base.h:447
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:802
void BuildArgvUtf8()
Builds the UTF8 based argv variable.
Definition pgm_base.cpp:282
bool InitPgm(bool aHeadless=false, bool aIsUnitTest=false)
Initialize this program.
Definition pgm_base.cpp:327
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:130
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:132
void SaveCommonSettings()
Save the program (process) settings subset which are stored .kicad_common.
Definition pgm_base.cpp:532
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:94
void Destroy()
Definition kicad.cpp:449
void MacOpenFile(const wxString &aFileName) override
Specific to MacOSX (not used under Linux or Windows).
Definition kicad.cpp:436
void OnPgmExit()
Definition kicad.cpp:408
APP_SETTINGS_BASE * PgmSettings()
Definition pgm_kicad.h:59
int OnPgmRun()
Definition kicad.cpp:402
BIN_MOD m_bm
Definition pgm_kicad.h:72
Container for project specific data.
Definition project.h:66
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:644
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 std::vector< std::string > preprocessArgs(int argc, char **argv)
Pre-process command line arguments to handle negative numeric values.
static CLI::PCB_IMPORT_COMMAND pcbImportCmd
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:164
#define KFCTL_CLI
Running as CLI app.
Definition kiway.h:165
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.