Exemple #1
0
mmGUIApp::mmGUIApp(): m_frame(0), m_setting_db(0), m_optParam("")
{
#if wxUSE_ON_FATAL_EXCEPTION
    // catch fatal exceptions
    wxHandleFatalExceptions(true);
#endif
}
bool CaMuleExternalConnector::OnInit()
{
#ifndef __WINDOWS__ 
	#if wxUSE_ON_FATAL_EXCEPTION
		// catch fatal exceptions
		wxHandleFatalExceptions(true);
	#endif
#endif

	// If we didn't know that OnInit is called only once when creating the
	// object, it could cause a memory leak. The two pointers below should
	// be free()'d before assigning the new value.
	// cppcheck-suppress publicAllocationError
	m_strFullVersion = strdup((const char *)unicode2char(GetMuleVersion()));
	m_strOSDescription = strdup((const char *)unicode2char(wxGetOsDescription()));

	// Handle uncaught exceptions
	InstallMuleExceptionHandler();

	bool retval = wxApp::OnInit();
	OnInitCommandSet();
	InitCustomLanguages();
	SetLocale(m_language);
	return retval;
}
//! @brief Initializes the application.
//!
//! It will open the main window and connect default to server or open the connect window.
bool UpdaterApp::OnInit()
{
    //this triggers the Cli Parser amongst other stuff
    if (!wxApp::OnInit())
        return false;

    assert( m_logstream_target );
    wxLogStream* m_log_stream = new wxLogStream( m_logstream_target );
    m_log_stream->SetLogLevel( wxLOG_Trace );
    wxLog::SetActiveTarget( m_log_stream );
    wxLogMessage( _T("m_exe_to_update ") + m_exe_to_update);
    wxLogMessage( _T("m_version ") + m_version);

#if wxUSE_ON_FATAL_EXCEPTION
    wxHandleFatalExceptions( true );
#endif

    //this needs to called _before_ mainwindow instance is created
    wxInitAllImageHandlers();
     //TODO needed?
    wxImage::AddHandler(new wxPNGHandler);
    wxFileSystem::AddHandler(new wxZipFSHandler);
    wxSocketBase::Initialize();

    m_timer->Start( TIMER_INTERVAL );

	if( m_version == _T("-1") )
		m_version = GetLatestVersion();

	m_updater_window = new UpdaterMainwindow( m_version );
	m_updater_window->Show( true );
	SetTopWindow( m_updater_window );

	return Updater().StartUpdate( m_version, m_exe_to_update );
}
 /** OnInit
  *
  * Initializes the program
  */
