Example #1
0
wxString wxGetUserId()
{
    static const int maxLoginLen = 256; // FIXME arbitrary number

    wxString buf;
    bool ok = wxGetUserId(wxStringBuffer(buf, maxLoginLen), maxLoginLen);

    if ( !ok )
        buf.Empty();

    return buf;
}
Example #2
0
void wxTerminal::DoWritePrompt()
{
	wxString prompt;
	for ( size_t n=0; n < m_promptFormat.Len(); ++n ) {
		wxChar c = m_promptFormat[n];
		if ( c != wxT('%') ) prompt += c;             // If this is a standard character, add it to the string
		else {
			c = m_promptFormat[++n];                    // If it was '%', the next char determines what to do
			if ( c==wxT('%') ) {
				prompt += c;                          // %% really means it
				continue;
			}
			if ( c==wxT('H') ) {
				prompt += wxGetFullHostName();        // Full host-name
				continue;
			}
			if ( c==wxT('h') ) {
				prompt += wxGetHostName();            // Less-full host-name
				continue;
			}
			if ( c==wxT('u') ) {
				prompt += wxGetUserId();              // Add user-name to prompt
				continue;
			}
			if ( c==wxT('w') ) {
				prompt += m_workingDir;                 // Add Current Working Dir
				continue;
			}
			if ( c==wxT('W') ) {
				wxString tmpwd = m_workingDir;
				wxString sep   = wxFileName::GetPathSeparator();
				if(tmpwd.EndsWith(sep)) {
					tmpwd.RemoveLast();
				}
				prompt += tmpwd.AfterLast(wxFILE_SEP_PATH);    // Filename-bit only of cwd
				continue;
			}
		}
	}

	int promptStart = m_textCtrl->GetLastPosition();
	m_textCtrl->AppendText( prompt ); //   write the prompt,
	// Cancel it, whether there's a valid one or not:  even an old selection interferes
	m_textCtrl->SetSelection( m_textCtrl->GetLastPosition(), m_textCtrl->GetLastPosition() );
	m_textCtrl->SetInsertionPointEnd();
	m_commandStart = m_textCtrl->GetInsertionPoint();

	m_textCtrl->SetStyle(promptStart, m_commandStart-1, m_promptStyle);
	// restore default style
	m_textCtrl->SetDefaultStyle( m_defaultStyle );
	m_textCtrl->SetFocus();
}
Example #3
0
void InteractiveOutputTestCase::TestUserInfo()
{
#ifdef TEST_INFO_FUNCTIONS
    wxPuts(wxT("*** Testing user info functions ***\n"));

    wxPrintf(wxT("User id is:\t%s\n"), wxGetUserId().c_str());
    wxPrintf(wxT("User name is:\t%s\n"), wxGetUserName().c_str());
    wxPrintf(wxT("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
    wxPrintf(wxT("Email address:\t%s\n"), wxGetEmailAddress().c_str());

    wxPuts(wxEmptyString);
#endif // TEST_INFO_FUNCTIONS
}
Example #4
0
void AddTodoDlg::LoadUsers() const
{
    wxChoice* cmb = XRCCTRL(*this, "chcUser", wxChoice);

    wxArrayString users;
    Manager::Get()->GetConfigManager(_T("todo_list"))->Read(_T("users"), &users);

    cmb->Clear();
    cmb->Append(users);

    if (cmb->GetCount() == 0)
        cmb->Append(wxGetUserId());
    cmb->SetSelection(0);
}
Example #5
0
wxChar* wxGetUserHome ( const wxString &rUser )
#endif
{
    wxChar*    zHome;
    wxString   sUser1(rUser);

    wxChar *wxBuffer = new wxChar[256];
#ifndef __EMX__
    if (!sUser1.empty())
    {
        wxChar                      zTmp[64];

        if (wxGetUserId( zTmp
                        ,sizeof(zTmp)/sizeof(char)
                       ))
        {
            // Guests belong in the temp dir
            if (wxStricmp(zTmp, _T("annonymous")) == 0)
            {
                if ((zHome = wxGetenv(_T("TMP"))) != NULL    ||
                    (zHome = wxGetenv(_T("TMPDIR"))) != NULL ||
                    (zHome = wxGetenv(_T("TEMP"))) != NULL)
                    delete[] wxBuffer;
                    return *zHome ? zHome : (wxChar*)_T("\\");
            }
            if (wxStricmp(zTmp, WXSTRINGCAST sUser1) == 0)
                sUser1 = wxEmptyString;
        }
    }
#endif
    if (sUser1.empty())
    {
        if ((zHome = wxGetenv(_T("HOME"))) != NULL)
        {
            wxStrcpy(wxBuffer, zHome);
            wxUnix2DosFilename(wxBuffer);
#if wxUSE_UNICODE
            wxWCharBuffer retBuffer (wxBuffer);
            delete[] wxBuffer;
            return retBuffer;
#else
            wxStrcpy(zHome, wxBuffer);
            delete[] wxBuffer;
            return zHome;
#endif
        }
    }
    delete[] wxBuffer;
    return (wxChar*)wxEmptyString; // No home known!
}
Example #6
0
wxString wxGetEmailAddress()
{
    wxString email;

    wxString host = wxGetFullHostName();
    if ( !host.empty() )
    {
        wxString user = wxGetUserId();
        if ( !user.empty() )
        {
            email << user << wxT('@') << host;
        }
    }

    return email;
}
Example #7
0
///
/// Detect if another instance of this application is running.
//  Returns true if there is and it is forbidden, otherwise false
//
// We must initialize m_pInstanceChecker even if m_bMultipleInstancesOK
// is true so CMainDocument::OnPoll() can call IsMgrMultipleInstance().
///
bool CBOINCGUIApp::DetectDuplicateInstance() {
#ifdef __WXMAC__
    m_pInstanceChecker = new wxSingleInstanceChecker(
            wxTheApp->GetAppName() + '-' + wxGetUserId(),
            wxFileName::GetHomeDir() + "/Library/Application Support/BOINC"
            );
#else
    m_pInstanceChecker = new wxSingleInstanceChecker();
#endif
    if (m_pInstanceChecker->IsAnotherRunning()) {
        if (m_bMultipleInstancesOK) return false;
#ifdef __WXMSW__
        CTaskBarIcon::FireAppRestore();
#endif
        return true;
    }
    return false;
}
Example #8
0
bool ManagerApp::OnInit() {
    const wxString name = wxString::Format(wxT("RCT3Manager-%s"), wxGetUserId().c_str());
    m_checker = new wxSingleInstanceChecker(name);
    if ( m_checker->IsAnotherRunning() ) {
        wxLogError(_("Another program instance is already running, aborting."));
        return false;
    }

	::wxInitAllImageHandlers();
    //wxXmlResource::Get()->InitAllHandlers();
    wxFileSystem::AddHandler(new wxArchiveFSHandler);
    wxFileSystem::AddHandler(new wxFilterFSHandler);
    wxFileSystem::AddHandler(new wxMemoryFSHandler);

    wxBZipClassFactory cf;

    xmlcpp::wxXmlInputCallbackFileSystem::Init();

    m_appdir = wxFileName(argv[0]).GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME);

    wxFileConfig::Set(new wxFileConfig(wxT("RCT3 Manager"), wxT("Freeware"), m_appdir.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME)+wxT("RCT3 Manager.conf"), wxT(""), wxCONFIG_USE_LOCAL_FILE));

    // *&^$% GraphicsMagick
    wxString appenv = wxT("MAGICK_CONFIGURE_PATH=") + m_appdir.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME);
    putenv(appenv.mb_str(wxConvLocal));

    if (!CheckInstallDir())
        return false;

    InitResources();

    if (!CheckManagerDB())
        return false;
    if (!CheckFilesDB())
        return false;

    frmMain* main = new frmMain(NULL);
    main->Show(true);
    SetTopWindow(main);

    return true;

}
Example #9
0
void AddTodoDlg::OnDelUser(wxCommandEvent&)
{
    wxChoice* cmb = XRCCTRL(*this, "chcUser", wxChoice);
    int sel = cmb->GetCurrentSelection();
    if (sel == wxNOT_FOUND)
        return;

    wxString msg; msg.Printf(_T("Are you sure you want to delete the user '%s'?"), cmb->GetString(sel).c_str());
    if (cbMessageBox(msg, _T("Confirmation"), wxICON_QUESTION | wxYES_NO) == wxID_NO)
       return;

    cmb->Delete(sel);
    if (cmb->GetCount() == 0)
    {
        cmb->Append(wxGetUserId());
        cbMessageBox(_T("Default user has been re-added to list of users."), _T("Information"), wxICON_INFORMATION);
    }
    cmb->SetSelection(0);
} // end of OnDelUser
Example #10
0
bool wxGetUserName(wxChar *buf, int sz)
{
#ifdef HAVE_PW_GECOS
    struct passwd *who;

    *buf = wxT('\0');
    if ((who = getpwuid (getuid ())) != NULL)
    {
        char *comma = strchr(who->pw_gecos, ',');
        if (comma)
            *comma = '\0'; // cut off non-name comment fields
        wxStrlcpy(buf, wxSafeConvertMB2WX(who->pw_gecos), sz);
        return true;
    }

    return false;
#else // !HAVE_PW_GECOS
    return wxGetUserId(buf, sz);
#endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
}
Example #11
0
wxTarUser::wxTarUser()
{
#ifdef __UNIX__
    uid = getuid();
    gid = getgid();
    wxString usr = wxTarUserName(uid);
    wxString grp = wxTarGroupName(gid);
#else
    uid = 0;
    gid = 0;
    wxString usr = wxGetUserId();
    wxString grp = _("unknown");
#endif

    uname = new wxChar[usr.length() + 1];
    wxStrcpy(uname, usr.c_str());

    gname = new wxChar[grp.length() + 1];
    wxStrcpy(gname, grp.c_str());
}
Example #12
0
bool CodeLiteApp::IsSingleInstance(const wxCmdLineParser& parser)
{
    // check for single instance
    if(clConfig::Get().Read(kConfigSingleInstance, false)) {
        wxString name = wxString::Format(wxT("CodeLite-%s"), wxGetUserId().c_str());
        
        wxString path;
#ifndef __WXMSW__
        path = "/tmp";
#endif
        m_singleInstance = new wxSingleInstanceChecker(name, path);
        if(m_singleInstance->IsAnotherRunning()) {
            // prepare commands file for the running instance
            wxArrayString files;
            for(size_t i = 0; i < parser.GetParamCount(); i++) {
                wxString argument = parser.GetParam(i);

                // convert to full path and open it
                wxFileName fn(argument);
                fn.MakeAbsolute();
                files.Add(fn.GetFullPath());
            }

            try {
                // Send the request
                clSocketClient client;
                bool dummy;
                client.ConnectRemote("127.0.0.1", SINGLE_INSTANCE_PORT, dummy);

                JSONRoot json(cJSON_Object);
                json.toElement().addProperty("args", files);
                client.WriteMessage(json.toElement().format());
                return false;

            } catch(clSocketException& e) {
                CL_ERROR("Failed to send single instance request: %s", e.what());
            }
        }
    }
    return true;
}
Example #13
0
bool RemindMe::OnInit() {
	InstanceChecker = new wxSingleInstanceChecker(wxString::Format(wxT("remind.me-%s"), wxGetUserId().c_str()));
	if (InstanceChecker->IsAnotherRunning()) {
		wxMessageBox(_("The program is already running."));
		return false;
	}
	
	// initialize random number generator for UIDs
	srand(time(NULL));
		
	// add PNG support for icons
	wxImage::AddHandler(new wxPNGHandler);
	
	MainWindow = new MainFrame((wxWindow*)NULL);
	//MainWindow->Show();
	SetTopWindow(MainWindow);
	
	Connect(wxEVT_QUERY_END_SESSION, wxCloseEventHandler(RemindMe::OnQueryEndSession));
	
	return true;
}
Example #14
0
wxString wxGetUserHome ( const wxString &rUser )
{
    wxChar*    zHome;
    wxString   sUser(rUser);

    wxString home;

#ifndef __EMX__
    if (!sUser.empty())
    {
        const wxString currentUser = wxGetUserId();

        // Guests belong in the temp dir
        if ( currentUser == "annonymous" )
        {
            zHome = wxGetenv(_T("TMP"));
            if ( !zHome )
                zHome = wxGetenv(_T("TMPDIR"));
            if ( !zHome )
                zHome = wxGetenv(_T("TEMP"));

            if ( zHome && *zHome )
                return zHome;
        }

        if ( sUser == currentUser )
            sUser.clear();
    }
#endif
    if (sUser.empty())
    {
        if ((zHome = wxGetenv(_T("HOME"))) != NULL)
        {
            home = zHome;
            home.Replace("/", "\\");
        }
    }

    return home;
}
Example #15
0
bool CodeLiteApp::IsSingleInstance(const wxCmdLineParser &parser, const wxString &curdir)
{
    // check for single instance
    if ( clConfig::Get().Read("SingleInstance", false) ) {
        const wxString name = wxString::Format(wxT("CodeLite-%s"), wxGetUserId().c_str());

        m_singleInstance = new wxSingleInstanceChecker(name);
        if (m_singleInstance->IsAnotherRunning()) {
            // prepare commands file for the running instance
            wxString files;
            for (size_t i=0; i< parser.GetParamCount(); i++) {
                wxString argument = parser.GetParam(i);

                //convert to full path and open it
                wxFileName fn(argument);
                fn.MakeAbsolute(curdir);
                files << fn.GetFullPath() << wxT("\n");
            }

            if (files.IsEmpty() == false) {
                Mkdir(ManagerST::Get()->GetStarupDirectory() + wxT("/ipc"));

                wxString file_name, tmp_file;
                tmp_file 	<< ManagerST::Get()->GetStarupDirectory()
                            << wxT("/ipc/command.msg.tmp");

                file_name 	<< ManagerST::Get()->GetStarupDirectory()
                            << wxT("/ipc/command.msg");

                // write the content to a temporary file, once completed,
                // rename the file to the actual file name
                WriteFileUTF8(tmp_file, files);
                wxRenameFile(tmp_file, file_name);
            }
            return false;
        }
    }
    return true;
}
Example #16
0
EWXWEXPORT(wxString*,ELJApp_GetUserId)()
{
	wxString *result = new wxString();
	*result = wxGetUserId();
	return result;
}
Example #17
0
void NumValidatorTestCase::Interactive()
{
    // FIXME: This test fails on MSW buildbot slaves although works fine on
    //        development machine, no idea why. It seems to be a problem with
    //        wxUIActionSimulator rather the wxListCtrl control itself however.
    if ( wxGetUserId().Lower().Matches("buildslave*") )
        return;

    // Set a locale using comma as thousands separator character.
    wxLocale loc(wxLANGUAGE_ENGLISH_UK, wxLOCALE_DONT_LOAD_DEFAULT);

    m_text->SetValidator(
        wxIntegerValidator<unsigned>(NULL, wxNUM_VAL_THOUSANDS_SEPARATOR));

    // Create a sibling text control to be able to switch focus and thus
    // trigger the control validation/normalization.
    wxTextCtrl * const text2 = new wxTextCtrl(m_text->GetParent(), wxID_ANY);
    text2->Move(10, 80); // Just to see it better while debugging...
    wxFloatingPointValidator<float> valFloat(3);
    valFloat.SetRange(-10., 10.);
    text2->SetValidator(valFloat);

    wxUIActionSimulator sim;

    // Entering '-' in a control with positive range is not allowed.
    m_text->SetFocus();
    sim.Char('-');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "", m_text->GetValue() );

    // Neither is entering '.' or any non-digit character.
    sim.Text(".a+/");
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "", m_text->GetValue() );

    // Entering digits should work though and after leaving the control the
    // contents should be normalized.
    sim.Text("1234567");
    wxYield();
    text2->SetFocus();
    wxYield();
    if ( loc.IsOk() )
        CPPUNIT_ASSERT_EQUAL( "1,234,567", m_text->GetValue() );
    else
        CPPUNIT_ASSERT_EQUAL( "1234567", m_text->GetValue() );


    // Entering both '-' and '.' in this control should work but only in the
    // correct order.
    sim.Char('-');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-", text2->GetValue() );

    text2->SetInsertionPoint(0);
    sim.Char('.');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-", text2->GetValue() );

    text2->SetInsertionPointEnd();
    sim.Char('.');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.", text2->GetValue() );

    // Adding up to three digits after the point should work.
    sim.Text("987");
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.987", text2->GetValue() );

    // But no more.
    sim.Text("654");
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.987", text2->GetValue() );

    // We can remove one digit and another one though.
    sim.Char(WXK_BACK);
    sim.Char(WXK_BACK);
    sim.Char('6');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "-.96", text2->GetValue() );


    // Also test the range constraint.
    text2->Clear();

    sim.Char('9');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "9", text2->GetValue() );

    sim.Char('9');
    wxYield();
    CPPUNIT_ASSERT_EQUAL( "9", text2->GetValue() );
}
Example #18
0
// Get user name e.g. Julian Smart
bool wxGetUserName(wxChar *buf, int maxSize)
{
    wxCHECK_MSG( buf && ( maxSize > 0 ), false,
                    _T("empty buffer in wxGetUserName") );
#if defined(__WXWINCE__)
    wxLogNull noLog;
    wxRegKey key(wxRegKey::HKCU, wxT("ControlPanel\\Owner"));
    if(!key.Open(wxRegKey::Read))
        return false;
    wxString name;
    if(!key.QueryValue(wxT("Owner"),name))
        return false;
    wxStrncpy(buf, name.c_str(), maxSize-1);
    buf[maxSize-1] = _T('\0');
    return true;
#elif defined(USE_NET_API)
    CHAR szUserName[256];
    if ( !wxGetUserId(szUserName, WXSIZEOF(szUserName)) )
        return false;

    // TODO how to get the domain name?
    CHAR *szDomain = "";

    // the code is based on the MSDN example (also see KB article Q119670)
    WCHAR wszUserName[256];          // Unicode user name
    WCHAR wszDomain[256];
    LPBYTE ComputerName;

    USER_INFO_2 *ui2;         // User structure

    // Convert ANSI user name and domain to Unicode
    MultiByteToWideChar( CP_ACP, 0, szUserName, strlen(szUserName)+1,
            wszUserName, WXSIZEOF(wszUserName) );
    MultiByteToWideChar( CP_ACP, 0, szDomain, strlen(szDomain)+1,
            wszDomain, WXSIZEOF(wszDomain) );

    // Get the computer name of a DC for the domain.
    if ( NetGetDCName( NULL, wszDomain, &ComputerName ) != NERR_Success )
    {
        wxLogError(wxT("Can not find domain controller"));

        goto error;
    }

    // Look up the user on the DC
    NET_API_STATUS status = NetUserGetInfo( (LPWSTR)ComputerName,
            (LPWSTR)&wszUserName,
            2, // level - we want USER_INFO_2
            (LPBYTE *) &ui2 );
    switch ( status )
    {
        case NERR_Success:
            // ok
            break;

        case NERR_InvalidComputer:
            wxLogError(wxT("Invalid domain controller name."));

            goto error;

        case NERR_UserNotFound:
            wxLogError(wxT("Invalid user name '%s'."), szUserName);

            goto error;

        default:
            wxLogSysError(wxT("Can't get information about user"));

            goto error;
    }

    // Convert the Unicode full name to ANSI
    WideCharToMultiByte( CP_ACP, 0, ui2->usri2_full_name, -1,
            buf, maxSize, NULL, NULL );

    return true;

error:
    wxLogError(wxT("Couldn't look up full user name."));

    return false;
#else  // !USE_NET_API
    // Could use NIS, MS-Mail or other site specific programs
    // Use wxWidgets configuration data
    bool ok = GetProfileString(WX_SECTION, eUSERNAME, wxEmptyString, buf, maxSize - 1) != 0;
    if ( !ok )
    {
        ok = wxGetUserId(buf, maxSize);
    }

    if ( !ok )
    {
        wxStrncpy(buf, wxT("Unknown User"), maxSize);
    }

    return true;
#endif // Win32/16
}
Example #19
0
void WinEDA_App::InitEDA_Appl(const wxString & name)
/***************************************************/
{
wxString ident;
wxString EnvLang;

	ident = name + wxT("-") + wxGetUserId();
	m_Checker = new wxSingleInstanceChecker(ident);

	/* Init environnement
	(KICAD definit le chemin de kicad ex: set KICAD=d:\kicad) */
	m_Env_Defined = wxGetEnv( wxT("KICAD"), &m_KicadEnv);
	if ( m_Env_Defined )	// m_KicadEnv doit finir par "/" ou "\"
	{
		m_KicadEnv.Replace(WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP);
		if ( m_KicadEnv.Last() != '/' ) m_KicadEnv += UNIX_STRING_DIR_SEP;
	}

	/* Prepare On Line Help */
	m_HelpFileName = name + wxT(".html");

	// Init parametres pour configuration
	SetVendorName(wxT("kicad"));
	SetAppName(name);
	m_EDA_Config = new wxConfig(name);
	m_EDA_CommonConfig = new wxConfig(wxT("kicad_common"));

	/* Creation des outils de trace */
	DrawPen = new wxPen( wxT("GREEN"), 1, wxSOLID);
	DrawBrush = new wxBrush(wxT("BLACK"), wxTRANSPARENT);

	/* Creation des fontes utiles */
	g_StdFontPointSize = FONT_DEFAULT_SIZE;
	g_MsgFontPointSize = FONT_DEFAULT_SIZE;
	g_DialogFontPointSize = FONT_DEFAULT_SIZE;
	g_FixedFontPointSize = FONT_DEFAULT_SIZE;
	g_StdFont = new wxFont(g_StdFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL);
	g_MsgFont = new wxFont(g_StdFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL);
	g_DialogFont = new wxFont(g_DialogFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL);
	g_ItalicFont = new wxFont(g_DialogFontPointSize, wxFONTFAMILY_ROMAN, wxFONTSTYLE_ITALIC,  wxNORMAL);
	g_FixedFont = new wxFont(g_FixedFontPointSize, wxFONTFAMILY_MODERN, wxNORMAL, wxNORMAL);

	/* installation des gestionnaires de visu d'images (pour help) */
	wxImage::AddHandler(new wxPNGHandler);
	wxImage::AddHandler(new wxGIFHandler);
	wxImage::AddHandler(new wxJPEGHandler);
    wxFileSystem::AddHandler(new wxZipFSHandler);

	// Analyse command line & init binary path
	SetBinDir();

	// Internationalisation: chargement du Dictionnaire de kicad
	m_EDA_CommonConfig->Read(wxT("Language"), &m_LanguageId, wxLANGUAGE_DEFAULT);

bool succes = SetLanguage(TRUE);
	if ( ! succes )
		{
		}

	if ( atof("0,1") ) g_FloatSeparator = ','; // Nombres flottants = 0,1
	else  g_FloatSeparator = '.';

}
Example #20
0
bool CodeBlocksApp::OnInit()
{
#ifdef __WXMSW__
    InitCommonControls();
#endif

    wxLog::EnableLogging(true);

    SetAppName(_T("codeblocks"));

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

    wxTheClipboard->Flush();

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

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

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

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

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

        InitExceptionHandler();

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

        if ( !LoadConfig() )
            return false;

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

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

        InitLocale();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        CheckVersion();

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

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

        frame->StartupDone();

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

        if (platform::windows)
            InitAssociations();

        s_Loading = false;

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

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

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

        return true;
    }
    catch (cbException& exception)
    {
        exception.ShowErrorMessage();
    }
    catch (SquirrelError& exception)
    {
        Manager::Get()->GetScriptingManager()->DisplayErrors(&exception);
    }
    catch (const char* message)
    {
        wxSafeShowMessage(_T("Exception"), cbC2U(message));
    }
    catch (...)
    {
        wxSafeShowMessage(_T("Exception"), _T("Unknown exception was raised. The application will terminate immediately..."));
    }
    // if we reached here, return error
    return false;
}
Example #21
0
bool wxFBIPC::VerifySingleInstance( const wxString& file, bool switchTo )
{
    // Possible send a message to the running instance through this string later, for now it is left empty
    wxString expression = wxEmptyString;

    // Make path absolute
    wxFileName path( file );
    if ( !path.IsOk() )
    {
        wxLogError( wxT("This path is invalid: %s"), file.c_str() );
        return false;
    }

    if ( !path.IsAbsolute() )
    {
        if ( !path.MakeAbsolute() )
        {
            wxLogError( wxT("Could not make path absolute: %s"), file.c_str() );
            return false;
        }
    }

    // Check for single instance

    // Create lockfile/mutex name
    wxString name = wxString::Format( wxT("wxFormBuilder-%s-%s"), wxGetUserId().c_str(), path.GetFullPath().c_str() );

    // Get forbidden characters
    wxString forbidden = wxFileName::GetForbiddenChars();

    // Repace forbidded characters
    for ( size_t c = 0; c < forbidden.Length(); ++c )
    {
        wxString bad( forbidden.GetChar( c ) );
        name.Replace( bad.c_str(), wxT("_") );
    }

    // Paths are not case sensitive in windows
#ifdef __WXMSW__
    name = name.MakeLower();
#endif

    // GetForbiddenChars is missing "/" in unix. Prepend '.' to make lockfiles hidden
#ifndef __WXMSW__
    name.Replace( wxT("/"), wxT("_") );
    name.Prepend( wxT(".") );
#endif

    // Check to see if I already have a server with this name - if so, no need to make another!
    if ( m_server.get() )
    {
        if ( m_server->m_name == name )
        {
            return true;
        }
    }

    std::auto_ptr< wxSingleInstanceChecker > checker;
    {
        // Suspend logging, because error messages here are not useful
#ifndef __WXFB_DEBUG__
        wxLogNull stopLogging;
#endif
        checker.reset( new wxSingleInstanceChecker( name ) );
    }

    if ( !checker->IsAnotherRunning() )
    {
        // This is the first instance of this project, so setup a server and save the single instance checker
        if ( CreateServer( name ) )
        {
            m_checker = checker;
            return true;
        }
        else
        {
            return false;
        }
    }
    else if ( switchTo )
    {
        // Suspend logging, because error messages here are not useful
#ifndef __WXFB_DEBUG__
        wxLogNull stopLogging;
#endif

        // There is another app, so connect and send the expression

        // Cannot have a client and a server at the same time, due to the implementation of wxTCPServer and wxTCPClient,
        // so temporarily drop the server if there is one
        bool hadServer = false;
        wxString oldName;
        if ( m_server.get() != NULL )
        {
            oldName = m_server->m_name;
            m_server.reset();
            hadServer = true;
        }

        // Create the client
        std::auto_ptr< AppClient > client( new AppClient );

        // Create the connection
        std::auto_ptr< wxConnectionBase > connection;
#ifdef __WXMSW__
        connection.reset( client->MakeConnection( wxT("localhost"), name, name ) );
#else
        bool connected = false;
        for ( int i = m_port; i < m_port + 20; ++i )
        {
#if wxVERSION_NUMBER < 2900
            wxString nameWithPort = wxString::Format( wxT("%i%s"), i, name.c_str() );
            connection.reset( client->MakeConnection( wxT("127.0.0.1"), nameWithPort, name ) );
#else
            wxString sPort = wxString::Format( "%i", i );
            connection.reset( client->MakeConnection( "localhost", sPort, name ) );
#endif
            if ( NULL != connection.get() )
            {
                connected = true;
                wxChar* pid = (wxChar*)connection->Request( wxT("PID"), NULL );
                if ( NULL != pid )
                {
                    wxLogStatus( wxT("%s already open in process %s"), file.c_str(), pid );
                }
                break;
            }
        }
        if ( !connected )
        {
            wxLogError( wxT("There is a lockfile named '%s', but unable to make a connection to that instance."), name.c_str() );
        }
#endif

        // Drop the connection and client
        connection.reset();
        client.reset();

        // Create the server again, if necessary
        if ( hadServer )
        {
            CreateServer( oldName );
        }
    }
    return false;
}
Example #22
0
void EDA_APP::InitEDA_Appl( const wxString& aName, EDA_APP_T aId )
{
    wxString EnvLang;

    m_Id = aId;
    m_Checker = new wxSingleInstanceChecker( aName.Lower() + wxT( "-" ) + wxGetUserId() );

    // Init KiCad environment
    // the environment variable KICAD (if exists) gives the kicad path:
    // something like set KICAD=d:\kicad
    bool isDefined = wxGetEnv( wxT( "KICAD" ), &m_KicadEnv );

    if( isDefined )    // ensure m_KicadEnv ends by "/"
    {
        m_KicadEnv.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP );

        if( !m_KicadEnv.IsEmpty() && m_KicadEnv.Last() != '/' )
            m_KicadEnv += UNIX_STRING_DIR_SEP;
    }

    // Prepare On Line Help. Use only lower case for help file names, in order to
    // avoid problems with upper/lower case file names under windows and unix.
