Ejemplo n.º 1
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;
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
0
bool DolphinApp::OnInit()
{
	Bind(wxEVT_QUERY_END_SESSION, &DolphinApp::OnEndSession, this);
	Bind(wxEVT_END_SESSION, &DolphinApp::OnEndSession, this);

	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 (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_NONE, nullptr, nullptr, nullptr, wxCMD_LINE_VAL_NONE, 0
		}
	};

	// Gets the command line parameters
	wxCmdLineParser parser(cmdLineDesc, argc, argv);
	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);
	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

#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

	UICommon::CreateDirectories();
	UICommon::Init();

	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;
}
Ejemplo n.º 4
0
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;
}
Ejemplo n.º 5
0
bool CTimeServerApp::OnInit()
{
	SetVendorName(VENDOR_NAME);

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

	if (!m_nolog) {
		wxString logBaseName = LOG_BASE_NAME;
		if (!m_name.IsEmpty()) {
			logBaseName.Append(wxT("_"));
			logBaseName.Append(m_name);
		}

#if defined(__WINDOWS__)
		if (m_logDir.IsEmpty())
			m_logDir = wxFileName::GetHomeDir();
#else
		if (m_logDir.IsEmpty())
			m_logDir = LOG_DIR;
#endif

		wxLog* log = new CLogger(m_logDir, logBaseName);
		wxLog::SetActiveTarget(log);
	} else {
		new wxLogNull;
	}

	m_logChain = new wxLogChain(new CTimeServerLogRedirect);

#if defined(__WINDOWS__)
	m_config = new CTimeServerConfig(new wxConfig(APPLICATION_NAME), m_name);
#else
	if (m_confDir.IsEmpty())
		m_confDir = CONF_DIR;

	m_config = new CTimeServerConfig(m_confDir, m_name);
#endif

	wxString frameName = APPLICATION_NAME + wxT(" - ");
	if (!m_name.IsEmpty()) {
		frameName.Append(m_name);
		frameName.Append(wxT(" - "));
	}
	frameName.Append(VERSION);

	wxPoint position = wxDefaultPosition;

	int x, y;
	getPosition(x, y);
	if (x >= 0 && y >= 0)
		position = wxPoint(x, y);

	m_frame = new CTimeServerFrame(frameName, position, m_gui);
	m_frame->Show();

	SetTopWindow(m_frame);

	wxLogInfo(wxT("Starting ") + APPLICATION_NAME + wxT(" - ") + VERSION);

	// Log the SVN revsion and the version of wxWidgets and the Operating System
	wxLogInfo(SVNREV);
	wxLogInfo(wxT("Using wxWidgets %d.%d.%d on %s"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, ::wxGetOsDescription().c_str());

	createThread();

	return true;
}
Ejemplo n.º 6
0
bool CDStarRepeaterApp::OnInit()
{
	SetVendorName(VENDOR_NAME);

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

	if (!m_nolog) {
		wxString logBaseName = LOG_BASE_NAME;
		if (!m_name.IsEmpty()) {
			logBaseName.Append(wxT("_"));
			logBaseName.Append(m_name);
		}

#if defined(__WINDOWS__)
		if (m_logDir.IsEmpty())
			m_logDir = ::wxGetHomeDir();
#else
		if (m_logDir.IsEmpty())
			m_logDir = wxT(LOG_DIR);
#endif

		wxLog* log = new CLogger(m_logDir, logBaseName);
		wxLog::SetActiveTarget(log);
	} else {
		new wxLogNull;
	}

	m_logChain = new wxLogChain(new CDStarRepeaterLogger);

	wxString appName;
	if (!m_name.IsEmpty())
		appName = APPLICATION_NAME + wxT(" ") + m_name;
	else
		appName = APPLICATION_NAME;

#if !defined(__WINDOWS__)
	appName.Replace(wxT(" "), wxT("_"));
	m_checker = new wxSingleInstanceChecker(appName, wxT("/tmp"));
#else
	m_checker = new wxSingleInstanceChecker(appName);
#endif

	bool ret = m_checker->IsAnotherRunning();
	if (ret) {
		wxLogError(wxT("Another copy of the D-Star Repeater is running, exiting"));
		return false;
	}

#if defined(__WINDOWS__)
	if (m_confDir.IsEmpty())
		m_confDir = ::wxGetHomeDir();

	m_config = new CDStarRepeaterConfig(new wxConfig(APPLICATION_NAME), m_confDir, CONFIG_FILE_NAME, m_name);
#else
	if (m_confDir.IsEmpty())
		m_confDir = wxT(CONF_DIR);

	m_config = new CDStarRepeaterConfig(m_confDir, CONFIG_FILE_NAME, m_name);
#endif

	wxString type;
	m_config->getModem(type);

	wxString frameName = APPLICATION_NAME + wxT(" (") + type + wxT(") - ");
	if (!m_name.IsEmpty()) {
		frameName.Append(m_name);
		frameName.Append(wxT(" - "));
	}
	frameName.Append(VERSION);

	wxPoint position = wxDefaultPosition;

	int x, y;
	m_config->getPosition(x, y);
	if (x >= 0 && y >= 0)
		position = wxPoint(x, y);

	m_frame = new CDStarRepeaterFrame(frameName, type, position, m_gui);
	m_frame->Show();

	SetTopWindow(m_frame);

	wxLogInfo(wxT("Starting ") + APPLICATION_NAME + wxT(" - ") + VERSION);

	// Log the version of wxWidgets and the Operating System
	wxLogInfo(wxT("Using wxWidgets %d.%d.%d on %s"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, ::wxGetOsDescription().c_str());

	createThread();

	return true;
}
bool CTimerControlApp::OnInit()
{
	SetVendorName(VENDOR_NAME);

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

	if (!m_nolog) {
		wxString logBaseName = LOG_BASE_NAME;
		if (!m_name.IsEmpty()) {
			logBaseName.Append(wxT("_"));
			logBaseName.Append(m_name);
		}

		if (m_logDir.IsEmpty())
			m_logDir = wxFileName::GetHomeDir();

		wxLog* log = new CLogger(m_logDir, logBaseName);
		wxLog::SetActiveTarget(log);
	} else {
		new wxLogNull;
	}

#if defined(__WINDOWS__)
	m_config = new CTimerControlConfig(new wxConfig(APPLICATION_NAME), m_name);
#else
	if (m_confDir.IsEmpty())
		m_confDir = CONF_DIR;

	m_config = new CTimerControlConfig(m_confDir, m_name);
#endif

	wxString frameName = APPLICATION_NAME + wxT(" - ");
	if (!m_name.IsEmpty()) {
		frameName.Append(m_name);
		frameName.Append(wxT(" - "));
	}
	frameName.Append(VERSION);

	if (!m_name.IsEmpty()) {
		wxString fileBase = SCHEDULE_BASE_NAME;
		fileBase.Append(wxT("_"));
		fileBase.Append(m_name);
		fileBase.Replace(wxT(" "), wxT("_"));

		wxString dir = m_confDir;
		if (dir.IsEmpty())
			dir = wxFileName::GetHomeDir();

		wxFileName fileName(dir, fileBase, wxT("dat"));
		m_fileName = fileName.GetFullPath();
	} else {
		wxString dir = m_confDir;
		if (dir.IsEmpty())
			dir = wxFileName::GetHomeDir();

		wxFileName fileName(dir, SCHEDULE_BASE_NAME, wxT("dat"));
		m_fileName = fileName.GetFullPath();
	}

	wxPoint position = wxDefaultPosition;

	int x, y;
	getPosition(x, y);
	if (x >= 0 && y >= 0)
		position = wxPoint(x, y);

	bool delay;
	getDelay(delay);

	m_frame = new CTimerControlFrame(frameName, position, delay);
	m_frame->Show();

	SetTopWindow(m_frame);

	wxLogInfo(wxT("Starting ") + APPLICATION_NAME + wxT(" - ") + VERSION);

	// Log the SVN revsion and the version of wxWidgets and the Operating System
	wxLogInfo(SVNREV);
	wxLogInfo(wxT("Using wxWidgets %d.%d.%d on %s"), wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER, ::wxGetOsDescription().c_str());

	createThread();

	return wxApp::OnInit();
}
Ejemplo n.º 8
0
bool MyApp::OnInit( void )
{
    try
    {
        SetAppName( APP_NAME );
        SetVendorName( APP_VENDOR );

        respath = wxFindAppPath( argv[0], wxGetCwd(), _T("FNPATH"), _T("fn") );

#ifdef __WXMSW__

        if (respath.Last() != '\\') respath += '\\';
        shaderPath = respath + _T("GLSL\\");
        iconsPath  = respath + _T("icons\\");
        
        int fd;
        FILE *fp;
        AllocConsole();
        fd = _open_osfhandle( (long)GetStdHandle( STD_OUTPUT_HANDLE ), 0);
        fp = _fdopen( fd, "w" );
        *stdout = *fp;
        setvbuf( stdout, NULL, _IONBF, 0 );

// TODO fix may not work.
#elif __WXMAC__

        // If we use the above code to get the same on OSX, I get a segfault somewhere
        // therefore I use the OSX native code here:

        // OSX only: Try to find the resource path...
        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef resourcesURL = CFBundleCopyBundleURL( mainBundle );
        CFStringRef str = CFURLCopyFileSystemPath( resourcesURL, kCFURLPOSIXPathStyle );
        CFRelease( resourcesURL );
        char path[ PATH_MAX ];

        CFStringGetCString( str, path, FILENAME_MAX, kCFStringEncodingASCII );
        CFRelease( str );
        fprintf( stderr, "%s", path );

        respath = wxString::FromAscii( path );

        respath += _T( "/Contents/Resources/" );
        shaderPath = respath + _T( "GLSL/" );
        iconsPath = respath + _T( "icons/" );
        std::cout << std::endl << iconsPath << std::endl;

#else
        if ( respath.Last() != '/' )
            respath += '/';
        shaderPath = respath + _T("GLSL/");
        iconsPath = respath + _T("icons/");

#endif

        Logger::getInstance()->print( wxT( "Warning: This version of Fibernavigator is debug compiled." ), LOGLEVEL_DEBUG );
        Logger::getInstance()->print( wxT( "For better performance please compile a Release version."), LOGLEVEL_DEBUG );
        Logger::getInstance()->print( wxString::Format( wxT( "respath: %s" ), respath.c_str() ), LOGLEVEL_DEBUG );
        Logger::getInstance()->print( wxString::Format( wxT( "shader: %s" ), shaderPath.c_str() ), LOGLEVEL_DEBUG );

        // Create the main frame window
        frame = new MainFrame( wxT("Fiber Navigator"), wxPoint( 50, 50 ), wxSize( 800, 600 ) );
        SceneManager::getInstance()->setMainFrame( frame );
        SceneManager::getInstance()->setTreeCtrl( frame->m_pTreeWidget );

#ifdef __WXMSW__
        // Give it an icon (this is ignored in MDI mode: uses resources)
        frame->SetIcon( wxIcon( _T( "sashtest_icn" ) ) );
#endif

        frame->SetMinSize( wxSize( 800, 600 ) );
        frame->SetSize( wxSize( 1024, 768 ) );

        frame->Show( true );
        SetTopWindow( frame );

        wxString cmd;
        wxString cmdFileName;
        wxCmdLineParser cmdParser( desc, argc, argv );
        cmdParser.Parse( false );

        if ( cmdParser.GetParamCount() > 0 )
        {
            Loader loader = Loader(frame, frame->m_pListCtrl );
            for ( size_t i = 0; i < cmdParser.GetParamCount(); ++i )
            {
                cmd = cmdParser.GetParam( i );
                wxFileName fName( cmd );
                fName.Normalize( wxPATH_NORM_LONG | wxPATH_NORM_DOTS | wxPATH_NORM_TILDE | wxPATH_NORM_ABSOLUTE );
                cmdFileName = fName.GetFullPath();

                if ( cmdParser.Found(_T("d")) &&  ( i == 0 ) )
                {
                    loader( cmdFileName );
                    frame->createDistanceMapAndIso();
                }
                else if ( cmdParser.Found( _T( "p" ) ) &&  ( i == cmdParser.GetParamCount() -1 ) )
                {
                    frame->screenshot( wxT( "" ), cmdFileName );
                }
                else
                {
                    loader( cmdFileName );
                }
            }
        }

        if ( cmdParser.Found( _T( "e" ) ) )
        {
            exit( 0 );
        }
        
        return true;

    }
    catch ( ... )
    {
        Logger::getInstance()->print( wxT( "Something went wrong, terribly wrong" ), LOGLEVEL_ERROR );
        return false;
    }
    
    Logger::getInstance()->print( wxT( "End on init main" ), LOGLEVEL_DEBUG );
    wxFrame *the_frame = new wxFrame(NULL, 1, argv[0]);

    the_frame->Show(true);
    return true;
}
Ejemplo n.º 9
0
bool MyApp::OnInit()
{
    int i, j;
    unsigned int *sdimp;
    int longdim;

    /* debug */
    if (G_verbose() > G_verbose_std()) {
	for (i = 0; i < numviews; i++) {
	    fprintf(stderr, "\nVIEW %d: ", i + 1);
	    for (j = 0; j < frames; j++) {
		fprintf(stderr, "%s ", vfiles[i][j]);
	    }
	}
    }
    fprintf(stderr, "\n");

    vrows = Rast_window_rows();
    vcols = Rast_window_cols();
    nrows = vrows;
    ncols = vcols;

    /* short dimension */
    sdimp = nrows > ncols ? &ncols : &nrows;

    /* these proportions should work fine for 1 or 4 views, but for
       2 views, want to double the narrow dim & for 3 views triple it */
    if (numviews == 2)
	*sdimp *= 2;
    else if (numviews == 3)
	*sdimp *= 3;

    longdim = nrows > ncols ? nrows : ncols;

    scale = 1.0;

    {				/* find animation image size */
	int max, min;
	char *p;

	max = DEF_MAX;
	min = DEF_MIN;

	if ((p = getenv("XGANIM_SIZE")))
	    max = min = atoi(p);

	if (longdim > max)	/* scale down */
	    scale = (float)max / longdim;
	else if (longdim < min)	/* scale up */
	    scale = (float)min / longdim;
    }

    vscale = scale;
    if (numviews == 4)
	vscale = scale / 2.;

    nrows = (unsigned int) (nrows * scale);
    ncols = (unsigned int) (ncols * scale);
    /* now nrows & ncols are the size of the combined - views image */
    vrows = (int) (vrows * vscale);
    vcols = (int) (vcols * vscale);
    /* now vrows & vcols are the size for each sub-image */

    /* add to nrows & ncols for borders */
    /* irows, icols used for vert/horizontal determination in loop below */
    irows = nrows;
    icols = ncols;
    nrows += (1 + (nrows / vrows)) * BORDER_W;
    ncols += (1 + (ncols / vcols)) * BORDER_W;

    gd.speed = 100;
    gd.direction = 1;
    gd.shownames = 1;

    mainwin = new MyFrame(wxString("GRASS Animate", wxConvISO8859_1), ncols, nrows, &gd);
    mainwin->Show();
    SetTopWindow(mainwin);

    for (j = 0; j < MAXIMAGES; j++)
	sprintf(frame[j], "%2d", j + 1);

    return true;
}
Ejemplo n.º 10
0
bool MadEditApp::OnInit()
{
    xm::EncodingManager::PreInit();

    xm::RemoteAccessInit();

	wxm::AppPath::Instance().Init(GetAppName());

    // parse commandline to filelist
    wxm::FileList filelist;
    for(int i=1; i<argc; i++)
    {
        wxFileName filename(argv[i]);
        filename.MakeAbsolute();
        filelist.Append(filename.GetFullPath());
    }

    // init wxConfig
	wxFileConfig *cfg=new wxFileConfig(wxEmptyString, wxEmptyString, wxm::AppPath::Instance().ConfigPath(), 
	                                   wxEmptyString, wxCONFIG_USE_RELATIVE_PATH|wxCONFIG_USE_NO_ESCAPE_CHARACTERS);
    cfg->SetExpandEnvVars(false);
    cfg->SetRecordDefaults(true);
    wxFileConfig::Set(cfg);

    bool bSingleInstance=true;
    cfg->Read(wxT("/wxMEdit/SingleInstance"), &bSingleInstance, true);

    // check SingleInstance and send filelist to previous instance
    if(bSingleInstance && OpenFilesInPrevInst(filelist.String()))
        return false;

#ifdef __WXGTK__
    bool bDisableWarningMessage = true;
    cfg->Read(wxT("/wxMEdit/DisableWarningMessage"), &bDisableWarningMessage, true);
    if(bDisableWarningMessage)
    {
        // redirect "IPP request failed" message to /dev/null
        int fdnull = open ("/dev/null", O_WRONLY, 0);
        if(fdnull >= 0)
        {
            dup2(fdnull, STDERR_FILENO);
        }
    }
#endif


    // init locale
    wxString strlang;
    cfg->Read(wxT("/wxMEdit/Language"), &strlang);
    int lang=g_LanguageValue[0];
    if(!strlang.IsEmpty())
    {
        strlang.MakeLower();
        for(size_t idx=1; idx<g_LanguageCount; idx++)
        {
            if(strlang == wxString(g_LanguageString[idx]).Lower())
            {
                lang=g_LanguageValue[idx];
                break;
            }
        }
    }

    wxm::AppPath& path = wxm::AppPath::Instance();
    g_Locale.Init(lang);
    g_Locale.AddCatalogLookupPathPrefix(wxT("./locale/"));
    g_Locale.AddCatalogLookupPathPrefix(path.AppDir() + wxT("locale/"));
    if (path.AppDir() != path.HomeDir())
        g_Locale.AddCatalogLookupPathPrefix(path.HomeDir() + wxT("locale/"));
#ifndef __WXMSW__
# ifdef DATA_DIR
    g_Locale.AddCatalogLookupPathPrefix(wxT(DATA_DIR"/locale/"));
# endif
#endif

    g_Locale.AddCatalog(wxT("wxmedit"));

    // set colors
    wxm::SetL10nHtmlColors();

    wxm::UpdatePeriods::Instance().Initialize();

#if defined(__WXMSW__) || defined(__WXGTK__)
    bool maximize=false;
    cfg->Read(wxT("/wxMEdit/WindowMaximize"), &maximize, false);
#endif
    wxPoint pos=wxDefaultPosition;
    wxSize size;
    wxRect rect = wxGetClientDisplayRect(); // FIXME: multi-monitor
    size.x = std::min(rect.width, wxm::DEFAULT_WINDOW_WIDTH);
    size.y = std::min(rect.height, wxm::DEFAULT_WINDOW_HEIGHT);

    long x=0,y=0,w=0,h=0;
    cfg->Read(wxT("/wxMEdit/WindowLeft"), &x);
    cfg->Read(wxT("/wxMEdit/WindowTop"), &y);
    cfg->Read(wxT("/wxMEdit/WindowWidth"), &w);
    cfg->Read(wxT("/wxMEdit/WindowHeight"), &h);

    if(x+w>0 && y+h>0)
    //if(w>0 && h>0)
    {
        size.x=w;
        size.y=h;

        pos.x=x;
        pos.y=y;
    }

    // load FontWidth buffers
    cfg->Read(wxT("/wxMEdit/FontWidthBufferMaxCount"), &FontWidthManager::MaxCount, 10);
    if(FontWidthManager::MaxCount < 4) FontWidthManager::MaxCount=4;
    else if(FontWidthManager::MaxCount>40) FontWidthManager::MaxCount=40;
    FontWidthManager::Init(wxm::AppPath::Instance().HomeDir());


    // create the main frame
    MadEditFrame *myFrame = new MadEditFrame(nullptr, 1 , wxEmptyString, pos, size);
    SetTopWindow(myFrame);

#if defined(__WXMSW__) || defined(__WXGTK__)
    if (maximize)
        myFrame->Maximize(true);
#endif

    myFrame->Show(true);


#if defined(__WXGTK__) && wxMAJOR_VERSION == 2
    if(bSingleInstance)
    {
        GtkPizza *pizza = GTK_PIZZA(myFrame->m_mainWidget);
        Window win=GDK_WINDOW_XWINDOW(pizza->bin_window);
        XSetSelectionOwner(g_Display, g_MadEdit_atom, win, CurrentTime);
        gdk_window_add_filter(nullptr, my_gdk_filter, nullptr);
    }
#endif

    wxm::AutoCheckUpdates(cfg);

    // reload files previously opened
    wxString files;
    cfg->Read(wxT("/wxMEdit/ReloadFilesList"), &files);
    files += filelist.String();

    if(!files.IsEmpty())
    {
        // use OnReceiveMessage() to open the files
        OnReceiveMessage(files.c_str(), (files.size()+1)*sizeof(wxChar));
    }

    if(myFrame->OpenedFileCount()==0)
    {
        myFrame->OpenFile(wxEmptyString, false);
    }

    return true;
}
Ejemplo n.º 11
0
    virtual bool OnInit()
    {
        SetAppName("codelite-terminal");
        wxFileName configDir(wxStandardPaths::Get().GetUserDataDir(), "");
        configDir.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);

        m_persistency = new MyPersistenceManager();
        wxPersistenceManager::Set(*m_persistency);
        wxTerminalOptions& m_options = wxTerminalOptions::Get();

        // m_persistencManager = new clPersistenceManager();
        // wxPersistenceManager::Set(*m_persistencManager);
#ifdef __WXMSW__
        typedef BOOL WINAPI (*SetProcessDPIAwareFunc)();
        HINSTANCE user32Dll = LoadLibrary(L"User32.dll");
        if(user32Dll) {
            SetProcessDPIAwareFunc pFunc = (SetProcessDPIAwareFunc)GetProcAddress(user32Dll, "SetProcessDPIAware");
            if(pFunc) { pFunc(); }
            FreeLibrary(user32Dll);
        }
#endif
        wxCmdLineParser parser(wxApp::argc, wxApp::argv);
        parser.SetDesc(cmdLineDesc);
        const wxArrayString& argv = wxApp::argv.GetArguments();

        for(const wxString& arg : argv) {
            if(arg.StartsWith("--wait")) {
                m_options.SetWaitOnExit(true);
            } else if(arg.StartsWith("--help")) {
                // Print usage and exit
                std::cout << parser.GetUsageString() << std::endl;
                wxExit();
            } else if(arg.StartsWith("--title")) {
                wxString title = arg.AfterFirst('=');
                m_options.SetTitle(title);
            } else if(arg.StartsWith("--print-tty")) {
                m_options.SetPrintTTY(true);
                wxString ttyfile = arg.AfterFirst('=');
                m_options.SetTtyfile(ttyfile);
            } else if(arg.StartsWith("--working-directory")) {
                wxString wd = arg.AfterFirst('=');
                m_options.SetWorkingDirectory(wd);
            } else if(arg.StartsWith("--command")) {
                wxString cmd = arg.AfterFirst('=');
                m_options.SetCommand(cmd);
            } else if(arg.StartsWith("--file")) {
                wxString cmdfile = arg.AfterFirst('=');
                m_options.SetCommandFromFile(cmdfile);
            } else if(arg.StartsWith("--log")) {
                wxString logfile = arg.AfterFirst('=');
                m_options.SetLogfile(logfile);
            }
        }

        // Add the common image handlers
        wxImage::AddHandler(new wxPNGHandler);
        wxImage::AddHandler(new wxJPEGHandler);

        MainFrame* mainFrame = new MainFrame(NULL);
        SetTopWindow(mainFrame);
        return GetTopWindow()->Show();
    }
//! @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;
}
Ejemplo n.º 13
0
bool MyPicsApp::OnInit()
{    
    wxImage::AddHandler( new wxJPEGHandler );
    wxImage::AddHandler( new wxICOHandler );

    // extract the applications resources to files, so we can use them.
    // we could have just put all
    // the resources in the .zip file, but then how would i have 
    // demostrated the other ExtractXXX functions? :)

    // extract all resources of same type (in this case imagess 
    // pecified as type "image" in the .rc file),in one call, 
    // u can specify any type you want, but if you
    // use a number, make shure its an unsigned int OVER 255.
    // Also note that the exCount param passed here is optional.
    int exCount=0;
    bool resOk = m_Resources.ExtractResources(wxT("image"), &exCount);
    if(resOk)
    {
        wxLogDebug(wxT("%d files extracted to %s using ExtractResources()"),
        exCount, m_Resources.GetResourceDir());
    }

    // extract a single resource file "wxmswres.h" of type "txtfile"
    // note that the resource name sould be the same in the .rc file
    // as the desired extracted file name INCLUDING EXTENSION, same
    // goes for ExtractResources()
    resOk = resOk && m_Resources.ExtractResource(wxT("wxmswres.h"),
        wxT("txtfile"));

    if(resOk)
    {
        wxLogDebug(wxT("resource file wxmswres.h extracted to %s using ExtractResource()"),
            m_Resources.GetResourceDir());
    }

    // extract resources contained in a zip file, in this case, the .mo 
    // catalog files, compressed to reduce .exe size
    exCount=0;
    resOk = resOk && m_Resources.ExtractZipResources(wxT("langcats"),
        wxT("zipfile"), &exCount);
    if(resOk)
    {
        wxLogDebug(wxT("%d files extracted to %s using ExtractZipResources()"),
            exCount, m_Resources.GetResourceDir());
    }

    // if the ExtractXXX functions returned true, the resources were
    // extracted successfully, but still you can check if some
    // resource is actually there using this function
    if(m_Resources.RcExtracted(wxT("wx_es.mo")))
        wxLogDebug(wxT("guess what??, wx_ex.mo was extracted successfully"));

    if(!resOk)
    {
        // oops! something went wrong, we better quit here
        wxMessageBox(_("Failed to extract the app´s resources.\nTerminating app..."),
            _("Fatal Error"), wxOK | wxCENTRE | wxICON_ERROR);
        return false;
    }

    // ask user for application language
    DlgLang dlg(NULL);
    wxString langName = dlg.GetSelLanguage();

    // now set the locale & load the app & standar wxWidgets catalogs
    // (previously extracted), but only if selected language was spanish, 
    // since wxWidgets & strings in source code are in english
    
    // set lookup path to our resource dir first!! , or wxLocale
    // will NOT find the catalogs & fail!
    m_Locale.AddCatalogLookupPathPrefix(m_Resources.GetResourceDir());

    bool iInitOk = false; bool cInitOk = false;
    int langId = langName==_("Spanish") ? 
        wxLANGUAGE_SPANISH_MODERN : wxLANGUAGE_ENGLISH_US;

    iInitOk= m_Locale.Init(langId, wxLOCALE_CONV_ENCODING);
    if(!iInitOk)
        wxLogDebug(wxT("Failed to initialize locale!"));

    if(iInitOk && langId == wxLANGUAGE_SPANISH_MODERN)
    {
        cInitOk = m_Locale.AddCatalog(wxT("wx_es"));
        cInitOk = cInitOk && m_Locale.AddCatalog(wxT("mypics_es"));
    }
    if(!cInitOk)
        wxLogDebug(wxT("Failed to load one or more catalogs!"));

    // create the app´s main window (go look at MyFrame´s creation code)
    MyFrame* pFrame = new MyFrame(NULL);
    pFrame->Maximize();
    pFrame->Show();
    SetTopWindow(pFrame);
    return true;
}
Ejemplo n.º 14
0
bool WinEDA_App::OnInit(void)
/****************************/
{
wxString FFileName;

	EDA_Appl = this;
	InitEDA_Appl( wxT("pcbnew") );

    if ( m_Checker && m_Checker->IsAnotherRunning() )
    {
        if ( ! IsOK(NULL, _("Pcbnew is already running, Continue?") ) )
			return false;
    }

	/* Add image handlers for screen hardcopy */
	wxImage::AddHandler( new wxPNGHandler );
	wxImage::AddHandler( new wxJPEGHandler );

	ScreenPcb = new PCB_SCREEN(NULL, NULL, PCB_FRAME);
	GetSettings();

	if(argc > 1)
		{
		FFileName = MakeFileName(wxEmptyString, argv[1], PcbExtBuffer);
		wxSetWorkingDirectory( wxPathOnly(FFileName) );
		}

	Read_Config(FFileName);
	g_DrawBgColor = BLACK;

	/* allocation de la memoire pour le fichier et autres buffers: */
	/* On reserve BUFMEMSIZE octets de ram pour calcul */
	buf_work = adr_lowmem = (char*)MyZMalloc(BUFMEMSIZE) ;  /* adresse de la zone de calcul */
	adr_himem = adr_lowmem + BUFMEMSIZE; /* adr limite haute */
	adr_max = adr_lowmem;

	if( adr_lowmem == NULL )
	{
		printf( "No Memory, Fatal err Memory alloc\n" );
		return(FALSE) ;
	}
	m_PcbFrame = new WinEDA_PcbFrame(NULL, this, wxT("PcbNew"),
				 wxPoint(0,0), wxSize(600,400) );
	m_PcbFrame->SetTitle(Main_Title);
	ScreenPcb->SetParentFrame(m_PcbFrame);
	ActiveScreen = ScreenPcb;
	m_PcbFrame->m_Pcb = new BOARD(NULL, m_PcbFrame);

	SetTopWindow(m_PcbFrame);
	m_PcbFrame->Show(TRUE);

	if( CreateServer(m_PcbFrame, KICAD_PCB_PORT_SERVICE_NUMBER) )
	{
		SetupServerFunction(RemoteCommand);
	}

	m_PcbFrame->Zoom_Automatique(TRUE);

	/* Load file specified in the command line. */
	if ( ! FFileName.IsEmpty() )
	{
		wxClientDC dc(m_PcbFrame->DrawPanel);
		m_PcbFrame->DrawPanel->PrepareGraphicContext(&dc);
		m_PcbFrame->LoadOnePcbFile(FFileName, &dc, FALSE);
	}

	return TRUE;
}
Ejemplo n.º 15
0
bool Rpcs3App::OnInit()
{
	static const wxCmdLineEntryDesc desc[]
	{
		{ wxCMD_LINE_SWITCH, "h", "help", "Command line options:\nh (help): Help and commands\nt (test): For directly executing a (S)ELF", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
		{ wxCMD_LINE_SWITCH, "t", "test", "Run in test mode on (S)ELF", wxCMD_LINE_VAL_NONE },
		{ wxCMD_LINE_PARAM, NULL, NULL, "(S)ELF", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
		{ wxCMD_LINE_NONE }
	};
	
	parser.SetDesc(desc);
	parser.SetCmdLine(argc, argv);

	if (parser.Parse())
	{
		// help was given, terminating
		this->Exit();
	}

	s_gui_cfg.open(fs::get_config_dir() + "/config_gui.yml", fs::read + fs::write + fs::create);
	g_gui_cfg = YAML::Load(s_gui_cfg.to_string());

	EmuCallbacks callbacks;

	callbacks.call_after = [](std::function<void()> func)
	{
		wxGetApp().CallAfter(std::move(func));
	};

	callbacks.process_events = [this]()
	{
		m_MainFrame->Update();
		wxGetApp().ProcessPendingEvents();
	};

	callbacks.exit = [this]()
	{
		wxGetApp().Exit();
	};

	callbacks.send_dbg_command = [](DbgCommand id, cpu_thread* t)
	{
		wxGetApp().SendDbgCommand(id, t);
	};

	callbacks.get_kb_handler = PURE_EXPR(g_cfg_kb_handler.get()());

	callbacks.get_mouse_handler = PURE_EXPR(g_cfg_mouse_handler.get()());

	callbacks.get_pad_handler = PURE_EXPR(g_cfg_pad_handler.get()());

	callbacks.get_gs_frame = [](frame_type type, int w, int h) -> std::unique_ptr<GSFrameBase>
	{
		switch (type)
		{
		case frame_type::OpenGL: return std::make_unique<GLGSFrame>(w, h);
		case frame_type::DX12: return std::make_unique<GSFrame>("DirectX 12", w, h);
		case frame_type::Null: return std::make_unique<GSFrame>("Null", w, h);
		case frame_type::Vulkan: return std::make_unique<GSFrame>("Vulkan", w, h);
		}

		throw EXCEPTION("Invalid Frame Type (0x%x)", type);
	};

	callbacks.get_gs_render = PURE_EXPR(g_cfg_gs_render.get()());

	callbacks.get_audio = PURE_EXPR(g_cfg_audio_render.get()());

	callbacks.get_msg_dialog = []() -> std::shared_ptr<MsgDialogBase>
	{
		return std::make_shared<MsgDialogFrame>();
	};

	callbacks.get_save_dialog = []() -> std::unique_ptr<SaveDialogBase>
	{
		return std::make_unique<SaveDialogFrame>();
	};

	Emu.SetCallbacks(std::move(callbacks));

	TheApp = this;
	SetAppName("RPCS3");
	wxInitAllImageHandlers();

	Emu.Init();

	m_MainFrame = new MainFrame();
	SetTopWindow(m_MainFrame);
	m_MainFrame->Show();
	m_MainFrame->DoSettings(true);

	OnArguments(parser);

	return true;
}
Ejemplo n.º 16
0
bool TopedApp::OnInit() {
//   DATC = DEBUG_NEW DataCenter();
    initDBLib();
    Toped = DEBUG_NEW tui::TopedFrame( wxT( "wx_Toped" ), wxPoint(50,50), wxSize(1200,900) );

    console::ted_log_ctrl *logWindow = DEBUG_NEW console::ted_log_ctrl(Toped->logwin());
    delete wxLog::SetActiveTarget(logWindow);

    CmdList = Toped->cmdlist();
    // Create the main block parser block - WARNING! blockSTACK structure MUST already exist!
    CMDBlock = DEBUG_NEW parsercmd::cmdMAIN();
    tellstdfunc::initFuncLib(Toped, Toped->view());
    InitInternalFunctions(static_cast<parsercmd::cmdMAIN*>(CMDBlock));

    SetTopWindow(Toped);
    Toped->Show(TRUE);

    GetFontDir();
    if (!LoadFontFile("arial1")) return FALSE;

    GetLogDir();
    if (!GetLogFileName()) return FALSE;
    bool recovery_mode = false;
    if (CheckCrashLog())
    {
        wxMessageDialog* dlg1 = DEBUG_NEW  wxMessageDialog(Toped,
                                wxT("Last session didn't exit normally. Start recovery?"),
                                wxT("Toped"),
                                wxYES_NO | wxICON_WARNING);
        if (wxID_YES == dlg1->ShowModal())
            recovery_mode = true;
        else
            tell_log(console::MT_WARNING,"Recovery rejected.");
        dlg1->Destroy();
        if (!recovery_mode) SaveIgnoredCrashLog();
    }
    if (recovery_mode)
    {
        tell_log(console::MT_WARNING,"Starting recovery ...");
        wxString inputfile;
        inputfile << wxT("#include \"") << logFileName.c_str() << wxT("\"");
        Console->parseCommand(inputfile, false);
        tell_log(console::MT_WARNING,"Exit recovery mode.");
        static_cast<parsercmd::cmdMAIN*>(CMDBlock)->recoveryDone();
        LogFile.init(std::string(logFileName.mb_str()), true);
    }
    else
    {
        LogFile.init(std::string(logFileName.mb_str()));
        //   wxLog::AddTraceMask("thread");
        if (1 < argc)
        {
            wxString inputfile;
            for (int i=1; i<argc; i++)
            {
                inputfile.Clear();
                inputfile << wxT("#include \"") << argv[i] << wxT("\"");
                Console->parseCommand(inputfile);
            }
        }
    }
    tell_log(console::MT_WARNING,"Please report a bugs to [email protected] or [email protected]");
    return TRUE;
}
Ejemplo n.º 17
0
bool gravApp::OnInit()
{
    grav = new gravManager();
    // defaults - can be changed by command line
    windowWidth = 900; windowHeight = 550;
    startX = 10; startY = 50;
    // gravManager's windowwidth/height will be set by the glcanvas's resize
    // callback

    parser.SetCmdLine( argc, argv );

    videoSessionListener = new VideoListener( grav );
    audioSessionListener = new AudioManager();
    sessionManager = new SessionManager( videoSessionListener,
                                            audioSessionListener );
    //videoInitialized = false; audioInitialized = false;

    if ( !handleArgs() )
    {
        delete grav;
        return false;
    }

    // Some weirdness happens if this is called before arg handling, etc.
    gravUtil::initLogging();
    // Set verbosity here, nothing should use gravUtil::logVerbose before this.
    if ( verbose )
        wxLog::SetVerbose( true );
    if ( VPMverbose )
        vpmlog_set_log_level( VPMLOG_LEVEL_DEBUG );

    // GUI setup
    mainFrame = new Frame( (wxFrame*)NULL, -1, _("grav"),
                        wxPoint( startX, startY ),
                        wxSize( windowWidth, windowHeight ) );
    mainFrame->Show( true );
    mainFrame->SetName( _("main grav frame") );
    mainFrame->setSourceManager( grav );
    SetTopWindow( mainFrame );
    if ( startFullscreen )
        mainFrame->ShowFullScreen( true );

    int treeX = 960; int treeY = 50;
    // forces resize - for some reason it doesn't draw inner contents until
    // resized
    int treeWidth = 251; int treeHeight = 501;
    treeFrame = new SideFrame( mainFrame, -1, _("grav menu"),
                            wxPoint( treeX, treeY ),
                            wxSize( treeWidth, treeHeight ) );
    treeFrame->Show( true );
    treeFrame->SetSizeHints( 250, 500, 250, 500 );

    treePanel = new wxPanel( treeFrame, wxID_ANY, treeFrame->GetPosition(),
                                treeFrame->GetSize() );
    treeNotebook = new wxNotebook( treePanel, wxID_ANY,
                               treePanel->GetPosition(), treePanel->GetSize() );

    int attribList[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 24,
                            0 };

    canvas = new GLCanvas( mainFrame, grav, attribList,
                            mainFrame->GetClientSize() );
    sourceTree = new TreeControl( treeNotebook );
    sourceTree->setSourceManager( grav );
    sessionTree = new SessionTreeControl( treeNotebook );
    treeNotebook->AddPage( sourceTree, _("Videos"), true );
    treeNotebook->AddPage( sessionTree, _("Sessions") );
    // sizer for the notebook in general
    wxBoxSizer* treeSizer = new wxBoxSizer( wxVERTICAL );
    treePanel->SetSizer( treeSizer );
    treeSizer->Fit( treeFrame );
    treeSizer->Add( treeNotebook, wxEXPAND );
    treeSizer->Show( treeNotebook );
    treeSizer->Layout();

    // put the main frame on top
    mainFrame->Raise();

    // log here instead of in handleargs, see above/in handleargs
    // (handleargs is where the timer intervals actually get set)
    // might be that we can't do logging until main window is created
    if ( fps > 1000 )
    {
        gravUtil::logVerbose( "grav::warning: invalid fps value %li, "
                              "reset to 60\n", fps );
        // note the "fps" variable here is just the input from the command line,
        // the timer interval - what actually determines the rendering timing -
        // has already been reset to 16ms in handleArgs
    }

    if ( printVersion )
    {
        std::string ver = "grav ";
        ver += gravUtil::getVersionString();
        gravUtil::logMessage( ver.c_str() );
    }

    if ( disablePython )
    {
        PythonTools::disableInit = true;
    }

    // since these bools are used in glinit, set them before glinit
    GLUtil::getInstance()->setShaderEnable( enableShaders );
    GLUtil::getInstance()->setBufferFontUsage( bufferFont );

    // initialize GL stuff (+ shaders) needs to be done AFTER attriblist is
    // used in making the canvas
    if ( !GLUtil::getInstance()->initGL() )
    {
        // bail out if something failed
        gravUtil::logError( "grav::OnInit(): ERROR: initGL() failed, "
                "exiting\n" );
        delete grav;
        return false;
    }

    if ( headerSet )
        grav->setHeaderString( header );

    timer = new RenderTimer( canvas, timerInterval );
    //timer->Start();
    //wxStopWatch* t2 = new wxStopWatch();
    //videoSession_listener->setTimer( t2 );

    earth = new Earth();
    input = new InputHandler( earth, grav, mainFrame );

    // frame needs reference to inputhandler to generate help window for
    // shortcut hotkeys
    mainFrame->setInputHandler( input );

    // add the input handler to the chain of things that can handle
    // events & give the canvas focus so we don't have to click on it to
    // start sending key events
    canvas->PushEventHandler( input );
    canvas->SetFocus();
    canvas->setTimer( timer );

    if ( !disablePython )
    {
        venueClientController = new VenueClientController( 0.0f, 0.0f, grav );
        venueClientController->setSessionControl( sessionTree );
    }

    grav->setEarth( earth );
    grav->setInput( input );
    grav->setTree( sourceTree );
    grav->setBorderTex( "border.png" );
    grav->setVideoListener( videoSessionListener );
    grav->setCanvas( canvas );
    grav->setVenueClientController( venueClientController ); // may be null
    grav->setAudio( audioSessionListener ); // may not necessarily be used

    mapRTP();

    sessionTree->setSessionManager( sessionManager );
    for ( unsigned int i = 0; i < initialVideoAddresses.size(); i++ )
    {
        gravUtil::logVerbose ( "grav::initializing video address %s\n",
                    initialVideoAddresses[i].c_str() );
        sessionTree->addSession( initialVideoAddresses[i], false,
                    addToAvailableVideoList );

        if ( haveVideoKey )
            sessionTree->setEncryptionKey( initialVideoAddresses[i],
                                            initialVideoKey );
    }
    for ( unsigned int i = 0; i < initialAudioAddresses.size(); i++ )
    {
        gravUtil::logVerbose ( "grav::initializing audio address %s\n",
                    initialAudioAddresses[i].c_str() );
        sessionTree->addSession( initialAudioAddresses[i], true, false );

        if ( haveAudioKey )
            sessionTree->setEncryptionKey( initialAudioAddresses[i],
                                            initialAudioKey );
    }

    if ( getAGVenueStreams && !disablePython )
    {
        venueClientController->updateVenueStreams();
        venueClientController->addAllVenueStreams();
    }

    if ( autoRotateAvailableVideo )
        sessionTree->startTimer( rotateIntervalMS );

    gravUtil::logVerbose( "grav::init function complete\n" );
    return true;
}
Ejemplo n.º 18
0
bool CBOINCGUIApp::SetActiveGUI(int iGUISelection, bool bShowWindow) {
    CBOINCBaseFrame* pNewFrame = NULL;
    CBOINCBaseFrame* pOldFrame = m_pFrame;
    wxInt32          iTop = 0;
    wxInt32          iLeft = 0;
    wxInt32          iHeight = 0;
    wxInt32          iWidth = 0;


    // Create the new window
    if ((iGUISelection != m_iGUISelected) || !m_pFrame) {

        // Reterieve the desired window state before creating the
        //   desired frames
        if (BOINC_ADVANCEDGUI == iGUISelection) {
            m_pConfig->SetPath(wxT("/"));
            m_pConfig->Read(wxT("YPos"), &iTop, 30);
            m_pConfig->Read(wxT("XPos"), &iLeft, 30);
            m_pConfig->Read(wxT("Width"), &iWidth, 800);
            m_pConfig->Read(wxT("Height"), &iHeight, 600);
        } else {
            m_pConfig->SetPath(wxT("/Simple"));
            m_pConfig->Read(wxT("YPos"), &iTop, 30);
            m_pConfig->Read(wxT("XPos"), &iLeft, 30);
#ifdef __WXMAC__
            m_pConfig->Read(wxT("Width"), &iWidth, 409);
            m_pConfig->Read(wxT("Height"), &iHeight, 561);
#else
            m_pConfig->Read(wxT("Width"), &iWidth, 416);
            m_pConfig->Read(wxT("Height"), &iHeight, 570);
#endif
        }


        // Make sure that the new window is going to be visible
        //   on a screen
#ifdef __WXMAC__
        Rect titleRect = {iTop, iLeft, iTop+22, iLeft+iWidth };
        InsetRect(&titleRect, 5, 5);                // Make sure at least a 5X5 piece visible
        RgnHandle displayRgn = NewRgn();
        CopyRgn(GetGrayRgn(), displayRgn);          // Region encompassing all displays
        Rect menuRect = ((**GetMainDevice())).gdRect;
        menuRect.bottom = GetMBarHeight() + menuRect.top;
        RgnHandle menuRgn = NewRgn();
        RectRgn(menuRgn, &menuRect);                // Region hidden by menu bar
        DiffRgn(displayRgn, menuRgn, displayRgn);   // Subtract menu bar retion
        if (!RectInRgn(&titleRect, displayRgn))
            iTop = iLeft = 30;
        DisposeRgn(menuRgn);
        DisposeRgn(displayRgn);
#else
	    // If either co-ordinate is less then 0 then set it equal to 0 to ensure
	    // it displays on the screen.
	    if ( iLeft < 0 ) iLeft = 30;
	    if ( iTop < 0 ) iTop = 30;

	    // Read the size of the screen
	    wxInt32 iMaxWidth = wxSystemSettings::GetMetric( wxSYS_SCREEN_X );
	    wxInt32 iMaxHeight = wxSystemSettings::GetMetric( wxSYS_SCREEN_Y );

	    // Max sure that it doesn't go off to the right or bottom
	    if ( iLeft + iWidth > iMaxWidth ) iLeft = iMaxWidth - iWidth;
	    if ( iTop + iHeight > iMaxHeight ) iTop = iMaxHeight - iHeight;
#endif

        // Create the main window
        //
        if (BOINC_ADVANCEDGUI == iGUISelection) {
            // Initialize the advanced gui window
            pNewFrame = new CAdvancedFrame(
                m_pSkinManager->GetAdvanced()->GetApplicationName(), 
                m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
                m_pSkinManager->GetAdvanced()->GetApplicationIcon32(),
                wxPoint(iLeft, iTop),
                wxSize(iWidth, iHeight)
            );
        } else {
            // Initialize the simple gui window
            pNewFrame = new CSimpleFrame(
                m_pSkinManager->GetAdvanced()->GetApplicationName(), 
                m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
                m_pSkinManager->GetAdvanced()->GetApplicationIcon32(),
                wxPoint(iLeft, iTop),
                wxSize(iWidth, iHeight)
            );
        }

        wxASSERT(pNewFrame);

        if (pNewFrame) {
            SetTopWindow(pNewFrame);

            // Store the new frame for future use
            m_pFrame = pNewFrame;

            // Hide the old one if it exists.  We must do this 
            // after updating m_pFrame to prevent Mac OSX from
            // hiding the application
            if (pOldFrame) pOldFrame->Hide();

            // Delete the old one if it exists
            // Note: this has the side effect of hiding the Event Log
            if (pOldFrame) pOldFrame->Destroy();

            // Show the new frame if needed (and show the Event Log if open)
            if (pNewFrame && bShowWindow) pNewFrame->Show();
        }
    }

    // Show the new frame if needed 
    if (m_pFrame && bShowWindow) {
        if (m_pEventLog) {
            m_pEventLog->Show();
            m_pEventLog->Raise();
#ifdef __WXMSW__
            ::SetForegroundWindow((HWND)m_pEventLog->GetHWND());
#endif
        }

        if (!m_pFrame->IsShown()) {
            m_pFrame->Show();
        }
        m_pFrame->Raise();

#ifdef __WXMSW__
        ::SetForegroundWindow((HWND)m_pFrame->GetHWND());
#endif
    }

    m_iGUISelected = iGUISelection;
    m_pConfig->SetPath(wxT("/"));
    m_pConfig->Write(wxT("GUISelection"), iGUISelection);

    return true;
}
Ejemplo n.º 19
0
//--------------------------------------------------------------------------------
bool iPoseApp::OnInit()
//--------------------------------------------------------------------------------
{
  mafPictureFactory::GetPictureFactory()->Initialize();
  #include "iPose/pic/FRAME_ICON16x16.xpm"
  mafADDPIC(FRAME_ICON16x16);
  
  #include "iPose/pic/FRAME_ICON32x32.xpm"
  mafADDPIC(FRAME_ICON32x32);
    
  #include "iPose/pic/MDICHILD_ICON.xpm"
  mafADDPIC(MDICHILD_ICON);

  int result;
 
  result = medVMEFactory::Initialize();
  assert(result == MAF_OK);

	result = medPipeFactoryVME::Initialize();
	assert(result==MAF_OK);

  result = mafInteractionFactory::Initialize();
  assert(result==MAF_OK);

  m_Logic = new mafLogicWithManagers();
  m_Logic->GetTopWin()->SetTitle("iPose");
  m_Logic->Configure();
  SetTopWindow(mafGetFrame());  

	wxRegKey RegKey(wxString("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\iPose"));
	if(RegKey.Exists())
	{
		RegKey.Create();
		wxString revision;
		RegKey.QueryValue(wxString("DisplayVersion"), revision);
		m_Logic->SetRevision(revision);
	}
	else
	{
		wxString revision="0.1";
		m_Logic->SetRevision(revision);
	}

  //------------------------- Importers -------------------------
  medGUIDicomSettings *dicomSettings=new medGUIDicomSettings(NULL,"DICOM");
  m_Logic->Plug(new medOpImporterDicomOffis("DICOM"),"Images",true,dicomSettings);
  m_Logic->Plug(new mafOpImporterSTL("STL"),"Geometries");
  //-------------------------------------------------------------

  //------------------------- Exporters -------------------------
  m_Logic->Plug(new mafOpExporterSTL("STL"),"Geometries");
  //-------------------------------------------------------------

  //------------------------- Operations -------------------------
  m_Logic->Plug(new iposeOpMove(),"Move");
  m_Logic->Plug(new mafOp2DMeasure(),"Measure");
  //-------------------------------------------------------------

  //------------------------- Views -------------------------
  mafViewVTK *viso = new mafViewVTK("Isosurface");
  viso->PlugVisualPipe("mafVMEVolumeGray", "mafPipeIsosurface",MUTEX);
  viso->PlugVisualPipe("medVMELabeledVolume", "mafPipeIsosurface",MUTEX);
  viso->PlugVisualPipe("mafVMEVolumeLarge","mafPipeIsosurface",MUTEX);
  m_Logic->Plug(viso);

  mafViewOrthoSlice *viewOrthoSlice = new mafViewOrthoSlice("OrthoSlice");
  viewOrthoSlice->PackageView();
  m_Logic->Plug(viewOrthoSlice);
  //-------------------------------------------------------------

  wxBitmap splashBitmap;
  splashBitmap.LoadFile("../Splash/iposeSplash.bmp", wxBITMAP_TYPE_BMP);
  m_Logic->ShowSplashScreen(splashBitmap); 

  // show the application
  m_Logic->Show();

  m_Logic->Init(0,NULL); // calls FileNew - which create the root

  return TRUE;
}
Ejemplo n.º 20
0
bool CBOINCGUIApp::SetActiveGUI(int iGUISelection, bool bShowWindow) {
    wxLogTrace(wxT("Function Start/End"), wxT("CBOINCGUIApp::SetActiveGUI - Function Begin"));
    wxLogTrace(wxT("Function Start/End"), wxT("CBOINCGUIApp::SetActiveGUI - GUI Selection: '%d', Show: %d'"), iGUISelection, (int)bShowWindow);

    CBOINCBaseFrame* pNewFrame = NULL;
    CBOINCBaseFrame* pOldFrame = m_pFrame;
    wxInt32          iTop = 0;
    wxInt32          iLeft = 0;
    wxInt32          iHeight = 0;
    wxInt32          iWidth = 0;


    // Create the new window
    if ((iGUISelection != m_iGUISelected) || !m_pFrame) {

        // Retrieve the desired window state before creating the
        //   desired frames
        if (BOINC_ADVANCEDGUI == iGUISelection) {
            m_pConfig->SetPath(wxT("/"));
            m_pConfig->Read(wxT("YPos"), &iTop, 30);
            m_pConfig->Read(wxT("XPos"), &iLeft, 30);
            m_pConfig->Read(wxT("Width"), &iWidth, 800);
            m_pConfig->Read(wxT("Height"), &iHeight, 600);
            // Guard against a rare situation where registry values are zero
            if (iWidth < 50) iWidth = 800;
            if (iHeight < 50) iHeight = 600;
        } else {
            m_pConfig->SetPath(wxT("/Simple"));
            m_pConfig->Read(wxT("YPos"), &iTop, 30);
            m_pConfig->Read(wxT("XPos"), &iLeft, 30);

            // We don't save Simple View's width & height since it's 
            // window is not resizable, so don't try to read them
#ifdef __WXMAC__
//            m_pConfig->Read(wxT("Width"), &iWidth, 409);
//            m_pConfig->Read(wxT("Height"), &iHeight, 561);
            iWidth = 409;
            iHeight = 561;
#else
//            m_pConfig->Read(wxT("Width"), &iWidth, 416);
//            m_pConfig->Read(wxT("Height"), &iHeight, 570);
            iWidth = 416;
            iHeight = 570;
#endif
        }


        // Make sure that the new window is going to be visible
        //   on a screen
#ifdef __WXMAC__
    if (!IsWindowOnScreen(iLeft, iTop, iWidth, iHeight)) {
        iTop = iLeft = 30;
    }
#else
	    // If either co-ordinate is less then 0 then set it equal to 0 to ensure
	    // it displays on the screen.
	    if ( iLeft < 0 ) iLeft = 30;
	    if ( iTop < 0 ) iTop = 30;

	    // Read the size of the screen
	    wxInt32 iMaxWidth = wxSystemSettings::GetMetric( wxSYS_SCREEN_X );
	    wxInt32 iMaxHeight = wxSystemSettings::GetMetric( wxSYS_SCREEN_Y );

	    // Max sure that it doesn't go off to the right or bottom
	    if ( iLeft + iWidth > iMaxWidth ) iLeft = iMaxWidth - iWidth;
	    if ( iTop + iHeight > iMaxHeight ) iTop = iMaxHeight - iHeight;
#endif

        // Create the main window
        //
        if (BOINC_ADVANCEDGUI == iGUISelection) {
            // Initialize the advanced gui window
            pNewFrame = new CAdvancedFrame(
                m_pSkinManager->GetAdvanced()->GetApplicationName(), 
                m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
                m_pSkinManager->GetAdvanced()->GetApplicationIcon32(),
                wxPoint(iLeft, iTop),
                wxSize(iWidth, iHeight)
            );
        } else {
            // Initialize the simple gui window
            pNewFrame = new CSimpleFrame(
                m_pSkinManager->GetAdvanced()->GetApplicationName(), 
                m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
                m_pSkinManager->GetAdvanced()->GetApplicationIcon32(),
                wxPoint(iLeft, iTop),
                wxSize(iWidth, iHeight)
            );
        }

        wxASSERT(pNewFrame);

        if (pNewFrame) {
            SetTopWindow(pNewFrame);

            // Store the new frame for future use
            m_pFrame = pNewFrame;

            // Hide the old one if it exists.  We must do this 
            // after updating m_pFrame to prevent Mac OSX from
            // hiding the application
            if (pOldFrame) pOldFrame->Hide();

            // Delete the old one if it exists
            if (pOldFrame) pOldFrame->Destroy();

            if (iGUISelection != m_iGUISelected) {
                m_iGUISelected = iGUISelection;
                m_pConfig->SetPath(wxT("/"));
                m_pConfig->Write(wxT("GUISelection"), iGUISelection);
                m_pConfig->Flush();
            }
        }
    }

    // Show the new frame if needed 
    if (m_pFrame && bShowWindow) {
        if (m_pEventLog) {
            m_pEventLog->Show();
            m_pEventLog->Raise();
#ifdef __WXMSW__
            ::SetForegroundWindow((HWND)m_pEventLog->GetHWND());
#endif
        }

        if (!m_pFrame->IsShown()) {
            m_pFrame->Show();
        }
        if (m_pFrame->IsIconized()) {
            m_pFrame->Maximize(false);
        }
        m_pFrame->Raise();

#ifdef __WXMSW__
        ::SetForegroundWindow((HWND)m_pFrame->GetHWND());
#endif
    }

    wxLogTrace(wxT("Function Start/End"), wxT("CBOINCGUIApp::SetActiveGUI - Function End"));
    return true;
}
Ejemplo n.º 21
0
bool App::OnInit()
{	
	// create a new frame and set it as the top most application window
	wxFrame* frame = new wxFrame(NULL, -1, wxT("Skopein"), wxDefaultPosition, wxSize( 1, 1));
	
	SetTopWindow(frame);
	
	// make menu
	wxMenu *fileMenu = new wxMenu;
	fileMenu->Append(wxID_SAVE, _("&Save\tS"));
	fileMenu->Append(ID_SETTINGS, _("Settings"));
	fileMenu->AppendSeparator();
    fileMenu->Append(wxID_EXIT, _("&Exit\tAlt-X"));
	
	wxMenu *aboutMenu = new wxMenu;
    aboutMenu->Append(wxID_ABOUT, wxT("Info"));
	
	
	wxMenuBar* menuBar = new wxMenuBar( wxMB_DOCKABLE );
    menuBar->Append(fileMenu, _("&File"));
	menuBar->Append(aboutMenu, wxT("&About")); //edit
	frame->SetMenuBar(menuBar);
	
	
	// create notebook and add sites
	frame->CreateStatusBar();
	mNotebook = new wxNotebook(frame,ID_NOTEBOOK);
	mOsziPage = new OsziPage(mNotebook,frame->GetStatusBar());
	mNotebook->AddPage(mOsziPage,_("Oscilloscope"),true);
	mFFTPage = new FFTPage(mNotebook,frame->GetStatusBar());
	mNotebook->AddPage(mFFTPage,wxT("FFT"));
	
	// create buttons and global widgets
	wxBoxSizer *buttonsizer = new wxBoxSizer( wxVERTICAL );
	buttonsizer->Add(new wxStaticText( frame, wxID_ANY,_("com port:")),0,wxALL, 5);
#ifdef __unix__
	frame->SetIcon(wxICON(Icon));

	mDeviceFilePicker = new wxFilePickerCtrl(frame, ID_DEVICE_PICKER_CTRL,wxT("/dev/"),wxEmptyString, wxT("tty*"),
                                        wxDefaultPosition, wxSize(110,-1),wxFLP_FILE_MUST_EXIST);
	buttonsizer->Add(mDeviceFilePicker,0,wxALL, 5);
#elif __WIN32__
	frame->SetIcon(wxIcon(Icon_xpm));
	
	wxChoice* comchoise = new wxChoice( frame, ID_COM_PORT);
	wxArrayString ports;
	ports.Add("COM 1");
	ports.Add("COM 2");
	ports.Add("COM 3");
	ports.Add("COM 4");
	ports.Add("COM 5");
	ports.Add("COM 6");
	ports.Add("COM 7");
	ports.Add("COM 8");

	comchoise->Append(ports);
	buttonsizer->Add(comchoise,0,wxALL, 5);
#endif
		
	buttonsizer->Add(new wxButton( frame, ID_MESSURE, _("Measure") ),0,wxALL, 5);
	
	// create sizer and add notebook and global buttons
	wxBoxSizer *topsizer = new  wxBoxSizer(wxHORIZONTAL);
	topsizer->Add(mNotebook,1, wxGROW | wxALL, 5);
	topsizer->Add(buttonsizer,0, wxALIGN_TOP| wxALL, 5);
	frame->SetSizerAndFit(topsizer);

	// show main frame
	GetTopWindow()->Show();
	
	// init timer
	mTimer.Start(50);

	// enter the application's main loop
	return true;
}
Ejemplo n.º 22
0
bool CMainApp::OnInit()
{
  m_pSingleInstance = new wxSingleInstanceChecker(wxT("c'mon"));
  if (m_pSingleInstance->IsAnotherRunning()) {
    delete m_pSingleInstance;
    return false;
  }

  // Check wether user dir exists
  wxFileName fn;
  fn.Assign(wxStandardPaths::Get().GetUserLocalDataDir(), wxT("cmon"), wxEmptyString);
  if (!fn.DirExists()) {
    fn.Mkdir();
  }

  // Initialize Log
  wxLog::SetActiveTarget(new
      CFileLog(CGlobalPreferences::getLogFileName(), 1024*1024, 5));

  // Initialize the locale catalogs we'll be using
  wxLocale::AddCatalogLookupPathPrefix(".");
  m_Locale.Init(wxLANGUAGE_DEFAULT);
  m_Locale.AddCatalog("wxstd");
  m_Locale.AddCatalog("hzshared");
  m_Locale.AddCatalog("gui");

  // Initialize all GUI resources (fonts, bitmaps, etc.)
  wxInitAllImageHandlers();
  RESOURCES::init();

  // Load preferences from registry
  m_pPrefs = GetGlobalPrefs();

  // Load plug-in DLLs
  m_pPluginLoader = new CPluginLoader();
  m_pPluginLoader->init();

  // Init Sockets
  wxSocketBase::Initialize();

  // Create/Open database
  m_pDB = new CDBBackend(m_pPrefs->getDBFileName());
  if (!m_pDB->isOk()) {
    wxMessageBox(wxString::FromUTF8(m_pDB->getLastError().c_str()),
        wxMessageBoxCaptionStr, wxICON_ERROR|wxOK);
  }
  // Create Journal model
  m_pJournalModel = new CJournalModel(m_pDB);
  // Restore resolvers
  m_pResolverModel = new CResolverModel(m_pDB);

  // Resync Resolvers
  const TAddressbookMap& books = m_pPluginLoader->getAddressbooks();
  TAddressbookMap::const_iterator bit = books.begin();
  for (; bit != books.end(); ++bit) {
    if (!m_pResolverModel->hasEntry((*bit).second->getName())) {
      CAddressBookResolver *pR = new CAddressBookResolver((*bit).second);
      pR->setName((*bit).second->getName());
      pR->enable();
      m_pResolverModel->prependEntry(pR);
    }
  }

  // Create main application window
  m_pFrame = new CMainFrame();

  // Create call notification system
  m_pNotificationMgr = new CNotificationMgr(this);
  // Register for call monitor notifications
  const TCallMonitorMap& cms = m_pPluginLoader->getCallMonitors();
  TCallMonitorMap::const_iterator cit = cms.begin();
  for (; cit != cms.end(); ++cit) {
    (*cit).second->registerCallObserver(this);
  }
  // Finally show main window
  if (!m_pPrefs->getPrefs().startHidden()) {
    m_pFrame->Show();
  }
  SetTopWindow(m_pFrame);

  return true;
}
Ejemplo n.º 23
0
// Initialise this in OnInit, not statically
bool MyApp::OnInit(void)
{//=====================

int j;
wxChar *p;
char param[80];


if(argc > 1)
{
	p = argv[1];
	j = 0;
	while((param[j] = p[j]) != 0) j++;

	if((strcmp(param,"--help")==0) || (strcmp(param,"-h")==0))
	{
		printf(about_string2,espeak_Info(NULL));
		printf("%s", help_text);
		exit(0);
	}

	ConfigInit();

	if(strcmp(param,"--compile")==0)
	{
	    LoadPhData(NULL);
        samplerate_native = samplerate = 22050;
		CompilePhonemeData();
		CompileIntonation();
	}
    exit(0);
}

	ConfigInit();
	gui_flag = 1;
	// It seems that the wctype functions don't work until the locale has been set
	// to something other than the default "C".  Then, not only Latin1 but also the
	// other characters give the correct results with iswalpha() etc.
	if(setlocale(LC_CTYPE,"en_US.UTF-8") == NULL)
	{
		if(setlocale(LC_CTYPE,"UTF-8") == NULL)
			setlocale(LC_CTYPE,"");
	}

	if((frame_w == 0) || (frame_h == 0))
	{
		frame_w = 800;
		frame_h = 768;
	}

  // Create the main frame window
	myframe = new MyFrame(NULL, -1, AppName, wxPoint(frame_x, frame_y), wxSize(frame_w, frame_h),
                      wxDEFAULT_FRAME_STYLE |
                      wxNO_FULL_REPAINT_ON_RESIZE |
                      wxHSCROLL | wxVSCROLL);


	// Make a menubar
	myframe->SetMenuBar(MakeMenu(0, voice_name2));
	myframe->CreateStatusBar();
	myframe->SetVoiceTitle(voice_name2);

//	myframe->Maximize();
	myframe->Show(TRUE);

	SetTopWindow(myframe);
	wxInitAllImageHandlers();
//	wxImage::AddHandler(wxPNGHandler);
  return TRUE;
}
Ejemplo n.º 24
0
// The `main program' equivalent, creating the windows and returning the
// main frame
bool AudacityApp::OnInit()
{
   // Unused strings that we want to be translated, even though
   // we're not using them yet...
   wxString future1 = _("Master Gain Control");
   wxString future2 = _("Input Meter");
   wxString future3 = _("Output Meter");

   ::wxInitAllImageHandlers();

   wxFileSystem::AddHandler(new wxZipFSHandler);

   InitPreferences();

	#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__) && !defined(__CYGWIN__)
		this->AssociateFileTypes(); 
	#endif

   //
   // Paths: set search path and temp dir path
   //

   wxString home = wxGetHomeDir();
   mAppHomeDir = home;

   // On Unix systems, the default temp dir is in /tmp.
   // Search path (in this order):
   // * The AUDACITY_PATH environment variable
   // * The current directory
   // * The user's .audacity-files directory in their home directory
   // * The "share" and "share/doc" directories in their install path
   #ifdef __WXGTK__
   defaultTempDir.Printf(wxT("/tmp/audacity1.2-%s"), wxGetUserId().c_str());
   wxString pathVar = wxGetenv(wxT("AUDACITY_PATH"));
   if (pathVar != wxT(""))
      AddMultiPathsToPathList(pathVar, audacityPathList);
   AddUniquePathToPathList(FROMFILENAME(::wxGetCwd()), audacityPathList);
   AddUniquePathToPathList(wxString::Format(wxT("%s/.audacity-files"),
                                            home.c_str()),
                           audacityPathList);
   #ifdef AUDACITY_NAME
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/%s"),
                                               wxT(INSTALL_PREFIX), wxT(AUDACITY_NAME)),
                              audacityPathList);
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/doc/%s"),
                                               wxT(INSTALL_PREFIX), wxT(AUDACITY_NAME)),
                              audacityPathList);
   #else
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/audacity"),
                                               wxT(INSTALL_PREFIX)),
                              audacityPathList);
      AddUniquePathToPathList(wxString::Format(wxT("%s/share/doc/audacity"),
                                               wxT(INSTALL_PREFIX)),
                              audacityPathList);
   #endif

   AddUniquePathToPathList(wxString::Format(wxT("%s/share/locale"),
                                            wxT(INSTALL_PREFIX)),
                           audacityPathList);

   #endif

   wxFileName tmpFile;
   tmpFile.AssignTempFileName(wxT("nn"));
   wxString tmpDirLoc = tmpFile.GetPath(wxPATH_GET_VOLUME);
   ::wxRemoveFile(FILENAME(tmpFile.GetFullPath()));

   // On Mac and Windows systems, use the directory which contains Audacity.
   #ifdef __WXMSW__
   // On Windows, the path to the Audacity program is in argv[0]
   wxString progPath = wxPathOnly(argv[0]);
   AddUniquePathToPathList(progPath, audacityPathList);
   AddUniquePathToPathList(progPath+wxT("\\Languages"), audacityPathList);
   defaultTempDir.Printf(wxT("%s\\audacity_1_2_temp"), tmpDirLoc.c_str());
   #endif
   #ifdef __MACOSX__
   // On Mac OS X, the path to the Audacity program is in argv[0]
   wxString progPath = wxPathOnly(argv[0]);

   AddUniquePathToPathList(progPath, audacityPathList);
   // If Audacity is a "bundle" package, then the root directory is
   // the great-great-grandparent of the directory containing the executable.
   AddUniquePathToPathList(progPath+wxT("/../../../"), audacityPathList);

   AddUniquePathToPathList(progPath+wxT("/Languages"), audacityPathList);
   AddUniquePathToPathList(progPath+wxT("/../../../Languages"), audacityPathList);
   defaultTempDir.Printf(wxT("%s/audacity1.2-%s"),
                         tmpDirLoc.c_str(),
                         wxGetUserId().c_str());
   #endif
   #ifdef __MACOS9__
   // On Mac OS 9, the initial working directory is the one that
   // contains the program.
   wxString progPath = wxGetCwd();
   AddUniquePathToPathList(progPath, audacityPathList);
   AddUniquePathToPathList(progPath+wxT(":Languages"), audacityPathList);
   defaultTempDir.Printf(wxT("%s/audacity_1_2_temp"), tmpDirLoc.c_str());
   #endif

   // BG: Create a temporary window to set as the top window
   wxFrame *temporarywindow = new wxFrame(NULL, -1, wxT("temporarytopwindow"));
   SetTopWindow(temporarywindow);

   // Locale
   // wxWindows 2.3 has a much nicer wxLocale API.  We can make this code much
   // better once we move to wx 2.3/2.4.

   wxString lang = gPrefs->Read(wxT("/Locale/Language"), wxT(""));

   // Pop up a dialog the first time the program is run
   if (lang == wxT(""))
      lang = ChooseLanguage(NULL);