bool BBBApp::OnInit()
{
    srand(time(NULL));
    logger.reset(new LoggerWx());

    if (!wxApp::OnInit())
        return false;
#ifndef __WIN32
    wxHandleFatalExceptions();
#endif
    wxInitAllImageHandlers();

    SetVendorName("Bottomless Block Builder");
    SetAppName("Bottomless Block Builder");

    wxBitmap bitmap(panels_gfx_xpm);
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(112, 16, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(0, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(16, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(32, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(48, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(64, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(80, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(96, 0, 16, 16)));
    panelImages.push_back(bitmap.GetSubBitmap(wxRect(112, 0, 16, 16)));

    BBBFrame* frame = new BBBFrame();
    frame->Show();

    return true;
}
Exemple #5
0
bool Springsettings::OnInit()
{
	wxSetEnv( _T("UBUNTU_MENUPROXY"), _T("0") );
    //this triggers the Cli Parser amongst other stuff
    if (!wxApp::OnInit())
        return false;

	SetAppName(_T("SpringSettings"));
	const wxString configdir = TowxString(SlPaths::GetConfigfileDir());
	if ( !wxDirExists(configdir) )
		wxMkdir(configdir);

	if (!m_crash_handle_disable) {
	#if wxUSE_ON_FATAL_EXCEPTION
		wxHandleFatalExceptions( true );
	#endif
	#if defined(__WXMSW__) && defined(ENABLE_DEBUG_REPORT)
		//this undocumented function acts as a workaround for the dysfunctional
		// wxUSE_ON_FATAL_EXCEPTION on msw when mingw is used (or any other non SEH-capable compiler )
		SetUnhandledExceptionFilter(filter);
	#endif
	}

    //initialize all loggers
	//TODO non-constant parameters
	wxLogChain* logchain  = 0;
	wxLogWindow* loggerwin = InitializeLoggingTargets( 0, m_log_console, m_log_file_path, m_log_window_show, m_log_verbosity, logchain );
	//this needs to called _before_ mainwindow instance is created

#ifdef __WXMSW__
	wxString path = wxPathOnly( wxStandardPaths::Get().GetExecutablePath() ) + wxFileName::GetPathSeparator() + _T("locale");
#else
	#if defined(LOCALE_INSTALL_DIR)
		wxString path ( _T(LOCALE_INSTALL_DIR) );
	#else
		// use a dummy name here, we're only interested in the base path
		wxString path = wxStandardPaths::Get().GetLocalizedResourcesDir(_T("noneWH"),wxStandardPaths::ResourceCat_Messages);
		path = path.Left( path.First(_T("noneWH") ) );
	#endif
#endif
	m_translationhelper = new wxTranslationHelper( GetAppName().Lower(), path );

    SetSettingsStandAlone( true );

	// configure unitsync paths before trying to load
	SlPaths::ReconfigureUnitsync();

	//unitsync first load, NEEDS to be blocking
	LSL::usync().ReloadUnitSyncLib();

	settings_frame* frame = new settings_frame(NULL,GetAppName());
    SetTopWindow(frame);
    frame->Show();

    if ( loggerwin ) { // we got a logwindow, lets set proper parent win
        loggerwin->GetFrame()->SetParent( frame );
    }

    return true;
}
Exemple #6
0
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame((wxFrame *)NULL, -1, title, pos, size)
{
    wxMenu *menuFile = new wxMenu;

    menuFile->Append(ID_Crash, _T("&Crash!"));
    menuFile->Append(ID_GenerateCrashReport, _T("&Generate Crash Report"));
    menuFile->Append(ID_About, _T("&About..."));
    menuFile->AppendSeparator();
    menuFile->Append(ID_Quit, _T("E&xit"));

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, _T("&File"));

    SetMenuBar(menuBar);

    CreateStatusBar();
    SetStatusText(_T("Welcome to wxWindows!"));

    wxHtmlWindow* html = new wxHtmlWindow(this, -1);

    wxString msg;
    msg << wxT("wxHandleFatalExceptions: ") << wxHandleFatalExceptions() << wxT("<br>");
    msg << wxT("wxCrashReport::GetFileName(): ") << wxCrashReport::GetFileName() << wxT("<br>");

    html->SetPage(msg);

    wxSizer* boxSizer = new wxBoxSizer(wxHORIZONTAL);
    boxSizer->Add(html, 1, wxEXPAND);
    SetSizer(boxSizer);
}
Exemple #7
0
    virtual bool OnInit()
    {
        wxHandleFatalExceptions();

        if ( !wxApp::OnInit() )
            return false;

        return true;
    }
Exemple #8
0
bool DolphinApp::OnInit()
{
  std::lock_guard<std::mutex> lk(s_init_mutex);
  if (!wxApp::OnInit())
    return false;

  Bind(wxEVT_QUERY_END_SESSION, &DolphinApp::OnEndSession, this);
  Bind(wxEVT_END_SESSION, &DolphinApp::OnEndSession, this);
  Bind(wxEVT_IDLE, &DolphinApp::OnIdle, this);
  Bind(wxEVT_ACTIVATE_APP, &DolphinApp::OnActivate, this);

  // Register message box and translation handlers
  RegisterMsgAlertHandler(&wxMsgAlert);
  RegisterStringTranslator(&wxStringTranslator);

#if wxUSE_ON_FATAL_EXCEPTION
  wxHandleFatalExceptions(true);
#endif

  UICommon::SetUserDirectory(m_user_path.ToStdString());
  UICommon::CreateDirectories();
  InitLanguageSupport();  // The language setting is loaded from the user directory
  UICommon::Init();

  if (m_select_video_backend && !m_video_backend_name.empty())
    SConfig::GetInstance().m_strVideoBackend = WxStrToStr(m_video_backend_name);

  if (m_select_audio_emulation)
    SConfig::GetInstance().bDSPHLE = (m_audio_emulation_name.Upper() == "HLE");

  VideoBackendBase::ActivateBackend(SConfig::GetInstance().m_strVideoBackend);

  DolphinAnalytics::Instance()->ReportDolphinStart("wx");

  wxToolTip::Enable(!SConfig::GetInstance().m_DisableTooltips);

  // Enable the PNG image handler for screenshots
  wxImage::AddHandler(new wxPNGHandler);

  // We have to copy the size and position out of SConfig now because CFrame's OnMove
  // handler will corrupt them during window creation (various APIs like SetMenuBar cause
  // event dispatch including WM_MOVE/WM_SIZE)
  wxRect window_geometry(SConfig::GetInstance().iPosX, SConfig::GetInstance().iPosY,
                         SConfig::GetInstance().iWidth, SConfig::GetInstance().iHeight);
  main_frame = new CFrame(nullptr, wxID_ANY, StrToWxStr(scm_rev_str), window_geometry,
                          m_use_debugger, m_batch_mode, m_use_logger);
  SetTopWindow(main_frame);

  AfterInit();

  return true;
}
Exemple #9
0
	virtual bool OnInit()
	{
		wxHandleFatalExceptions();

		wxImage::AddHandler(new wxPNGHandler());
		wxImage::AddHandler(new wxJPEGHandler());
		wxImage::AddHandler(new wxGIFHandler());

		m_locale.Init();

		SetAppName("RLReplayManager");
		SetAppDisplayName("RL Replay Manager");

		ManagerFrame* frame = new ManagerFrame(NULL);
		frame->Show();

		return true;
	}
Exemple #10
0
bool QSPApp::OnInit()
{
	wxLog::EnableLogging(true);

	log_stream.open("log_qspgui.txt");
	logger = new wxLogStream(&log_stream);
	//logger->SetTimestamp("%Y-%m-%d %H:%M:%S");
	//formatter = logger->SetFormatter(new wxLogFormatter());
	wxHandleFatalExceptions(true);
	wxInitAllImageHandlers();
	QSPInit();
	logger->LogText("qsp initialized");

	try { InitUI(); }
	catch (...)
	{
		logger->LogText("exception during ui initialization.");
	}

	logger->LogText("ui initialized");
	return true;
}
Exemple #11
0
bool DolphinApp::OnInit()
{
	if (!wxApp::OnInit())
		return false;

	Bind(wxEVT_QUERY_END_SESSION, &DolphinApp::OnEndSession, this);
	Bind(wxEVT_END_SESSION, &DolphinApp::OnEndSession, this);

	// Register message box and translation handlers
	RegisterMsgAlertHandler(&wxMsgAlert);
	RegisterStringTranslator(&wxStringTranslator);

#if wxUSE_ON_FATAL_EXCEPTION
	wxHandleFatalExceptions(true);
#endif

	UICommon::SetUserDirectory(m_user_path.ToStdString());
	UICommon::CreateDirectories();
	InitLanguageSupport(); // The language setting is loaded from the user directory
	UICommon::Init();

	if (m_select_video_backend && !m_video_backend_name.empty())
		SConfig::GetInstance().m_strVideoBackend = WxStrToStr(m_video_backend_name);

	if (m_select_audio_emulation)
		SConfig::GetInstance().bDSPHLE = (m_audio_emulation_name.Upper() == "HLE");

	VideoBackend::ActivateBackend(SConfig::GetInstance().m_strVideoBackend);

	// Enable the PNG image handler for screenshots
	wxImage::AddHandler(new wxPNGHandler);

	int x = SConfig::GetInstance().iPosX;
	int y = SConfig::GetInstance().iPosY;
	int w = SConfig::GetInstance().iWidth;
	int h = SConfig::GetInstance().iHeight;

	// The following is not needed with X11, where window managers
	// do not allow windows to be created off the desktop.
#ifdef _WIN32
	// Out of desktop check
	int leftPos = GetSystemMetrics(SM_XVIRTUALSCREEN);
	int topPos = GetSystemMetrics(SM_YVIRTUALSCREEN);
	int width =  GetSystemMetrics(SM_CXVIRTUALSCREEN);
	int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
	if ((leftPos + width) < (x + w) || leftPos > x || (topPos + height) < (y + h) || topPos > y)
		x = y = wxDefaultCoord;
#elif defined __APPLE__
	if (y < 1)
		y = wxDefaultCoord;
#endif

	main_frame = new CFrame(nullptr, wxID_ANY,
	                        StrToWxStr(scm_rev_str),
	                        wxPoint(x, y), wxSize(w, h),
	                        m_use_debugger, m_batch_mode, m_use_logger);

	SetTopWindow(main_frame);
	main_frame->SetMinSize(wxSize(400, 300));

	AfterInit();

	return true;
}
bool MusikApp::OnInit()
{
	if(Prefs.bEnableCrashHandling)
	{
#if wxUSE_DEBUGREPORT
		// fatal exceptions handling
		wxHandleFatalExceptions (true);
#endif
	}

#ifdef __WXMAC__
	m_locale.AddCatalogLookupPathPrefix( MusikGetStaticDataPath() );
#else
#ifdef __WXMSW__
    m_locale.AddCatalogLookupPathPrefix(wxT("locale"));
#if wxCHECK_VERSION(2,5,4)
    wxStandardPaths stdpaths;
    m_locale.AddCatalogLookupPathPrefix(stdpaths.GetDataDir() + wxT("/locale"));
#endif
#endif
#endif
	wxArrayString arrParams;
	{
		wxLogNull lognull;
		const wxLanguageInfo * pLangInfo = wxLocale::FindLanguageInfo(Prefs.sLocale);
		if(pLangInfo == NULL)
			m_locale.Init(wxLANGUAGE_DEFAULT);
		else
			m_locale.Init(pLangInfo->Language);
		m_locale.AddCatalog(MUSIKAPPNAME);
	
		static const wxCmdLineEntryDesc cmdLineDesc[] =
		{
			{ wxCMD_LINE_PARAM,  NULL, NULL, wxT("mp3/ogg file"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_PARAM_OPTIONAL},
			{ wxCMD_LINE_NONE }
		};
	
		wxCmdLineParser parser(argc, argv);
		parser.SetDesc(cmdLineDesc);
	
		parser.Parse(false);
	
		for (size_t i = 0; i <parser.GetParamCount(); i++)
		{
			arrParams.Add(parser.GetParam(i));
		}
		m_pSingleInstanceChecker = new wxSingleInstanceChecker(wxString(wxT(".")) << GetAppName() << wxT(".single_instance_check"));
	}
	if ( m_pSingleInstanceChecker->IsAnotherRunning() )
	{
		MusikAppClient client;
		MusikAppConnection *pConn = (MusikAppConnection *)client.MakeConnection(wxT("localhost"),MUSIK_APP_SERVICE,wxT("wxMusikInternal"));
		if(pConn)
		{
			wxString sData;

			if(arrParams.GetCount())
			{
				for( size_t i = 0; i < arrParams.GetCount(); i++)
				{
					sData += arrParams[i];
					sData += wxT("\n");
				}
		#if wxUSE_UNICODE
				pConn->Poke(wxT("PlayFiles"),sData.GetWriteBuf(sData.Length()),sData.Length()*sizeof(wxChar),wxIPC_UNICODETEXT);
		#else
				pConn->Poke(wxT("PlayFiles"),sData.GetWriteBuf(sData.Length()),sData.Length(),wxIPC_TEXT);
		#endif
			}
			pConn->Poke(wxT("RaiseFrame"),NULL,0,wxIPC_PRIVATE);
			return false;
		}
	}

	wxImage::AddHandler(new wxPNGHandler);
	wxImage::AddHandler(new wxJPEGHandler);
	wxImage::AddHandler( new wxXPMHandler );
	wxImage::AddHandler( new wxBMPHandler );
	wxImage::AddHandler( new wxGIFHandler );



	//--- setup our home dir ---//
	if ( !wxDirExists( MUSIK_HOME_DIR ) )
		wxMkdir( MUSIK_HOME_DIR );

	//-----------------------------------------//
	//--- check to see if a new version has	---//
	//--- been installed. if it has, see	---//
	//--- if any core changes need to be	---//
	//--- made.								---//
	//-----------------------------------------//
	CheckOldVersion();
	
	//--- assure playlists directory exists ---//
	if ( !wxDirExists( MUSIK_PLAYLIST_DIR ) )
		wxMkdir( MUSIK_PLAYLIST_DIR );

	//--- load library and paths ---//
	if(!wxGetApp().Library.Load())
	{
		wxMessageBox( _("Initialization of library failed."), MUSIKAPPNAME_VERSION, wxOK | wxICON_ERROR );
		return FALSE;
	}
	g_Paths.Load();

    Player.Init(arrParams.GetCount() > 0);


	//-------------------//
	//--- main window ---//
	//-------------------//
    MusikFrame *pMain = new MusikFrame();

	//--- restore placement or use defaults ---//
	if ( !SetFramePlacement( pMain, wxGetApp().Prefs.sFramePlacement ) )
	{
		wxSize Size( 
			wxSystemSettings::GetMetric( wxSYS_SCREEN_X ) * 75 / 100, 
			wxSystemSettings::GetMetric( wxSYS_SCREEN_Y ) * 75 / 100 );
		pMain->SetSize( Size );
		pMain->Center();
	}
	new MusikLogWindow(pMain,wxString::Format(_("%s Logging Window"),MUSIKAPPNAME),MUSIK_LW_ClearContentOnClose|MUSIK_LW_ShowOnLog); 
	
	wxLog::SetVerbose(Prefs.bLogVerbose);

	SetTopWindow( pMain );

	//--- start webserver if necessary ---//
	if ( Prefs.bWebServerEnable )
		WebServer.Start(wxGetApp().Prefs.nWebServerPort);

	//--- autostart stuff ---//
	if ( Prefs.bFirstRun )
	{
		wxCommandEvent dummy_ev;
		pMain->OnSetupPaths(dummy_ev);
	}
	else if (Prefs.bAutoAdd || arrParams.GetCount() > 0)
	{	
        if(Prefs.bAutoAdd)
			pMain->AutoUpdate();
		if(arrParams.GetCount() > 0)
			pMain->AutoUpdate(arrParams,MUSIK_UpdateFlags::InsertFilesIntoPlayer|MUSIK_UpdateFlags::PlayFiles);
	}
	
    if (Prefs.bShowLibraryOnStart)
		g_SourcesCtrl->SelectLibrary();
	else
		g_SourcesCtrl->SelectNowPlaying();
	g_PlaylistBox->Update();

    pMain->Show();

	m_pServer = new MusikAppServer;
	if(m_pServer)
		m_pServer->Create(MUSIK_APP_SERVICE);
	return TRUE;
}
//! @brief Initializes the application.
//!
//! It will open the main window and connect default to server or open the connect window.
bool SpringLobbyApp::OnInit()
{
	wxSetEnv( _T("UBUNTU_MENUPROXY"), _T("0") );
    //this triggers the Cli Parser amongst other stuff
    if (!wxApp::OnInit())
		return false;
	SetAppName( m_appname );

    if (!m_crash_handle_disable) {
    #if wxUSE_ON_FATAL_EXCEPTION
        wxHandleFatalExceptions( true );
    #endif
    #if defined(__WXMSW__) && defined(ENABLE_DEBUG_REPORT)
        //this undocumented function acts as a workaround for the dysfunctional
        // wxUSE_ON_FATAL_EXCEPTION on msw when mingw is used (or any other non SEH-capable compiler )
        SetUnhandledExceptionFilter(filter);
    #endif
    }

    //initialize all loggers, we'll use the returned pointer to set correct parent window later
    wxLogChain* logchain = 0;
	wxLogWindow *loggerwin = InitializeLoggingTargets( 0, m_log_console, m_log_file_path, m_log_window_show, !m_crash_handle_disable, m_log_verbosity, logchain );

    //this needs to called _before_ mainwindow instance is created
    wxInitAllImageHandlers();
    wxFileSystem::AddHandler(new wxZipFSHandler);
    wxSocketBase::Initialize();


#ifdef __WXMSW__
    wxString path = wxPathOnly( wxStandardPaths::Get().GetExecutablePath() ) + wxFileName::GetPathSeparator() + _T("locale");
#else
	#if defined(LOCALE_INSTALL_DIR)
		wxString path ( _T(LOCALE_INSTALL_DIR) );
	#else
		// use a dummy name here, we're only interested in the base path
		wxString path = wxStandardPaths::Get().GetLocalizedResourcesDir(_T("noneWH"),wxStandardPaths::ResourceCat_Messages);
		path = path.Left( path.First(_T("noneWH") ) );
	#endif
#endif
    m_translationhelper = new wxTranslationHelper( *( (wxApp*)this ), path );
    m_translationhelper->Load();

	if ( !wxDirExists( GetConfigfileDir() ) )
		wxMkdir( GetConfigfileDir() );

#ifdef __WXMSW__
	sett().SetSearchSpringOnlyInSLPath( sett().GetSearchSpringOnlyInSLPath() );
#endif
	sett().SetSpringBinary( sett().GetCurrentUsedSpringIndex(), sett().GetCurrentUsedSpringBinary() );
	sett().SetUnitSync( sett().GetCurrentUsedSpringIndex(), sett().GetCurrentUsedUnitSync() );

	if ( sett().DoResetPerspectives() )
	{
		//we do this early on and reset the config var a little later so we can save a def. perps once mw is created
		sett().RemoveLayouts();
		sett().SetDoResetPerspectives( false );
		ui().mw().SavePerspectives( _T("SpringLobby-default") );
	}

	sett().RefreshSpringVersionList();

	//this should take off the firstload time considerably *ie nil it :P )
	mapSelectDialog();
	if ( !m_customizer_archive_name.IsEmpty() )
	{//this needsto happen before usync load
		sett().SetForcedSpringConfigFilePath( GetCustomizedEngineConfigFilePath() );
	}
	//unitsync first load, NEEDS to be blocking
	const bool usync_loaded = usync().ReloadUnitSyncLib();
	if ( !sett().IsFirstRun() && !usync_loaded )
	{
		customMessageBox( SL_MAIN_ICON, _("Please check that the file given in Preferences->Spring is a proper, readable unitsync library"),
						 _("Coulnd't load required unitsync library"), wxOK );
	}

	#ifndef DISABLE_SOUND
		//sound sources/buffer init
		sound();
	#endif


	CacheAndSettingsSetup();

	if ( !m_customizer_archive_name.IsEmpty() ) {
		if ( SLcustomizations().Init( m_customizer_archive_name ) ) {
			ui().mw().SetIcons( SLcustomizations().GetAppIconBundle() );
		}
		else {
			customMessageBox( SL_MAIN_ICON, _("Couldn't load customizations for ") + m_customizer_archive_name + _("\nPlease check that that is the correct name, passed in qoutation"), _("Fatal error"), wxOK );
//            wxLogError( _("Couldn't load customizations for ") + m_customizer_archive_name + _("\nPlease check that that is the correct name, passed in qoutation"), _("Fatal error") );
			exit( OnExit() );//for some twisted reason returning false here does not terminate the app
		}
	}

	notificationManager(); //needs to be initialized too
    ui().ShowMainWindow();
    SetTopWindow( &ui().mw() );
	if ( sett().DoResetPerspectives() )
	{
		//now that mainwindow is shown, we can save what is the default layout and remove the flag to reset
		sett().SetDoResetPerspectives( false );
		ui().mw().SavePerspectives( _T("SpringLobby-default") );
	}

	//interim fix for resize crashes on metacity and kwin
	#ifdef __WXMSW__
		mapSelectDialog().Reparent( &ui().mw() );
	#endif

    ui().FirstRunWelcome();
    m_timer->Start( TIMER_INTERVAL );

    ui().mw().SetLogWin( loggerwin, logchain );

#ifndef NO_TORRENT_SYSTEM
    plasmaInterface();
//    plasmaInterface().InitResourceList();
//	plasmaInterface().FetchResourceList();
#endif


    return true;
}
Exemple #14
0
bool DolphinApp::OnInit()
{
	InitLanguageSupport();

	// Declarations and definitions
	bool UseDebugger = false;
	bool UseLogger = false;
	bool selectVideoBackend = false;
	bool selectAudioEmulation = false;

	wxString videoBackendName;
	wxString audioEmulationName;
	wxString userPath;

#if wxUSE_CMDLINE_PARSER // Parse command lines
	wxCmdLineEntryDesc cmdLineDesc[] =
	{
		{
			wxCMD_LINE_SWITCH, "h", "help",
			"Show this help message",
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP
		},
		{
			wxCMD_LINE_SWITCH, "d", "debugger",
			"Opens the debugger",
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_SWITCH, "l", "logger",
			"Opens the logger",
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, "e", "exec",
			"Loads the specified file (DOL,ELF,GCM,ISO,WAD)",
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_SWITCH, "b", "batch",
			"Exit Dolphin with emulator",
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, "V", "video_backend",
			"Specify a video backend",
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, "A", "audio_emulation",
			"Low level (LLE) or high level (HLE) audio",
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, "m", "movie",
			"Play a movie file",
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, "U", "user",
			"User folder path",
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0
		}
	};

	// Gets the command line parameters
	wxCmdLineParser parser(cmdLineDesc, argc, argv);
	if (parser.Parse() != 0)
	{
		return false;
	}

	UseDebugger = parser.Found("debugger");
	UseLogger = parser.Found("logger");
	LoadFile = parser.Found("exec", &FileToLoad);
	BatchMode = parser.Found("batch");
	selectVideoBackend = parser.Found("video_backend", &videoBackendName);
	selectAudioEmulation = parser.Found("audio_emulation", &audioEmulationName);
	playMovie = parser.Found("movie", &movieFile);

	if (parser.Found("user", &userPath))
	{
		File::CreateFullPath(WxStrToStr(userPath) + DIR_SEP);
		File::GetUserPath(D_USER_IDX, userPath.ToStdString() + DIR_SEP);
	}
#endif // wxUSE_CMDLINE_PARSER

	// Register message box and translation handlers
	RegisterMsgAlertHandler(&wxMsgAlert);
	RegisterStringTranslator(&wxStringTranslator);

	// "ExtendedTrace" looks freakin' dangerous!!!
#ifdef _WIN32
	EXTENDEDTRACEINITIALIZE(".");
	SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter);
#elif wxUSE_ON_FATAL_EXCEPTION
	wxHandleFatalExceptions(true);
#endif

#ifndef _M_ARM
	// TODO: if First Boot
	if (!cpu_info.bSSE2)
	{
		PanicAlertT("Hi,\n\nDolphin requires that your CPU has support for SSE2 extensions.\n"
				"Unfortunately your CPU does not support them, so Dolphin will not run.\n\n"
				"Sayonara!\n");
		return false;
	}
#endif
#ifdef __APPLE__
	if (floor(NSAppKitVersionNumber) < NSAppKitVersionNumber10_7)
	{
		PanicAlertT("Hi,\n\nDolphin requires Mac OS X 10.7 or greater.\n"
				"Unfortunately you're running an old version of OS X.\n"
				"The last Dolphin version to support OS X 10.6 is Dolphin 3.5\n"
				"Please upgrade to 10.7 or greater to use the newest Dolphin version.\n\n"
				"Sayonara!\n");
		return false;
	}
#endif

	// Copy initial Wii NAND data from Sys to User.
	File::CopyDir(File::GetSysDirectory() + WII_USER_DIR DIR_SEP,
	              File::GetUserPath(D_WIIUSER_IDX));

	File::CreateFullPath(File::GetUserPath(D_USER_IDX));
	File::CreateFullPath(File::GetUserPath(D_CACHE_IDX));
	File::CreateFullPath(File::GetUserPath(D_CONFIG_IDX));
	File::CreateFullPath(File::GetUserPath(D_DUMPDSP_IDX));
	File::CreateFullPath(File::GetUserPath(D_DUMPTEXTURES_IDX));
	File::CreateFullPath(File::GetUserPath(D_GAMESETTINGS_IDX));
	File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX));
	File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX) + USA_DIR DIR_SEP);
	File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX) + EUR_DIR DIR_SEP);
	File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX) + JAP_DIR DIR_SEP);
	File::CreateFullPath(File::GetUserPath(D_HIRESTEXTURES_IDX));
	File::CreateFullPath(File::GetUserPath(D_MAILLOGS_IDX));
	File::CreateFullPath(File::GetUserPath(D_MAPS_IDX));
	File::CreateFullPath(File::GetUserPath(D_SCREENSHOTS_IDX));
	File::CreateFullPath(File::GetUserPath(D_SHADERS_IDX));
	File::CreateFullPath(File::GetUserPath(D_STATESAVES_IDX));
	File::CreateFullPath(File::GetUserPath(D_THEMES_IDX));

	LogManager::Init();
	SConfig::Init();
	VideoBackend::PopulateList();
	WiimoteReal::LoadSettings();

	if (selectVideoBackend && videoBackendName != wxEmptyString)
		SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend =
			WxStrToStr(videoBackendName);

	if (selectAudioEmulation)
	{
		if (audioEmulationName == "HLE")
			SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = true;
		else if (audioEmulationName == "LLE")
			SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = false;
	}

	VideoBackend::ActivateBackend(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend);

	// Enable the PNG image handler for screenshots
	wxImage::AddHandler(new wxPNGHandler);

	SetEnableAlert(SConfig::GetInstance().m_LocalCoreStartupParameter.bUsePanicHandlers);

	int x = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosX;
	int y = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosY;
	int w = SConfig::GetInstance().m_LocalCoreStartupParameter.iWidth;
	int h = SConfig::GetInstance().m_LocalCoreStartupParameter.iHeight;