#if defined ONLINE_HELP_FILES_FORMAT_IS_HTML
    m_HelpFileName = aName.Lower() + wxT( ".html" );
#elif defined ONLINE_HELP_FILES_FORMAT_IS_PDF
    m_HelpFileName = aName.Lower() + wxT( ".pdf" );
#else
    #error Help files format not defined
#endif

    // Init parameters for configuration
    SetVendorName( wxT( "KiCad" ) );
    SetAppName( aName.Lower() );
    SetTitle( aName );
    m_settings = new wxConfig();
    wxASSERT( m_settings != NULL );
    m_commonSettings = new wxConfig( CommonConfigPath );
    wxASSERT( m_commonSettings != NULL );

    // Install some image handlers, mainly for help
    wxImage::AddHandler( new wxPNGHandler );
    wxImage::AddHandler( new wxGIFHandler );
    wxImage::AddHandler( new wxJPEGHandler );
    wxFileSystem::AddHandler( new wxZipFSHandler );

    // Analyze the command line & init binary path
    SetBinDir();
    SetDefaultSearchPaths();
    SetLanguagePath();
    ReadPdfBrowserInfos();

    // Internationalization: loading the kicad suitable Dictionary
    wxString languageSel;
    m_commonSettings->Read( languageCfgKey, &languageSel);
    m_LanguageId = wxLANGUAGE_DEFAULT;

    // Search for the current selection
    for( unsigned int ii = 0; ii < LANGUAGE_DESCR_COUNT; ii++ )
    {
        if( s_Language_List[ii].m_Lang_Label == languageSel )
        {
            m_LanguageId = s_Language_List[ii].m_WX_Lang_Identifier;
            break;
        }
    }

    bool succes = SetLanguage( true );

    if( !succes )
    {
    }

    // Set locale option for separator used in float numbers
    SetLocaleTo_Default();
}
Example #23
0
wxString Path::Normalise(const wxString &path){
#ifdef __WXMSW__
	//We only need to set this up once, and do it the first time
	if(DriveLabels.empty()){
		TCHAR drives[256];  
		if(GetLogicalDriveStrings(256, drives)){  
			LPTSTR drive = drives;
			int offset = _tcslen(drive) + 1;  
			while(*drive){  
				wxString volumename = wxEmptyString;
				TCHAR label[256]; 
				if(GetVolumeInformation(drive, label, sizeof(label), NULL, 0, NULL, NULL, 0)){
					volumename.Printf(wxT("%s"),label); 
					if(volumename != wxEmptyString){
						DriveLabels[volumename] = wxString(drive).Left(2);
					}
				}
				drive += offset;  
			}
		}
	}
#endif
	if(path.find("@") == wxNOT_FOUND){
		return path;
	}
	wxString token;
	wxString normalised = wxEmptyString;
	wxDateTime now = wxDateTime::Now();  
	wxStringTokenizer tkz(path, wxT("@"), wxTOKEN_RET_EMPTY_ALL);
	bool previousmatched = true;
    wxFileConfig config("", "", Locations::GetSettingsPath() + "variables.ini");
	while(tkz.HasMoreTokens()){
        token = tkz.GetNextToken();
		wxString strValue, read;
		if(token == "date"){
			token = now.FormatISODate();
			normalised += token;
			previousmatched = true;
		}
		else if(token == "time"){
			token = now.Format("%H") + "-" +  now.Format("%M");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "YYYY" || token == "year"){
			token = now.Format("%Y");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "MM" || token == "month"){
			token = now.Format("%m");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "monthname"){
            token = wxDateTime::GetMonthName(wxDateTime::Now().GetMonth());
			normalised += token;
			previousmatched = true;
		}
		else if(token == "monthshortname"){
            token = wxDateTime::GetMonthName(wxDateTime::Now().GetMonth(), wxDateTime::Name_Abbr);
			normalised += token;
			previousmatched = true;
		}
		else if(token == "DD" || token == "day"){
			token = now.Format("%d");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "dayname"){
            token = wxDateTime::GetWeekDayName(wxDateTime::Now().GetWeekDay());
			normalised += token;
			previousmatched = true;
		}
		else if(token == "dayshortname"){
            token = wxDateTime::GetWeekDayName(wxDateTime::Now().GetWeekDay(), wxDateTime::Name_Abbr);
			normalised += token;
			previousmatched = true;
		}
		else if(token == "hh" || token == "hour"){
			token = now.Format(wxT("%H"));
			normalised += token;
			previousmatched = true;
		}
		else if(token == "mm" || token == "minute"){
			token = now.Format("%M");
			normalised += token;
			previousmatched = true;
		}
		else if(token == "dayofweek"){
            int num = wxDateTime::Now().GetWeekDay();
            if(num == 0)
                num = 7;
            token = wxString::Format("%d", num);
			normalised += token;
			previousmatched = true;
		}
		else if(token == "weekofyear"){
            int num = wxDateTime::Now().GetWeekOfYear();
            token = wxString::Format("%d", num);
			normalised += token;
			previousmatched = true;
		}
		else if(token == wxT("drive")){
			normalised += wxPathOnly(wxStandardPaths::Get().GetExecutablePath()).Left(2);
			previousmatched = true;
		}
		else if(token == wxT("docs")){
			normalised += wxStandardPaths::Get().GetDocumentsDir();
			previousmatched = true;
		}
        else if(token == "username"){
            normalised += wxGetUserId();
            previousmatched = true;
        }
		else if(token == wxT("volume")){
			#ifdef __WXMSW__
				wxString name = wxEmptyString;
				WCHAR volumeLabel[256]; 
				GetVolumeInformation(wxPathOnly(wxStandardPaths::Get().GetExecutablePath()).Left(3), volumeLabel, sizeof(volumeLabel), NULL, 0, NULL, NULL, 0);
				name.Printf(wxT("%s"),volumeLabel); 
				normalised += name;
			#endif
			previousmatched = true;
		}
		else if(token == wxT("label")){
		 	wxFileConfig autorun("", "", wxPathOnly(wxStandardPaths::Get().GetExecutablePath()).Left(3) + wxFILE_SEP_PATH + wxT("autorun.inf"));
			wxString label = autorun.Read(wxT("Autorun/Label"));
			normalised += label;
			previousmatched = true;
		}
		else if(DriveLabels[token] != wxEmptyString){
			normalised += DriveLabels[token];
			previousmatched = true;
		}
		else if(wxGetEnv(token , &strValue)){
			normalised += strValue;
			previousmatched = true;
		}
		else if(config.HasGroup(token) && config.Read(token + wxT("/") + wxGetFullHostName(), &read)){
			normalised += read;
			previousmatched = true;
		}
		else if(config.HasGroup(token) && config.Read(token + wxT("/") + _("Other"), &read)){
			normalised += read;
			previousmatched = true;
		}
		else{
			if(previousmatched){
				normalised += token;
			}
			else{
				normalised = normalised + wxT("@") + token;
			}
			//This time we did not match
			previousmatched = false;
		}
	}
	if(normalised.Length() == 2 && normalised.Right(1) == wxT(":")){
		normalised += wxFILE_SEP_PATH;
	}
	wxFileName flReturn(normalised);
	if(flReturn.IsOk()){
		//If we havent made any changes in this run then return, else scan again
		//as new variables may have been added
		return normalised == path ? path : Normalise(normalised);
	}
	return wxEmptyString;
}
Example #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;
}
Example #25
0
void ListBaseTestCase::ItemClick()
{
    // FIXME: This test fail under wxGTK because we get 3 FOCUSED events and
    //        2 SELECTED ones instead of the one of each we expect for some
    //        reason, this needs to be debugged as it may indicate a bug in the
    //        generic wxListCtrl implementation.
#if wxUSE_UIACTIONSIMULATOR && !defined(__WXGTK__)

    // FIXME: This test fails on MSW buildbot slaves although works fine on
    //        development machine, no idea why. It seems to be a problem with
    //        wxUIActionSimulator rather the wxListCtrl control itself however.
    if ( wxGetUserId().Lower().Matches("buildslave*") )
        return;

    wxTestableFrame* frame = wxStaticCast(wxTheApp->GetTopWindow(),
                                          wxTestableFrame);

    wxListCtrl* const list = GetList();

    list->InsertColumn(0, "Column 0", wxLIST_FORMAT_LEFT, 60);
    list->InsertColumn(1, "Column 1", wxLIST_FORMAT_LEFT, 50);
    list->InsertColumn(2, "Column 2", wxLIST_FORMAT_LEFT, 40);

    list->InsertItem(0, "Item 0");
    list->SetItem(0, 1, "first column");
    list->SetItem(0, 2, "second column");

    EventCounter count(list, wxEVT_COMMAND_LIST_ITEM_SELECTED);
    EventCounter count1(list, wxEVT_COMMAND_LIST_ITEM_FOCUSED);
    EventCounter count2(list, wxEVT_COMMAND_LIST_ITEM_ACTIVATED);
    EventCounter count3(list, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK);

    wxUIActionSimulator sim;

    wxRect pos;
    list->GetItemRect(0, pos);

    //We move in slightly so we are not on the edge
    wxPoint point = list->ClientToScreen(pos.GetPosition()) + wxPoint(2, 2);

    sim.MouseMove(point);
    wxYield();

    sim.MouseClick();
    wxYield();

    sim.MouseDblClick();
    wxYield();

    sim.MouseClick(wxMOUSE_BTN_RIGHT);
    wxYield();

    // when the first item was selected the focus changes to it, but not
    // on subsequent clicks
    CPPUNIT_ASSERT_EQUAL(1, frame->GetEventCount(wxEVT_COMMAND_LIST_ITEM_FOCUSED));
    CPPUNIT_ASSERT_EQUAL(1, frame->GetEventCount(wxEVT_COMMAND_LIST_ITEM_SELECTED));
    CPPUNIT_ASSERT_EQUAL(1, frame->GetEventCount(wxEVT_COMMAND_LIST_ITEM_ACTIVATED));
    CPPUNIT_ASSERT_EQUAL(1, frame->GetEventCount(wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK));

    //tidy up when we are finished
    list->ClearAll();
#endif // wxUSE_UIACTIONSIMULATOR
}
Example #26
0
bool PGM_BASE::initPgm()
{
    wxFileName pgm_name( App().argv[0] );

    wxConfigBase::DontCreateOnDemand();

    wxInitAllImageHandlers();

    m_pgm_checker = new wxSingleInstanceChecker( pgm_name.GetName().Lower() + wxT( "-" ) +
                                                 wxGetUserId(), GetKicadLockFilePath() );

    if( m_pgm_checker->IsAnotherRunning() )
    {
        wxString quiz = wxString::Format(
            _( "%s is already running, Continue?" ),
            GetChars( pgm_name.GetName() )
            );

        if( !IsOK( NULL, quiz ) )
            return false;
    }

    // Init KiCad environment
    // the environment variable KICAD (if exists) gives the kicad path:
    // something like set KICAD=d:\kicad
    bool isDefined = wxGetEnv( wxT( "KICAD" ), &m_kicad_env );

    if( isDefined )    // ensure m_kicad_env ends by "/"
    {
        m_kicad_env.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP );

        if( !m_kicad_env.IsEmpty() && m_kicad_env.Last() != '/' )
            m_kicad_env += UNIX_STRING_DIR_SEP;
    }

    // Init parameters for configuration
    App().SetVendorName( wxT( "KiCad" ) );
    App().SetAppName( pgm_name.GetName().Lower() );

    // Install some image handlers, mainly for help
    if( wxImage::FindHandler( wxBITMAP_TYPE_PNG ) == NULL )
        wxImage::AddHandler( new wxPNGHandler );

    if( wxImage::FindHandler( wxBITMAP_TYPE_GIF ) == NULL )
        wxImage::AddHandler( new wxGIFHandler );

    if( wxImage::FindHandler( wxBITMAP_TYPE_JPEG ) == NULL )
        wxImage::AddHandler( new wxJPEGHandler );

    wxFileSystem::AddHandler( new wxZipFSHandler );

    // Analyze the command line & initialize the binary path
    setExecutablePath();

    SetLanguagePath();

    // OS specific instantiation of wxConfigBase derivative:
    m_common_settings = GetNewConfig( KICAD_COMMON );

    // Only define the default environment variable if they haven't been set in the
    // .kicad_common configuration file.
    if( m_common_settings && !m_common_settings->HasGroup( pathEnvVariables ) )
    {
        wxString envVarName = wxT( "KIGITHUB" );
        ENV_VAR_ITEM envVarItem;
        wxString envValue;
        wxFileName tmpFileName;

        envVarItem.SetValue( wxString( wxT( "https://github.com/KiCad" ) ) );
        envVarItem.SetDefinedExternally( wxGetEnv( envVarName, NULL ) );
        m_local_env_vars[ envVarName ] = envVarItem;

        wxFileName baseSharePath;
        baseSharePath.AssignDir( wxString( wxT( DEFAULT_INSTALL_PATH ) ) );

#if !defined( __WXMAC__ )
        baseSharePath.AppendDir( wxT( "share" ) );
        baseSharePath.AppendDir( wxT( "kicad" ) );
#endif

        // KISYSMOD
        envVarName = wxT( "KISYSMOD" );
        if( wxGetEnv( envVarName, &envValue ) == true && !envValue.IsEmpty() )
        {
            tmpFileName.AssignDir( envValue );
            envVarItem.SetDefinedExternally( true );
        }
        else
        {
            tmpFileName = baseSharePath;
            tmpFileName.AppendDir( wxT( "modules" ) );
            envVarItem.SetDefinedExternally( false );
        }
        envVarItem.SetValue( tmpFileName.GetFullPath() );
        m_local_env_vars[ envVarName ] = envVarItem;

        // KISYS3DMOD
        envVarName = wxT( "KISYS3DMOD" );
        if( wxGetEnv( envVarName, &envValue ) == true && !envValue.IsEmpty() )
        {
            tmpFileName.AssignDir( envValue );
            envVarItem.SetDefinedExternally( true );
        }
        else
        {
            tmpFileName.AppendDir( wxT( "packages3d" ) );
            envVarItem.SetDefinedExternally( false );
        }
        envVarItem.SetValue( tmpFileName.GetFullPath() );
        m_local_env_vars[ envVarName ] = envVarItem;

        // KICAD_PTEMPLATES
        envVarName = wxT( "KICAD_PTEMPLATES" );
        if( wxGetEnv( envVarName, &envValue ) == true && !envValue.IsEmpty() )
        {
            tmpFileName.AssignDir( envValue );
            envVarItem.SetDefinedExternally( true );
        }
        else
        {
            tmpFileName = baseSharePath;
            tmpFileName.AppendDir( wxT( "template" ) );
            envVarItem.SetDefinedExternally( false );
        }
        envVarItem.SetValue( tmpFileName.GetFullPath() );
        m_local_env_vars[ envVarName ] = envVarItem;
    }

    ReadPdfBrowserInfos();      // needs m_common_settings

    // Init user language *before* calling loadCommonSettings, because
    // env vars could be incorrectly initialized on Linux
    // (if the value contains some non ASCII7 chars, the env var is not initialized)
    SetLanguage( true );

    loadCommonSettings();

    // Set locale option for separator used in float numbers
    SetLocaleTo_Default();

