Example #1
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;
}