KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pgm_base.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 (C) 2008 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 1992-2023 KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, you may find one here:
20 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21 * or you may search the http://www.gnu.org website for the version 2 license,
22 * or you may write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 */
25
33#include <wx/html/htmlwin.h>
34#include <wx/fs_zip.h>
35#include <wx/dir.h>
36#include <wx/filename.h>
37#include <wx/propgrid/propgrid.h>
38#include <wx/snglinst.h>
39#include <wx/stdpaths.h>
40#include <wx/sysopt.h>
41#include <wx/filedlg.h>
42#include <wx/ffile.h>
43#include <wx/tooltip.h>
44
45#include <advanced_config.h>
47#include <bitmaps.h>
48#include <build_version.h>
49#include <common.h>
50#include <confirm.h>
51#include <core/arraydim.h>
52#include <id.h>
54#include <kiplatform/policy.h>
55#include <macros.h>
57#include <paths.h>
58#include <pgm_base.h>
59#include <policy_keys.h>
60#include <python_scripting.h>
63#include <string_utils.h>
64#include <systemdirsappend.h>
65#include <core/thread_pool.h>
66#include <trace_helpers.h>
67
68#include <widgets/wx_splash.h>
69
70#ifdef KICAD_USE_SENTRY
71#include <boost/uuid/uuid_io.hpp>
72#include <boost/uuid/uuid_generators.hpp>
73#include <sentry.h>
74#include <build_version.h>
75#endif
76
77#ifdef KICAD_IPC_API
79#include <api/api_server.h>
80#include <python_manager.h>
81#endif
82
92#undef _
93#define _(s) s
95{
96 { wxLANGUAGE_DEFAULT, ID_LANGUAGE_DEFAULT, _( "Default" ), false },
97// { wxLANGUAGE_INDONESIAN, ID_LANGUAGE_INDONESIAN, wxT( "Bahasa Indonesia" ), true },
98 { wxLANGUAGE_CZECH, ID_LANGUAGE_CZECH, wxT( "Čeština" ), true },
99 { wxLANGUAGE_DANISH, ID_LANGUAGE_DANISH, wxT( "Dansk" ), true },
100 { wxLANGUAGE_GERMAN, ID_LANGUAGE_GERMAN, wxT( "Deutsch" ), true },
101 { wxLANGUAGE_GREEK, ID_LANGUAGE_GREEK, wxT( "Ελληνικά" ), true },
102 { wxLANGUAGE_ENGLISH, ID_LANGUAGE_ENGLISH, wxT( "English" ), true },
103 { wxLANGUAGE_SPANISH, ID_LANGUAGE_SPANISH, wxT( "Español" ), true },
104 { wxLANGUAGE_SPANISH_MEXICAN, ID_LANGUAGE_SPANISH_MEXICAN,
105 wxT( "Español (Latinoamericano)" ), true },
106 { wxLANGUAGE_FRENCH, ID_LANGUAGE_FRENCH, wxT( "Français" ), true },
107 { wxLANGUAGE_KOREAN, ID_LANGUAGE_KOREAN, wxT( "한국어"), true },
108 { wxLANGUAGE_ITALIAN, ID_LANGUAGE_ITALIAN, wxT( "Italiano" ), true },
109 { wxLANGUAGE_LITHUANIAN, ID_LANGUAGE_LITHUANIAN, wxT( "Lietuvių" ), true },
110// { wxLANGUAGE_HUNGARIAN, ID_LANGUAGE_HUNGARIAN, wxT( "Magyar" ), true },
111 { wxLANGUAGE_DUTCH, ID_LANGUAGE_DUTCH, wxT( "Nederlands" ), true },
112 { wxLANGUAGE_JAPANESE, ID_LANGUAGE_JAPANESE, wxT( "日本語" ), true },
113 { wxLANGUAGE_THAI, ID_LANGUAGE_THAI, wxT( "ภาษาไทย" ), true },
114 { wxLANGUAGE_POLISH, ID_LANGUAGE_POLISH, wxT( "Polski" ), true },
115 { wxLANGUAGE_PORTUGUESE, ID_LANGUAGE_PORTUGUESE, wxT( "Português" ),true },
116 { wxLANGUAGE_PORTUGUESE_BRAZILIAN, ID_LANGUAGE_PORTUGUESE_BRAZILIAN,
117 wxT( "Português (Brasil)" ), true },
118 { wxLANGUAGE_RUSSIAN, ID_LANGUAGE_RUSSIAN, wxT( "Русский" ), true },
119// { wxLANGUAGE_SERBIAN, ID_LANGUAGE_SERBIAN, wxT( "Српски" ), true },
120 { wxLANGUAGE_FINNISH, ID_LANGUAGE_FINNISH, wxT( "Suomi" ), true },
121 { wxLANGUAGE_SWEDISH, ID_LANGUAGE_SWEDISH, wxT( "Svenska" ), true },
122// { wxLANGUAGE_VIETNAMESE, ID_LANGUAGE_VIETNAMESE, wxT( "Tiếng Việt" ), true },
123// { wxLANGUAGE_TURKISH, ID_LANGUAGE_TURKISH, wxT( "Türkçe" ), true },
124 { wxLANGUAGE_UKRAINIAN, ID_LANGUAGE_UKRANIAN, wxT( "Українська" ), true },
125 { wxLANGUAGE_CHINESE_SIMPLIFIED, ID_LANGUAGE_CHINESE_SIMPLIFIED,
126 wxT( "简体中文" ), true },
127 { wxLANGUAGE_CHINESE_TRADITIONAL, ID_LANGUAGE_CHINESE_TRADITIONAL,
128 wxT( "繁體中文" ), true },
129 { 0, 0, "", false } // Sentinel
130};
131#undef _
132#define _(s) wxGetTranslation((s))
133
134
136{
137 m_locale = nullptr;
138 m_Printing = false;
139 m_Quitting = false;
140 m_argcUtf8 = 0;
141 m_argvUtf8 = nullptr;
142 m_splash = nullptr;
144
145 setLanguageId( wxLANGUAGE_DEFAULT );
146
147 ForceSystemPdfBrowser( false );
148}
149
150
152{
153 HideSplash();
154 Destroy();
155
156 for( int n = 0; n < m_argcUtf8; n++ )
157 {
158 free( m_argvUtf8[n] );
159 }
160
161 delete[] m_argvUtf8;
162}
163
164
166{
168
169#ifdef KICAD_USE_SENTRY
170 sentry_close();
171#endif
172
173 // unlike a normal destructor, this is designed to be called more than once safely:
174 delete m_locale;
175 m_locale = nullptr;
176
177 m_pgm_checker.reset();
178}
179
180
182{
183 wxASSERT( wxTheApp );
184 return *wxTheApp;
185}
186
187
188void PGM_BASE::SetTextEditor( const wxString& aFileName )
189{
190 m_text_editor = aFileName;
192}
193
194
195const wxString& PGM_BASE::GetTextEditor( bool aCanShowFileChooser )
196{
197 wxString editorname = m_text_editor;
198
199 if( !editorname )
200 {
201 if( !wxGetEnv( wxT( "EDITOR" ), &editorname ) )
202 {
203 // If there is no EDITOR variable set, try the desktop default
204#ifdef __WXMAC__
205 editorname = wxT( "/usr/bin/open -e" );
206#elif __WXX11__
207 editorname = wxT( "/usr/bin/xdg-open" );
208#endif
209 }
210 }
211
212 // If we still don't have an editor name show a dialog asking the user to select one
213 if( !editorname && aCanShowFileChooser )
214 {
215 DisplayInfoMessage( nullptr, _( "No default editor found, you must choose one." ) );
216
217 editorname = AskUserForPreferredEditor();
218 }
219
220 // If we finally have a new editor name request it to be copied to m_text_editor and
221 // saved to the preferences file.
222 if( !editorname.IsEmpty() )
223 SetTextEditor( editorname );
224
225 // m_text_editor already has the same value that editorname, or empty if no editor was
226 // found/chosen.
227 return m_text_editor;
228}
229
230
231const wxString PGM_BASE::AskUserForPreferredEditor( const wxString& aDefaultEditor )
232{
233 // Create a mask representing the executable files in the current platform
234#ifdef __WINDOWS__
235 wxString mask( _( "Executable file" ) + wxT( " (*.exe)|*.exe" ) );
236#else
237 wxString mask( _( "Executable file" ) + wxT( " (*)|*" ) );
238#endif
239
240 // Extract the path, name and extension from the default editor (even if the editor's
241 // name was empty, this method will succeed and return empty strings).
242 wxString path, name, ext;
243 wxFileName::SplitPath( aDefaultEditor, &path, &name, &ext );
244
245 // Show the modal editor and return the file chosen (may be empty if the user cancels
246 // the dialog).
247 return wxFileSelector( _( "Select Preferred Editor" ), path, name, wxT( "." ) + ext,
248 mask, wxFD_OPEN | wxFD_FILE_MUST_EXIST, nullptr );
249}
250
251
252#ifdef KICAD_USE_SENTRY
253bool PGM_BASE::IsSentryOptedIn()
254{
255 KIPLATFORM::POLICY::PBOOL policyState =
258 {
259 return policyState == KIPLATFORM::POLICY::PBOOL::ENABLED;
260 }
261
262 return m_sentry_optin_fn.Exists();
263}
264
265
266void PGM_BASE::SetSentryOptIn( bool aOptIn )
267{
268 if( aOptIn )
269 {
270 if( !m_sentry_uid_fn.Exists() )
271 {
272 sentryCreateUid();
273 }
274
275 if( !m_sentry_optin_fn.Exists() )
276 {
277 wxFFile sentryInitFile( m_sentry_optin_fn.GetFullPath(), "w" );
278 sentryInitFile.Write( "" );
279 sentryInitFile.Close();
280 }
281 }
282 else
283 {
284 if( m_sentry_optin_fn.Exists() )
285 {
286 wxRemoveFile( m_sentry_optin_fn.GetFullPath() );
287 sentry_close();
288 }
289 }
290}
291
292
293wxString PGM_BASE::sentryCreateUid()
294{
295 boost::uuids::uuid uuid = boost::uuids::random_generator()();
296 wxString userGuid = boost::uuids::to_string( uuid );
297
298 wxFFile sentryInitFile( m_sentry_uid_fn.GetFullPath(), "w" );
299 sentryInitFile.Write( userGuid );
300 sentryInitFile.Close();
301
302 return userGuid;
303}
304
305
306void PGM_BASE::ResetSentryId()
307{
308 m_sentryUid = sentryCreateUid();
309}
310
311
312const wxString& PGM_BASE::GetSentryId()
313{
314 return m_sentryUid;
315}
316
317
318void PGM_BASE::sentryInit()
319{
320 m_sentry_optin_fn = wxFileName( PATHS::GetUserCachePath(), "sentry-opt-in" );
321 m_sentry_uid_fn = wxFileName( PATHS::GetUserCachePath(), "sentry-uid" );
322
323 if( IsSentryOptedIn() )
324 {
325 wxFFile sentryInitFile( m_sentry_uid_fn.GetFullPath() );
326 sentryInitFile.ReadAll( &m_sentryUid );
327 sentryInitFile.Close();
328
329 if( m_sentryUid.IsEmpty() || m_sentryUid.length() != 36 )
330 {
331 m_sentryUid = sentryCreateUid();
332 }
333
334 sentry_options_t* options = sentry_options_new();
335
336 #ifndef KICAD_SENTRY_DSN
337 # error "Project configuration error, missing KICAD_SENTRY_DSN"
338 #endif
339
340 sentry_options_set_dsn( options, KICAD_SENTRY_DSN );
341
342 wxFileName tmp;
343 tmp.AssignDir( PATHS::GetUserCachePath() );
344 tmp.AppendDir( "sentry" );
345
346#ifdef __WINDOWS__
347 sentry_options_set_database_pathw( options, tmp.GetPathWithSep().wc_str() );
348#else
349 sentry_options_set_database_path( options, tmp.GetPathWithSep().c_str() );
350#endif
351 sentry_options_set_symbolize_stacktraces( options, true );
352 sentry_options_set_auto_session_tracking( options, false );
353
354 sentry_options_set_release( options, GetCommitHash().ToStdString().c_str() );
355
356 // This just gives us more filtering within sentry, issues still get grouped across
357 // environments.
358 sentry_options_set_environment( options, GetMajorMinorVersion().c_str() );
359
360 sentry_init( options );
361
362 sentry_value_t user = sentry_value_new_object();
363 sentry_value_set_by_key( user, "id", sentry_value_new_string( m_sentryUid.c_str() ) );
364 sentry_set_user( user );
365
366 sentry_set_tag( "kicad.version", GetBuildVersion().ToStdString().c_str() );
367 }
368}
369
370
371void PGM_BASE::sentryPrompt()
372{
373 if( !IsGUI() )
374 return;
375
376 KIPLATFORM::POLICY::PBOOL policyState =
378
380 && !m_settings_manager->GetCommonSettings()->m_DoNotShowAgain.data_collection_prompt )
381 {
382 wxMessageDialog optIn = wxMessageDialog(
383 nullptr,
384 _( "KiCad can anonymously report crashes and special event "
385 "data to developers in order to aid identifying critical bugs "
386 "across the user base more effectively and help profile "
387 "functionality to guide improvements. \n"
388 "If you choose to voluntarily participate, KiCad will automatically "
389 "handle sending said reports when crashes or events occur. \n"
390 "Your design files such as schematic or PCB are not shared in this process." ),
391 _( "Data collection opt in request" ), wxYES_NO | wxCENTRE );
392
393 int result = optIn.ShowModal();
394
395 if( result == wxID_YES )
396 {
397 SetSentryOptIn( true );
398 sentryInit();
399 }
400 else
401 {
402 SetSentryOptIn( false );
403 }
404
405 m_settings_manager->GetCommonSettings()->m_DoNotShowAgain.data_collection_prompt = true;
406 }
407}
408#endif
409
410
412{
413 const wxArrayString& argArray = App().argv.GetArguments();
414 m_argcUtf8 = argArray.size();
415
416 m_argvUtf8 = new char*[m_argcUtf8 + 1];
417 for( int n = 0; n < m_argcUtf8; n++ )
418 {
419 m_argvUtf8[n] = wxStrdup( argArray[n].ToUTF8() );
420 }
421
422 m_argvUtf8[m_argcUtf8] = NULL; // null terminator at end of argv
423}
424
425
427{
428 // Disabling until we change to load each DSO at startup rather than lazy-load when needed.
429 // Note that once the splash screen is re-enabled, there are some remaining bugs to fix:
430 // Any wxWidgets error dialogs that appear during startup are hidden by the splash screen,
431 // so we either need to prevent these from happening (probably not feasible) or else change
432 // the error-handling path to make sure errors go on top of the splash.
433#if 0
434 if( m_splash )
435 return;
436
437 m_splash = new WX_SPLASH( KiBitmap( BITMAPS::splash ), wxSPLASH_CENTRE_ON_SCREEN, 0,
438 NULL, -1, wxDefaultPosition, wxDefaultSize,
439 wxBORDER_NONE | wxSTAY_ON_TOP );
440 wxYield();
441#endif
442}
443
444
446{
447 if( !m_splash )
448 return;
449
450 m_splash->Close( true );
451 m_splash->Destroy();
452 m_splash = nullptr;
453}
454
455
456bool PGM_BASE::InitPgm( bool aHeadless, bool aSkipPyInit, bool aIsUnitTest )
457{
458#if defined( __WXMAC__ )
459 // Set the application locale to the system default
460 wxLogNull noLog;
461 wxLocale loc;
462 loc.Init();
463#endif
464
465 // Just make sure we init precreate any folders early for later code
466 // In particular, the user cache path is the most likely to be hit by startup code
468
470
471#ifdef KICAD_USE_SENTRY
472 sentryInit();
473#endif
474 wxString pgm_name;
475
477 if( App().argc == 0 )
478 pgm_name = wxT( "kicad" );
479 else
480 pgm_name = wxFileName( App().argv[0] ).GetName().Lower();
481
482#ifdef KICAD_USE_SENTRY
483 sentry_set_tag( "kicad.app", pgm_name.c_str() );
484#endif
485
486 wxInitAllImageHandlers();
487
488 // Without this the wxPropertyGridManager segfaults on Windows.
489 if( !wxPGGlobalVars )
490 wxPGInitResourceModule();
491
492#ifndef __WINDOWS__
493 if( wxString( wxGetenv( "HOME" ) ).IsEmpty() )
494 {
495 DisplayErrorMessage( nullptr, _( "Environment variable HOME is empty. "
496 "Unable to continue." ) );
497 return false;
498 }
499#endif
500
501 // Ensure the instance checker directory exists
502 // It should be globally writable because it is shared between all users on Linux, and so on a
503 // multi-user machine, other need to be able to access it to check for the lock files or make
504 // their own lock files.
505 wxString instanceCheckerDir = PATHS::GetInstanceCheckerPath();
506 PATHS::EnsurePathExists( instanceCheckerDir );
507 wxChmod( instanceCheckerDir, wxPOSIX_USER_READ | wxPOSIX_USER_WRITE | wxPOSIX_USER_EXECUTE |
508 wxPOSIX_GROUP_READ | wxPOSIX_GROUP_WRITE | wxPOSIX_GROUP_EXECUTE |
509 wxPOSIX_OTHERS_READ | wxPOSIX_OTHERS_WRITE | wxPOSIX_OTHERS_EXECUTE );
510
511 wxString instanceCheckerName = wxString::Format( wxS( "%s-%s" ), pgm_name,
513
514 m_pgm_checker = std::make_unique<wxSingleInstanceChecker>();
515 m_pgm_checker->Create( instanceCheckerName, instanceCheckerDir );
516
517 // Init KiCad environment
518 // the environment variable KICAD (if exists) gives the kicad path:
519 // something like set KICAD=d:\kicad
520 bool isDefined = wxGetEnv( wxT( "KICAD" ), &m_kicad_env );
521
522 if( isDefined ) // ensure m_kicad_env ends by "/"
523 {
525
526 if( !m_kicad_env.IsEmpty() && m_kicad_env.Last() != '/' )
528 }
529
530 // Init parameters for configuration
531 App().SetVendorName( wxT( "KiCad" ) );
532 App().SetAppName( pgm_name );
533
534 // Install some image handlers, mainly for help
535 if( wxImage::FindHandler( wxBITMAP_TYPE_PNG ) == nullptr )
536 wxImage::AddHandler( new wxPNGHandler );
537
538 if( wxImage::FindHandler( wxBITMAP_TYPE_GIF ) == nullptr )
539 wxImage::AddHandler( new wxGIFHandler );
540
541 if( wxImage::FindHandler( wxBITMAP_TYPE_JPEG ) == nullptr )
542 wxImage::AddHandler( new wxJPEGHandler );
543
544 wxFileSystem::AddHandler( new wxZipFSHandler );
545
546 // Analyze the command line & initialize the binary path
547 wxString tmp;
549 SetDefaultLanguage( tmp );
550
551#ifdef _MSC_VER
552 // We need to set this because the internal fontconfig logic
553 // seems to search relative to the dll rather the other logic it
554 // has to look for the /etc folder above the dll
555 wxSetEnv( "FONTCONFIG_PATH", PATHS::GetWindowsFontConfigDir() );
556#endif
557
558 m_settings_manager = std::make_unique<SETTINGS_MANAGER>( aHeadless );
559 m_background_jobs_monitor = std::make_unique<BACKGROUND_JOBS_MONITOR>();
560 m_notifications_manager = std::make_unique<NOTIFICATIONS_MANAGER>();
561
562#ifdef KICAD_IPC_API
563 m_plugin_manager = std::make_unique<API_PLUGIN_MANAGER>( &App() );
564#endif
565
566 // Our unit test mocks break if we continue
567 // A bug caused InitPgm to terminate early in unit tests and the mocks are...simplistic
568 // TODO fix the unit tests so this can be removed
569 if( aIsUnitTest )
570 return false;
571
572 // Something got in the way of settings load: can't continue
573 if( !m_settings_manager->IsOK() )
574 return false;
575
576 // Set up built-in environment variables (and override them from the system environment if set)
577 COMMON_SETTINGS* commonSettings = GetCommonSettings();
578 commonSettings->InitializeEnvironment();
579
580 // Load color settings after env is initialized
581 m_settings_manager->ReloadColorSettings();
582
583 // Load common settings from disk after setting up env vars
584 GetSettingsManager().Load( commonSettings );
585
586#ifdef KICAD_IPC_API
587 // If user doesn't have a saved Python interpreter, try (potentially again) to find one
588 if( commonSettings->m_Api.python_interpreter.IsEmpty() )
589 commonSettings->m_Api.python_interpreter = PYTHON_MANAGER::FindPythonInterpreter();
590#endif
591
592 // Init user language *before* calling loadSettings, because
593 // env vars could be incorrectly initialized on Linux
594 // (if the value contains some non ASCII7 chars, the env var is not initialized)
595 SetLanguage( tmp, true );
596
597 // Now that translations are available, inform the user if the OS is unsupported
599
601
602#ifdef KICAD_USE_SENTRY
603 sentryPrompt();
604#endif
605
606 ReadPdfBrowserInfos(); // needs GetCommonSettings()
607
609
610 // Create the python scripting stuff
611 // Skip it fot applications that do not use it
612 if( !aSkipPyInit )
613 m_python_scripting = std::make_unique<SCRIPTING>();
614
615 // TODO(JE): Remove this if apps are refactored to not assume Prj() always works
616 // Need to create a project early for now (it can have an empty path for the moment)
618
619#ifdef KICAD_IPC_API
620 m_plugin_manager->ReloadPlugins();
621#endif
622
623 // This sets the maximum tooltip display duration to 10s (up from 5) but only affects
624 // Windows as other platforms display tooltips while the mouse is not moving
625 if( !aHeadless )
626 {
627 wxToolTip::Enable( true );
628 wxToolTip::SetAutoPop( 10000 );
629 }
630
631 if( ADVANCED_CFG::GetCfg().m_UpdateUIEventInterval != 0 )
632 wxUpdateUIEvent::SetUpdateInterval( ADVANCED_CFG::GetCfg().m_UpdateUIEventInterval );
633
634 // Now the application can safely start, show the splash screen
635 if( !aHeadless )
636 ShowSplash();
637
638 return true;
639}
640
641
643{
645
646 for( const std::pair<wxString, ENV_VAR_ITEM> it : GetCommonSettings()->m_Env.vars )
647 {
648 wxLogTrace( traceEnvVars, wxT( "PGM_BASE::loadSettings: Found entry %s = %s" ),
649 it.first, it.second.GetValue() );
650
651 // Do not store the env var PROJECT_VAR_NAME ("KIPRJMOD") definition if for some reason
652 // it is found in config. (It is reserved and defined as project path)
653 if( it.first == PROJECT_VAR_NAME )
654 continue;
655
656 // Don't set bogus empty entries in the environment
657 if( it.first.IsEmpty() )
658 continue;
659
660 // Do not overwrite vars set by the system environment with values from the settings file
661 if( it.second.GetDefinedExternally() )
662 continue;
663
664 SetLocalEnvVariable( it.first, it.second.GetValue() );
665 }
666}
667
668
670{
671 // GetCommonSettings() is not initialized until fairly late in the
672 // process startup: InitPgm(), so test before using:
673 if( GetCommonSettings() )
674 GetCommonSettings()->m_System.working_dir = wxGetCwd();
675}
676
677
679{
680 return m_settings_manager ? m_settings_manager->GetCommonSettings() : nullptr;
681}
682
683
684bool PGM_BASE::SetLanguage( wxString& aErrMsg, bool first_time )
685{
686 // Suppress wxWidgets error popups if locale is not found
687 wxLogNull doNotLog;
688
689 if( first_time )
690 {
691 setLanguageId( wxLANGUAGE_DEFAULT );
692
693 // First time SetLanguage is called, the user selected language id is set
694 // from common user config settings
695 wxString languageSel = GetCommonSettings()->m_System.language;
696
697 // Search for the current selection
698 for( unsigned ii = 0; LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
699 {
700 if( LanguagesList[ii].m_Lang_Label == languageSel )
701 {
702 setLanguageId( LanguagesList[ii].m_WX_Lang_Identifier );
703 break;
704 }
705 }
706 }
707
708 // dictionary file name without extend (full name is kicad.mo)
709 wxString dictionaryName( wxT( "kicad" ) );
710
711 delete m_locale;
712 m_locale = new wxLocale;
713
714 // don't use wxLOCALE_LOAD_DEFAULT flag so that Init() doesn't return
715 // false just because it failed to load wxstd catalog
716 if( !m_locale->Init( m_language_id ) )
717 {
718 wxLogTrace( traceLocale, wxT( "This language is not supported by the system." ) );
719
720 setLanguageId( wxLANGUAGE_DEFAULT );
721 delete m_locale;
722
723 m_locale = new wxLocale;
724 m_locale->Init( wxLANGUAGE_DEFAULT );
725
726 aErrMsg = _( "This language is not supported by the operating system." );
727 return false;
728 }
729 else if( !first_time )
730 {
731 wxLogTrace( traceLocale, wxT( "Search for dictionary %s.mo in %s" ) ,
732 dictionaryName, m_locale->GetName() );
733 }
734
735 if( !first_time )
736 {
737 // If we are here, the user has selected another language.
738 // Therefore the new preferred language name is stored in common config.
739 // Do NOT store the wxWidgets language Id, it can change between wxWidgets
740 // versions, for a given language
741 wxString languageSel;
742
743 // Search for the current selection language name
744 for( unsigned ii = 0; LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
745 {
746 if( LanguagesList[ii].m_WX_Lang_Identifier == m_language_id )
747 {
748 languageSel = LanguagesList[ii].m_Lang_Label;
749 break;
750 }
751 }
752
754 cfg->m_System.language = languageSel;
755 cfg->SaveToFile( GetSettingsManager().GetPathForSettingsFile( cfg ) );
756 }
757
758 // Try adding the dictionary if it is not currently loaded
759 if( !m_locale->IsLoaded( dictionaryName ) )
760 m_locale->AddCatalog( dictionaryName );
761
762 // Verify the Kicad dictionary was loaded properly
763 // However, for the English language, the dictionary is not mandatory, as
764 // all messages are already in English, just restricted to ASCII7 chars,
765 // the verification is skipped.
766 if( !m_locale->IsLoaded( dictionaryName ) && m_language_id != wxLANGUAGE_ENGLISH )
767 {
768 wxLogTrace( traceLocale, wxT( "Unable to load dictionary %s.mo in %s" ),
769 dictionaryName, m_locale->GetName() );
770
771 setLanguageId( wxLANGUAGE_DEFAULT );
772 delete m_locale;
773
774 m_locale = new wxLocale;
775 m_locale->Init( wxLANGUAGE_DEFAULT );
776
777 aErrMsg = _( "The KiCad language file for this language is not installed." );
778 return false;
779 }
780
781 return true;
782}
783
784
785bool PGM_BASE::SetDefaultLanguage( wxString& aErrMsg )
786{
787 // Suppress error popups from wxLocale
788 wxLogNull doNotLog;
789
790 setLanguageId( wxLANGUAGE_DEFAULT );
791
792 // dictionary file name without extend (full name is kicad.mo)
793 wxString dictionaryName( wxT( "kicad" ) );
794
795 delete m_locale;
796 m_locale = new wxLocale;
797 m_locale->Init();
798
799 // Try adding the dictionary if it is not currently loaded
800 if( !m_locale->IsLoaded( dictionaryName ) )
801 m_locale->AddCatalog( dictionaryName );
802
803 // Verify the Kicad dictionary was loaded properly
804 // However, for the English language, the dictionary is not mandatory, as
805 // all messages are already in English, just restricted to ASCII7 chars,
806 // the verification is skipped.
807 if( !m_locale->IsLoaded( dictionaryName ) && m_language_id != wxLANGUAGE_ENGLISH )
808 {
809 wxLogTrace( traceLocale, wxT( "Unable to load dictionary %s.mo in %s" ),
810 dictionaryName, m_locale->GetName() );
811
812 setLanguageId( wxLANGUAGE_DEFAULT );
813 delete m_locale;
814
815 m_locale = new wxLocale;
816 m_locale->Init();
817
818 aErrMsg = _( "The KiCad language file for this language is not installed." );
819 return false;
820 }
821
822 return true;
823}
824
825
827{
828 wxLogTrace( traceLocale, wxT( "Select language ID %d from %d possible languages." ),
829 menu_id, (int)arrayDim( LanguagesList )-1 );
830
831 for( unsigned ii = 0; LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
832 {
833 if( menu_id == LanguagesList[ii].m_KI_Lang_Identifier )
834 {
835 setLanguageId( LanguagesList[ii].m_WX_Lang_Identifier );
836 break;
837 }
838 }
839}
840
841
843{
844 const wxLanguageInfo* langInfo = wxLocale::GetLanguageInfo( m_language_id );
845
846 if( !langInfo )
847 return "";
848 else
849 {
850 wxString str = langInfo->GetCanonicalWithRegion();
851 str.Replace( "_", "-" );
852
853 return str;
854 }
855}
856
857
859{
860#ifdef _MSC_VER
861 wxLocale::AddCatalogLookupPathPrefix( PATHS::GetWindowsBaseSharePath()
862 + wxT( "locale" ) );
863#endif
864 wxLocale::AddCatalogLookupPathPrefix( PATHS::GetLocaleDataPath() );
865
866 if( wxGetEnv( wxT( "KICAD_RUN_FROM_BUILD_DIR" ), nullptr ) )
867 {
868 wxFileName fn( Pgm().GetExecutablePath() );
869 fn.RemoveLastDir();
870 fn.AppendDir( wxT( "translation" ) );
871 wxLocale::AddCatalogLookupPathPrefix( fn.GetPath() );
872 }
873}
874
875
876bool PGM_BASE::SetLocalEnvVariable( const wxString& aName, const wxString& aValue )
877{
878 wxString env;
879
880 if( aName.IsEmpty() )
881 {
882 wxLogTrace( traceEnvVars,
883 wxT( "PGM_BASE::SetLocalEnvVariable: Attempt to set empty variable to "
884 "value %s" ),
885 aValue );
886 return false;
887 }
888
889 // Check to see if the environment variable is already set.
890 if( wxGetEnv( aName, &env ) )
891 {
892 wxLogTrace( traceEnvVars,
893 wxT( "PGM_BASE::SetLocalEnvVariable: Environment variable %s already set "
894 "to %s" ),
895 aName, env );
896 return env == aValue;
897 }
898
899 wxLogTrace( traceEnvVars,
900 wxT( "PGM_BASE::SetLocalEnvVariable: Setting local environment variable %s to %s" ),
901 aName, aValue );
902
903 return wxSetEnv( aName, aValue );
904}
905
906
908{
909 // Overwrites externally defined environment variable until the next time the application
910 // is run.
911 for( const std::pair<wxString, ENV_VAR_ITEM> m_local_env_var : GetCommonSettings()->m_Env.vars )
912 {
913 wxLogTrace( traceEnvVars,
914 wxT( "PGM_BASE::SetLocalEnvVariables: Setting local environment variable %s "
915 "to %s" ),
916 m_local_env_var.first,
917 m_local_env_var.second.GetValue() );
918 wxSetEnv( m_local_env_var.first, m_local_env_var.second.GetValue() );
919 }
920}
921
922
924{
925 return GetCommonSettings()->m_Env.vars;
926}
927
928
930{
931 if( !wxTheApp )
932 return false;
933
934 return wxTheApp->IsGUI();
935}
936
937
938void PGM_BASE::HandleException( std::exception_ptr aPtr )
939{
940 try
941 {
942 if( aPtr )
943 std::rethrow_exception( aPtr );
944 }
945 catch( const IO_ERROR& ioe )
946 {
947 wxLogError( ioe.What() );
948 }
949 catch( const std::exception& e )
950 {
951#ifdef KICAD_USE_SENTRY
952 if( IsSentryOptedIn() )
953 {
954 sentry_value_t exc = sentry_value_new_exception( "exception", e.what() );
955 sentry_value_set_stacktrace( exc, NULL, 0 );
956
957 sentry_value_t sentryEvent = sentry_value_new_event();
958 sentry_event_add_exception( sentryEvent, exc );
959 sentry_capture_event( sentryEvent );
960 }
961#endif
962
963 wxLogError( wxT( "Unhandled exception class: %s what: %s" ),
964 From_UTF8( typeid( e ).name() ), From_UTF8( e.what() ) );
965 }
966 catch( ... )
967 {
968 wxLogError( wxT( "Unhandled exception of unknown type" ) );
969 }
970}
971
972
973#ifdef KICAD_USE_SENTRY
974struct SENTRY_ASSERT_CACHE_KEY
975{
976 wxString file;
977 int line;
978 wxString func;
979 wxString cond;
980 wxString msg;
981};
982
983
984bool operator<( const SENTRY_ASSERT_CACHE_KEY& aKey1, const SENTRY_ASSERT_CACHE_KEY& aKey2 )
985{
986 return aKey1.file < aKey2.file ||
987 aKey1.line < aKey2.line ||
988 aKey1.func < aKey2.func ||
989 aKey1.cond < aKey2.cond ||
990 aKey1.msg < aKey2.msg;
991}
992#endif
993
994
995void PGM_BASE::HandleAssert( const wxString& aFile, int aLine, const wxString& aFunc,
996 const wxString& aCond, const wxString& aMsg )
997{
998 wxString assertStr;
999
1000 // Log the assertion details to standard log
1001 if( !aMsg.empty() )
1002 {
1003 assertStr = wxString::Format( "Assertion failed at %s:%d in %s: %s - %s", aFile, aLine,
1004 aFunc, aCond, aMsg );
1005 }
1006 else
1007 {
1008 assertStr = wxString::Format( "Assertion failed at %s:%d in %s: %s", aFile, aLine, aFunc,
1009 aCond );
1010 }
1011
1012#ifndef NDEBUG
1013 wxLogError( assertStr );
1014#endif
1015
1016#ifdef KICAD_USE_SENTRY
1017 if( IsSentryOptedIn() )
1018 {
1019 static std::set<SENTRY_ASSERT_CACHE_KEY> assertCache;
1020
1021 SENTRY_ASSERT_CACHE_KEY key = { aFile, aLine, aFunc, aCond, aMsg };
1022
1023 if( assertCache.find( key ) == assertCache.end() )
1024 {
1025 sentry_value_t exc = sentry_value_new_exception( "assert", assertStr );
1026 sentry_value_set_stacktrace( exc, NULL, 0 );
1027
1028 sentry_value_t sentryEvent = sentry_value_new_event();
1029 sentry_event_add_exception( sentryEvent, exc );
1030 sentry_capture_event( sentryEvent );
1031 assertCache.insert( key );
1032 }
1033 }
1034#endif
1035}
1036
1037
1038const wxString& PGM_BASE::GetExecutablePath() const
1039{
1040 return PATHS::GetExecutablePath();
1041}
1042
1043
1045{
1046 SetPdfBrowserName( GetCommonSettings()->m_System.pdf_viewer_name );
1048}
1049
1050
1052{
1055}
1056
1058
1060{
1061 wxASSERT( process ); // KIFACE_GETTER has already been called.
1062 return *process;
1063}
1064
1065// Similar to PGM_BASE& Pgm(), but return nullptr when a *.ki_face is run from a python script.
1067{
1068 return process;
1069}
1070
1072{
1073 process = pgm;
1074}
const char * name
Definition: DXF_plotter.cpp:57
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
Definition: arraydim.h:31
wxBitmap KiBitmap(BITMAPS aBitmap, int aHeightTag)
Construct a wxBitmap from an image identifier Returns the image from the active theme if the image ha...
Definition: bitmap.cpp:104
wxString GetMajorMinorVersion()
Get only the major and minor version in a string major.minor.
wxString GetCommitHash()
Get the commit hash as a string.
wxString GetBuildVersion()
Get the full KiCad version string.
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void InitializeEnvironment()
Creates the built-in environment variables and sets their default values.
ENVIRONMENT m_Env
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
Definition: ki_exception.h:77
virtual const wxString What() const
A composite of Problem() and Where()
Definition: exceptions.cpp:30
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
Calls Store() and then writes the contents of the JSON document to a file.
static void Cleanup()
Call curl_global_cleanup for the application.
Definition: kicad_curl.cpp:42
static void Init()
Call curl_global_init for the application.
Definition: kicad_curl.cpp:33
void Load()
Loads notifications stored from disk.
static wxString GetInstanceCheckerPath()
Gets the path used for wxSingleInstanceChecker lock files.
Definition: paths.cpp:381
static void EnsureUserPathsExist()
Ensures/creates user default paths.
Definition: paths.cpp:422
static bool EnsurePathExists(const wxString &aPath)
Attempts to create a given path if it does not exist.
Definition: paths.cpp:402
static wxString GetUserCachePath()
Gets the stock (install) 3d viewer plugins path.
Definition: paths.cpp:344
static wxString GetLocaleDataPath()
Gets the locales translation data path.
Definition: paths.cpp:257
static const wxString & GetExecutablePath()
Definition: paths.cpp:547
Container for data for KiCad programs.
Definition: pgm_base.h:102
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition: pgm_base.cpp:678
virtual wxApp & App()
Returns a bare naked wxApp which may come from wxPython, SINGLE_TOP, or kicad.exe.
Definition: pgm_base.cpp:181
std::unique_ptr< NOTIFICATIONS_MANAGER > m_notifications_manager
Definition: pgm_base.h:410
int m_argcUtf8
argv parameters converted to utf8 form, because wxwidgets has opinions and will return argv as either...
Definition: pgm_base.h:441
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
Definition: pgm_base.cpp:923
bool m_Printing
wxWidgets on MSW tends to crash if you spool up more than one print job at a time.
Definition: pgm_base.h:386
void setLanguageId(int aId)
Trap all changes in here, simplifies debugging.
Definition: pgm_base.h:399
std::unique_ptr< SETTINGS_MANAGER > m_settings_manager
Definition: pgm_base.h:408
void loadCommonSettings()
Loads internal settings from COMMON_SETTINGS.
Definition: pgm_base.cpp:642
virtual void SetPdfBrowserName(const wxString &aFileName)
Definition: pgm_base.h:189
wxLocale * m_locale
The KICAD system environment variable.
Definition: pgm_base.h:424
void Destroy()
Definition: pgm_base.cpp:165
wxSplashScreen * m_splash
Definition: pgm_base.h:443
bool InitPgm(bool aHeadless=false, bool aSkipPyInit=false, bool aIsUnitTest=false)
Initialize this program.
Definition: pgm_base.cpp:456
char ** m_argvUtf8
Definition: pgm_base.h:438
virtual void ReadPdfBrowserInfos()
Read the PDF browser choice from the common configuration.
Definition: pgm_base.cpp:1044
bool IsGUI()
Determine if the application is running with a GUI.
Definition: pgm_base.cpp:929
bool m_use_system_pdf_browser
Definition: pgm_base.h:427
bool m_Quitting
Definition: pgm_base.h:390
virtual NOTIFICATIONS_MANAGER & GetNotificationsManager() const
Definition: pgm_base.h:148
void BuildArgvUtf8()
Builds the UTF8 based argv variable.
Definition: pgm_base.cpp:411
virtual const wxString & GetPdfBrowserName() const
Definition: pgm_base.h:187
virtual void SetTextEditor(const wxString &aFileName)
Definition: pgm_base.cpp:188
std::unique_ptr< wxSingleInstanceChecker > m_pgm_checker
Checks if there is another copy of Kicad running at the same time.
Definition: pgm_base.h:415
virtual bool SetLocalEnvVariable(const wxString &aName, const wxString &aValue)
Sets the environment variable aName to aValue.
Definition: pgm_base.cpp:876
wxString m_kicad_env
Definition: pgm_base.h:422
virtual void ForceSystemPdfBrowser(bool aFlg)
Force the use of system PDF browser, even if a preferred PDF browser is set.
Definition: pgm_base.h:204
virtual void SetLocalEnvVariables()
Updates the local environment with the contents of the current ENV_VAR_MAP stored in the COMMON_SETTI...
Definition: pgm_base.cpp:907
virtual void SetLanguagePath()
Definition: pgm_base.cpp:858
bool SetDefaultLanguage(wxString &aErrMsg)
Set the default language without reference to any preferences.
Definition: pgm_base.cpp:785
void ShowSplash()
Definition: pgm_base.cpp:426
wxString m_text_editor
Filename of the app selected for browsing PDFs.
Definition: pgm_base.h:430
virtual ~PGM_BASE()
Definition: pgm_base.cpp:151
std::unique_ptr< SCRIPTING > m_python_scripting
Definition: pgm_base.h:412
virtual void SetLanguageIdentifier(int menu_id)
Set in .m_language_id member the wxWidgets language identifier ID from the KiCad menu id (internal me...
Definition: pgm_base.cpp:826
int m_language_id
Definition: pgm_base.h:425
std::unique_ptr< BACKGROUND_JOBS_MONITOR > m_background_jobs_monitor
Definition: pgm_base.h:409
void HandleException(std::exception_ptr aPtr)
A exception handler to be used at the top level if exceptions bubble up that for.
Definition: pgm_base.cpp:938
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:995
virtual wxString GetLanguageTag()
Definition: pgm_base.cpp:842
virtual const wxString & GetTextEditor(bool aCanShowFileChooser=true)
Return the path to the preferred text editor application.
Definition: pgm_base.cpp:195
virtual const wxString & GetExecutablePath() const
Definition: pgm_base.cpp:1038
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition: pgm_base.h:142
void HideSplash()
Definition: pgm_base.cpp:445
virtual void WritePdfBrowserInfos()
Save the PDF browser choice to the common configuration.
Definition: pgm_base.cpp:1051
void SaveCommonSettings()
Save the program (process) settings subset which are stored .kicad_common.
Definition: pgm_base.cpp:669
bool m_PropertyGridInitialized
Definition: pgm_base.h:392
virtual const wxString AskUserForPreferredEditor(const wxString &aDefaultEditor=wxEmptyString)
Shows a dialog that instructs the user to select a new preferred editor.
Definition: pgm_base.cpp:231
virtual bool SetLanguage(wxString &aErrMsg, bool first_time=false)
Set the dictionary file name for internationalization.
Definition: pgm_base.cpp:684
bool LoadProject(const wxString &aFullPath, bool aSetActive=true)
Loads a project or sets up a new project with a specified path.
bool WarnUserIfOperatingSystemUnsupported()
Checks if the operating system is explicitly unsupported and displays a disclaimer message box.
Definition: common.cpp:689
The common library.
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition: confirm.cpp:332
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition: confirm.cpp:305
This file is part of the common library.
#define _(s)
bool operator<(const FOOTPRINT_INFO &lhs, const FOOTPRINT_INFO &rhs)
#define WIN_STRING_DIR_SEP
Definition: gestfich.h:37
#define UNIX_STRING_DIR_SEP
Definition: gestfich.h:36
const wxChar *const traceLocale
Flag to enable locale debug output.
const wxChar *const traceEnvVars
Flag to enable debug output of environment variable operations.
@ ID_LANGUAGE_SWEDISH
Definition: id.h:139
@ ID_LANGUAGE_CHINESE_SIMPLIFIED
Definition: id.h:129
@ ID_LANGUAGE_GERMAN
Definition: id.h:113
@ ID_LANGUAGE_DUTCH
Definition: id.h:131
@ ID_LANGUAGE_GREEK
Definition: id.h:114
@ ID_LANGUAGE_LITHUANIAN
Definition: id.h:135
@ ID_LANGUAGE_PORTUGUESE_BRAZILIAN
Definition: id.h:118
@ ID_LANGUAGE_DEFAULT
Definition: id.h:107
@ ID_LANGUAGE_POLISH
Definition: id.h:125
@ ID_LANGUAGE_THAI
Definition: id.h:138
@ ID_LANGUAGE_JAPANESE
Definition: id.h:132
@ ID_LANGUAGE_ITALIAN
Definition: id.h:121
@ ID_LANGUAGE_KOREAN
Definition: id.h:127
@ ID_LANGUAGE_RUSSIAN
Definition: id.h:116
@ ID_LANGUAGE_CZECH
Definition: id.h:126
@ ID_LANGUAGE_UKRANIAN
Definition: id.h:140
@ ID_LANGUAGE_SPANISH
Definition: id.h:111
@ ID_LANGUAGE_PORTUGUESE
Definition: id.h:117
@ ID_LANGUAGE_ENGLISH
Definition: id.h:108
@ ID_LANGUAGE_SPANISH_MEXICAN
Definition: id.h:112
@ ID_LANGUAGE_CHINESE_TRADITIONAL
Definition: id.h:130
@ ID_LANGUAGE_FINNISH
Definition: id.h:110
@ ID_LANGUAGE_DANISH
Definition: id.h:106
@ ID_LANGUAGE_FRENCH
Definition: id.h:109
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
This file contains miscellaneous commonly used macros and functions.
PBOOL GetPolicyBool(const wxString &aKey)
Definition: gtk/policy.cpp:26
void SetPgm(PGM_BASE *pgm)
Definition: pgm_base.cpp:1071
static PGM_BASE * process
Definition: pgm_base.cpp:1057
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: pgm_base.cpp:1059
PGM_BASE * PgmOrNull()
similar to PGM_BASE& Pgm(), but return a reference that can be nullptr when running a shared lib from...
Definition: pgm_base.cpp:1066
LANGUAGE_DESCR LanguagesList[]
An array containing all the languages that KiCad supports.
Definition: pgm_base.cpp:94
#define _(s)
Current list of languages supported by KiCad.
Definition: pgm_base.cpp:132
see class PGM_BASE
KICOMMON_API LANGUAGE_DESCR LanguagesList[]
An array containing all the languages that KiCad supports.
Definition: pgm_base.cpp:94
KICOMMON_API PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: pgm_base.cpp:1059
#define POLICY_KEY_DATACOLLECTION
Definition: policy_keys.h:30
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
Definition: project.h:39
APIIMPORT wxPGGlobalVarsClass * wxPGGlobalVars
wxString From_UTF8(const char *cstring)
A small class to handle the list of existing translations.
Definition: pgm_base.h:68
int m_KI_Lang_Identifier
KiCad identifier used in menu selection (See id.h)
Definition: pgm_base.h:73
wxString m_Lang_Label
Labels used in menus.
Definition: pgm_base.h:76
System directories search utilities.
wxLogTrace helper definitions.