KiCad PCB EDA Suite
Loading...
Searching...
No Matches
single_top.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) 2014 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
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, see <https://www.gnu.org/licenses/>.
19 */
20
21
22/*
23
24 This is a program launcher for a single KIFACE DSO. It only mimics a KIWAY,
25 not actually implements one, since only a single DSO is supported by it.
26
27 It is compiled multiple times, once for each standalone program and as such
28 gets different compiler command line supplied #defines from CMake.
29
30*/
31
32
33#include <typeinfo>
34#include <wx/app.h>
35#include <wx/cmdline.h>
36#include <wx/dialog.h>
37#include <wx/filename.h>
38#include <wx/stdpaths.h>
39#include <wx/html/htmlwin.h>
40
41#include <api/api_server.h>
42#include <kiway.h>
43#include <build_version.h>
44#include <pgm_base.h>
45#include <app_monitor.h>
46#include <kiway_player.h>
47#include <macros.h>
48#include <confirm.h>
50
54#include <paths.h>
55
56#include <kiplatform/app.h>
58
59#include <git2.h>
60#include <git/git_backend.h>
61#include <git/libgit_backend.h>
62#include <thread_pool.h>
63
66
67#ifdef KICAD_USE_SENTRY
68#include <sentry.h>
69#endif
70
71// Only a single KIWAY is supported in this single_top top level component,
72// which is dedicated to loading only a single DSO.
74
75
76// implement a PGM_BASE and a wxApp side by side:
77
81static struct PGM_SINGLE_TOP : public PGM_BASE
82{
83 bool OnPgmInit();
84
85 void OnPgmExit()
86 {
87 // Abort and wait on any background jobs
88 GetKiCadThreadPool().purge();
89 GetKiCadThreadPool().wait();
90
91 // Library preloads aren't in the threadpool, but KIWAY::OnKifaceEnd() will cancel them
92
93 Kiway.OnKiwayEnd();
94
95 m_api_server.reset();
96
98 {
100 m_settings_manager->Save();
101 }
102
103 // Destroy PGM_BASE earlier than wxApp and static destruction would
105
106 if( GIT_BACKEND* backend = GetGitBackend() )
107 {
108 backend->Shutdown();
109 delete backend;
110 SetGitBackend( nullptr );
111 }
112 }
113
114 void MacOpenFile( const wxString& aFileName ) override
115 {
116 wxFileName filename( aFileName );
117
118 if( filename.FileExists() )
119 {
120 #if 0
121 // this pulls in EDA_DRAW_FRAME type info, which we don't want in
122 // the single_top link image.
123 KIWAY_PLAYER* frame = dynamic_cast<KIWAY_PLAYER*>( App().GetTopWindow() );
124 #else
125 KIWAY_PLAYER* frame = (KIWAY_PLAYER*) App().GetTopWindow();
126 #endif
127 if( frame )
128 {
129 if( wxWindow* blocking_win = frame->Kiway().GetBlockingDialog() )
130 blocking_win->Close( true );
131
132 frame->OpenProjectFiles( std::vector<wxString>( 1, aFileName ) );
133 }
134 }
135 }
136
138
139
140// A module to allow Html module initialization/cleanup
141// When a wxHtmlWindow is used *only* in a dll/so module, the Html text is displayed
142// as plain text.
143// This helper class is just used to force wxHtmlWinParser initialization
144// see https://groups.google.com/forum/#!topic/wx-users/FF0zv5qGAT0
145class HtmlModule: public wxModule
146{
147public:
149 virtual bool OnInit() override { AddDependency( CLASSINFO( wxHtmlWinParser ) ); return true; };
150 virtual void OnExit() override {};
151
152private:
154};
155
157
158
159#ifdef NDEBUG
160// Define a custom assertion handler
161void CustomAssertHandler( const wxString& file,
162 int line,
163 const wxString& func,
164 const wxString& cond,
165 const wxString& msg )
166{
167 Pgm().HandleAssert( file, line, func, cond, msg );
168}
169#endif
170
171
176struct APP_SINGLE_TOP : public wxApp
177{
178 APP_SINGLE_TOP() : wxApp()
179 {
180 SetPgm( &program );
181
182 // Init the environment each platform wants
184 }
185
186
187 bool OnInit() override
188 {
189#ifdef NDEBUG
190 // These checks generate extra assert noise
191 wxSizerFlags::DisableConsistencyChecks();
192 wxDISABLE_DEBUG_SUPPORT();
193 wxSetAssertHandler( CustomAssertHandler );
194#endif
195
196 // Perform platform-specific init tasks
197 if( !KIPLATFORM::APP::Init() )
198 return false;
199
200#ifndef DEBUG
201 // Enable logging traces to the console in release build.
202 // This is usually disabled, but it can be useful for users to run to help
203 // debug issues and other problems.
204 if( wxGetEnv( wxS( "KICAD_ENABLE_WXTRACE" ), nullptr ) )
205 {
206 wxLog::EnableLogging( true );
207 wxLog::SetLogLevel( wxLOG_Trace );
208 }
209#endif
210
211 // Force wxHtmlWinParser initialization when a wxHtmlWindow is used only
212 // in a shared library (.so or .dll file)
213 // Otherwise the Html text is displayed as plain text.
214 HtmlModule html_init;
215
216 try
217 {
218 return program.OnPgmInit();
219 }
220 catch( ... )
221 {
222 Pgm().HandleException( std::current_exception() );
223 }
224
225 program.OnPgmExit();
226
227 return false;
228 }
229
230 int OnExit() override
231 {
232 // Drain wxPendingDelete (frames deferred via Destroy()) before tearing down
233 // PGM_BASE singletons. On macOS the dock-quit path leaves frames in this
234 // queue at OnExit() time, and their canvas destructors call into
235 // Pgm().GetGLContextManager(). Running OnPgmExit() first would null that
236 // pointer out from under them. See https://gitlab.com/kicad/code/kicad/-/issues/23373
237 int ret = wxApp::OnExit();
238 program.OnPgmExit();
239 program.ExitIfTeardownUnsafe();
240
241 return ret;
242 }
243
244 int OnRun() override
245 {
246 int ret = -1;
247
248 try
249 {
250 ret = wxApp::OnRun();
251 }
252 catch(...)
253 {
254 Pgm().HandleException( std::current_exception() );
255 }
256
257 program.SetRunResult( ret );
258
259 return ret;
260 }
261
262 int FilterEvent( wxEvent& aEvent ) override
263 {
264 return Pgm().FilterAppEvent( aEvent );
265 }
266
267 void OnUnhandledException() override
268 {
269 Pgm().HandleException( std::current_exception(), true );
270 }
271
272#if defined( DEBUG )
280 virtual bool OnExceptionInMainLoop() override
281 {
282 try
283 {
284 throw;
285 }
286 catch( ... )
287 {
288 Pgm().HandleException( std::current_exception() );
289 }
290
291 return false; // continue on. Return false to abort program
292 }
293#endif
294
295#ifdef __WXMAC__
296
304 void MacOpenFile( const wxString& aFileName ) override
305 {
306 Pgm().MacOpenFile( aFileName );
307 }
308
309#endif
310};
311
312IMPLEMENT_APP( APP_SINGLE_TOP )
313
314
316{
317#if defined(DEBUG)
318 wxString absoluteArgv0 = wxStandardPaths::Get().GetExecutablePath();
319
320 if( !wxIsAbsolutePath( absoluteArgv0 ) )
321 {
322 wxLogError( wxT( "No meaningful argv[0]" ) );
323 return false;
324 }
325#endif
326
327 // Initialize the git backend before trying to initialize individual programs
329 GetGitBackend()->Init();
330
331 if( !GetGitBackend()->IsLibraryAvailable() )
332 {
333 const git_error* err = git_error_last();
334 wxString msg = wxS( "Failed to initialize git library" );
335
336 if( err && err->message )
337 msg += wxS( ": " ) + wxString::FromUTF8( err->message );
338
339 wxLogError( msg );
340 return false;
341 }
342
343 if( !InitPgm( false ) )
344 {
345 // Clean up
346 OnPgmExit();
347 return false;
348 }
349
350#if !defined(BUILD_KIWAY_DLL)
351
352 // Only pcb_calculator uses this code currently, as it is not split to use
353 // single_top as a link image separate from a *.kiface.
354 // i.e. it is a single part link image so doesn't need to load a *.kiface.
355
356 // Get the getter, it is statically linked into this binary image.
357 KIFACE_GETTER_FUNC* ki_getter = &KIFACE_GETTER;
358
359 int kiface_version;
360
361 // Get the KIFACE.
362 KIFACE* kiface = ki_getter( &kiface_version, KIFACE_VERSION, this );
363
364 // Trick the KIWAY into thinking it loaded a KIFACE, by recording the KIFACE
365 // in the KIWAY. It needs to be there for KIWAY::OnKiwayEnd() anyways.
366 Kiway.set_kiface( KIWAY::KifaceType( TOP_FRAME ), kiface );
367#endif
368
369 // Tell the settings manager about the current Kiway
370 GetSettingsManager().SetKiway( &Kiway );
371
372 GetSettingsManager().RegisterSettings( new KICAD_SETTINGS );
373
374
375 if( const COMMON_SETTINGS* cfg = Pgm().GetCommonSettings() )
376 {
377 if( cfg->m_Appearance.app_theme == APP_THEME::DARK )
379 else if( cfg->m_Appearance.app_theme == APP_THEME::AUTO )
381 }
382
383 // Create the API server thread once the app event loop exists
384 m_api_server = std::make_unique<KICAD_API_SERVER>();
385
386 // Use KIWAY to create a top window, which registers its existence also.
387 // "TOP_FRAME" is a macro that is passed on compiler command line from CMake,
388 // and is one of the types in FRAME_T.
389 KIWAY_PLAYER* frame = Kiway.Player( TOP_FRAME, true );
390
391 if( frame == nullptr )
392 {
393 // Clean up
394 OnPgmExit();
395 return false;
396 }
397
398 Kiway.SetTop( frame );
399
400 STARTWIZARD startWizard;
401 startWizard.CheckAndRun( frame );
402
403 // Load library tables after startup wizard
404 GetLibraryManager().LoadGlobalTables();
405
406 App().SetTopWindow( frame ); // wxApp gets a face.
407 App().SetAppDisplayName( frame->GetAboutTitle() );
408
409 wxString relaunchDisplayName = frame->GetAboutTitle() + " " + GetMajorMinorVersion();
411
412 // Allocate a slice of time to show the frame and update wxWidgets widgets
413 // (especially setting valid sizes) after creating frame and before calling
414 // OpenProjectFiles() that can update/use some widgets.
415 // The 2 calls to wxSafeYield are needed on wxGTK for best results.
416 wxSafeYield();
417 HideSplash();
418 frame->Show();
419 wxSafeYield();
420
421 // Now after the frame processing, the rest of the positional args are files
422 std::vector<wxString> fileArgs;
423
424
425 static const wxCmdLineEntryDesc desc[] = {
426 { wxCMD_LINE_PARAM, nullptr, nullptr, "File to load", wxCMD_LINE_VAL_STRING,
427 wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_PARAM_OPTIONAL },
428 { wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0 }
429 };
430
431 wxCmdLineParser parser( App().argc, App().argv );
432 parser.SetDesc( desc );
433 parser.Parse( false );
434
435 if( parser.GetParamCount() )
436 {
437 /*
438 gerbview handles multiple project data files, i.e. gerber files on
439 cmd line. Others currently do not, they handle only one. For common
440 code simplicity we simply pass all the arguments in however, each
441 program module can do with them what they want, ignore, complain
442 whatever. We don't establish policy here, as this is a multi-purpose
443 launcher.
444 */
445
446 for( size_t i = 0; i < parser.GetParamCount(); i++ )
447 fileArgs.push_back( parser.GetParam( i ) );
448
449 // special attention to a single argument: argv[1] (==argSet[0])
450 if( fileArgs.size() == 1 )
451 {
452 wxFileName argv1( fileArgs[0] );
453
454#if defined(PGM_DATA_FILE_EXT)
455 // PGM_DATA_FILE_EXT, if present, may be different for each compile,
456 // it may come from CMake on the compiler command line, but often does not.
457 // This facility is mostly useful for those program footprints
458 // supporting a single argv[1].
459 if( !argv1.GetExt() )
460 argv1.SetExt( wxT( PGM_DATA_FILE_EXT ) );
461#endif
462 argv1.MakeAbsolute();
463
464 fileArgs[0] = argv1.GetFullPath();
465 }
466
467 frame->OpenProjectFiles( fileArgs );
468 }
469
470 if( KIFACE* topFrame = Kiway.KiFACE( KIWAY::KifaceType( TOP_FRAME ) ) )
471 topFrame->PreloadLibraries( &Kiway );
472
474
475 m_api_server->SetReadyToReply();
476
477 return true;
478}
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
wxString GetAboutTitle() const
virtual void Init()=0
virtual bool OnInit() override
virtual void OnExit() override
wxDECLARE_DYNAMIC_CLASS(HtmlModule)
KIWAY & Kiway() const
Return a reference to the KIWAY that this object has an opportunity to participate in.
A wxFrame capable of the OpenProjectFiles function, meaning it can load a portion of a KiCad project.
virtual bool OpenProjectFiles(const std::vector< wxString > &aFileList, int aCtl=0)
Open a project or set of files given by aFileList.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
static FACE_T KifaceType(FRAME_T aFrameType)
A simple mapping function which returns the FACE_T which is known to implement aFrameType.
Definition kiway.cpp:351
wxWindow * GetBlockingDialog()
Gets the window pointer to the blocking dialog (to send it signals)
Definition kiway.cpp:705
static const wxString & GetExecutablePath()
Definition paths.cpp:623
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:600
virtual wxApp & App()
Return a bare naked wxApp which may come from wxPython, SINGLE_TOP, or kicad.exe.
Definition pgm_base.cpp:236
void PreloadDesignBlockLibraries(KIWAY *aKiway)
Starts a background job to preload the global and project design block libraries.
Definition pgm_base.cpp:946
virtual void MacOpenFile(const wxString &aFileName)=0
Specific to MacOSX (not used under Linux or Windows).
std::unique_ptr< SETTINGS_MANAGER > m_settings_manager
Definition pgm_base.h:442
int FilterAppEvent(wxEvent &aEvent)
Handle events that must be seen once per application, before any window processes them.
void Destroy()
Definition pgm_base.cpp:190
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:861
bool InitPgm(bool aHeadless=false, bool aIsUnitTest=false)
Initialize this program.
Definition pgm_base.cpp:373
std::unique_ptr< KICAD_API_SERVER > m_api_server
Definition pgm_base.h:448
void HandleAssert(const wxString &aFile, int aLine, const wxString &aFunc, const wxString &aCond, const wxString &aMsg)
A common assert handler to be used between single_top and kicad.
Definition pgm_base.cpp:898
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
void HideSplash()
Definition pgm_base.cpp:341
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:126
void SaveCommonSettings()
Save the program (process) settings subset which are stored .kicad_common.
Definition pgm_base.cpp:591
void CheckAndRun(wxWindow *parent)
This file is part of the common library.
void SetGitBackend(GIT_BACKEND *aBackend)
GIT_BACKEND * GetGitBackend()
KIFACE * KIFACE_GETTER_FUNC(int *aKIFACEversion, int aKIWAYversion, PGM_BASE *aProgram)
Point to the one and only KIFACE export.
Definition kiway.h:590
#define KIFACE_GETTER
Definition kiway.h:110
#define KIFACE_VERSION
Definition kiway.h:109
#define KFCTL_STANDALONE
Running as a standalone Top.
Definition kiway.h:174
This file contains miscellaneous commonly used macros and functions.
bool Init()
Perform application-specific initialization tasks.
Definition unix/app.cpp:46
void EnableDarkMode(bool aForce)
Definition unix/app.cpp:64
void Init()
Perform environment initialization tasks.
void SetAppDetailsForWindow(wxWindow *aWindow, const wxString &aRelaunchCommand, const wxString &aRelaunchDisplayName)
Sets the relaunch command for taskbar pins, this is intended for Windows.
void SetPgm(PGM_BASE *pgm)
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
PGM_SINGLE_TOP program
wxIMPLEMENT_DYNAMIC_CLASS(HtmlModule, wxModule)
KIWAY Kiway(KFCTL_STANDALONE)
Implement a bare naked wxApp (so that we don't become dependent on functionality in a wxApp derivativ...
int OnRun() override
int OnExit() override
void OnUnhandledException() override
bool OnInit() override
int FilterEvent(wxEvent &aEvent) override
Implement a participant in the KIWAY alchemy.
Definition kiway.h:153
Implement PGM_BASE with its own OnPgmInit() and OnPgmExit().
void MacOpenFile(const wxString &aFileName) override
Specific to MacOSX (not used under Linux or Windows).
IFACE KIFACE_BASE kiface("pcb_test_frame", KIWAY::FACE_PCB)
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.