#ifdef _WIN32
	if (File::Exists("www.dolphin-emulator.com.txt"))
	{
		File::Delete("www.dolphin-emulator.com.txt");
		MessageBox(nullptr,
				   L"This version of Dolphin was downloaded from a website stealing money from developers of the emulator. Please "
				   L"download Dolphin from the official website instead: http://dolphin-emu.org/",
				   L"Unofficial version detected", MB_OK | MB_ICONWARNING);
		ShellExecute(nullptr, L"open", L"http://dolphin-emu.org/?ref=badver", nullptr, nullptr, SW_SHOWDEFAULT);
		exit(0);
	}
#endif

	// The following is not needed with X11, where window managers
	// do not allow windows to be created off the desktop.
#ifdef _WIN32
	// Out of desktop check
	int leftPos = GetSystemMetrics(SM_XVIRTUALSCREEN);
	int topPos = GetSystemMetrics(SM_YVIRTUALSCREEN);
	int width =  GetSystemMetrics(SM_CXVIRTUALSCREEN);
	int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
	if ((leftPos + width) < (x + w) || leftPos > x || (topPos + height) < (y + h) || topPos > y)
		x = y = wxDefaultCoord;
#elif defined __APPLE__
	if (y < 1)
		y = wxDefaultCoord;
#endif

	main_frame = new CFrame((wxFrame*)nullptr, wxID_ANY,
				StrToWxStr(scm_rev_str),
				wxPoint(x, y), wxSize(w, h),
				UseDebugger, BatchMode, UseLogger);
	SetTopWindow(main_frame);
	main_frame->SetMinSize(wxSize(400, 300));

	// Postpone final actions until event handler is running.
	// Updating the game list makes use of wxProgressDialog which may
	// only be run after OnInit() when the event handler is running.
	m_afterinit = new wxTimer(this, wxID_ANY);
	m_afterinit->Start(1, wxTIMER_ONE_SHOT);

	return true;
}
//  Called from MyApp() immediately upon entry to MyApp::OnInit()
void OCPNPlatform::Initialize_1( void )
{
    
#ifdef OCPN_USE_CRASHRPT
#ifndef _DEBUG
    // Install Windows crash reporting
    
    CR_INSTALL_INFO info;
    memset(&info, 0, sizeof(CR_INSTALL_INFO));
    info.cb = sizeof(CR_INSTALL_INFO);
    info.pszAppName = _T("OpenCPN");
    
    wxString version_crash = str_version_major + _T(".") + str_version_minor + _T(".") + str_version_patch;
    info.pszAppVersion = version_crash.c_str();
    
    int type = MiniDumpWithDataSegs;  // Include the data sections from all loaded modules.
    // This results in the inclusion of global variables
    
    type |=  MiniDumpNormal;// | MiniDumpWithPrivateReadWriteMemory | MiniDumpWithIndirectlyReferencedMemory;
    info.uMiniDumpType = (MINIDUMP_TYPE)type;
    
    // Install all available exception handlers....
    info.dwFlags = CR_INST_ALL_POSSIBLE_HANDLERS;
    
    //  Except memory allocation failures
    info.dwFlags &= ~CR_INST_NEW_OPERATOR_ERROR_HANDLER;
    
    //  Allow user to attach files
    info.dwFlags |= CR_INST_ALLOW_ATTACH_MORE_FILES;
    
    //  Allow user to add more info
    info.dwFlags |= CR_INST_SHOW_ADDITIONAL_INFO_FIELDS;
    
    
    // URL for sending error reports over HTTP.
    if(g_bEmailCrashReport){
        info.pszEmailTo = _T("*****@*****.**");
        info.pszSmtpProxy = _T("mail.bigdumboat.com:587");
        info.pszUrl = _T("http://bigdumboat.com/crashrpt/ocpn_crashrpt.php");
        info.uPriorities[CR_HTTP] = 1;  // First try send report over HTTP
    }
    else{
        info.dwFlags |= CR_INST_DONT_SEND_REPORT;
        info.uPriorities[CR_HTTP] = CR_NEGATIVE_PRIORITY;       // don't send at all
    }
    
    info.uPriorities[CR_SMTP] = CR_NEGATIVE_PRIORITY;  // Second try send report over SMTP
    info.uPriorities[CR_SMAPI] = CR_NEGATIVE_PRIORITY; //1; // Third try send report over Simple MAPI
    
    wxStandardPaths& crash_std_path = g_Platform->GetStdPaths();
    
    wxString crash_rpt_save_locn = crash_std_path.GetConfigDir();
    if( g_bportable ) {
        wxFileName exec_path_crash( crash_std_path.GetExecutablePath() );
        crash_rpt_save_locn = exec_path_crash.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
    }
    
    wxString locn = crash_rpt_save_locn + _T("\\CrashReports");
    
    if(!wxDirExists( locn ) )
        wxMkdir( locn );
    
    if(wxDirExists( locn ) ){
        wxCharBuffer buf = locn.ToUTF8();
        wchar_t wlocn[256];
        if(buf && (locn.Length() < sizeof(wlocn)) ){
            MultiByteToWideChar( 0, 0, buf.data(), -1, wlocn, sizeof(wlocn)-1);
            info.pszErrorReportSaveDir = (LPCWSTR)wlocn;
        }
    }
    
    // Provide privacy policy URL
    wxFileName exec_path_crash( crash_std_path.GetExecutablePath() );
    wxString policy_file =  exec_path_crash.GetPath( wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR );
    policy_file += _T("PrivacyPolicy.txt");
    policy_file.Prepend(_T("file:"));
    
    info.pszPrivacyPolicyURL = policy_file.c_str();;
    
    int nResult = crInstall(&info);
    if(nResult!=0) {
        TCHAR buff[256];
        crGetLastErrorMsg(buff, 256);
        MessageBox(NULL, buff, _T("crInstall error, Crash Reporting disabled."), MB_OK);
    }
    
    // Establish the crash callback function
    crSetCrashCallback( CrashCallback, NULL );
    
    // Take screenshot of the app window at the moment of crash
    crAddScreenshot2(CR_AS_PROCESS_WINDOWS|CR_AS_USE_JPEG_FORMAT, 95);
    
    //  Mark some files to add to the crash report
    wxString home_data_crash = crash_std_path.GetConfigDir();
    if( g_bportable ) {
        wxFileName f( crash_std_path.GetExecutablePath() );
        home_data_crash = f.GetPath();
    }
    appendOSDirSlash( &home_data_crash );
    
    wxString config_crash = _T("opencpn.ini");
    config_crash.Prepend( home_data_crash );
    crAddFile2( config_crash.c_str(), NULL, NULL, CR_AF_MISSING_FILE_OK | CR_AF_ALLOW_DELETE );
    
    wxString log_crash = _T("opencpn.log");
    log_crash.Prepend( home_data_crash );
    crAddFile2( log_crash.c_str(), NULL, NULL, CR_AF_MISSING_FILE_OK | CR_AF_ALLOW_DELETE );
    
#endif
#endif

    
#ifdef LINUX_CRASHRPT
#if wxUSE_ON_FATAL_EXCEPTION
    // fatal exceptions handling
    wxHandleFatalExceptions (true);
#endif
#endif

#ifdef __WXMSW__
    //  Invoke my own handler for failures of malloc/new
    _set_new_handler( MyNewHandler );
    //  configure malloc to call the New failure handler on failure
    _set_new_mode(1);
#endif    
    
    //    On MSW, force the entire process to run on one CPU core only
    //    This resolves some difficulty with wxThread syncronization
#if 0
#ifdef __WXMSW__
    //Gets the current process handle
    HANDLE hProc = GetCurrentProcess();
    DWORD procMask;
    DWORD sysMask;
    HANDLE hDup;
    DuplicateHandle( hProc, hProc, hProc, &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS );
    
    //Gets the current process affinity mask
    GetProcessAffinityMask( hDup, &procMask, &sysMask );
    
    // Take a simple approach, and assume up to 4 processors
    DWORD newMask;
    if( ( procMask & 1 ) == 1 ) newMask = 1;
    else
        if( ( procMask & 2 ) == 2 ) newMask = 2;
        else
            if( ( procMask & 4 ) == 4 ) newMask = 4;
            else
                if( ( procMask & 8 ) == 8 ) newMask = 8;
                
                //Set te affinity mask for the process
                BOOL res = SetProcessAffinityMask( hDup, (DWORD_PTR) newMask );
            
            if( res == 0 ) {
                //Error setting affinity mask!!
            }
#endif
#endif
            
#ifdef __WXMSW__
            
            //    Handle any Floating Point Exceptions which may leak thru from other
            //    processes.  The exception filter is in cutil.c
            //    Seems to only happen for W98
            
            wxPlatformInfo Platform;
            if( Platform.GetOperatingSystemId() == wxOS_WINDOWS_9X ) SetUnhandledExceptionFilter (&MyUnhandledExceptionFilter);
#endif
            
#ifdef __WXMSW__
            //     _CrtSetBreakAlloc(25503);
#endif
            

#ifndef __WXMSW__
            //      Setup Linux SIGNAL handling, for external program control
            
            //      Build the sigaction structure
            sa_all.sa_handler = catch_signals;// point to my handler
            sigemptyset(&sa_all.sa_mask);// make the blocking set
            // empty, so that all
            // other signals will be
            // unblocked during my handler
            sa_all.sa_flags = 0;
            
            sigaction(SIGUSR1, NULL, &sa_all_old);// save existing action for this signal
            
            //      Register my request for some signals
            sigaction(SIGUSR1, &sa_all, NULL);
            
            sigaction(SIGUSR1, NULL, &sa_all_old);// inspect existing action for this signal
            
            sigaction(SIGTERM, &sa_all, NULL);
            sigaction(SIGTERM, NULL, &sa_all_old);
#endif
            
}
Exemple #16
0
bool CBOINCGUIApp::OnInit() {
    // Initialize globals
#ifdef SANDBOX
    g_use_sandbox = true;
#else
    g_use_sandbox = false;
#endif

    s_bSkipExitConfirmation = false;
    m_bFilterEvents = false;
    m_bAboutDialogIsOpen = false;

    // Initialize class variables
    m_pInstanceChecker = NULL;
    m_pLocale = NULL;
    m_pSkinManager = NULL;
    m_pFrame = NULL;
    m_pDocument = NULL;
    m_pTaskBarIcon = NULL;
    m_pEventLog = NULL;
#ifdef __WXMAC__
    m_pMacDockIcon = NULL;
#endif
    m_strBOINCMGRExecutableName = wxEmptyString;
    m_strBOINCMGRRootDirectory = wxEmptyString;
    m_strBOINCMGRDataDirectory = wxEmptyString;
    m_strHostNameArg = wxEmptyString;
    m_strPasswordArg = wxEmptyString;
    m_iRPCPortArg = GUI_RPC_PORT;
    m_strBOINCArguments = wxEmptyString;
    m_strISOLanguageCode = wxEmptyString;
    m_bGUIVisible = true;
    m_bDebugSkins = false;
    m_bMultipleInstancesOK = false;
    m_bBOINCMGRAutoStarted = false;
    m_iBOINCMGRDisableAutoStart = 0;
    m_iShutdownCoreClient = 0;
    m_iDisplayExitDialog = 1;
    m_iGUISelected = BOINC_SIMPLEGUI;
    m_bSafeMessageBoxDisplayed = 0;

    // Initialize local variables
    int      iErrorCode = 0;
    int      iSelectedLanguage = 0;
    bool     bOpenEventLog = false;
    wxString strDesiredSkinName = wxEmptyString;
    wxString strDialogMessage = wxEmptyString;
    bool     success = false;


#ifndef __WXMAC__
    // call this to tell the library to call our OnFatalException()
    wxHandleFatalExceptions();
#endif

    // Configure wxWidgets platform specific code
#ifdef __WXMSW__
    wxSystemOptions::SetOption(wxT("msw.staticbox.optimized-paint"), 0);
#endif
#ifdef __WXMAC__
    // In wxMac-2.8.7, default wxListCtrl::RefreshItem() does not work
    // so use traditional generic implementation.
    // This has been fixed in wxMac-2.8.8, but the Mac native implementation:
    //  - takes 3 times the CPU time as the Mac generic version.
    //  - seems to always redraw entire control even if asked to refresh only one row.
    //  - causes major flicker of progress bars, (probably due to full redraws.)
    wxSystemOptions::SetOption(wxT("mac.listctrl.always_use_generic"), 1);

    AEInstallEventHandler( kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP((AEEventHandlerProcPtr)QuitAppleEventHandler), 0, false );

    // Cache the current process serial number
    GetCurrentProcess(&m_psnCurrentProcess);
#endif


    // Commandline parsing is done in wxApp::OnInit()
    if (!wxApp::OnInit()) {
        return false;
    }

    if (g_use_sandbox) {
        wxCHANGE_UMASK(2);  // Set file creation mask to be writable by both user and group
                            // Our umask will be inherited by all our child processes
    }

    // Setup application and company information
    SetAppName(wxT("BOINC Manager"));
    SetVendorName(wxT("Space Sciences Laboratory, U.C. Berkeley"));


    // Initialize the configuration storage module
    m_pConfig = new wxConfig(GetAppName());
    wxConfigBase::Set(m_pConfig);
    wxASSERT(m_pConfig);


    // Restore Application State
    m_pConfig->SetPath(wxT("/"));
    m_pConfig->Read(wxT("AutomaticallyShutdownClient"), &m_iShutdownCoreClient, 0L);
    m_pConfig->Read(wxT("DisplayShutdownClientDialog"), &m_iDisplayExitDialog, 1L);
    m_pConfig->Read(wxT("DisableAutoStart"), &m_iBOINCMGRDisableAutoStart, 0L);
    m_pConfig->Read(wxT("Language"), &iSelectedLanguage, 0L);
    m_pConfig->Read(wxT("GUISelection"), &m_iGUISelected, BOINC_SIMPLEGUI);
    m_pConfig->Read(wxT("EventLogOpen"), &bOpenEventLog);


    // Should we abort the BOINC Manager startup process?
    if (m_bBOINCMGRAutoStarted && m_iBOINCMGRDisableAutoStart) {
        return false;
    }

    // Detect where BOINC Manager executable name.
    DetectExecutableName();

    // Detect where BOINC Manager was installed too.
    DetectRootDirectory();

    // Detect where the BOINC Data files are.
    DetectDataDirectory();


    // Switch the current directory to the BOINC Data directory
    if (!GetDataDirectory().IsEmpty()) {
    	success = wxSetWorkingDirectory(GetDataDirectory());
        if (!success) {
            if (!g_use_sandbox) {
                if (!wxDirExists(GetDataDirectory())) {
                    success = wxMkdir(GetDataDirectory(), 0777);    // Does nothing if dir exists
                }
            }
        }
    }

    if (!success) iErrorCode = -1016;

    // Initialize the BOINC Diagnostics Framework
    int dwDiagnosticsFlags =
#ifdef _DEBUG
        BOINC_DIAG_HEAPCHECKENABLED |
        BOINC_DIAG_MEMORYLEAKCHECKENABLED |
#endif
        BOINC_DIAG_DUMPCALLSTACKENABLED | 
        BOINC_DIAG_PERUSERLOGFILES |
        BOINC_DIAG_REDIRECTSTDERR |
        BOINC_DIAG_REDIRECTSTDOUT |
        BOINC_DIAG_TRACETOSTDOUT;

    diagnostics_init(dwDiagnosticsFlags, "stdoutgui", "stderrgui");

#ifdef _NDEBUG
    wxSetAssertHandler(BOINCAssertHandler);
#endif

    // Enable Logging and Trace Masks
    m_pLog = new wxLogBOINC();
    wxLog::SetActiveTarget(m_pLog);

    m_pLog->AddTraceMask(wxT("Assert"));
    m_pLog->AddTraceMask(wxT("Function Start/End"));
    m_pLog->AddTraceMask(wxT("Function Status"));


    // Initialize the internationalization module
#ifdef __WXMSW__
    // On Windows, set all locales for this thread on a per-thread basis
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
#endif
    m_pLocale = new wxLocale();
    wxASSERT(m_pLocale);

    // Look for the localization files by absolute and relative locations.
    //   preference given to the absolute location.
    m_pLocale->Init(iSelectedLanguage);
    if (!m_strBOINCMGRRootDirectory.IsEmpty()) {
        m_pLocale->AddCatalogLookupPathPrefix(
            wxString(m_strBOINCMGRRootDirectory + wxT("locale"))
        );
    }
    m_pLocale->AddCatalogLookupPathPrefix(wxT("locale"));
    m_pLocale->AddCatalog(wxT("BOINC-Manager"));
    m_pLocale->AddCatalog(wxT("BOINC-Client"));
    m_pLocale->AddCatalog(wxT("BOINC-Web"));

    InitSupportedLanguages();

	m_strISOLanguageCode = m_pLocale->GetCanonicalName();

    // Note: JAWS for Windows will only speak the context-sensitive
    // help if you use this help provider:
    wxHelpProvider::Set(new wxHelpControllerHelpProvider());

    // Enable known image types
    wxInitAllImageHandlers();

    // Initialize the skin manager
    m_pSkinManager = new CSkinManager(m_bDebugSkins);
    wxASSERT(m_pSkinManager);


    // Load desired manager skin
    m_pConfig->Read(wxT("Skin"), &strDesiredSkinName, m_pSkinManager->GetDefaultSkinName());
    m_pSkinManager->ReloadSkin(strDesiredSkinName);


#ifdef SANDBOX
    // Make sure owners, groups and permissions are correct for the current setting of g_use_sandbox
    char path_to_error[MAXPATHLEN];
    path_to_error[0] = '\0';
    
    if (!iErrorCode) {
#if (defined(__WXMAC__) && defined(_DEBUG))     // TODO: implement this for other platforms
        // GDB can't attach to applications which are running as a different user   
        //  or group, so fix up data with current user and group during debugging
        if (check_security(g_use_sandbox, true, NULL, 0)) {
            CreateBOINCUsersAndGroups();
            SetBOINCDataOwnersGroupsAndPermissions();
            SetBOINCAppOwnersGroupsAndPermissions(NULL);
        }
#endif
        iErrorCode = check_security(
            g_use_sandbox, true, path_to_error, sizeof(path_to_error)
        );
    }

    if (iErrorCode) {

        ShowApplication(true);

        if (iErrorCode == -1099) {
            strDialogMessage.Printf(
                _("You currently are not authorized to manage the client.\n\nTo run %s as this user, please:\n  - reinstall %s answering \"Yes\" to the question about\n     non-administrative users\n or\n  - contact your administrator to add you to the 'boinc_master'\n     user group."),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str(),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str()
            );
        } else {
            strDialogMessage.Printf(
                _("%s ownership or permissions are not set properly; please reinstall %s.\n(Error code %d"),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str(),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str(),
                iErrorCode
            );
            if (path_to_error[0]) {
                strDialogMessage += _(" at ");
                strDialogMessage += wxString::FromUTF8(path_to_error);
            }
            strDialogMessage += _(")");
            
            fprintf(stderr, "%s\n", (const char*)strDialogMessage.utf8_str());
        }

        wxMessageDialog* pDlg = new wxMessageDialog(
                                    NULL, 
                                    strDialogMessage, 
                                    m_pSkinManager->GetAdvanced()->GetApplicationName(), 
                                    wxOK
                                    );

        pDlg->ShowModal();
        if (pDlg)
            pDlg->Destroy();

        return false;
    }
#endif      // SANDBOX


#ifdef __WXMSW__
    // Perform any last minute checks that should keep the manager
    // from starting up.
    wxString strRebootPendingFile = 
        GetRootDirectory() + wxFileName::GetPathSeparator() + wxT("RebootPending.txt");
    
    if (wxFile::Exists(strRebootPendingFile)) {
        wxMessageDialog dialog(
            NULL,
            _("A reboot is required in order for BOINC to run properly.\nPlease reboot your computer and try again."),
            _("BOINC Manager"),
            wxOK|wxICON_ERROR
        );

        dialog.ShowModal();
        return false;
    }
#endif

    // Detect if BOINC Manager is already running, if so, bring it into the
    // foreground and then exit.
    if (DetectDuplicateInstance()) {
            return false;
    }

    // Initialize the main document
    m_pDocument = new CMainDocument();
    wxASSERT(m_pDocument);

    m_pDocument->OnInit();


    // Is there a condition in which the Simple GUI should not be used?
    if (BOINC_SIMPLEGUI == m_iGUISelected) {
        // Screen too small?
        if (wxGetDisplaySize().GetHeight() < 600) {
            m_iGUISelected = BOINC_ADVANCEDGUI;
        }
    }


    // Initialize the task bar icon
	m_pTaskBarIcon = new CTaskBarIcon(
        m_pSkinManager->GetAdvanced()->GetApplicationName(), 
        m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationDisconnectedIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationSnoozeIcon()
#ifdef __WXMAC__
        , wxTBI_CUSTOM_STATUSITEM
#endif
    );
    wxASSERT(m_pTaskBarIcon);
#ifdef __WXMAC__
    m_pMacDockIcon = new CTaskBarIcon(
        m_pSkinManager->GetAdvanced()->GetApplicationName(), 
        m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationDisconnectedIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationSnoozeIcon()
        , wxTBI_DOCK
    );
    wxASSERT(m_pMacDockIcon);
#endif

    // Startup the System Idle Detection code
    IdleTrackerAttach();
    
#ifdef __WXMAC__
    ProcessSerialNumber psn;
    ProcessInfoRec pInfo;
    OSStatus err;
    
    memset(&pInfo, 0, sizeof(pInfo));
    pInfo.processInfoLength = sizeof( ProcessInfoRec );
    err = GetProcessInformation(&m_psnCurrentProcess, &pInfo);
    if (!err) {
        psn = pInfo.processLauncher;
        memset(&pInfo, 0, sizeof(pInfo));
        pInfo.processInfoLength = sizeof( ProcessInfoRec );
        err = GetProcessInformation(&psn, &pInfo);
    }
    // Don't open main window if we were started automatically at login
    if (pInfo.processSignature == 'lgnw') {  // Login Window app
        m_bGUIVisible = false;

        // If the system was just started, we usually get a "Connection
        // failed" error if we try to connect too soon, so delay a bit.
        sleep(10);
    }
#endif

    // Show the UI
    SetActiveGUI(m_iGUISelected, m_bGUIVisible);

    if (!m_bGUIVisible) {
        ShowApplication(false);
	}

    if (bOpenEventLog) {
        DisplayEventLog(m_bGUIVisible);
        if (m_bGUIVisible && m_pFrame) {
            m_pFrame->Raise();
        }
    }
    
    return true;
}
Exemple #17
0
// App
bool MultiMC::OnInit()
{
#if __WXGTK__ || defined MSVC
	// Only works with Linux GCC or MSVC
	wxHandleFatalExceptions();
#endif
	exitAction = EXIT_NORMAL;
	startMode = START_NORMAL;
	updateQuiet = false;
	useProvidedDir = false;

	// This is necessary for the update system since it calls OnInitCmdLine
	// to set up the command line arguments that the update system uses.
	if (!wxApp::OnInit())
		return false;

#if OSX
	{
		wxFileName mmcDir = wxFileName::DirName(wxStandardPaths::Get().GetResourcesDir());
		mmcDir.Normalize();

		if (!mmcDir.DirExists())
			mmcDir.Mkdir(0777, wxPATH_MKDIR_FULL);

		wxSetWorkingDirectory(mmcDir.GetFullPath());
	}
#else
	if (!useProvidedDir)
	{
		wxFileName mmcDir (wxStandardPaths::Get().GetExecutablePath());
		wxSetWorkingDirectory(mmcDir.GetPath());
	}
	else
	{
		// do use provided directory
		wxSetWorkingDirectory(providedDir.GetFullPath());
	}
#endif

	if (!InitAppSettings())
	{
		wxLogError(_("Failed to initialize settings."));
		return false;
	}

	SetAppName(_("MultiMC"));
	InstallLangFiles();
	localeHelper.UpdateLangList();

	// Load language.
	long langID = wxLANGUAGE_UNKNOWN;
	if (settings->GetUseSystemLang())
		langID = wxLocale::GetSystemLanguage();
	else
		langID = settings->GetLanguageID();
	langID = localeHelper.FindClosestMatch(langID);

	// If no matching language is found, use English.
	if (langID == wxLANGUAGE_UNKNOWN)
	{
		langID = wxLANGUAGE_ENGLISH_US;
	}

	if (!localeHelper.SetLanguage((wxLanguage)langID))
	{
		localeHelper.SetLanguage(wxLANGUAGE_ENGLISH_US);
		wxLogError(_("Failed to set language. Language set to English."));
	}
	
	wxString cwd = wxGetCwd();
	if(cwd.Contains("!"))
	{
		wxLogError(_("MultiMC has been started from a path that contains '!':\n%s\nThis would break Minecraft. Please move it to a different place."), cwd.c_str());
		return false;
	}

	wxInitAllImageHandlers();
	wxSocketBase::Initialize();
	
	wxMemoryInputStream iconInput16(multimc16, sizeof(multimc16));
	wxMemoryInputStream iconInput32(multimc32, sizeof(multimc32));
	wxMemoryInputStream iconInput64(multimc64, sizeof(multimc64));
	wxMemoryInputStream iconInput128(multimc128, sizeof(multimc128));
	wxIcon icon16,icon32,icon64,icon128;
	icon16.CopyFromBitmap(wxBitmap(wxImage(iconInput16)));
	icon32.CopyFromBitmap(wxBitmap(wxImage(iconInput32)));
	icon64.CopyFromBitmap(wxBitmap(wxImage(iconInput64)));
	icon128.CopyFromBitmap(wxBitmap(wxImage(iconInput128)));
	AppIcons.AddIcon(icon16);
	AppIcons.AddIcon(icon32);
	AppIcons.AddIcon(icon64);
	AppIcons.AddIcon(icon128);
	
	wxFileSystem::AddHandler(new wxArchiveFSHandler);
	// 	wxFileSystem::AddHandler(new wxMemoryFSHandler);
	
	if (!settings->GetInstDir().DirExists())
		settings->GetInstDir().Mkdir();
	if (!settings->GetModsDir().DirExists())
		settings->GetModsDir().Mkdir();
	if (!settings->GetLwjglDir().DirExists())
		settings->GetLwjglDir().Mkdir();
	
	switch (startMode)
	{
	case START_NORMAL:
		{
			MainWindow *mainWin = new MainWindow();
			mainWin->SetName(wxT("MainWindow"));
			if (!wxPersistenceManager::Get().RegisterAndRestore(mainWin))
			{
				mainWin->CenterOnScreen();
			}
			SetTopWindow(mainWin);
			mainWin->Show();
			mainWin->OnStartup();
			return true;
		}

	case START_LAUNCH_INSTANCE:
		{
			MainWindow *mainWin = new MainWindow();
			mainWin->SetName(wxT("MainWindow"));
			if (!wxPersistenceManager::Get().RegisterAndRestore(mainWin))
			{
				mainWin->CenterOnScreen();
			}
			SetTopWindow(mainWin);
			mainWin->launchInstance = launchInstance;
			mainWin->OnStartup();
			mainWin->Hide();
			return true;
		}

	case START_INSTALL_UPDATE:
		InstallUpdate();
		return false;
	}

	return false;
}
Exemple #18
0
bool CodeBlocksApp::OnInit()
{
#ifdef __WXMSW__
    InitCommonControls();
#endif

    wxLog::EnableLogging(true);

    SetAppName(_T("codeblocks"));

    s_Loading              = true;
    m_pBatchBuildDialog    = nullptr;
    m_BatchExitCode        = 0;
    m_Batch                = false;
    m_BatchNotify          = false;
    m_Build                = false;
    m_ReBuild              = false;
    m_Clean                = false;
    m_HasProject           = false;
    m_HasWorkSpace         = false;
    m_SafeMode             = false;
    m_BatchWindowAutoClose = true;

    wxTheClipboard->Flush();

    wxCmdLineParser& parser = *Manager::GetCmdLineParser();
    parser.SetDesc(cmdLineDesc);

    // NOTE: crash handler explicitly disabled because it causes problems
    //       with plugins loading/unloading...
    //
    // static CrashHandler crash_handler(!m_CrashHandler);

    // we'll do this once and for all at startup
    wxFileSystem::AddHandler(new wxZipFSHandler);
    wxFileSystem::AddHandler(new wxMemoryFSHandler);
    wxXmlResource::Get()->InsertHandler(new wxToolBarAddOnXmlHandler);
    wxXmlResource::Get()->InsertHandler(new wxScrollingDialogXmlHandler);
    wxInitAllImageHandlers();
    wxXmlResource::Get()->InitAllHandlers();

    Manager::Get()->GetLogManager()->Log(F(wxT("Starting ") + appglobals::AppName + wxT(" ") +
                                           appglobals::AppActualVersionVerb + wxT(" ") +
                                           appglobals::AppBuildTimestamp));

    try
    {
    #if (wxUSE_ON_FATAL_EXCEPTION == 1)
        wxHandleFatalExceptions(true);
    #endif

        InitExceptionHandler();

        delete wxMessageOutput::Set(new cbMessageOutputNull); // No output. (suppress warnings about unknown options from plugins)
        if (ParseCmdLine(nullptr) == -1) // only abort if '--help' was passed in the command line
        {
            delete wxMessageOutput::Set(new wxMessageOutputMessageBox);
            parser.Usage();
            return false;
        }

        if ( !LoadConfig() )
            return false;

        // set safe-mode appropriately
        PluginManager::SetSafeMode(m_SafeMode);

        // If not in batch mode, and no startup-script defined, initialise XRC
        if(!m_Batch && m_Script.IsEmpty() && !InitXRCStuff())
            return false;

        InitLocale();

        if (m_DDE && !m_Batch && Manager::Get()->GetConfigManager(_T("app"))->ReadBool(_T("/environment/use_ipc"), true))
        {
            // Create a new client
            DDEClient *client = new DDEClient;
            DDEConnection* connection = nullptr;
            wxLogNull ln; // own error checking implemented -> avoid debug warnings
            connection = (DDEConnection *)client->MakeConnection(_T("localhost"), F(DDE_SERVICE, wxGetUserId().wx_str()), DDE_TOPIC);

            if (connection)
            {
                // don't eval here just forward the whole command line to the other instance
                wxString cmdLine;
                for (int i = 1 ; i < argc; ++i)
                    cmdLine += wxString(argv[i]) + _T(' ');

                if ( !cmdLine.IsEmpty() )
                {
                    // escape openings and closings so it is easily possible to find the end on the rx side
                    cmdLine.Replace(_T("("), _T("\\("));
                    cmdLine.Replace(_T(")"), _T("\\)"));
                    connection->Execute(_T("[CmdLine({") + cmdLine + _T("})]"));
                }

                // On Linux, C::B has to be raised explicitly if it's wanted
                if (Manager::Get()->GetConfigManager(_T("app"))->ReadBool(_T("/environment/raise_via_ipc"), true))
                    connection->Execute(_T("[Raise]"));
                connection->Disconnect();
                delete connection;
                delete client;

                // return false to end the application
                return false;
            }
            // free memory DDE-/IPC-clients, if we are here connection could not be established and there is no need to free it
            delete client;
        }
        // Now we can start the DDE-/IPC-Server, if we did it earlier we would connect to ourselves
        if (m_DDE && !m_Batch)
        {
            g_DDEServer = new DDEServer(nullptr);
            g_DDEServer->Create(F(DDE_SERVICE, wxGetUserId().wx_str()));
        }

        m_pSingleInstance = nullptr;
        if (   Manager::Get()->GetConfigManager(_T("app"))->ReadBool(_T("/environment/single_instance"), true)
            && !parser.Found(_T("multiple-instance")) )
        {
            const wxString name = wxString::Format(_T("Code::Blocks-%s"), wxGetUserId().wx_str());

            m_pSingleInstance = new wxSingleInstanceChecker(name, ConfigManager::GetTempFolder());
            if (m_pSingleInstance->IsAnotherRunning())
            {
                /* NOTE: Due to a recent change in logging code, this visual warning got disabled.
                   So the wxLogError() has been changed to a cbMessageBox(). */
                cbMessageBox(_("Another program instance is already running.\nCode::Blocks is currently configured to only allow one running instance.\n\nYou can access this Setting under the menu item 'Environment'."),
                            _T("Code::Blocks"), wxOK | wxICON_ERROR);
                return false;
            }
        }
        // Splash screen moved to this place, otherwise it would be short visible, even if we only pass filenames via DDE/IPC
        // we also don't need it, if only a single instance is allowed
        Splash splash(!m_Batch && m_Script.IsEmpty() && m_Splash &&
                      Manager::Get()->GetConfigManager(_T("app"))->ReadBool(_T("/environment/show_splash"), true));
        InitDebugConsole();

        Manager::SetBatchBuild(m_Batch || !m_Script.IsEmpty());
        Manager::Get()->GetScriptingManager();
        MainFrame* frame = nullptr;
        frame = InitFrame();
        m_Frame = frame;

        // plugins loaded -> check command line arguments again
        delete wxMessageOutput::Set(new wxMessageOutputBest); // warn about unknown options
        if ( ParseCmdLine(m_Frame) == 0 )
        {
            if (Manager::Get()->GetConfigManager(_T("app"))->ReadBool(_T("/environment/blank_workspace"), true) == false)
                Manager::Get()->GetProjectManager()->LoadWorkspace();
        }

        if (m_SafeMode) wxLog::EnableLogging(true); // re-enable logging in safe-mode

        if (m_Batch)
        {
            Manager::SetAppStartedUp(true);

            // the compiler plugin might be waiting for this
            CodeBlocksEvent event(cbEVT_APP_STARTUP_DONE);
            Manager::Get()->ProcessEvent(event);

            Manager::Get()->RegisterEventSink(cbEVT_COMPILER_FINISHED, new cbEventFunctor<CodeBlocksApp, CodeBlocksEvent>(this, &CodeBlocksApp::OnBatchBuildDone));
            s_Loading = false;
            LoadDelayedFiles(frame);

            BatchJob();
            frame->Close();
            return true;
        }

        if (!m_Script.IsEmpty())
        {
            s_Loading = false;
            LoaderBase* loader = Manager::Get()->GetFileManager()->Load(m_Script);

            if (loader->GetData())
                Manager::Get()->GetScriptingManager()->LoadBuffer(cbC2U(loader->GetData()));

            delete loader;
            frame->Close();
            return true;
        }

        CheckVersion();

        // run startup script
        try
        {
            wxString startup = ConfigManager::LocateDataFile(_T("startup.script"), sdScriptsUser | sdScriptsGlobal);
            if (!startup.IsEmpty())
                Manager::Get()->GetScriptingManager()->LoadScript(startup);
        }
        catch (SquirrelError& exception)
        {
            Manager::Get()->GetScriptingManager()->DisplayErrors(&exception);
        }
        Manager::ProcessPendingEvents();

        // finally, show the app
        splash.Hide();
        SetTopWindow(frame);
        frame->Show();

        frame->StartupDone();

        frame->ShowTips(); // this func checks if the user wants tips, so no need to check here

        if (platform::windows)
            InitAssociations();

        s_Loading = false;

        LoadDelayedFiles(frame);
        AttachDebugger();
        Manager::Get()->GetProjectManager()->WorkspaceChanged();

        // all done
        Manager::SetAppStartedUp(true);

        CodeBlocksEvent event(cbEVT_APP_STARTUP_DONE);
        Manager::Get()->ProcessEvent(event);

        return true;
    }
    catch (cbException& exception)
    {
        exception.ShowErrorMessage();
    }
    catch (SquirrelError& exception)
    {
        Manager::Get()->GetScriptingManager()->DisplayErrors(&exception);
    }
    catch (const char* message)
    {
        wxSafeShowMessage(_T("Exception"), cbC2U(message));
    }
    catch (...)
    {
        wxSafeShowMessage(_T("Exception"), _T("Unknown exception was raised. The application will terminate immediately..."));
    }
    // if we reached here, return error
    return false;
}
Exemple #19
0
///////////////////////////
// Initialization function
// -----------------------
// Gets called when application starts, creates MainFrame
bool AegisubApp::OnInit() {
	try {
		// Initialize randomizer
		srand(time(NULL));

		// App name
		SetAppName(_T("Aegisub"));
		#ifndef _DEBUG
		wxHandleFatalExceptions(true);
		#endif

		// Set config file
		GetFullPath(argv[0]);
		GetFolderName();
		Options.SetFile(folderName + _T("/config.dat"));
		Options.Load();
		AssTime::UseMSPrecision = Options.AsBool(_T("Use nonstandard Milisecond Times"));
		AssDialogue::keepData = Options.AsBool(_T("Keep raw dialogue data"));

		// Set hotkeys file
		Hotkeys.SetFile(folderName + _T("/hotkeys.dat"));
		Hotkeys.Load();

#ifdef __WINDOWS__
		// Set locale
		int lang = Options.AsInt(_T("Locale Code"));
		if (lang == -1) {
			lang = locale.PickLanguage();
			Options.SetInt(_T("Locale Code"),lang);
			Options.Save();
		}
		locale.Init(lang);
#else
		locale.Init(wxLocale::GetSystemLanguage());
#endif

		// Load export filters
		AssExportFilterChain::PrepareFilters();

		// Set association
		RegistryAssociate();

		// Get parameter subs
		wxArrayString subs;
		for (int i=1;i<argc;i++) {
			subs.Add(argv[i]);
		}

		// Open main frame
		frame = new FrameMain(subs);
		frame->Show(true);
		SetTopWindow(frame);
	}

	catch (const wchar_t *err) {
		wxMessageBox(err,_T("Fatal error while initializing"));
		return false;
	}

	catch (...) {
		wxMessageBox(_T("Unhandled exception"),_T("Fatal error while initializing"));
		return false;
	}

	return true;
}
Exemple #20
0
bool CodeLiteApp::OnInit()
{
#if defined(__WXGTK__) || defined(__WXMAC__)
    // block signal pipe
    sigset_t mask_set;
    sigemptyset( &mask_set );
    sigaddset(&mask_set, SIGPIPE);
    sigprocmask(SIG_SETMASK, &mask_set, NULL);

    // Handle sigchld
    struct sigaction sa;
    sigfillset(&sa.sa_mask);
    sa.sa_handler = ChildTerminatedSingalHandler;
    sa.sa_flags = 0;
    sigaction(SIGCHLD, &sa, NULL);

#ifdef __WXGTK__
    // Insall signal handlers
    signal(SIGSEGV, WaitForDebugger);
    signal(SIGABRT, WaitForDebugger);
#endif

#endif

    wxSocketBase::Initialize();

#if wxUSE_ON_FATAL_EXCEPTION
    //trun on fatal exceptions handler
    wxHandleFatalExceptions(true);
#endif

#ifdef __WXMSW__
    // as described in http://jrfonseca.dyndns.org/projects/gnu-win32/software/drmingw/
    // load the exception handler dll so we will get Dr MinGW at runtime
    m_handler = LoadLibrary(wxT("exchndl.dll"));

    // Enable this process debugging priviliges
    //EnableDebugPriv();
#endif


    // Init resources and add the PNG handler
    wxSystemOptions::SetOption(_T("msw.remap"), 0);
    wxSystemOptions::SetOption("msw.notebook.themed-background", 0);
    wxXmlResource::Get()->InitAllHandlers();
    wxImage::AddHandler( new wxPNGHandler );
    wxImage::AddHandler( new wxCURHandler );
    wxImage::AddHandler( new wxICOHandler );
    wxImage::AddHandler( new wxXPMHandler );
    wxImage::AddHandler( new wxGIFHandler );
    InitXmlResource();

    wxLog::EnableLogging(false);
    wxString homeDir(wxEmptyString);

    //parse command line
    wxCmdLineParser parser;
    parser.SetDesc(cmdLineDesc);
    parser.SetCmdLine(wxAppBase::argc, wxAppBase::argv);
    if (parser.Parse() != 0) {
        return false;
    }

    if (parser.Found(wxT("h"))) {
        // print usage
        parser.Usage();
        return false;
    }

    if (parser.Found(wxT("n"))) {
        // Load codelite without plugins
        SetPluginLoadPolicy(PP_None);
    }

    wxString plugins;
    if (parser.Found(wxT("p"), &plugins)) {
        wxArrayString pluginsArr = ::wxStringTokenize(plugins, wxT(","));
        // Trim and make lower case
        for(size_t i=0; i<pluginsArr.GetCount(); i++) {
            pluginsArr.Item(i).Trim().Trim(false).MakeLower();
        }

        // Load codelite without plugins
        SetAllowedPlugins(pluginsArr);
        SetPluginLoadPolicy(PP_FromList);
    }

    wxString newBaseDir(wxEmptyString);
    if (parser.Found(wxT("b"), &newBaseDir)) {
#if defined (__WXMSW__)
        homeDir = newBaseDir;
#else
        wxLogDebug("Ignoring the Windows-only --basedir option as not running Windows");
#endif
    }
 
    wxString newDataDir(wxEmptyString);
    if (parser.Found(wxT("d"), &newDataDir)) {
        clStandardPaths::Get().SetUserDataDir(newDataDir);
    }
    
    // Copy gdb pretty printers from the installation folder to a writeable location
    // this is  needed because python complies the files and in most cases the user
    // running codelite has no write permissions to /usr/share/codelite/...
    DoCopyGdbPrinters();
    
    // Since GCC 4.8.2 gcc has a default colored output
    // which breaks codelite output parsing
    // to disable this, we need to set GCC_COLORS to an empty
    // string.
    // https://sourceforge.net/p/codelite/bugs/946/
    // http://gcc.gnu.org/onlinedocs/gcc/Language-Independent-Options.html
    ::wxSetEnv("GCC_COLORS", "");
    
#if defined (__WXGTK__)
    if (homeDir.IsEmpty()) {
        SetAppName(wxT("codelite"));
        homeDir = clStandardPaths::Get().GetUserDataDir(); // By default, ~/Library/Application Support/codelite or ~/.codelite
        if (!wxFileName::Exists(homeDir)) {
            wxLogNull noLog;
            wxFileName::Mkdir(homeDir, wxS_DIR_DEFAULT,  wxPATH_MKDIR_FULL);
            wxCHECK_MSG(wxFileName::DirExists(homeDir), false, "Failed to create the requested data dir");
        }

        //Create the directory structure
        wxLogNull noLog;
        wxMkdir(homeDir);
        wxMkdir(homeDir + wxT("/lexers/"));
        wxMkdir(homeDir + wxT("/rc/"));
        wxMkdir(homeDir + wxT("/images/"));
        wxMkdir(homeDir + wxT("/templates/"));
        wxMkdir(homeDir + wxT("/config/"));
        wxMkdir(homeDir + wxT("/tabgroups/"));

        //copy the settings from the global location if needed
        wxString installPath( INSTALL_DIR, wxConvUTF8 );
        if ( ! CopySettings(homeDir, installPath ) ) return false;
        ManagerST::Get()->SetInstallDir( installPath );

    } else {
        wxFileName fn(homeDir);
        fn.MakeAbsolute();
        ManagerST::Get()->SetInstallDir( fn.GetFullPath() );
    }

#elif defined (__WXMAC__)
    SetAppName(wxT("codelite"));
    homeDir = clStandardPaths::Get().GetUserDataDir();
    if (!wxFileName::Exists(homeDir)) {
        wxLogNull noLog;
        wxFileName::Mkdir(homeDir, wxS_DIR_DEFAULT,  wxPATH_MKDIR_FULL);
        wxCHECK_MSG(wxFileName::DirExists(homeDir), false, "Failed to create the requested data dir");
    }

    {
        wxLogNull noLog;

        //Create the directory structure
        wxMkdir(homeDir);
        wxMkdir(homeDir + wxT("/lexers/"));
        wxMkdir(homeDir + wxT("/rc/"));
        wxMkdir(homeDir + wxT("/images/"));
        wxMkdir(homeDir + wxT("/templates/"));
        wxMkdir(homeDir + wxT("/config/"));
        wxMkdir(homeDir + wxT("/tabgroups/"));
    }

    wxString installPath( MacGetBasePath() );
    ManagerST::Get()->SetInstallDir( installPath );
    //copy the settings from the global location if needed
    CopySettings(homeDir, installPath);
    
#else //__WXMSW__
    if (homeDir.IsEmpty()) { //did we got a basedir from user?
        homeDir = ::wxGetCwd();
    }
    wxFileName fnHomdDir(homeDir + wxT("/"));

    // try to locate the menu/rc.xrc file
    wxFileName fn(homeDir + wxT("/rc"), wxT("menu.xrc"));
    if (!fn.FileExists()) {
        // we got wrong home directory
        wxFileName appFn( wxAppBase::argv[0] );
        homeDir = appFn.GetPath();
    }

    if (fnHomdDir.IsRelative()) {
        fnHomdDir.MakeAbsolute();
        homeDir = fnHomdDir.GetPath();
    }

    ManagerST::Get()->SetInstallDir( homeDir );
#endif

    // Update codelite revision and Version
    EditorConfigST::Get()->Init(clGitRevision, wxT("2.0.2") );

    ManagerST::Get()->SetOriginalCwd(wxGetCwd());
    ::wxSetWorkingDirectory(homeDir);
    // Load all of the XRC files that will be used. You can put everything
    // into one giant XRC file if you wanted, but then they become more
    // diffcult to manage, and harder to reuse in later projects.
    // The menubar
    if (!wxXmlResource::Get()->Load( DoFindMenuFile(ManagerST::Get()->GetInstallDir(), wxT("2.0")) ) )
        return false;

    // keep the startup directory
    ManagerST::Get()->SetStarupDirectory(::wxGetCwd());

    // set the performance output file name
    PERF_OUTPUT(wxString::Format(wxT("%s/codelite.perf"), wxGetCwd().c_str()).mb_str(wxConvUTF8));

    // Initialize the configuration file locater
    ConfFileLocator::Instance()->Initialize(ManagerST::Get()->GetInstallDir(), ManagerST::Get()->GetStarupDirectory());

    Manager *mgr = ManagerST::Get();

    // set the CTAGS_REPLACEMENT environment variable
    wxSetEnv(wxT("CTAGS_REPLACEMENTS"), ManagerST::Get()->GetStarupDirectory() + wxT("/ctags.replacements"));

    long style = wxSIMPLE_BORDER;
#if defined (__WXMSW__) || defined (__WXGTK__)
    style |= wxFRAME_NO_TASKBAR;

#else // Mac
    wxUnusedVar(style);

#endif

    //read the last frame size from the configuration file
    // Initialise editor configuration files
#ifdef __WXMSW__
    {
        wxLogNull noLog;
        wxFileName::Mkdir(clStandardPaths::Get().GetUserDataDir(), wxS_DIR_DEFAULT,  wxPATH_MKDIR_FULL);
    }
#endif

    EditorConfigST::Get()->SetInstallDir( mgr->GetInstallDir() );
    EditorConfig *cfg = EditorConfigST::Get();
    if ( !cfg->Load() ) {
        CL_ERROR(wxT("Failed to load configuration file: %s/config/codelite.xml"), wxGetCwd().c_str());
        return false;
    }

#ifdef __WXGTK__
    bool redirect = clConfig::Get().Read("RedirectLogOutput", true);
    if (redirect) {
        // Redirect stdout/error to a file
        wxFileName stdout_err(clStandardPaths::Get().GetUserDataDir(), "codelite-stdout-stderr.log");
        FILE* new_stdout = ::freopen(stdout_err.GetFullPath().mb_str(wxConvISO8859_1).data(), "a+b", stdout);
        FILE* new_stderr = ::freopen(stdout_err.GetFullPath().mb_str(wxConvISO8859_1).data(), "a+b", stderr);
        wxUnusedVar(new_stderr);
        wxUnusedVar(new_stdout);
    }
#endif

    // Set the log file verbosity
    FileLogger::Get()->SetVerbosity( clConfig::Get().Read("LogVerbosity", FileLogger::Error) );
    CL_DEBUG(wxT("Starting codelite..."));

    // check for single instance
    if ( !IsSingleInstance(parser, ManagerST::Get()->GetOriginalCwd()) ) {
        return false;
    }

    //---------------------------------------------------------
    // Set environment variable for CodeLiteDir (make it first
    // on the list so it can be used by other variables)
    //---------------------------------------------------------
    EvnVarList vars;
    EnvironmentConfig::Instance()->Load();
    EnvironmentConfig::Instance()->ReadObject(wxT("Variables"), &vars);

    vars.InsertVariable(wxT("Default"), wxT("CodeLiteDir"), ManagerST::Get()->GetInstallDir());
    EnvironmentConfig::Instance()->WriteObject(wxT("Variables"), &vars);

    //---------------------------------------------------------
    
#ifdef __WXMSW__

    // Read registry values
    MSWReadRegistry();

#endif

    GeneralInfo inf;
    cfg->ReadObject(wxT("GeneralInfo"), &inf);

    // Set up the locale if appropriate
    if (EditorConfigST::Get()->GetOptions()->GetUseLocale()) {
        int preferredLocale = wxLANGUAGE_ENGLISH;
        // The locale had to be saved as the canonical locale name, as the wxLanguage enum wasn't consistent between wx versions
        wxString preferredLocalename = EditorConfigST::Get()->GetOptions()->GetPreferredLocale();
        if (!preferredLocalename.IsEmpty()) {
            const wxLanguageInfo* info = wxLocale::FindLanguageInfo(preferredLocalename);
            if (info) {
                preferredLocale = info->Language;
                if (preferredLocale == wxLANGUAGE_UNKNOWN) {
                    preferredLocale = wxLANGUAGE_ENGLISH;
                }
            }
        }

#if defined (__WXGTK__)
        // Cater for a --prefix= build. This gets added automatically to the search path for catalogues.
        // So hack in the standard ones too, otherwise wxstd.mo will be missed
        wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/share/locale"));
        wxLocale::AddCatalogLookupPathPrefix(wxT("/usr/local/share/locale"));

#elif defined(__WXMSW__)
        wxLocale::AddCatalogLookupPathPrefix(ManagerST::Get()->GetInstallDir() + wxT("\\locale"));
#endif

        // This has to be done before the catalogues are added, as otherwise the wrong one (or none) will be found
        m_locale.Init(preferredLocale);

        bool codelitemo_found = m_locale.AddCatalog(wxT("codelite"));
        if (!codelitemo_found) {
            m_locale.AddCatalog(wxT("CodeLite")); // Hedge bets re our spelling
        }

        if (!codelitemo_found) {
            // I wanted to 'un-init' the locale if no translations were found
            // as otherwise, in a RTL locale, menus, dialogs etc will be displayed RTL, in English...
            // However I couldn't find a way to do this
        }
    }

    // Append the binary's dir to $PATH. This makes codelite-cc available even for a --prefix= installation
#if defined(__WXMSW__)
    wxChar pathsep(wxT(';'));
#else
    wxChar pathsep(wxT(':'));
#endif
    wxString oldpath;
    wxGetEnv(wxT("PATH"), &oldpath);
    wxFileName execfpath(wxStandardPaths::Get().GetExecutablePath());
    wxSetEnv(wxT("PATH"), oldpath + pathsep + execfpath.GetPath());
    wxString newpath;
    wxGetEnv(wxT("PATH"), &newpath);

    // Don't show the splash screen when opening codelite to view
    // a file, this is done to reduce the load time
//    if(parser.GetParamCount() > 0)
//        showSplash = false;

    // Create the main application window
    clMainFrame::Initialize( parser.GetParamCount() == 0 );
    m_pMainFrame = clMainFrame::Get();
    m_pMainFrame->Show(TRUE);
    SetTopWindow(m_pMainFrame);

    long lineNumber(0);
    parser.Found(wxT("l"), &lineNumber);
    if (lineNumber > 0) {
        lineNumber--;
    } else {
        lineNumber = 0;
    }

    for (size_t i=0; i< parser.GetParamCount(); i++) {
        wxString argument = parser.GetParam(i);

        //convert to full path and open it
        wxFileName fn(argument);
        fn.MakeAbsolute(ManagerST::Get()->GetOriginalCwd());

        if (fn.GetExt() == wxT("workspace")) {
            ManagerST::Get()->OpenWorkspace(fn.GetFullPath());
        } else {
            clMainFrame::Get()->GetMainBook()->OpenFile(fn.GetFullPath(), wxEmptyString, lineNumber);
        }
    }

    wxLogMessage(wxString::Format(wxT("Install path: %s"), ManagerST::Get()->GetInstallDir().c_str()));
    wxLogMessage(wxString::Format(wxT("Startup Path: %s"), ManagerST::Get()->GetStarupDirectory().c_str()));

#ifdef __WXGTK__
    // Needed on GTK
    if (clMainFrame::Get()->GetMainBook()->GetActiveEditor() == NULL) {
        clMainFrame::Get()->GetOutputPane()->GetBuildTab()->SetFocus();
    }
#endif

    // Especially with the OutputView open, CodeLite was consuming 50% of a cpu, mostly in updateui
    // The next line limits the frequency of UpdateUI events to every 100ms
    wxUpdateUIEvent::SetUpdateInterval(100);

    return TRUE;
}
//! @brief Initializes the application.
//!
//! It will open the main window and connect default to server or open the connect window.
bool SpringLobbyApp::OnInit()
{

	wxSetEnv(_T("UBUNTU_MENUPROXY"), _T("0"));
	//this triggers the Cli Parser amongst other stuff
	if (!wxApp::OnInit())
		return false;
	SetAppName(m_appname);
#if wxUSE_ON_FATAL_EXCEPTION
	wxHandleFatalExceptions(!m_crash_handle_disable);
#else
	try {
#endif

	const wxString m_log_file_path = SlPaths::GetLobbyWriteDir() + "springlobby.log";

	//initialize all loggers, we'll use the returned pointer to set correct parent window later
	wxLogWindow* loggerwin = Logger::InitializeLoggingTargets(0, m_log_console, m_log_file_path, m_log_window_show, m_log_verbosity);

	wxLogMessage(_T("%s started"), TowxString(GetSpringlobbyAgent()).c_str());

	//this needs to called _before_ mainwindow instance is created
	wxInitAllImageHandlers();
	wxFileSystem::AddHandler(new wxZipFSHandler);
	wxSocketBase::Initialize();


	m_translationhelper = new wxTranslationHelper(GetAppName().Lower(), getLocalePath());

	const std::string configdir = SlPaths::GetConfigfileDir();
	wxLogMessage("Config dir: %s", configdir.c_str());
	SlPaths::mkDir(configdir);

	if (cfg().ReadBool(_T("/ResetLayout"))) {
		wxLogMessage("Resetting Layout...");
		//we do this early on and reset the config var a little later so we can save a def. perps once mw is created
		sett().RemoveLayouts();
		cfg().Write(_T( "/ResetLayout" ), false);
		ui().mw().SavePerspectives(_T("SpringLobby-default"));
	}

	if (SlPaths::IsPortableMode()) {
		// change write path for downloader if in portable mode
		fileSystem->setWritePath(SlPaths::GetExecutableFolder());
	} else {
		// only search if not in portable mode
		SlPaths::SetSpringBinary(SlPaths::GetCurrentUsedSpringIndex(), SlPaths::GetSpringBinary());
		SlPaths::SetUnitSync(SlPaths::GetCurrentUsedSpringIndex(), SlPaths::GetUnitSync());
	}
	wxLogMessage("Configuring Unitsync...");
	// configure unitsync paths before trying to load
	SlPaths::ReconfigureUnitsync();

	sett().Setup(m_translationhelper);

	notificationManager(); //needs to be initialized too

	wxLogMessage("Showing Main Window");
	ui().ShowMainWindow();
	SetTopWindow(&ui().mw());
	ui().mw().SetLogWin(loggerwin);

	//unitsync first load, FIXME move to a thread!
	wxLogMessage("Refreshing Spring Version List...");
	SlPaths::RefreshSpringVersionList();
	if (LSL::usync().ReloadUnitSyncLib()) {
		GlobalEventManager::Instance()->Send(GlobalEventManager::OnUnitsyncReloaded);
	} else {
		wxLogWarning("Couldn't load unitsync");
	}

	wxLogWarning("%s", TowxString(GetSpringlobbyInfo()).c_str());

	ui().OnInit();

#if !wxUSE_ON_FATAL_EXCEPTION
}
catch (std::exception& ex)
{
	wxLogError(_T("Error had happened: " + wxString(ex.what())));
}
#endif

return true;
}
Exemple #22
0
bool DolphinApp::OnInit()
{
	InitLanguageSupport();

	// Declarations and definitions
	bool UseDebugger = false;
	bool UseLogger = false;
	bool selectVideoBackend = false;
	bool selectAudioEmulation = false;

	wxString videoBackendName;
	wxString audioEmulationName;

#if wxUSE_CMDLINE_PARSER // Parse command lines
	wxCmdLineEntryDesc cmdLineDesc[] =
	{
		{
			wxCMD_LINE_SWITCH, wxS("h"), wxS("help"),
			_("Show this help message"),
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP
		},
		{
			wxCMD_LINE_SWITCH, wxS("d"), wxS("debugger"),
			_("Opens the debugger"),
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_SWITCH, wxS("l"), wxS("logger"),
			_("Opens the logger"),
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, wxS("e"), wxS("exec"),
			_("Loads the specified file (DOL,ELF,GCM,ISO,WAD)"),
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_SWITCH, wxS("b"), wxS("batch"),
			_("Exit Dolphin with emulator"),
			wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, wxS("V"), wxS("video_backend"),
			_("Specify a video backend"),
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_OPTION, wxS("A"), wxS("audio_emulation"),
			_("Low level (LLE) or high level (HLE) audio"),
			wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
		},
		{
			wxCMD_LINE_NONE, NULL, NULL, NULL, wxCMD_LINE_VAL_NONE, 0
		}
	};

	// Gets the command line parameters
	wxCmdLineParser parser(cmdLineDesc, argc, argv);
	if (parser.Parse() != 0)
	{
		return false;
	} 

	UseDebugger = parser.Found(wxT("debugger"));
	UseLogger = parser.Found(wxT("logger"));
	LoadFile = parser.Found(wxT("exec"), &FileToLoad);
	BatchMode = parser.Found(wxT("batch"));
	selectVideoBackend = parser.Found(wxT("video_backend"),
		&videoBackendName);
	// TODO:  This currently has no effect.  Implement or delete.
	selectAudioEmulation = parser.Found(wxT("audio_emulation"),
		&audioEmulationName);
#endif // wxUSE_CMDLINE_PARSER

#if defined _DEBUG && defined _WIN32
	int tmpflag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	tmpflag |= _CRTDBG_DELAY_FREE_MEM_DF;
	_CrtSetDbgFlag(tmpflag);
#endif

	// Register message box and translation handlers
	RegisterMsgAlertHandler(&wxMsgAlert);
	RegisterStringTranslator(&wxStringTranslator);

	// "ExtendedTrace" looks freakin dangerous!!!
#ifdef _WIN32
	EXTENDEDTRACEINITIALIZE(".");
	SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter);