#ifdef NOT_RQD
//TIDY-ME: (CleanSpeech) Language prompt??
// The prompt for language only happens ONCE on a system.
// I don't think we should disable it JKC
   wxString lang = gPrefs->Read(wxT("/Locale/Language"), "en");  //lda

// Pop up a dialog the first time the program is run
//lda   if (lang == "")
//lda      lang = ChooseLanguage(NULL);
#endif
   gPrefs->Write(wxT("/Locale/Language"), lang);

   if (lang != wxT("en")) {
      wxLogNull nolog;
      mLocale = new wxLocale(wxT(""), lang, wxT(""), true, true);

      for(unsigned int i=0; i<audacityPathList.GetCount(); i++)
         mLocale->AddCatalogLookupPathPrefix(audacityPathList[i]);

#ifdef AUDACITY_NAME
      mLocale->AddCatalog(wxT(AUDACITY_NAME));
#else
      mLocale->AddCatalog(wxT("audacity"));
#endif
   } else
      mLocale = NULL;

   // Initialize internationalisation (number formats etc.)
   //
   // This must go _after_ creating the wxLocale instance because
   // creating the wxLocale instance sets the application-wide locale.
   Internat::Init();

   // Init DirManager, which initializes the temp directory
   // If this fails, we must exit the program.

   if (!InitTempDir()) {
      FinishPreferences();
      return false;
   }

   // More initialization
   InitCleanSpeech();

   InitDitherers();
   InitAudioIO();

   LoadEffects();

