31#include <wx/eventfilter.h>
32#include <wx/html/htmlwin.h>
35#include <wx/filename.h>
37#include <wx/propgrid/propgrid.h>
38#include <wx/stdpaths.h>
40#include <wx/filedlg.h>
42#include <wx/tooltip.h>
79#include <winrt/base.h>
108 wxT(
"Español (Latinoamericano)" ),
true },
127 wxT(
"Português (Brasil)" ),
true },
141 wxT(
"简体中文" ),
true },
143 wxT(
"繁體中文" ),
true },
147#define _(s) wxGetTranslation((s))
213 winrt::uninit_apartment();
238 wxASSERT( wxTheApp );
256 if( !wxGetEnv( wxT(
"EDITOR" ), &editorname ) )
260 editorname = wxT(
"/usr/bin/open -e" );
262 editorname = wxT(
"/usr/bin/xdg-open" );
268 if( !editorname && aCanShowFileChooser )
277 if( !editorname.IsEmpty() )
290 wxString mask(
_(
"Executable file" ) + wxT(
" (*.exe)|*.exe" ) );
292 wxString mask(
_(
"Executable file" ) + wxT(
" (*)|*" ) );
298 wxFileName::SplitPath( aDefaultEditor, &
path, &
name, &ext );
302 return wxFileSelector(
_(
"Select Preferred Editor" ),
path,
name, wxT(
"." ) + ext,
303 mask, wxFD_OPEN | wxFD_FILE_MUST_EXIST,
nullptr );
309 const wxArrayString& argArray =
App().argv.GetArguments();
315 m_argvUtf8[n] = wxStrdup( argArray[n].ToUTF8() );
334 NULL, -1, wxDefaultPosition, wxDefaultSize,
335 wxBORDER_NONE | wxSTAY_ON_TOP );
354#if defined( __WXGTK__ ) && defined( KICAD_DESKTOP_APP_NAME )
357 if( aPgmName == wxT(
"kicad" ) )
358 return wxT( KICAD_DESKTOP_APP_NAME );
360 if( aPgmName == wxT(
"eeschema" ) || aPgmName == wxT(
"pcbnew" ) || aPgmName == wxT(
"gerbview" )
361 || aPgmName == wxT(
"pcb_calculator" ) )
364 wxString appName = aPgmName == wxT(
"pcb_calculator" ) ? wxT(
"pcbcalculator" ) : aPgmName;
365 return wxString( wxT( KICAD_DESKTOP_APP_PREFIX ) ) + wxT(
"." ) + appName;
369 return wxEmptyString;
375#if defined( __WXMAC__ )
396 if(
App().argc == 0 )
397 pgm_name = wxT(
"kicad" );
399 pgm_name = wxFileName(
App().argv[0] ).GetName().Lower();
403 wxInitAllImageHandlers();
407 wxImage::SetDefaultLoadFlags( wxImage::GetDefaultLoadFlags() & ~wxImage::Load_Verbose );
409#if !wxCHECK_VERSION( 3, 3, 0 )
412 wxPGInitResourceModule();
416 if( wxString( wxGetenv(
"HOME" ) ).IsEmpty() )
419 "Unable to continue." ) );
427 bool isDefined = wxGetEnv( wxT(
"KICAD" ), &
m_kicad_env );
438 App().SetVendorName( wxT(
"KiCad" ) );
439 App().SetAppName( pgm_name );
443#if defined( __WXGTK__ ) && defined( KICAD_DESKTOP_APP_NAME )
458 if( !wxGetEnv(
"FONTCONFIG_PATH", NULL ) )
464 wxSetEnv(
"FONTCONFIG_PATH", PATHS::GetWindowsFontConfigDir() );
469 winrt::init_apartment(winrt::apartment_type::single_threaded);
528 wxToolTip::Enable(
true );
529 wxToolTip::SetAutoPop( 10000 );
535#if defined( __WXMSW__ ) || defined( __WXOSX__ )
540 App().Bind( wxEVT_QUERY_END_SESSION,
541 [
this]( wxCloseEvent& aEvent )
544 App().OnQueryEndSession( aEvent );
547 App().Bind( wxEVT_END_SESSION,
548 [
this]( wxCloseEvent& aEvent )
551 App().OnEndSession( aEvent );
568 for(
const std::pair<wxString, ENV_VAR_ITEM> it :
GetCommonSettings()->m_Env.vars )
570 wxLogTrace(
traceEnvVars, wxT(
"PGM_BASE::loadSettings: Found entry %s = %s" ),
571 it.first, it.second.GetValue() );
579 if( it.first.IsEmpty() )
583 if( it.second.GetDefinedExternally() )
620 for(
unsigned ii = 0;
LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
631 wxString dictionaryName( wxT(
"kicad" ) );
640 wxLogTrace(
traceLocale, wxT(
"This language is not supported by the system." ) );
646 m_locale->Init( wxLANGUAGE_DEFAULT );
648 aErrMsg =
_(
"This language is not supported by the operating system." );
651 else if( !first_time )
653 wxLogTrace(
traceLocale, wxT(
"Search for dictionary %s.mo in %s" ) ,
654 dictionaryName,
m_locale->GetName() );
663 wxString languageSel;
666 for(
unsigned ii = 0;
LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
681 if( !
m_locale->IsLoaded( dictionaryName ) )
682 m_locale->AddCatalog( dictionaryName );
690 wxLogTrace(
traceLocale, wxT(
"Unable to load dictionary %s.mo in %s" ),
691 dictionaryName,
m_locale->GetName() );
697 m_locale->Init( wxLANGUAGE_DEFAULT );
699 aErrMsg =
_(
"The KiCad language file for this language is not installed." );
715 wxString dictionaryName( wxT(
"kicad" ) );
722 if( !
m_locale->IsLoaded( dictionaryName ) )
723 m_locale->AddCatalog( dictionaryName );
731 wxLogTrace(
traceLocale, wxT(
"Unable to load dictionary %s.mo in %s" ),
732 dictionaryName,
m_locale->GetName() );
740 aErrMsg =
_(
"The KiCad language file for this language is not installed." );
750 wxLogTrace(
traceLocale, wxT(
"Select language ID %d from %d possible languages." ),
753 for(
unsigned ii = 0;
LanguagesList[ii].m_KI_Lang_Identifier != 0; ii++ )
766 const wxLanguageInfo* langInfo = wxLocale::GetLanguageInfo(
m_language_id );
774 wxString str = langInfo->GetCanonicalWithRegion();
775 str.Replace(
"_",
"-" );
785 wxLocale::AddCatalogLookupPathPrefix( PATHS::GetWindowsBaseSharePath() + wxT(
"locale" ) );
793 fn.AppendDir( wxT(
"translation" ) );
794 wxLocale::AddCatalogLookupPathPrefix( fn.GetPath() );
803 if( aName.IsEmpty() )
806 wxT(
"PGM_BASE::SetLocalEnvVariable: Attempt to set empty variable to "
813 if( wxGetEnv( aName, &env ) )
816 wxT(
"PGM_BASE::SetLocalEnvVariable: Environment variable %s already set "
819 return env == aValue;
823 wxT(
"PGM_BASE::SetLocalEnvVariable: Setting local environment variable %s to %s" ),
826 return wxSetEnv( aName, aValue );
834 for(
const std::pair<wxString, ENV_VAR_ITEM> m_local_env_var :
GetCommonSettings()->m_Env.vars )
837 wxT(
"PGM_BASE::SetLocalEnvVariables: Setting local environment variable %s "
839 m_local_env_var.first,
840 m_local_env_var.second.GetValue() );
841 wxSetEnv( m_local_env_var.first, m_local_env_var.second.GetValue() );
857 return wxTheApp->IsGUI();
866 std::rethrow_exception( aPtr );
870 wxLogError( ioe.
What() );
878 catch(
const std::exception& e )
882 wxLogError( wxT(
"Unhandled exception class: %s what: %s" ),
888 wxLogError( wxT(
"Unhandled exception of unknown type" ) );
899 const wxString& aCond,
const wxString& aMsg )
906 assertStr = wxString::Format(
"Assertion failed at %s:%d in %s: %s - %s", aFile, aLine,
907 aFunc, aCond, aMsg );
911 assertStr = wxString::Format(
"Assertion failed at %s:%d in %s: %s", aFile, aLine, aFunc,
916 wxLogError( assertStr );
919#ifdef KICAD_USE_SENTRY
955 [
this, aKiway]() ->
void
967 std::shared_ptr<BACKGROUND_JOB_REPORTER>
reporter =
972 reporter->Report(
_(
"Loading Design Block Libraries" ) );
979 std::string payload =
"";
1011 wxLogTrace(
traceLibraries,
"RegisterLibraryLoadStatusBar: statusBar=%p", aStatusBar );
1031 wxLogTrace(
traceLibraries,
"UnregisterLibraryLoadStatusBar: statusBar=%p", aStatusBar );
1044 wxLogTrace(
traceLibraries,
"AddLibraryLoadMessages: message_count=%zu", aMessages.size() );
1046 if( aMessages.empty() )
1058 wxLogTrace(
traceLibraries,
" -> forwarding to statusBar=%p", statusBar );
1059 statusBar->AddWarningMessages(
"load", aMessages );
1069 wxLogTrace(
traceLibraries,
"ClearLibraryLoadMessages: status bars=%zu",
1075 statusBar->ClearWarningMessages(
"load" );
1083 if( aEvent.GetEventType() == wxEVT_SYS_COLOUR_CHANGED )
1086 if( aEvent.GetEventType() == wxEVT_SHOW )
1088 wxShowEvent&
event =
static_cast<wxShowEvent&
>( aEvent );
1089 wxDialog* dialog =
dynamic_cast<wxDialog*
>(
event.GetEventObject() );
1093 if( event.IsShown() && dialog->IsModal() )
1110 return wxEventFilter::Event_Skip;
void ExitFastIfAccessWorkerAbandoned(int aExitCode)
Ends the process without the normal teardown when an Access engine worker was abandoned,...
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
wxBitmap KiBitmap(BITMAPS aBitmap, int aHeightTag)
Construct a wxBitmap from an image identifier Returns the image from the active theme if the image ha...
BITMAP_STORE * GetBitmapStore()
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void LogAssert(const ASSERT_CACHE_KEY &aKey, const wxString &aMsg)
void LogException(const wxString &aMsg, bool aUnhandled)
void AddTag(const wxString &aKey, const wxString &aValue)
static SENTRY * Instance()
std::shared_ptr< BACKGROUND_JOB > Create(const wxString &aName)
Creates a background job with the given name.
void Remove(std::shared_ptr< BACKGROUND_JOB > job)
Removes the given background job from any lists and frees it.
void ThemeChanged()
Notifies the store that the icon theme has been changed by the user, so caches must be invalidated.
void InitializeEnvironment()
Creates the built-in environment variables and sets their default values.
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
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.
static void Init()
Call curl_global_init for the application.
KISTATUSBAR is a wxStatusBar suitable for Kicad manager.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
virtual void ExpressMail(FRAME_T aDestination, MAIL_T aCommand, std::string &aPayload, wxWindow *aSource=nullptr, bool aFromOtherThread=false)
Send aPayload to aDestination from aSource.
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
bool RunPreload(PROGRESS_REPORTER &aReporter, std::atomic_bool &aAbort)
Starts AsyncLoad() and waits for it on the calling thread, reporting progress to aReporter.
void Load()
Load notifications stored from disk.
static bool RunningFromBuildDir()
True when KiCad runs from its build tree or KICAD_RUN_FROM_BUILD_DIR is set.
static void EnsureUserPathsExist()
Ensures/creates user default paths.
static wxString GetLocaleDataPath()
Gets the locales translation data path.
static const wxString & GetExecutablePath()
Container for data for KiCad programs.
virtual COMMON_SETTINGS * GetCommonSettings() const
virtual wxApp & App()
Return a bare naked wxApp which may come from wxPython, SINGLE_TOP, or kicad.exe.
std::unique_ptr< NOTIFICATIONS_MANAGER > m_notifications_manager
void ExitIfTeardownUnsafe()
Ends the process at once when a worker abandoned inside a native driver makes the rest of the teardow...
void PreloadDesignBlockLibraries(KIWAY *aKiway)
Starts a background job to preload the global and project design block libraries.
virtual ENV_VAR_MAP & GetLocalEnvVariables() const
void WaitForDesignBlockPreload()
Waits for the design block preload to end, so it no longer reaches the project, and clears the cancel...
std::unique_ptr< LIBRARY_MANAGER > m_library_manager
bool m_Printing
wxWidgets on MSW tends to crash if you spool up more than one print job at a time.
void setLanguageId(int aId)
Trap all changes in here, simplifies debugging.
std::unique_ptr< API_PLUGIN_MANAGER > m_plugin_manager
std::unique_ptr< SETTINGS_MANAGER > m_settings_manager
void loadCommonSettings()
Load internal settings from COMMON_SETTINGS.
virtual void SetPdfBrowserName(const wxString &aFileName)
std::vector< KISTATUSBAR * > m_libraryLoadStatusBars
int FilterAppEvent(wxEvent &aEvent)
Handle events that must be seen once per application, before any window processes them.
wxSplashScreen * m_splash
virtual BACKGROUND_JOBS_MONITOR & GetBackgroundJobMonitor() const
char ** m_argvUtf8
argv parameters converted to utf8 form because wxWidgets has opinions.
BS::priority_thread_pool & GetThreadPool()
void UnregisterLibraryLoadStatusBar(KISTATUSBAR *aStatusBar)
Unregister a status bar from receiving library load warning messages.
void AddLibraryLoadMessages(const std::vector< KI_ERROR > &aMessages)
Add library load messages to all registered status bars.
virtual void ReadPdfBrowserInfos()
Read the PDF browser choice from the common configuration.
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.
bool IsGUI()
Determine if the application is running with a GUI.
bool m_use_system_pdf_browser
void CancelDesignBlockPreload()
Asks the design block preload to stop, without waiting for it.
void RegisterLibraryLoadStatusBar(KISTATUSBAR *aStatusBar)
Register a status bar to receive library load warning messages.
std::future< void > m_libraryPreloadReturn
virtual NOTIFICATIONS_MANAGER & GetNotificationsManager() const
std::shared_ptr< BACKGROUND_JOB > m_libraryPreloadBackgroundJob
void BuildArgvUtf8()
Builds the UTF8 based argv variable.
virtual const wxString & GetPdfBrowserName() const
std::atomic_bool m_libraryPreloadAbort
void ClearLibraryLoadMessages()
Clear library load messages from all registered status bars.
virtual void SetTextEditor(const wxString &aFileName)
std::vector< void * > m_ModalDialogs
virtual bool SetLocalEnvVariable(const wxString &aName, const wxString &aValue)
Set the environment variable aName to aValue.
bool InitPgm(bool aHeadless=false, bool aIsUnitTest=false)
Initialize this program.
wxString m_kicad_env
The KICAD system environment variable.
virtual void ForceSystemPdfBrowser(bool aFlg)
Force the use of system PDF browser, even if a preferred PDF browser is set.
virtual void SetLocalEnvVariables()
Update the local environment with the contents of the current ENV_VAR_MAP stored in the COMMON_SETTIN...
virtual void SetLanguagePath()
bool SetDefaultLanguage(wxString &aErrMsg)
Set the default language without reference to any preferences.
std::atomic_bool m_libraryPreloadInProgress
bool m_sessionEnding
Set while wx handles a session-end event.
wxString m_desktopAppId
freedesktop app id of this process, or empty.
virtual void SetLanguageIdentifier(int menu_id)
Set in .m_language_id member the wxWidgets language identifier ID from the KiCad menu id (internal me...
std::unique_ptr< BACKGROUND_JOBS_MONITOR > m_background_jobs_monitor
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.
virtual wxString GetLanguageTag()
virtual const wxString & GetTextEditor(bool aCanShowFileChooser=true)
Return the path to the preferred text editor application.
virtual const wxString & GetExecutablePath() const
virtual SETTINGS_MANAGER & GetSettingsManager() const
virtual void WritePdfBrowserInfos()
Save the PDF browser choice to the common configuration.
static wxString DesktopAppIdForProgram(const wxString &aPgmName)
Map a program name (argv[0] basename, lowercased) to the freedesktop application id of its installed ...
void SaveCommonSettings()
Save the program (process) settings subset which are stored .kicad_common.
bool m_PropertyGridInitialized
KICAD_SINGLETON m_singleton
std::mutex m_libraryLoadStatusBarsMutex
virtual const wxString AskUserForPreferredEditor(const wxString &aDefaultEditor=wxEmptyString)
Show a dialog that instructs the user to select a new preferred editor.
virtual bool SetLanguage(wxString &aErrMsg, bool first_time=false)
Set the dictionary file name for internationalization.
virtual DESIGN_BLOCK_LIBRARY_ADAPTER * DesignBlockLibs()
Return the table of design block libraries.
static wxString FindPythonInterpreter()
Searches for a Python intepreter on the user's system.
RAII class that sets an value at construction and resets it to the original value at destruction.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load 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.
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
This file is part of the common library.
#define WIN_STRING_DIR_SEP
#define UNIX_STRING_DIR_SEP
const wxChar *const traceLibraries
Flag to enable library table and library manager tracing.
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_NORWEGIAN_BOKMAL
@ ID_LANGUAGE_CHINESE_SIMPLIFIED
@ ID_LANGUAGE_PORTUGUESE_BRAZILIAN
@ ID_LANGUAGE_SPANISH_MEXICAN
@ ID_LANGUAGE_CHINESE_TRADITIONAL
std::map< wxString, ENV_VAR_ITEM > ENV_VAR_MAP
This file contains miscellaneous commonly used macros and functions.
thread_pool< 1 > priority_thread_pool
void SetPgm(PGM_BASE *pgm)
static PGM_BASE * process
PGM_BASE & Pgm()
The global program "get" accessor.
PGM_BASE * PgmOrNull()
Return a reference that can be nullptr when running a shared lib from a script, not from a kicad app.
LANGUAGE_DESCR LanguagesList[]
An array containing all the languages that KiCad supports.
#define _(s)
Current list of languages supported by KiCad.
KICOMMON_API LANGUAGE_DESCR LanguagesList[]
An array containing all the languages that KiCad supports.
KICOMMON_API PGM_BASE & Pgm()
The global program "get" accessor.
#define PROJECT_VAR_NAME
A variable name whose value holds the current project directory.
APIIMPORT wxPGGlobalVarsClass * wxPGGlobalVars
wxString From_UTF8(const char *cstring)
This struct represents a key being used for the std::set that deduplicates asserts during this runnin...
wxString python_interpreter
bool use_system_pdf_viewer
A small class to handle the list of existing translations.
System directories search utilities.
IbisParser parser & reporter
wxLogTrace helper definitions.