#elif wxUSE_ON_FATAL_EXCEPTION
	wxHandleFatalExceptions(true);
#endif

	// TODO: if First Boot
	if (!cpu_info.bSSE2) 
	{
		PanicAlertT("Hi,\n\nDolphin requires that your CPU has support for SSE2 extensions.\n"
				"Unfortunately your CPU does not support them, so Dolphin will not run.\n\n"
				"Sayonara!\n");
		return false;
	}

#ifdef _WIN32
	if (!wxSetWorkingDirectory(wxString(File::GetExeDirectory().c_str(), *wxConvCurrent)))
	{
		INFO_LOG(CONSOLE, "set working directory failed");
	}
#else
	//create all necessary directories in user directory
	//TODO : detect the revision and upgrade where necessary
	File::CopyDir(std::string(SHARED_USER_DIR GAMECONFIG_DIR DIR_SEP),
			File::GetUserPath(D_GAMECONFIG_IDX));
	File::CopyDir(std::string(SHARED_USER_DIR MAPS_DIR DIR_SEP),
			File::GetUserPath(D_MAPS_IDX));
	File::CopyDir(std::string(SHARED_USER_DIR SHADERS_DIR DIR_SEP),
			File::GetUserPath(D_SHADERS_IDX));
	File::CopyDir(std::string(SHARED_USER_DIR WII_USER_DIR DIR_SEP),
			File::GetUserPath(D_WIIUSER_IDX));
	File::CopyDir(std::string(SHARED_USER_DIR OPENCL_DIR DIR_SEP),
			File::GetUserPath(D_OPENCL_IDX));

	if (!File::Exists(File::GetUserPath(D_CONFIG_IDX)))
		File::CreateFullPath(File::GetUserPath(D_CONFIG_IDX));
	if (!File::Exists(File::GetUserPath(D_GCUSER_IDX)))
		File::CreateFullPath(File::GetUserPath(D_GCUSER_IDX));
	if (!File::Exists(File::GetUserPath(D_CACHE_IDX)))
		File::CreateFullPath(File::GetUserPath(D_CACHE_IDX));
	if (!File::Exists(File::GetUserPath(D_DUMPDSP_IDX)))
		File::CreateFullPath(File::GetUserPath(D_DUMPDSP_IDX));
	if (!File::Exists(File::GetUserPath(D_DUMPTEXTURES_IDX)))
		File::CreateFullPath(File::GetUserPath(D_DUMPTEXTURES_IDX));
	if (!File::Exists(File::GetUserPath(D_HIRESTEXTURES_IDX)))
		File::CreateFullPath(File::GetUserPath(D_HIRESTEXTURES_IDX));
	if (!File::Exists(File::GetUserPath(D_SCREENSHOTS_IDX)))
		File::CreateFullPath(File::GetUserPath(D_SCREENSHOTS_IDX));
	if (!File::Exists(File::GetUserPath(D_STATESAVES_IDX)))
		File::CreateFullPath(File::GetUserPath(D_STATESAVES_IDX));
	if (!File::Exists(File::GetUserPath(D_MAILLOGS_IDX)))
		File::CreateFullPath(File::GetUserPath(D_MAILLOGS_IDX));