#ifdef __WXMAC__

   // On the Mac, users don't expect a program to quit when you close the last window.
   // Create an offscreen frame with a menu bar.  The frame should never
   // be visible, but when all other windows are closed, this menu bar should
   // become visible.

   gParentFrame = new wxFrame(NULL, -1, wxT("invisible"), wxPoint(5000, 5000), wxSize(100, 100));

   wxMenu *fileMenu = new wxMenu();
   fileMenu->Append(wxID_NEW, wxT("&New\tCtrl+N"));
   fileMenu->Append(wxID_OPEN, wxT("&Open...\tCtrl+O"));
   /* i18n-hint: Mac OS X shortcut should be Ctrl+, */
   fileMenu->Append(wxID_PREFERENCES, _("&Preferences...\tCtrl+,"));

   wxMenuBar *menuBar = new wxMenuBar();
   menuBar->Append(fileMenu, wxT("&File"));

   gParentFrame->SetMenuBar(menuBar);

   gParentFrame->Show();

   SetTopWindow(gParentFrame);

#endif

   SetExitOnFrameDelete(true);


   ///////////////////////////////////////////////////////////////////
   //////////////////////////////////////////////////////////////////
   //Initiate pointers to toolbars here, and create 
   //the toolbars that should be loaded at startup.

   gControlToolBarStub = 
      LoadToolBar( wxT(""),true,
      gParentWindow,ControlToolBarID);
   gMixerToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableMixerToolBar"),true,
      gParentWindow,MixerToolBarID);
   gMeterToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableMeterToolBar"),true,
      gParentWindow,MeterToolBarID);
   gEditToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableEditToolBar"),true,
      gParentWindow,EditToolBarID);
   gTranscriptionToolBarStub = 
      LoadToolBar( wxT("/GUI/EnableTranscriptionToolBar"),false,
      gParentWindow,TranscriptionToolBarID);

   /// ToolBar Initiation Complete.
   ////////////////////////////////////////////////////////////////
   ////////////////////////////////////////////////////////////////

   AudacityProject *project = CreateNewAudacityProject(gParentWindow);
   SetTopWindow(project);

   delete temporarywindow;

   // Can't handle command-line args on Mac OS X yet...
   // Cygwin command-line parser below...
   #if !defined(__MACOSX__) && !defined(__CYGWIN__)
   // Parse command-line arguments
   if (argc > 1) {
      for (int option = 1; option < argc; option++) {
         if (!argv[option])
            continue;
         bool handled = false;

         if (!wxString(wxT("-help")).CmpNoCase(argv[option])) {
            wxPrintf(/* i18n-hint: '-help', '-test' and
                      '-blocksize' need to stay in English. */
                   _("Command-line options supported:\n  -help (this message)\n  -test (run self diagnostics)\n  -blocksize ### (set max disk block size in bytes)\n\nIn addition, specify the name of an audio file or Audacity project\nto open it.\n\n"));
            exit(0);
         }

         if (option < argc - 1 &&
             argv[option + 1] &&
             !wxString(wxT("-blocksize")).CmpNoCase(argv[option])) {
            long theBlockSize;
            if (wxString(argv[option + 1]).ToLong(&theBlockSize)) {
               if (theBlockSize >= 256 && theBlockSize < 100000000) {
                  wxFprintf(stderr, _("Using block size of %ld\n"),
                          theBlockSize);
                  Sequence::SetMaxDiskBlockSize(theBlockSize);
               }
            }
            option++;
            handled = true;
         }

         if (!handled && !wxString(wxT("-test")).CmpNoCase(argv[option])) {
            RunBenchmark(NULL);
            exit(0);
         }

         if (argv[option][0] == wxT('-') && !handled) {
            wxPrintf(_("Unknown command line option: %s\n"), argv[option]);
            exit(0);
         }

         if (!handled)
            project->OpenFile(argv[option]);

      }                         // for option...
   }                            // if (argc>1)
   #endif // not Mac OS X
	
   // Cygwin command line parser (by Dave Fancella)
   #if defined(__CYGWIN__)
   if (argc > 1) {
      int optionstart = 1;
      bool startAtOffset = false;
		
      // Scan command line arguments looking for trouble
      for (int option = 1; option < argc; option++) {
         if (!argv[option])
            continue;
         // Check to see if argv[0] is copied across other arguments.
         // This is the reason Cygwin gets its own command line parser.
         if (wxString(argv[option]).Lower().Contains(wxString(wxT("audacity.exe")))) {
            startAtOffset = true;
            optionstart = option + 1;
         }
      }
		
      for (int option = optionstart; option < argc; option++) {
         if (!argv[option])
            continue;
         bool handled = false;
         bool openThisFile = false;
         wxString fileToOpen;
			
         if (!wxString(wxT("-help")).CmpNoCase(argv[option])) {
            wxPrintf(/* i18n-hint: '-help', '-test' and
                      '-blocksize' need to stay in English. */
                   _("Command-line options supported:\n"
                     "  -help (this message)\n"
                     "  -test (run self diagnostics)\n"
                     "  -blocksize ### (set max disk block size in bytes)\n"
                     "\n"
                     "In addition, specify the name of an audio file or "
                     "Audacity project\n" "to open it.\n" "\n"));
            exit(0);
         }

         if (option < argc - 1 &&
             argv[option + 1] &&
             !wxString(wxT("-blocksize")).CmpNoCase(argv[option])) {
            long theBlockSize;
            if (wxString(argv[option + 1]).ToLong(&theBlockSize)) {
               if (theBlockSize >= 256 && theBlockSize < 100000000) {
                  wxFprintf(stderr, _("Using block size of %ld\n"),
                          theBlockSize);
                  Sequence::SetMaxDiskBlockSize(theBlockSize);
               }
            }
            option++;
            handled = true;
         }

         if (!handled && !wxString(wxT("-test")).CmpNoCase(argv[option])) {
            RunBenchmark(NULL);
            exit(0);
         }

         if (argv[option][0] == wxT('-') && !handled) {
            wxPrintf(_("Unknown command line option: %s\n"), argv[option]);
            exit(0);
         }
			
         if(handled)
            fileToOpen.Clear();
			
         if (!handled)
            fileToOpen = fileToOpen + wxT(" ") + argv[option];
         if(wxString(argv[option]).Lower().Contains(wxT(".aup")))
            openThisFile = true;
         if(openThisFile) {
            openThisFile = false;
            project->OpenFile(fileToOpen);
         }

      }                         // for option...
   }                            // if (argc>1)
   #endif // Cygwin command-line parser

   gInited = true;

   return TRUE;
}
Ejemplo n.º 25
0
// 'Main program' equivalent: the program execution "starts" here
bool CocoaDialogApp::OnInit()
{	
	if (utf8_args.GetCount() < 2)
		return OptionError();

	m_parentWnd = NULL;
	// This code is currently disabled, as it will end up
    // setting focus to a random window if parentwnd is busy.
	// http://blogs.msdn.com/oldnewthing/archive/2004/02/27/81155.aspx
#ifdef __WXMSW__
	// Use currently active window as parent
	HWND wnd = ::GetForegroundWindow();
	if (wnd) {
		m_parentWnd = new wxWindow();
		m_parentWnd->AssociateHandle(wnd);
	}
#endif //__WXMSW__
	
	// Parse the options
	const wxString runmode(utf8_args[1]);
	m_optionDict.SetRunmode(runmode);
	if (!m_optionDict.ParseArgs(utf8_args)) return OptionError();

//	m_optionDict.Print();

	//Initilizing image handlers
	//wxImage::AddHandler(new wxBMPHandler);
	wxImage::AddHandler(new wxPNGHandler);
	wxImage::AddHandler(new wxJPEGHandler);
	wxImage::AddHandler(new wxGIFHandler);
	wxImage::AddHandler(new wxICOHandler);

	// Show the Dialog
	if (runmode == wxT("inputbox")) {
		// Verify mandatory options
		if (!m_optionDict.HasOption(wxT("button1"))) return OptionError(wxT("At least one button has to be defined"));
		
		InputBox* inputBox = new InputBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
		SetTopWindow(inputBox);
	}
	else if (runmode == wxT("secure-inputbox")) {
		// Verify mandatory options
		if (!m_optionDict.HasOption(wxT("button1"))) return OptionError(wxT("At least one button has to be defined"));
		
		m_optionDict.SetOption(wxT("no-show"));
		
		new InputBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("standard-inputbox")) {
		m_optionDict.SetOption(wxT("button1"), wxT("Ok"));
		if (!m_optionDict.HasOption(wxT("no-cancel"))) m_optionDict.SetOption(wxT("button2"), wxT("Cancel"));

		new InputBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("secure-standard-inputbox")) {
		m_optionDict.SetOption(wxT("button1"), wxT("Ok"));
		if (!m_optionDict.HasOption(wxT("no-cancel"))) m_optionDict.SetOption(wxT("button2"), wxT("Cancel"));

		m_optionDict.SetOption(wxT("no-show"));

		new InputBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("progressbar")) {
		new ProgressBar(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("dropdown")) {
		// Verify mandatory options
		if (!m_optionDict.HasOption(wxT("button1"))) return OptionError(wxT("At least one button has to be defined."));
		if (!m_optionDict.HasMultiOption(wxT("items"))) return OptionError(wxT("Need to define items for dropdown box."));

		new DropdownBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("standard-dropdown")) {
		m_optionDict.SetOption(wxT("button1"), wxT("Ok"));
		m_optionDict.SetOption(wxT("button2"), wxT("Cancel"));
		// Verify mandatory options
		if (!m_optionDict.HasMultiOption(wxT("items"))) return OptionError(wxT("Need to define items for dropdown box."));

		new DropdownBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("msgbox")) {
		if (m_optionDict.HasOption(wxT("help"))) return OptionHelp(wxT("msgbox"));
		// Verify mandatory options
		if (!m_optionDict.HasOption(wxT("button1"))) return OptionError(wxT("At least one button has to be defined"));
		
		new MessageDialog(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("ok-msgbox")) {
		if (m_optionDict.HasOption(wxT("help"))) return OptionHelp(wxT("ok-msgbox"));
		m_optionDict.SetOption(wxT("button1"), wxT("Ok"));
		if (!m_optionDict.HasOption(wxT("no-cancel"))) m_optionDict.SetOption(wxT("button2"), wxT("Cancel"));
		
		new MessageDialog(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("yesno-msgbox")) {
		if (m_optionDict.HasOption(wxT("help"))) return OptionHelp(wxT("yesno-msgbox"));
		m_optionDict.SetOption(wxT("button1"), wxT("Yes"));
		m_optionDict.SetOption(wxT("button2"), wxT("No"));
		
		new MessageDialog(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("textbox")) {
		if (m_optionDict.HasOption(wxT("help"))) return OptionHelp(wxT("textbox"));
		// Verify mandatory options
		if (!m_optionDict.HasOption(wxT("button1"))) return OptionError(wxT("At least one button has to be defined"));
		
		new InputBox(m_parentWnd, m_optionDict, m_optionDict.HasOption(wxT("float")));
	}
	else if (runmode == wxT("fileselect") || runmode == wxT("filesave")) {
		ShowFileDialog();
		return false; // end program
	}
	else if (runmode == wxT("colourselect") || runmode == wxT("colorselect")) {
		ShowColourDialog();
		return false; // end program
	}
	else if (runmode == wxT("menu")) {
		ShowPopupMenu();
		return false; // end program
	}
#ifdef FEAT_BROWSER
	else if (runmode == wxT("html")) {
		new HtmlDialog(m_parentWnd, m_optionDict);
	}
#endif
	else return OptionError(wxT("Unknown runmode."));

	wxLogDebug(wxT("wxCD done"));

	return true;
}
Ejemplo n.º 26
0
bool hvApp::OnInit()
{
#ifdef __WXMOTIF__
    delete wxLog::SetActiveTarget(new wxLogStderr); // So dialog boxes aren't used
#endif

    // Don't exit on frame deletion, since the help window is programmed
    // to cause the app to exit even if it is still open. We need to have the app
    // close by other means.
    SetExitOnFrameDelete(false);

    wxArtProvider::Push(new AlternateArtProvider);

#ifdef __WXMAC__
    wxApp::s_macAboutMenuItemId = wxID_ABOUT;
    wxFileName::MacRegisterDefaultTypeAndCreator( wxT("htb") , 'HTBD' , 'HTBA' ) ;
#endif

    int istyle = wxHF_DEFAULT_STYLE|wxHF_OPEN_FILES;

    wxString service, windowName, titleFormat, argStr;
    wxString book[10];
    int bookCount = 0;
    int i;
    bool hasService = false;
    bool hasWindowName = false;
    bool createServer = false;

#if wxUSE_IPC
    m_server = NULL;
#endif

    // Help books are recognized by extension ".hhp" ".htb" or ".zip".
    // Service and window_name can occur anywhere in arguments,
    // but service must be first
    // Other arguments (topic?) could be added

    //  modes of operation:
    //  1) no arguments - stand alone, prompt user for book
    //  2) books only - stand alone, open books
    //  3) "--server" as (any) arg - start connection with default service;
    //     also open any books passed as other arguments
    //  4) at least one argument which is not book, and not "--server" - take first
    //     such argument as service, second (if present) as window name,
    //     start service, open any books

    for( i=1; i<argc; i++ )
    {
        argStr = argv[i];

        if ( argStr.Find( wxT(".hhp") ) >= 0
                || argStr.Find( wxT(".htb") ) >= 0
                || argStr.Find( wxT(".zip") ) >= 0 )
        {
            book[bookCount] = argStr;
            bookCount++;
        }
        else if ( argStr == wxT("--server") )
        {
            createServer = true;
#if defined(__WXMSW__)
            service = wxT("generic_helpservice");
#elif defined(__UNIX__)
            service = wxT("/tmp/") + wxString(wxT("generic_helpservice"));
#else
            service = wxT("4242");
#endif
        }
        else if ( !hasService )
        {
            service = argStr;
            hasService = true;
            createServer = true;
        }
        else if ( !hasWindowName )
        {
            windowName = argStr;
            hasWindowName = true;
        }
        else if ( argStr.Find( wxT("--Style") )  >= 0 )
        {
            long i;
            wxString numb = argStr.AfterLast(wxT('e'));
            if ( !(numb.ToLong(&i) ) )
            {
                wxLogError( wxT("Integer conversion failed for --Style") );
            }
            else
            {
                istyle = i;
            }
        }
        else
        {
            //unknown - could be topic?
        }
    }

    // No book - query user; but not on Mac, since there
    // may be an AppleEvent to open a document on the way
#ifndef __WXMAC__
    if ( bookCount < 1 )
    {
        wxString s = wxFileSelector( wxT("Open help file"),
                                     wxGetCwd(),
                                     wxEmptyString,
                                     wxEmptyString,
                                     wxT("Help books (*.htb)|*.htb|Help books (*.zip)|*.zip|HTML Help Project (*.hhp)|*.hhp"),
                                     wxFD_OPEN | wxFD_FILE_MUST_EXIST,
                                     NULL);

        if (!s.empty())
        {
            book[0] = s;
            bookCount = 1;
        }
    }
#endif

#if wxUSE_IPC

    if ( createServer )
    {
        // Create a new server
        m_server = new hvServer;

        if ( !m_server->Create(service) )
        {
            wxString wxm = wxT("Server Create failed - service: ");
            wxString xxm = wxm << service;
            wxLogError( xxm );
            //if MSW quits here, probably another copy already exists
            return false;
        }
        createServer = false;
        wxUnusedVar(createServer);
    }

#endif  // wxUSE_IPC

    //now add help
    wxInitAllImageHandlers();
    wxFileSystem::AddHandler(new wxZipFSHandler);

    SetVendorName(wxT("wxWidgets") );
    SetAppName(wxT("wxHTMLHelpServer") );
    wxConfig::Get(); // create an instance

    m_helpController = new wxHtmlHelpController( istyle );

    if ( !hasWindowName )
    {
        titleFormat = wxT("Help: %s") ;
    }
    else
    {
        //remove underscores
        windowName.Replace( wxT("_"), wxT(" ") );
        titleFormat = windowName;
    }

    m_helpController->SetTitleFormat( titleFormat );

    for( i=0; i<bookCount; i++ )
    {
        wxFileName fileName(book[i]);
        m_helpController->AddBook(fileName);
    }

#ifdef __WXMOTIF__
    delete wxLog::SetActiveTarget(new wxLogGui);
#endif

    m_helpController->DisplayContents();
    SetTopWindow(m_helpController->GetFrame());
    m_exitIfNoMainWindow = true;

    return true;
}
Ejemplo n.º 27
0
bool MyApp::OnInit() {
    MyFrame* frame = new MyFrame();
    SetTopWindow(frame);
    frame->Show(true);
    return true;
}
Ejemplo n.º 28
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"));

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

	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
	LSL::Util::config().ConfigurePaths(
		boost::filesystem::path(STD_STRING(SlPaths::GetCachePath())),
		boost::filesystem::path(STD_STRING(SlPaths::GetUnitSync())),
		boost::filesystem::path(STD_STRING(SlPaths::GetSpringBinary()))
	);

	//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;
}
Ejemplo n.º 29
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;
}
Ejemplo n.º 30
0
/// @brief Init the reporter.
bool Reporter::OnInit() {

	const std::string path_log(util::config_path() + "log/");
	wxFileName::Mkdir(path_log, 0777, wxPATH_MKDIR_FULL);
	agi::log::log = new agi::log::LogSink;
//	if ( !wxApp::OnInit() )
//		return false;

	wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, _("Reporter").c_str());


	static const wxCmdLineEntryDesc cmdLineDesc[] = {
		{ wxCMD_LINE_SWITCH, "c", "crash",      "Launch in crash mode.",	wxCMD_LINE_VAL_NONE, 0 },
		{ wxCMD_LINE_SWITCH, "r", "report",     "Launch in Report mode.",	wxCMD_LINE_VAL_NONE, 0 },
		{ wxCMD_LINE_SWITCH, "j", "json",		"Dump JSON file",			wxCMD_LINE_VAL_NONE, 0 },
		{ wxCMD_LINE_SWITCH, "h", "help",       "This help message",		wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
		{ wxCMD_LINE_NONE, NULL, NULL, NULL, wxCMD_LINE_VAL_NONE, 0 }
	};


	wxCmdLineParser parser(cmdLineDesc, argc, argv);

	parser.SetLogo("Aegisub Reporter version x.x");
	parser.SetCmdLine(argc, argv);
	switch ( parser.Parse() ) {
		case -1:
			return false;
			break; // Help
		case  0:
			break; // OK
		default:
			wxLogMessage(_T("Syntax error."));
			return false;
		break;
	}

	setlocale(LC_NUMERIC, "C");
 	setlocale(LC_CTYPE, "C");
	wxLocale *locale = new wxLocale();
	locale->Init(wxLANGUAGE_ENGLISH);
#ifdef __WINDOWS__
	wxStandardPathsBase &paths = wxStandardPaths::Get();
	locale->AddCatalogLookupPathPrefix(wxString::Format("%s/locale", paths.GetDataDir()));
	locale->AddCatalog(_T("reporter"));
#else
	locale->AddCatalog("reporter");
#endif
	locale->AddCatalog(_T("wxstd"));
	setlocale(LC_NUMERIC, "C");
	setlocale(LC_CTYPE, "C");


	mFrame *frame = new mFrame(_("Aegisub Reporter"));

	if (parser.Found("j")) {
		r->Save("report.json");
		std::cout << "Report saved to report.json" << std::endl;
		return false;
	}

	SetTopWindow(frame);

	r = new Report;
	frame->SetReport(r);

	return true;
}