#ifdef __WXMAC__
    // Always show filters on Open dialog to be able to choose plugin
    wxSystemOptions::SetOption( wxOSX_FILEDIALOG_ALWAYS_SHOW_TYPES, 1 );
#endif

    return true;
}
Example #27
0
bool wxGetUserName(wxChar *buf, int n)
{
    return wxGetUserId(buf, n);
}
Example #28
0
AddTodoDlg::AddTodoDlg(wxWindow* parent, wxArrayString users, wxArrayString types, std::bitset<(int)tdctError+1> supportedTdcts) :
    m_Users(users),
    m_Types(types),
    m_supportedTdcts(supportedTdcts)
{
    wxXmlResource::Get()->LoadObject(this, parent, _T("dlgAddToDo"),_T("wxScrollingDialog"));

    wxString lastUser  = Manager::Get()->GetConfigManager(_T("todo_list"))->Read(_T("last_used_user"));
    wxString lastType  = Manager::Get()->GetConfigManager(_T("todo_list"))->Read(_T("last_used_type"));
    wxString lastStyle = Manager::Get()->GetConfigManager(_T("todo_list"))->Read(_T("last_used_style"));
    wxString lastPos   = Manager::Get()->GetConfigManager(_T("todo_list"))->Read(_T("last_used_position"));
    bool lastDateReq   = Manager::Get()->GetConfigManager(_T("todo_list"))->ReadBool(_T("last_date_req"), false);

    // load users
    wxChoice* cmb = XRCCTRL(*this, "chcUser", wxChoice);
    cmb->Clear();
    for (unsigned int i = 0; i < m_Users.GetCount(); ++i)
        cmb->Append(m_Users[i]);

    if (m_Users.GetCount() == 0)
        cmb->Append(wxGetUserId());

    if (!lastUser.IsEmpty())
    {
        int sel = cmb->FindString(lastUser, true);
        if (sel != -1)
            cmb->SetSelection(sel);
    }
    else
        cmb->SetSelection(0);

    // load types
    cmb = XRCCTRL(*this, "chcType", wxChoice);
    cmb->Clear();
    for (unsigned int i = 0; i < m_Types.GetCount(); ++i)
        cmb->Append(m_Types[i]);

    if (m_Types.GetCount() == 0)
    {
        cmb->Append(_T("TODO"));
        cmb->Append(_T("@todo"));
        cmb->Append(_T("\\todo"));

        cmb->Append(_T("FIXME"));
        cmb->Append(_T("@fixme"));
        cmb->Append(_T("\\fixme"));

        cmb->Append(_T("NOTE"));
        cmb->Append(_T("@note"));
        cmb->Append(_T("\\note"));
    }

    if (!lastType.IsEmpty())
    {
        int sel = cmb->FindString(lastType, true);
        if (sel != -1)
            cmb->SetSelection(sel);
    }
    else
        cmb->SetSelection(0);

    cmb = XRCCTRL(*this, "chcStyle", wxChoice);
    cmb->Clear();
    if (m_supportedTdcts[(int)tdctLine])
        cmb->Append(_T("Line comment"));
    if (m_supportedTdcts[(int)tdctStream])
        cmb->Append(_T("Stream comment"));
    if (m_supportedTdcts[(int)tdctDoxygenLine])
        cmb->Append(_T("Doxygen line comment"));
    if (m_supportedTdcts[(int)tdctDoxygenStream])
        cmb->Append(_T("Doxygen stream comment"));
    if (m_supportedTdcts[(int)tdctWarning])
        cmb->Append(_T("Compiler warning"));
    if (m_supportedTdcts[(int)tdctError])
            cmb->Append(_T("Compiler error"));

    if (!lastStyle.IsEmpty())
    {
        int sel = cmb->FindString(lastStyle, true);
        if (sel != -1)
            cmb->SetSelection(sel);
    }
    else
        cmb->SetSelection(0);

    cmb = XRCCTRL(*this, "chcPosition", wxChoice);
    if (!lastPos.IsEmpty())
    {
        int sel = cmb->FindString(lastPos, true);
        if (sel != -1)
            cmb->SetSelection(sel);
    }

    XRCCTRL(*this, "ID_CHECKBOX1", wxCheckBox)->SetValue(lastDateReq);
}
Example #29
0
bool PGM_BASE::initPgm()
{
    wxFileName pgm_name( App().argv[0] );

    wxInitAllImageHandlers();

    m_pgm_checker = new wxSingleInstanceChecker( pgm_name.GetName().Lower() + wxT( "-" ) + wxGetUserId() );

    if( m_pgm_checker->IsAnotherRunning() )
    {
        wxString quiz = wxString::Format(
            _( "%s is already running, Continue?" ),
            GetChars( pgm_name.GetName() )
            );
        if( !IsOK( NULL, quiz ) )
            return false;
    }

    // Init KiCad environment
    // the environment variable KICAD (if exists) gives the kicad path:
    // something like set KICAD=d:\kicad
    bool isDefined = wxGetEnv( wxT( "KICAD" ), &m_kicad_env );

    if( isDefined )    // ensure m_kicad_env ends by "/"
    {
        m_kicad_env.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP );

        if( !m_kicad_env.IsEmpty() && m_kicad_env.Last() != '/' )
            m_kicad_env += UNIX_STRING_DIR_SEP;
    }

    // Init parameters for configuration
    App().SetVendorName( wxT( "KiCad" ) );
    App().SetAppName( pgm_name.GetName().Lower() );

    // Install some image handlers, mainly for help
    wxImage::AddHandler( new wxPNGHandler );
    wxImage::AddHandler( new wxGIFHandler );
    wxImage::AddHandler( new wxJPEGHandler );
    wxFileSystem::AddHandler( new wxZipFSHandler );

    // Analyze the command line & initialize the binary path
    setExecutablePath();

    SetLanguagePath();

    // OS specific instantiation of wxConfigBase derivative:
    m_common_settings = new wxConfig( KICAD_COMMON );

    ReadPdfBrowserInfos();      // needs m_common_settings

    loadCommonSettings();


    bool succes = SetLanguage( true );

    if( !succes )
    {
    }

    // Set locale option for separator used in float numbers
    SetLocaleTo_Default();

    return true;
}
Example #30
0
/**
 * Initialize the application
 */