#endif

	LogManager::Init();
	SConfig::Init();
	VideoBackend::PopulateList();
	WiimoteReal::LoadSettings();

	if (selectVideoBackend && videoBackendName != wxEmptyString)
		SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend =
			std::string(videoBackendName.mb_str());

	VideoBackend::ActivateBackend(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend);

	// Enable the PNG image handler for screenshots
	wxImage::AddHandler(new wxPNGHandler);

	SetEnableAlert(SConfig::GetInstance().m_LocalCoreStartupParameter.bUsePanicHandlers);

	int x = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosX;
	int y = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosY;
	int w = SConfig::GetInstance().m_LocalCoreStartupParameter.iWidth;
	int h = SConfig::GetInstance().m_LocalCoreStartupParameter.iHeight;

	// The following is not needed with X11, where window managers
	// do not allow windows to be created off the desktop.
#ifdef _WIN32
	// Out of desktop check
	HWND hDesktop = GetDesktopWindow();
	RECT rc;
	GetWindowRect(hDesktop, &rc);
	if (rc.right < x + w || rc.bottom < y + h)
		x = y = wxDefaultCoord;
#elif defined __APPLE__
	if (y < 1)
		y = wxDefaultCoord;
#endif

	main_frame = new CFrame((wxFrame*)NULL, wxID_ANY,
				wxString::FromAscii(svn_rev_str),
				wxPoint(x, y), wxSize(w, h),
				UseDebugger, BatchMode, UseLogger);
	SetTopWindow(main_frame);
	main_frame->SetMinSize(wxSize(400, 300));

	// Postpone final actions until event handler is running.
	// Updating the game list makes use of wxProgressDialog which may
	// only be run after OnInit() when the event handler is running.
	m_afterinit = new wxTimer(this, wxID_ANY);
	m_afterinit->Start(1, wxTIMER_ONE_SHOT);

	return true;
}
Exemple #23
0
/* MainApp::OnInit
 * Application initialization, run when program is started
 *******************************************************************/