bool MiniLaunchBar::OnInit() {
  //_CrtSetBreakAlloc(18609);  

  // Remove GUI log errors
  delete wxLog::SetActiveTarget(new wxLogStderr());

  #ifdef __WINDOWS__
  osInfo_.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  BOOL gotInfo = GetVersionEx(&osInfo_);
  if (!gotInfo) {
    osInfo_.dwMajorVersion = 5; // Assume Windows 2000
    osInfo_.dwMinorVersion = 0;
  }  
  #endif // __WINDOWS__

  TiXmlBase::SetCondenseWhiteSpace(false);

  singleInstanceChecker_ = NULL;
  mainFrame_ = NULL;
  locale_ = NULL;
  pluginManager_ = NULL;
  ftLibrary_ = NULL;
  ftFace_ = NULL;
  stopWatch_.Start();
  user_ = new User();

  allowedIconSizes_.push_back(SMALL_ICON_SIZE);
  allowedIconSizes_.push_back(MEDIUM_ICON_SIZE);
  allowedIconSizes_.push_back(LARGE_ICON_SIZE);
  allowedIconSizes_.push_back(EXTRA_LARGE_ICON_SIZE);

  // ***********************************************************************************
  // Initialize the command line object
  // ***********************************************************************************

  wxCmdLineEntryDesc cmdLineDesc[] = {
    { wxCMD_LINE_SWITCH, _T("u"), _T("useuserdatadir"), _("Uses user data directory to save settings.") },
    { wxCMD_LINE_OPTION, _T("d"), _T("datapath"),  _("Sets user data path (-u will be ignored)") },
    { wxCMD_LINE_SWITCH, _T("l"), _T("logwindow"), _("Displays the log window (useful for debugging)") },
    { wxCMD_LINE_SWITCH, _T("?"), _T("help"), _("Displays this help message") },
    { wxCMD_LINE_NONE }
  };

  fileCommandLine_.SetDesc(cmdLineDesc);  

  wxFileName executablePath = wxFileName(wxStandardPaths().GetExecutablePath());
  wxString applicationDirectory = executablePath.GetPath();
  wxString argumentsFilePath = applicationDirectory + _T("/Arguments.txt");

  if (wxFileName::FileExists(argumentsFilePath)) {

    wxTextFile file;
    bool success = file.Open(argumentsFilePath);
    if (!success) {
      ELOG(_T("Couldn't open ") + argumentsFilePath);
    } else {
      wxString line;
      wxString fileArgv;

      for (line = file.GetFirstLine(); !file.Eof(); line = file.GetNextLine()) {
        line = line.Trim(true).Trim(false);
        if (line == wxEmptyString) continue;        
        fileArgv += _T(" ") + line;        
      }

      fileCommandLine_.SetCmdLine(fileArgv);
      fileCommandLine_.Parse();
    }

  }

  commandLine_.SetDesc(cmdLineDesc);
  commandLine_.SetCmdLine(argc, argv);
  commandLine_.Parse(); 

  if (commandLine_.Found(_T("?"))) commandLine_.Usage();

  // Required to enable PNG support
  wxInitAllImageHandlers();

  // Setting this option to "0" removed the flickering.
  wxSystemOptions::SetOption(_T("msw.window.no-clip-children"), _T("0"));

  // ***********************************************************************************
  // Initialize the file paths
  // ***********************************************************************************

  FilePaths::InitializePaths();

  // If the setting file doesn't exist, assume it's the first time the app is launched
  isFirstLaunch_ = !wxFileName::FileExists(FilePaths::GetSettingsFile());

  // ***********************************************************************************
  // Initialize user
  // ***********************************************************************************

  GetUser()->Load();
  UserSettings* userSettings = GetUser()->GetSettings();

  // ***********************************************************************************
  // Initialize locale
  // ***********************************************************************************

  bool localeSet = false;

  wxLanguageInfo info;
  LNG(wxLANGUAGE_USER_DEFINED + 1, "an", LANG_SPANISH, SUBLANG_SPANISH, wxLayout_LeftToRight, "Aragonese");


  if (IsFirstLaunch()) {
    // If it is the first launch, try to detect the language

    int systemLanguage = wxLocale::GetSystemLanguage();
    
    if (systemLanguage != wxLANGUAGE_UNKNOWN) {
      const wxLanguageInfo* info = wxLocale::GetLanguageInfo(systemLanguage);
      if (info) {
        localeSet = ChangeLocale(info->CanonicalName);
        if (localeSet) {
          userSettings->SetString(_T("Locale"), Localization::Instance()->GetLanguageCodeOnly(info->CanonicalName));
        }
      }
    }
  } else {
    localeSet = ChangeLocale(userSettings->GetString(_T("Locale")));
  }
    
  if (!localeSet) {
    localeSet = ChangeLocale(_T("en"));
    if (!localeSet) {
      MessageBoxes::ShowError(_("Could not initialize locale."));
      ::wxExit();
    }
  }  

  // ***********************************************************************************
  // At this point, user settings are loaded
  // ***********************************************************************************

  if (userSettings->GetBool(_T("UniqueApplicationInstance"))) {
    const wxString name = wxString::Format(_T("%s-%s"), APPLICATION_NAME, wxGetUserId());
    singleInstanceChecker_ = new wxSingleInstanceChecker(name);

    if (singleInstanceChecker_->IsAnotherRunning()) {
      ILOG(_T("Another instance of the application is already running."));
      wxDELETE(singleInstanceChecker_);
      return false;
    }
  }

  // ***********************************************************************************
  // Load the skin file
  // ***********************************************************************************
  Styles::LoadSkinFile(FilePaths::GetSkinDirectory() + _T("/") + SKIN_FILE_NAME);

  // ***********************************************************************************
  // Create and initialize the main frame
  // ***********************************************************************************
  mainFrame_ = new MainFrame();
  mainFrame_->Show();
  mainFrame_->SetRotated(userSettings->GetBool(_T("Rotated")));  
  mainFrame_->UpdateTransparency();

  SetTopWindow(mainFrame_);

  if (IsFirstLaunch()) {
    user_->AddAutoAddExclusion(_T("*setup.exe"));
    user_->AddAutoAddExclusion(_T("*unins*.exe"));
    user_->AddAutoAddExclusion(_T("*installer.exe"));
    user_->AddAutoAddExclusion(_T("*unstall.exe"));
    user_->AddAutoAddExclusion(_T("*updater.exe"));
    user_->AddAutoAddExclusion(_T("*unwise.exe"));
    user_->AddAutoAddExclusion(_T("*uninst.exe"));
    user_->AddAutoAddExclusion(_T("*setup*.exe"));
    user_->AddAutoAddExclusion(_T("msiexec.exe"));
  } 

  if (userSettings->GetBool(_T("OptionPanelOpen"))) {
    mainFrame_->InvalidateLayout();
    mainFrame_->InvalidateMask();
    mainFrame_->Update();
    mainFrame_->OpenOptionPanel();
  }

  // ***********************************************************************************
  // Localize the main frame (this is going to recursively call
  // all the Localize() handlers)
  // ***********************************************************************************
  mainFrame_->Localize();  

  // Note: the rest of the initialization code is in MainFrame::OnIdle (on the first IDLE event)

  return true;
}