bool MainApp::OnInit()
{
	// Set locale to C so that the tokenizer will work properly
	// even in locales where the decimal separator is a comma.
	setlocale(LC_ALL, "C");

	// Init global variables
	Global::error = "";
	ArchiveManager::getInstance();
	init_ok = false;

	// Init variables
	action_invalid = new SAction("invalid", "Invalid Action", "", "Something's gone wrong here");

	// Setup system options
	wxSystemOptions::SetOption("mac.listctrl.always_use_generic", 1);

	// Set application name (for wx directory stuff)
#ifdef __WINDOWS__
	wxApp::SetAppName("SLADE3");
#else
	wxApp::SetAppName("slade3");
#endif

	// Handle exceptions using wxDebug stuff, but only in release mode
#ifdef NDEBUG
	wxHandleFatalExceptions(true);
#endif

	// Init application directories
	if (!initDirectories())
		return false;

	// Load image handlers
	wxInitAllImageHandlers();

	// Init logfile
	initLogFile();

	// Init keybinds
	KeyBind::initBinds();

	// Load configuration file
	wxLogMessage("Loading configuration");
	readConfigFile();
	Global::log_verbosity = log_verbosity;

	// Check that SLADE.pk3 can be found
	wxLogMessage("Loading resources");
	theArchiveManager->init();
	if (!theArchiveManager->resArchiveOK())
	{
		wxMessageBox("Unable to find slade.pk3, make sure it exists in the same directory as the SLADE executable", "Error", wxICON_ERROR);
		return false;
	}

	// Init lua
	Lua::init();

	// Calculate scaling factor (from system ppi)
	wxMemoryDC dc;
	Global::ppi_scale = (double)(dc.GetPPI().x) / 96.0;

	// Show splash screen
	theSplashWindow->init();
	theSplashWindow->show("Starting up...");

	// Init SImage formats
	SIFormat::initFormats();

	// Load program icons
	wxLogMessage("Loading icons");
	loadIcons();

	// Load program fonts
	Drawing::initFonts();

	// Load entry types
	wxLogMessage("Loading entry types");
	EntryDataFormat::initBuiltinFormats();
	EntryType::loadEntryTypes();

	// Load text languages
	wxLogMessage("Loading text languages");
	TextLanguage::loadLanguages();

	// Init text stylesets
	wxLogMessage("Loading text style sets");
	StyleSet::loadResourceStyles();
	StyleSet::loadCustomStyles();

	// Init colour configuration
	wxLogMessage("Loading colour configuration");
	ColourConfiguration::init();

	// Init nodebuilders
	NodeBuilders::init();

	// Init game executables
	Executables::init();

	// Init actions
	initActions();
	theMainWindow;

	// Init base resource
	wxLogMessage("Loading base resource");
	theArchiveManager->initBaseResource();
	wxLogMessage("Base resource loaded");

	// Show the main window
	theMainWindow->Show(true);
	SetTopWindow(theMainWindow);
	theSplashWindow->SetParent(theMainWindow);
	theSplashWindow->CentreOnParent();

	// Open any archives on the command line
	// argv[0] is normally the executable itself (i.e. Slade.exe)
	// and opening it as an archive should not be attempted...
	for (int a = 1; a < argc; a++)
	{
		string arg = argv[a];
		theArchiveManager->openArchive(arg);
	}

	// Hide splash screen
	theSplashWindow->hide();

	init_ok = true;
	wxLogMessage("SLADE Initialisation OK");

	// Init game configuration
	theGameConfiguration->init();

	// Show Setup Wizard if needed
	if (!setup_wizard_run)
	{
		SetupWizardDialog dlg(theMainWindow);
		dlg.ShowModal();
		setup_wizard_run = true;
	}

	// Check for updates
#ifdef __WXMSW__
	wxHTTP::Initialize();
	if (update_check)
		checkForUpdates(false);
#endif

	// Bind events
	Bind(wxEVT_MENU, &MainApp::onMenu, this);
	Bind(wxEVT_COMMAND_VERSIONCHECK_COMPLETED, &MainApp::onVersionCheckCompleted, this);

	return true;
}
Exemple #24
0
bool DolphinApp::OnInit()
{
    Bind(wxEVT_QUERY_END_SESSION, &DolphinApp::OnEndSession, this);
    Bind(wxEVT_END_SESSION, &DolphinApp::OnEndSession, this);

    // Declarations and definitions
    bool UseDebugger = false;
    bool UseLogger = false;
    bool selectVideoBackend = false;
    bool selectAudioEmulation = false;
    bool selectPerfDir = false;

    wxString videoBackendName;
    wxString audioEmulationName;
    wxString userPath;
    wxString perfDir;

#if wxUSE_CMDLINE_PARSER // Parse command lines
    wxCmdLineEntryDesc cmdLineDesc[] =
    {
        {
            wxCMD_LINE_SWITCH, "h", "help",
            "Show this help message",
            wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP
        },
        {
            wxCMD_LINE_SWITCH, "d", "debugger",
            "Opens the debugger",
            wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_SWITCH, "l", "logger",
            "Opens the logger",
            wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_OPTION, "e", "exec",
            "Loads the specified file (ELF, DOL, GCM, ISO, WBFS, CISO, GCZ, WAD)",
            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_SWITCH, "b", "batch",
            "Exit Dolphin with emulator",
            wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_OPTION, "V", "video_backend",
            "Specify a video backend",
            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_OPTION, "A", "audio_emulation",
            "Low level (LLE) or high level (HLE) audio",
            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_OPTION, "m", "movie",
            "Play a movie file",
            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_OPTION, "U", "user",
            "User folder path",
            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_OPTION, "P", "perf_dir",
            "Directory for Linux perf perf-$pid.map file",
            wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL
        },
        {
            wxCMD_LINE_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0
        }
    };

    // Gets the command line parameters
    wxCmdLineParser parser(cmdLineDesc, argc, argv);
    LoadFile = false;
    if (argc == 2 && File::Exists(argv[1].ToUTF8().data()))
    {
        LoadFile = true;
        FileToLoad = argv[1];
    }
    else if (parser.Parse() != 0)
    {
        return false;
    }

    UseDebugger = parser.Found("debugger");
    UseLogger = parser.Found("logger");
    if (!LoadFile)
        LoadFile = parser.Found("exec", &FileToLoad);
    BatchMode = parser.Found("batch");
    selectVideoBackend = parser.Found("video_backend", &videoBackendName);
    selectAudioEmulation = parser.Found("audio_emulation", &audioEmulationName);
    selectPerfDir = parser.Found("perf_dir", &perfDir);
    playMovie = parser.Found("movie", &movieFile);
    parser.Found("user", &userPath);
#endif // wxUSE_CMDLINE_PARSER

    // Register message box and translation handlers
    RegisterMsgAlertHandler(&wxMsgAlert);
    RegisterStringTranslator(&wxStringTranslator);

#if wxUSE_ON_FATAL_EXCEPTION
    wxHandleFatalExceptions(true);
#endif

    UICommon::SetUserDirectory(userPath.ToStdString());
    UICommon::CreateDirectories();
    InitLanguageSupport();	// The language setting is loaded from the user directory
    UICommon::Init();

    if (selectPerfDir)
    {
        SConfig::GetInstance().m_LocalCoreStartupParameter.m_perfDir =
            WxStrToStr(perfDir);
    }

    if (selectVideoBackend && videoBackendName != wxEmptyString)
        SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend =
            WxStrToStr(videoBackendName);

    if (selectAudioEmulation)
    {
        if (audioEmulationName == "HLE")
            SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = true;
        else if (audioEmulationName == "LLE")
            SConfig::GetInstance().m_LocalCoreStartupParameter.bDSPHLE = false;
    }

    VideoBackend::ActivateBackend(SConfig::GetInstance().m_LocalCoreStartupParameter.m_strVideoBackend);

    // Enable the PNG image handler for screenshots
    wxImage::AddHandler(new wxPNGHandler);

    int x = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosX;
    int y = SConfig::GetInstance().m_LocalCoreStartupParameter.iPosY;
    int w = SConfig::GetInstance().m_LocalCoreStartupParameter.iWidth;
    int h = SConfig::GetInstance().m_LocalCoreStartupParameter.iHeight;

    if (File::Exists("www.dolphin-emulator.com.txt"))
    {
        File::Delete("www.dolphin-emulator.com.txt");
        wxMessageDialog dlg(nullptr, _(
                                "This version of Dolphin was downloaded from a website stealing money from developers of the emulator. Please "
                                "download Dolphin from the official website instead: https://dolphin-emu.org/"),
                            _("Unofficial version detected"), wxOK | wxICON_WARNING);
        dlg.ShowModal();

        wxLaunchDefaultBrowser("https://dolphin-emu.org/?ref=badver");

        exit(0);
    }

    // The following is not needed with X11, where window managers
    // do not allow windows to be created off the desktop.
#ifdef _WIN32
    // Out of desktop check
    int leftPos = GetSystemMetrics(SM_XVIRTUALSCREEN);
    int topPos = GetSystemMetrics(SM_YVIRTUALSCREEN);
    int width =  GetSystemMetrics(SM_CXVIRTUALSCREEN);
    int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
    if ((leftPos + width) < (x + w) || leftPos > x || (topPos + height) < (y + h) || topPos > y)
        x = y = wxDefaultCoord;
#elif defined __APPLE__
    if (y < 1)
        y = wxDefaultCoord;
#endif

    main_frame = new CFrame(nullptr, wxID_ANY,
                            StrToWxStr(scm_rev_str),
                            wxPoint(x, y), wxSize(w, h),
                            UseDebugger, BatchMode, UseLogger);
    SetTopWindow(main_frame);
    main_frame->SetMinSize(wxSize(400, 300));

    AfterInit();

    return true;
}
Exemple #25
0
bool MyApp::OnInit()
{
#ifndef __WXMSW__
    if (wxPlatformInfo::Get().GetOperatingSystemId() & wxOS_UNIX)
    {
        wxStandardPaths::Get().SetInstallPrefix("/usr");
    }
#endif
    wxString datadir = wxStandardPaths::Get().GetDataDir() + wxFileName::GetPathSeparator();
    if (!setlocale(LC_CTYPE, ""))
    {
        fprintf(stderr, "Can't set the specified locale! "
                    "Check LANG, LC_CTYPE, LC_ALL.\n");
    return 1;
    }
    m_locale.Init();
    m_locale.AddCatalog("astercti");

    m_start_gui = ParseCmdLine();
    if (!m_start_gui) return true;

    m_config = NULL;
    m_config = new wxFileConfig(wxT("astercti"),
                                wxEmptyString,
                                wxT("astercti.ini"),
                                wxEmptyString,
                                wxCONFIG_USE_SUBDIR);
    wxFileName configfile = m_config->GetLocalFile("astercti.ini", wxCONFIG_USE_SUBDIR);
    if (!configfile.IsFileReadable())
    {
        std::ostringstream msg;
        msg << _("Error opening config file.") << std::endl
            << _("Sample config is at ") << configfile.GetFullPath() << ".default" << std::endl
            << _("Rename it to astercti.ini and edit.");
        wxLogError("%s", msg.str());
        return false;
    }

    m_chanstatuspool = new ChannelStatusPool(m_config->Read("dialplan/channel").ToStdString());
    if (m_config->HasEntry("lookup/lookup_url"))
    {
        m_lookuper = new CallerInfoLookuperURL(Cfg("lookup/lookup_url"));
    }
    else if (m_config->HasEntry("lookup/lookup_cmd"))
    {
        m_lookuper = new CallerInfoLookuperCmd(Cfg("lookup/lookup_cmd"));
    }
    else
    {
        m_lookuper = NULL;
    }
    wxPoint pos = m_config->ReadObject("autosave/position", wxDefaultPosition);
    wxSize size = m_config->ReadObject("autosave/size", wxSize(600, 400));
    asterisk = new Asterisk(m_config->Read("server/address").ToStdString(),
        5038,
        m_config->Read("server/username").ToStdString(),
        m_config->Read("server/password").ToStdString());
    bool maximized = m_config->ReadBool("autosave/maximized", false);
    m_mainframe = new MyFrame( "AsterCTI", pos, size, m_chanstatuspool, asterisk, m_lookuper, Cfg("lookup/caller_name_field"));
    if (maximized) m_mainframe->Maximize();
    m_mychanfilter = new MyChanFilter(m_config->Read("dialplan/channel").ToStdString());
    m_intmsgfilter = new InternalMessageFilter();
    m_numbershortener = new ShortenNumberModifier(m_config->Read("lookup/replace_number_prefix").ToStdString());
    asterisk->observable_descr = "asterisk";
    m_mychanfilter->observable_descr = "mychanfilter";
    m_intmsgfilter->observable_descr = "intmsgfilter";
    asterisk->broadcast(*m_mychanfilter);
    asterisk->broadcast(*m_intmsgfilter);
    asterisk->broadcast(*m_chanstatuspool);
    m_mychanfilter->broadcast(*m_numbershortener);
    m_numbershortener->broadcast(*m_mainframe);
    m_intmsgfilter->broadcast(*m_mainframe);
    notificationFrame *notifyframe = new notificationFrame(m_mainframe, m_chanstatuspool, asterisk, m_lookuper);
    Executer *executer = new Executer(m_lookuper);
    m_events = new EventGenerator(m_config->Read("dialplan/exten").ToStdString());
    m_events->broadcast(*m_mainframe);
    m_events->broadcast(*notifyframe);
    m_events->broadcast(*executer);
    m_numbershortener->broadcast(*m_events);
    m_intmsgfilter->broadcast(*m_events);
    wxIcon defaultIcon(ACTI_ICON("astercti"));
    wxIcon  missedIcon(ACTI_ICON("astercti-missed"));
    m_mainframe->SetIcon(defaultIcon);
    m_taskbaricon = new MyTaskBarIcon(defaultIcon, missedIcon, "AsterCTI: " + m_config->Read("dialplan/exten"));
    m_taskbaricon->SetMainFrame(m_mainframe);
    m_mainframe->SetTaskBarIcon(m_taskbaricon);
    m_mainframe->Show(!start_iconified);
    SetTopWindow(m_mainframe);
    SetExitOnFrameDelete(true);
    if (!m_lookuper)
    {
        m_mainframe->Log(_("Lookup URL and Lookup command are both unconfigured.\nLookup disabled."));
    }
    m_ipcServer = new IpcServer();
    if (!m_ipcServer->Create(IPC_SERVICENAME))
        wxLogMessage("Failure creating IPC Server %s", IPC_SERVICENAME);
#ifndef __WXMSW__
    wxHandleFatalExceptions();
#endif
    return true;
}