void OpenFilesListPlugin::RebuildOpenFilesTree()
{
    if (Manager::IsAppShuttingDown())
        return;

    EditorManager* mgr = Manager::Get()->GetEditorManager();

    m_pTree->Freeze();
    m_pTree->DeleteChildren(m_pTree->GetRootItem());
    if (!mgr->GetEditorsCount())
    {
        m_pTree->Thaw();
        return;
    }
    // loop all open editors
    for (int i = 0; i < mgr->GetEditorsCount(); ++i)
    {
        EditorBase* ed = mgr->GetEditor(i);
        if (!ed || !ed->VisibleToTree())
            continue;

        wxString shortname = ed->GetShortName();
        int mod = GetOpenFilesListIcon(ed);
        wxTreeItemId item = m_pTree->AppendItem(m_pTree->GetRootItem(), shortname, mod, mod, new OpenFilesListData(ed));
        if (mgr->GetActiveEditor() == ed)
            m_pTree->SelectItem(item);
    }

    m_pTree->SortChildren(m_pTree->GetRootItem());
    m_pTree->Expand(m_pTree->GetRootItem());
    m_pTree->Thaw();
}
Example #2
0
void ClangPlugin::OnEditorSave(CodeBlocksEvent& event)
{
    event.Skip();
#ifdef CLANGPLUGIN_TRACE_FUNCTIONS
    fprintf(stdout,"%s\n", __PRETTY_FUNCTION__);
#endif
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    cbEditor* ed = edMgr->GetBuiltinEditor(event.GetEditor());
    if (!ed)
    {
        return;
    }
    if ( m_TranslUnitId == -1 )
        return;
    std::map<wxString, wxString> unsavedFiles;
    // Our saved file is not yet known to all translation units since it's no longer in the unsaved files. We update them here
    unsavedFiles.insert(std::make_pair(ed->GetFilename(), ed->GetControl()->GetText()));
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        cbEditor* editor = edMgr->GetBuiltinEditor(i);
        if (editor && editor->GetModified())
            unsavedFiles.insert(std::make_pair(editor->GetFilename(), editor->GetControl()->GetText()));
    }
    ClangProxy::ReparseJob job( cbEVT_CLANG_ASYNCTASK_FINISHED, idClangReparse, m_TranslUnitId, m_CompileCommand, ed->GetFilename(), unsavedFiles, true);
    m_Proxy.AppendPendingJob(job);
}
Example #3
0
void ClangPlugin::OnCreateTranslationUnit( wxCommandEvent& event )
{
    if ( m_TranslUnitId != wxNOT_FOUND )
    {
        return;
    }
    wxString filename = event.GetString();
    if (filename.Length() == 0)
        return;

    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    cbEditor* ed = edMgr->GetBuiltinActiveEditor();
    if (ed)
    {
        if (filename != ed->GetFilename())
            return;
        std::map<wxString, wxString> unsavedFiles;
        for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
        {
            ed = edMgr->GetBuiltinEditor(i);
            if (ed && ed->GetModified())
                unsavedFiles.insert(std::make_pair(ed->GetFilename(), ed->GetControl()->GetText()));
        }
        ClangProxy::CreateTranslationUnitJob job( cbEVT_CLANG_ASYNCTASK_FINISHED, idClangCreateTU, filename, m_CompileCommand, unsavedFiles );
        m_Proxy.AppendPendingJob(job);
    }
}
void EditorTweaks::OnRelease(bool /*appShutDown*/)
{
    m_tweakmenu = 0;

//    EditorHooks::UnregisterHook(m_EditorHookId, true);
    EditorManager* em = Manager::Get()->GetEditorManager();
    for (int i=0;i<em->GetEditorsCount();i++)
    {
        cbEditor* ed=em->GetBuiltinEditor(i);
        if (ed && ed->GetControl())
        {
            ed->GetControl()->Disconnect(wxEVT_NULL,(wxObjectEventFunction) (wxEventFunction) (wxCharEventFunction)&EditorTweaks::OnKeyPress);
            ed->GetControl()->Disconnect(wxEVT_NULL,(wxObjectEventFunction) (wxEventFunction) (wxCharEventFunction)&EditorTweaks::OnChar);
        }
    }

    AlignerMenuEntry e;

    ConfigManager *cfg = Manager::Get()->GetConfigManager(_T("EditorTweaks"));
    std::sort (AlignerMenuEntries.begin(), AlignerMenuEntries.end(),CompareAlignerMenuEntryObject);
    std::reverse( AlignerMenuEntries.begin(), AlignerMenuEntries.end());
    int i = 0;
    for (; i < cfg->ReadInt(_T("/aligner/max_saved_entries"),defaultStoredAlignerEntries) && i < static_cast<int>(AlignerMenuEntries.size()) ; ++i)
    {
        cfg->Write(wxString::Format(_T("/aligner/first_name_%d"),i),AlignerMenuEntries[i].MenuName);
        cfg->Write(wxString::Format(_T("/aligner/first_argument_string_%d"),i) ,AlignerMenuEntries[i].ArgumentString);

        Disconnect(AlignerMenuEntries[i].id, wxEVT_COMMAND_MENU_SELECTED,  wxCommandEventHandler(EditorTweaks::OnAlign) );
    }
    cfg->Write(_T("/aligner/saved_entries"),i);
    for (; i < static_cast<int>(AlignerMenuEntries.size()) ; ++i)
        Disconnect(AlignerMenuEntries[i].id, wxEVT_COMMAND_MENU_SELECTED,  wxCommandEventHandler(EditorTweaks::OnAlign) );
    cfg->Write(wxT("/suppress_insert_key"), m_suppress_insert);
    cfg->Write(wxT("/convert_braces"),      m_convert_braces);
}
Example #5
0
void ClangPlugin::RequestReparse(const ClTranslUnitId translUnitId, const wxString& filename)
{
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    cbEditor* ed = edMgr->GetBuiltinActiveEditor();
    if (!ed)
    {
        return;
    }

    if (translUnitId == wxNOT_FOUND)
    {
        std::cout<<"Translation unit not found: "<<translUnitId<<" file="<<(const char*)ed->GetFilename().c_str()<<std::endl;
        return;
    }
    if ( translUnitId == m_TranslUnitId )
    {
        m_ReparseNeeded = 0;
    }

    std::map<wxString, wxString> unsavedFiles;
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        ed = edMgr->GetBuiltinEditor(i);
        if (ed && ed->GetModified())
            unsavedFiles.insert(std::make_pair(ed->GetFilename(), ed->GetControl()->GetText()));
    }
    ClangProxy::ReparseJob job( cbEVT_CLANG_ASYNCTASK_FINISHED, idClangReparse, translUnitId, m_CompileCommand, filename, unsavedFiles);
    m_Proxy.AppendPendingJob(job);
}
Example #6
0
cbDebuggerPlugin::SyncEditorResult cbDebuggerPlugin::SyncEditor(const wxString& filename, int line, bool setMarker)
{
    if (setMarker)
    {
        EditorManager* edMan = Manager::Get()->GetEditorManager();
        for (int i = 0; i < edMan->GetEditorsCount(); ++i)
        {
            cbEditor* ed = edMan->GetBuiltinEditor(i);
            if (ed)
                ed->SetDebugLine(-1);
        }
    }
    FileType ft = FileTypeOf(filename);
    if (ft != ftSource && ft != ftHeader && ft != ftResource)
    {
        // if the line is >= 0 and ft == ftOther assume, that we are in header without extension
        if (line < 0 || ft != ftOther)
        {
            ShowLog(false);
            Log(_("Unknown file: ") + filename, Logger::error);
            InfoWindow::Display(_("Unknown file"), _("File: ") + filename, 5000);

            return SyncFileUnknown; // don't try to open unknown files
        }
    }

    cbProject* project = Manager::Get()->GetProjectManager()->GetActiveProject();
    ProjectFile* f = project ? project->GetFileByFilename(filename, false, true) : nullptr;

    wxString unixfilename = UnixFilename(filename);
    wxFileName fname(unixfilename);

    if (project && fname.IsRelative())
        fname.MakeAbsolute(project->GetBasePath());

    // gdb can't work with spaces in filenames, so we have passed it the shorthand form (C:\MYDOCU~1 etc)
    // revert this change now so the file can be located and opened...
    // we do this by calling GetLongPath()
    cbEditor* ed = Manager::Get()->GetEditorManager()->Open(fname.GetLongPath());
    if (ed)
    {
        ed->Show(true);
        if (f && !ed->GetProjectFile())
            ed->SetProjectFile(f);
        ed->GotoLine(line - 1, false);
        if (setMarker)
            ed->SetDebugLine(line - 1);
        return SyncOk;
    }
    else
    {
        ShowLog(false);
        Log(_("Cannot open file: ") + filename, Logger::error);
        InfoWindow::Display(_("Cannot open file"), _("File: ") + filename, 5000);

        return SyncFileNotFound;
    }
}
void CodeRefactoring::GetOpenedFiles(wxArrayString& files)
{
    EditorManager* edMan = Manager::Get()->GetEditorManager();
    if (edMan)
    {
        for (int i = 0; i < edMan->GetEditorsCount(); ++i)
            files.Add(edMan->GetEditor(i)->GetFilename());
    }
}
Example #8
0
inline void CrashHandlerSaveEditorFiles(wxString& buf)
{
    wxString path;
    //get the "My Files" folder
    HRESULT result = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, wxStringBuffer(path, MAX_PATH));
    if (FAILED(result))
    {   //get at least the profiles folder
        path = ConfigManager::GetHomeFolder();
    }
    path << _T("\\cb-crash-recover");
    if (!wxDirExists(path)) wxMkdir(path);

    //make a sub-directory of the current date & time
    wxDateTime now = wxDateTime::Now();
    path << now.Format(_T("\\%Y%m%d-%H%M%S"));

    EditorManager* em = Manager::Get()->GetEditorManager();
    if (em)
    {
        bool AnyFileSaved = false;
        if (wxMkdir(path) && wxDirExists(path))
        {
            for (int i = 0; i < em->GetEditorsCount(); ++i)
            {
                cbEditor* ed = em->GetBuiltinEditor(em->GetEditor(i));
                if (ed)
                {
                    wxFileName fn(ed->GetFilename());
                    wxString fnpath = path + _T("/") + fn.GetFullName();
                    wxString newfnpath = fnpath;
                    // add number if filename already exists e.g. main.cpp.001, main.cpp.002, ...
                    int j = 1;
                    while (wxFileExists(newfnpath))
                        newfnpath = fnpath + wxString::Format(wxT(".%03d"),j);

                    if (cbSaveToFile(newfnpath,
                                    ed->GetControl()->GetText(),
                                    ed->GetEncoding(),
                                    ed->GetUseBom() ) )
                    {
                        AnyFileSaved = true;
                    }
                }
            }

            if (AnyFileSaved)
            {
                buf << _("The currently opened files have been saved to the directory\n");
                buf << path;
                buf << _("\nHopefully, this will prevent you from losing recent modifications.\n\n");
            }
            else
                wxRmdir(path);
        }
    }
}
void Highlighter::ClearAllIndications()const
{
    EditorManager *edm = Manager::Get()->GetEditorManager();
    for ( int i = 0 ; i < edm->GetEditorsCount() ; ++i)
    {
        cbEditor *ed = edm->GetBuiltinEditor( i );
        if ( ed )
            ClearAllIndications(ed->GetControl());
    }
}
Example #10
0
void cbDebuggerPlugin::ClearActiveMarkFromAllEditors()
{
    EditorManager* edMan = Manager::Get()->GetEditorManager();
    for (int i = 0; i < edMan->GetEditorsCount(); ++i)
    {
        cbEditor* ed = edMan->GetBuiltinEditor(i);
        if (ed)
            ed->SetDebugLine(-1);
    }
}
Example #11
0
void CompilerErrors::DoClearErrorMarkFromAllEditors()
{
	EditorManager* edMan = Manager::Get()->GetEditorManager();
	for (int i = 0; i < edMan->GetEditorsCount(); ++i)
	{
        cbEditor* ed = edMan->GetBuiltinEditor(i);
        if (ed)
            ed->SetErrorLine(-1);
	}
}
Example #12
0
inline void RefreshBreakpoints(cb_unused const cbDebuggerPlugin* plugin)
{
    EditorManager *editorManager = Manager::Get()->GetEditorManager();
    int count = editorManager->GetEditorsCount();
    for (int ii = 0; ii < count; ++ii)
    {
        EditorBase *editor = editorManager->GetEditor(ii);
        if (!editor->IsBuiltinEditor())
            continue;
        editor->RefreshBreakpointMarkers();
    }
}
void DisassemblyTextCtrl::ClearActiveMarkFromAllEditors()
{
    EditorManager* edMan = Manager::Get()->GetEditorManager();
//  Plugins are destroyed prior to EditorManager, so this is guaranteed to be valid at all times
//    if (!edMan)
//        return;
    for (int i = 0; i < edMan->GetEditorsCount(); ++i)
    {
        cbEditor* ed = edMan->GetBuiltinEditor(i);
        if (ed)
            ed->SetDebugLine(-1);
    }
}
Example #14
0
void Highlighter::TextsChanged()const
{
    EditorManager *edmgr = Manager::Get()->GetEditorManager();
    if(!edmgr)
        return;

    for ( int index = 0 ; index < edmgr->GetEditorsCount() ; ++index )
    {
        cbEditor *ed = edmgr->GetBuiltinEditor(index);
        if ( ed )
        {
            m_AlreadyChecked = false;
            m_OldCtrl = NULL;
            DoSetIndications(ed);
        }
    }
}
Example #15
0
LoaderBase* FileManager::Load(const wxString& file, bool reuseEditors)
{
    if (reuseEditors)
    {
        // if a file is opened in the editor, and the file get modified, we use the content of the
        // editor, otherwise, we still use the original file
        EditorManager* em = Manager::Get()->GetEditorManager();
        if (em)
        {
            wxFileName fileName(file);
            for (int i = 0; i < em->GetEditorsCount(); ++i)
            {
                cbEditor* ed = em->GetBuiltinEditor(em->GetEditor(i));
                if (ed && fileName == ed->GetFilename())
                {
                    if (!ed->GetModified())
                        break;
                    EditorReuser *nl = new EditorReuser(file, ed->GetControl()->GetText());
                    return nl;
                }
            }
        }
    }

    if (file.StartsWith(_T("http://")))
    {
        URLLoader *ul = new URLLoader(file);
        urlLoaderThread.Queue(ul);
        return ul;
    }

    FileLoader *fl = new FileLoader(file);

    if (file.length() > 2 && file[0] == _T('\\') && file[1] == _T('\\'))
    {
        // UNC files behave like "normal" files, but since we know they are served over the network,
        // we can run them independently from local filesystem files for higher concurrency
        uncLoaderThread.Queue(fl);
        return fl;
    }

    fileLoaderThread.Queue(fl);
    return fl;
}
Example #16
0
void EditorTweaks::OnAttach()
{
    // do whatever initialization you need for your plugin
    // NOTE: after this function, the inherited member variable
    // m_IsAttached will be TRUE...
    // You should check for it in other functions, because if it
    // is FALSE, it means that the application did *not* "load"
    // (see: does not need) this plugin...

    Manager* pm = Manager::Get();
    pm->RegisterEventSink(cbEVT_EDITOR_OPEN, new cbEventFunctor<EditorTweaks, CodeBlocksEvent>(this, &EditorTweaks::OnEditorOpen));

    m_tweakmenu=NULL;

    EditorManager* em = Manager::Get()->GetEditorManager();
    for (int i=0;i<em->GetEditorsCount();i++)
    {
        cbEditor* ed=em->GetBuiltinEditor(i);
        if (ed && ed->GetControl())
        {
            ed->GetControl()->SetOvertype(false);
            ed->GetControl()->Connect(wxEVT_KEY_DOWN,(wxObjectEventFunction) (wxEventFunction) (wxCharEventFunction)&EditorTweaks::OnKeyPress,NULL,this);
            ed->GetControl()->Connect(wxEVT_CHAR,(wxObjectEventFunction) (wxEventFunction) (wxCharEventFunction)&EditorTweaks::OnChar,NULL,this);
        }
    }


    AlignerMenuEntry e;

    ConfigManager *cfg = Manager::Get()->GetConfigManager(_T("EditorTweaks"));

    for (int i = 0 ; i < cfg->ReadInt(_T("/aligner/saved_entries"),defaultStoredAlignerEntries) ; ++i)
    {
        e.MenuName = cfg->Read(wxString::Format(_T("/aligner/first_name_%d"),i),defaultNames[i]);
        e.ArgumentString = cfg->Read(wxString::Format(_T("/aligner/first_argument_string_%d"),i) ,defaultStrings[i]);
        e.UsageCount = 0;
        e.id = wxNewId();
        AlignerMenuEntries.push_back(e);
        Connect(e.id, wxEVT_COMMAND_MENU_SELECTED,  wxCommandEventHandler(EditorTweaks::OnAlign) );
    }
    m_suppress_insert = cfg->ReadBool(wxT("/suppress_insert_key"), false);
    m_laptop_friendly = cfg->ReadBool(wxT("/laptop_friendly"),     false);
    m_convert_braces  = cfg->ReadBool(wxT("/convert_braces"),      false);
}
void OnlineSpellChecker::EnableOnlineChecks(bool check)
{
    m_doChecks = check;

    alreadychecked = false;

    EditorManager *edm = Manager::Get()->GetEditorManager();
    for ( int i = 0 ; i < edm->GetEditorsCount() ; ++i)
    {
        cbEditor *ed = edm->GetBuiltinEditor( i );

        if ( !ed ) continue;
        if ( check == false )
            // clear all indications set in a previous run
            ClearAllIndications(ed->GetControl());
        else
            OnEditorUpdateUI(ed);
    }
}
Example #18
0
void ClangPlugin::OnReparse( wxCommandEvent& /*event*/ )
{
#ifdef CLANGPLUGIN_TRACE_FUNCTIONS
    fprintf(stdout,"%s\n", __PRETTY_FUNCTION__);
#endif

    //m_DiagnosticTimer.Stop();

    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    cbEditor* ed = edMgr->GetBuiltinActiveEditor();
    if (!ed)
    {
        std::cout<<"No editor..."<<std::endl;
        return;
    }

    m_ReparseNeeded = 0;

    if (ed != m_pLastEditor)
    {
        //m_TranslUnitId = m_Proxy.GetTranslationUnitId(ed->GetFilename());
        m_TranslUnitId = wxNOT_FOUND;
        m_pLastEditor = ed;
        std::cout<<"Reparse: TranslUnitId set to "<<m_TranslUnitId<<std::endl;
    }
    if (m_TranslUnitId == wxNOT_FOUND)
    {
        std::cout<<"Translation unit not found: "<<m_TranslUnitId<<" file="<<(const char*)ed->GetFilename().c_str()<<std::endl;
        return;
    }

    //std::cout<<"Reparsing with translUnitId "<<m_TranslUnitId<<std::endl;
    std::map<wxString, wxString> unsavedFiles;
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        ed = edMgr->GetBuiltinEditor(i);
        if (ed && ed->GetModified())
            unsavedFiles.insert(std::make_pair(ed->GetFilename(), ed->GetControl()->GetText()));
    }
    ClangProxy::ReparseJob job( cbEVT_CLANG_ASYNCTASK_FINISHED, idClangReparse, m_TranslUnitId, m_CompileCommand, ed->GetFilename(), unsavedFiles);
    m_Proxy.AppendPendingJob(job);
    //m_ReparseBusy++;
}
Example #19
0
wxCondError ClangPlugin::GetCodeCompletionAt( const ClTranslUnitId translUnitId, const wxString& filename, const ClTokenPosition& loc, unsigned long timeout, std::vector<ClToken>& out_tknResults)
{
    std::map<wxString, wxString> unsavedFiles;
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        cbEditor* editor = edMgr->GetBuiltinEditor(i);
        if (editor && editor->GetModified())
            unsavedFiles.insert(std::make_pair(editor->GetFilename(), editor->GetControl()->GetText()));
    }
    ClangProxy::CodeCompleteAtJob job( cbEVT_CLANG_SYNCTASK_FINISHED, idClangCodeCompleteTask, 0, filename, loc, translUnitId, unsavedFiles);
    m_Proxy.AppendPendingJob(job);

    if (wxCOND_TIMEOUT == job.WaitCompletion(timeout))
    {
        return wxCOND_TIMEOUT;
    }
    out_tknResults = job.GetResults();

    return wxCOND_NO_ERROR;
}
Example #20
0
std::vector<ClangPlugin::CCToken> ClangPlugin::GetAutocompList(bool isAuto, cbEditor* ed, int& tknStart, int& tknEnd)
{
    std::vector<CCToken> tokens;
    if (ed != m_pLastEditor)
    {
        m_TranslUnitId = m_Proxy.GetTranslationUnitId(ed->GetFilename());
        m_pLastEditor = ed;
    }
    if (m_TranslUnitId == wxNOT_FOUND)
    {
        Manager::Get()->GetLogManager()->LogWarning(wxT("ClangLib: m_TranslUnitId == wxNOT_FOUND, cannot complete in file ") + ed->GetFilename());
        return tokens;
    }

    cbStyledTextCtrl* stc = ed->GetControl();
    const int style = stc->GetStyleAt(tknEnd);
    const wxChar curChar = stc->GetCharAt(tknEnd - 1);
    if (isAuto) // filter illogical cases of auto-launch
    {
        if (   (   curChar == wxT(':') // scope operator
                && stc->GetCharAt(tknEnd - 2) != wxT(':') )
            || (   curChar == wxT('>') // '->'
                && stc->GetCharAt(tknEnd - 2) != wxT('-') )
            || (   wxString(wxT("<\"/")).Find(curChar) != wxNOT_FOUND // #include directive (TODO: enumerate completable include files)
                && !stc->IsPreprocessor(style) ) )
        {
            return tokens;
        }
    }

    std::vector<ClToken> tknResults;
    const int line = stc->LineFromPosition(tknStart);
    std::map<wxString, wxString> unsavedFiles;
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        cbEditor* editor = edMgr->GetBuiltinEditor(i);
        if (editor && editor->GetModified())
            unsavedFiles.insert(std::make_pair(editor->GetFilename(), editor->GetControl()->GetText()));
    }
    const int lnStart = stc->PositionFromLine(line);
    int column = tknStart - lnStart;
    for (; column > 0; --column)
    {
        if (   !wxIsspace(stc->GetCharAt(lnStart + column - 1))
            || (column != 1 && !wxIsspace(stc->GetCharAt(lnStart + column - 2))) )
        {
            break;
        }
    }
    m_Proxy.CodeCompleteAt(isAuto, ed->GetFilename(), line + 1, column + 1, m_TranslUnitId, unsavedFiles, tknResults);
    const wxString& prefix = stc->GetTextRange(tknStart, tknEnd).Lower();
    bool includeCtors = true; // sometimes we get a lot of these
    for (int i = tknStart - 1; i > 0; --i)
    {
        wxChar chr = stc->GetCharAt(i);
        if (!wxIsspace(chr))
        {
            if (chr == wxT(';') || chr == wxT('}')) // last non-whitespace character
                includeCtors = false; // filter out ctors (they are unlikely to be wanted in this situation)
            break;
        }
    }
    if (prefix.Length() > 3) // larger context, match the prefix at any point in the token
    {
        for (std::vector<ClToken>::const_iterator tknIt = tknResults.begin();
             tknIt != tknResults.end(); ++tknIt)
        {
            if (tknIt->name.Lower().Find(prefix) != wxNOT_FOUND && (includeCtors || tknIt->category != tcCtorPublic))
                tokens.push_back(CCToken(tknIt->id, tknIt->name, tknIt->name, tknIt->weight, tknIt->category));
        }
    }
    else if (prefix.IsEmpty())
    {
        for (std::vector<ClToken>::const_iterator tknIt = tknResults.begin();
             tknIt != tknResults.end(); ++tknIt)
        {
            if (!tknIt->name.StartsWith(wxT("operator")) && (includeCtors || tknIt->category != tcCtorPublic)) // it is rather unlikely for an operator to be the desired completion
                tokens.push_back(CCToken(tknIt->id, tknIt->name, tknIt->name, tknIt->weight, tknIt->category));
        }
    }
    else // smaller context, only allow matches of the prefix at the beginning of the token
    {
        for (std::vector<ClToken>::const_iterator tknIt = tknResults.begin();
             tknIt != tknResults.end(); ++tknIt)
        {
            if (tknIt->name.Lower().StartsWith(prefix) && (includeCtors || tknIt->category != tcCtorPublic))
                tokens.push_back(CCToken(tknIt->id, tknIt->name, tknIt->name, tknIt->weight, tknIt->category));
        }
    }

    if (!tokens.empty())
    {
        if (prefix.IsEmpty() && tokens.size() > 1500) // reduce to give only top matches
        {
            std::partial_sort(tokens.begin(), tokens.begin() + 1000, tokens.end(), PrioritySorter());
            tokens.erase(tokens.begin() + 1000, tokens.end());
        }
        const int imgCount = m_ImageList.GetImageCount();
        for (int i = 0; i < imgCount; ++i)
            stc->RegisterImage(i, m_ImageList.GetBitmap(i));
        bool isPP = stc->GetLine(line).Strip(wxString::leading).StartsWith(wxT("#"));
        std::set<int> usedWeights;
        for (std::vector<CCToken>::iterator tknIt = tokens.begin();
             tknIt != tokens.end(); ++tknIt)
        {
            usedWeights.insert(tknIt->weight);
            switch (tknIt->category)
            {
                case tcNone:
                    if (isPP)
                        tknIt->category = tcMacroDef;
                    else if (std::binary_search(m_CppKeywords.begin(), m_CppKeywords.end(), GetActualName(tknIt->name)))
                        tknIt->category = tcLangKeyword;
                    break;

                case tcClass:
                case tcCtorPublic:
                case tcDtorPublic:
                case tcFuncPublic:
                case tcVarPublic:
                case tcEnum:
                case tcTypedef:
                    m_Proxy.RefineTokenType(m_TranslUnitId, tknIt->id, tknIt->category);
                    break;

                default:
                    break;
            }
        }
        // Clang sometimes gives many weight values, which can make completion more difficult
        // because results are less alphabetical. Use a compression map on the lower priority
        // values (higher numbers) to reduce the total number of weights used.
        if (usedWeights.size() > 3)
        {
            std::vector<int> weightsVec(usedWeights.begin(), usedWeights.end());
            std::map<int, int> weightCompr;
            weightCompr[weightsVec[0]] = weightsVec[0];
            weightCompr[weightsVec[1]] = weightsVec[1];
            int factor = (weightsVec.size() > 7 ? 3 : 2);
            for (size_t i = 2; i < weightsVec.size(); ++i)
                weightCompr[weightsVec[i]] = weightsVec[(i - 2) / factor + 2];
            for (std::vector<CCToken>::iterator tknIt = tokens.begin();
                 tknIt != tokens.end(); ++tknIt)
            {
                tknIt->weight = weightCompr[tknIt->weight];
            }
        }
    }

    return tokens;
}
Example #21
0
void Autosave::OnTimer(wxTimerEvent& e)
{
    if(e.GetId() == 10000)
    {
        PluginManager *plm = Manager::Get()->GetPluginManager();
        int method = Manager::Get()->GetConfigManager(_T("autosave"))->ReadInt(_T("method"));
        ProjectManager *pm = Manager::Get()->GetProjectManager();
        if(pm && pm->GetActiveProject())
        {
            if(cbProject * p = pm->GetActiveProject())
            {
                switch(method)
                {
                    case 0:
                    {
                        if(p->GetModified())
                        {
                            if(::wxRenameFile(p->GetFilename(), p->GetFilename() + _T(".bak")))
                                if(p->Save())
                                {
                                    CodeBlocksEvent e(cbEVT_PROJECT_SAVE, 0, p);
                                    plm->NotifyPlugins(e);
                                }
                        }
                        wxFileName file = p->GetFilename();
                        file.SetExt(_T("layout"));
                        wxString filename = file.GetFullPath();
                        if(::wxRenameFile(filename, filename + _T(".bak")))
                            p->SaveLayout();
                        break;
                    }
                    case 1:
                    {
                        if(p->GetModified() && p->Save())
                        {
                            CodeBlocksEvent e(cbEVT_PROJECT_SAVE, 0, p);
                            plm->NotifyPlugins(e);
                        }
                        p->SaveLayout();
                        break;
                    }
                    case 2:
                    case 3: // doesn't really make sense to keep so many versions of a project file
                    {
                        if (p->IsLoaded() == false)
                            return;
                        if(p->GetModified())
                        {
                            ProjectLoader loader(p);
                            if(loader.Save(p->GetFilename() + _T(".save")))
                            {
                                CodeBlocksEvent e(cbEVT_PROJECT_SAVE, 0, p);
                                plm->NotifyPlugins(e);
                            }
                            p->SetModified(); // the actual project file is still not updated!
                        }
                        wxFileName file = wxFileName(p->GetFilename());
                        file.SetExt(_T("layout"));
                        wxString filename = file.GetFullPath();
                        wxString temp = filename + _T(".temp");
                        wxString save = filename + _T(".save");
                        if(::wxFileExists(filename) && ::wxCopyFile(filename, temp))
                        {
                            p->SaveLayout();
                            ::wxRenameFile(filename, save);
                            ::wxRenameFile(temp, filename);
                        }
                        break;
                    }
                }
            }
        }
    }
    else if(e.GetId() == 20000)
    {
        int method = Manager::Get()->GetConfigManager(_T("autosave"))->ReadInt(_T("method"));
        EditorManager* em = Manager::Get()->GetEditorManager();

        if(em)
        {
            for(int i = 0; i < em->GetEditorsCount(); ++i)
            {
                cbEditor* ed = em->GetBuiltinEditor(em->GetEditor(i));
                if(ed && ed->GetModified())
                {
                    wxFileName fn(ed->GetFilename());
                    switch(method)
                    {
                        case 0:
                        {
                            if(::wxRenameFile(fn.GetFullPath(), fn.GetFullPath() + _T(".bak")))
                                cbSaveToFile(fn.GetFullPath(), ed->GetControl()->GetText(), ed->GetEncoding(), ed->GetUseBom());
                            break;
                        }
                        case 1:
                        {
                            ed->Save();
                            break;
                        }
                        case 2:
                        {
                            cbSaveToFile(fn.GetFullPath() + _T(".save"), ed->GetControl()->GetText(), ed->GetEncoding(), ed->GetUseBom());
                            ed->SetModified(); // the "real" file has not been saved!
                            break;
                        }
                        case 3:
                        {
                            wxString tmp1;
                            wxString tmp2;

                            for(unsigned int i = 8; i; --i)
                            {
                                tmp1.Printf(_T("%s/%s.%u.%s"), fn.GetPath().c_str(), fn.GetName().c_str(), i,   fn.GetExt().c_str());
                                tmp2.Printf(_T("%s/%s.%u.%s"), fn.GetPath().c_str(), fn.GetName().c_str(), i+1, fn.GetExt().c_str());

                                if(::wxFileExists(tmp2))
                                    ::wxRemoveFile(tmp2);
                                if(::wxFileExists(tmp1))
                                    ::wxRenameFile(tmp1, tmp2);
                            }

                            tmp1.Printf(_T("%s/%s.1.%s"), fn.GetPath().c_str(), fn.GetName().c_str(), fn.GetExt().c_str());

                            cbSaveToFile(tmp1, ed->GetControl()->GetText(), ed->GetEncoding(), ed->GetUseBom());
                            ed->SetModified(); // the "real" file has not been saved!
                            break;
                        }
                    }
                }

            }
        }
    }

}
Example #22
0
wxString ClangPlugin::GetSourceOf(cbEditor* ed)
{
    cbProject* project = nullptr;
    ProjectFile* opf = ed->GetProjectFile();
    if (opf)
        project = opf->GetParentProject();
    if (!project)
        project = Manager::Get()->GetProjectManager()->GetActiveProject();

    wxFileName theFile(ed->GetFilename());
    wxFileName candidateFile;
    bool isCandidate;
    wxArrayString fileArray;
    wxDir::GetAllFiles(theFile.GetPath(wxPATH_GET_VOLUME), &fileArray,
            theFile.GetName() + wxT(".*"), wxDIR_FILES | wxDIR_HIDDEN);
    wxFileName currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
    if (isCandidate)
        candidateFile = currentCandidateFile;
    else if (currentCandidateFile.IsOk())
        return currentCandidateFile.GetFullPath();

    fileArray.Clear();
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        cbEditor* edit = edMgr->GetBuiltinEditor(i);
        if (!edit)
            continue;

        ProjectFile* pf = edit->GetProjectFile();
        if (!pf)
            continue;

        fileArray.Add(pf->file.GetFullPath());
    }
    currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
    if (!isCandidate && currentCandidateFile.IsOk())
        return currentCandidateFile.GetFullPath();

    if (project)
    {
        fileArray.Clear();
        for (FilesList::const_iterator it = project->GetFilesList().begin();
                it != project->GetFilesList().end(); ++it)
        {
            ProjectFile* pf = *it;
            if (!pf)
                continue;

            fileArray.Add(pf->file.GetFullPath());
        }
        currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
        if (isCandidate && !candidateFile.IsOk())
            candidateFile = currentCandidateFile;
        else if (currentCandidateFile.IsOk())
            return currentCandidateFile.GetFullPath();

        wxArrayString dirs = project->GetIncludeDirs();
        for (int i = 0; i < project->GetBuildTargetsCount(); ++i)
        {
            ProjectBuildTarget* target = project->GetBuildTarget(i);
            if (target)
            {
                for (size_t ti = 0; ti < target->GetIncludeDirs().GetCount(); ++ti)
                {
                    wxString dir = target->GetIncludeDirs()[ti];
                    if (dirs.Index(dir) == wxNOT_FOUND)
                        dirs.Add(dir);
                }
            }
        }
        for (size_t i = 0; i < dirs.GetCount(); ++i)
        {
            wxString dir = dirs[i];
            Manager::Get()->GetMacrosManager()->ReplaceMacros(dir);
            wxFileName dname(dir);
            if (!dname.IsAbsolute())
                dname.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, project->GetBasePath());
            fileArray.Clear();
            wxDir::GetAllFiles(dname.GetPath(), &fileArray, theFile.GetName() + wxT(".*"), wxDIR_FILES | wxDIR_HIDDEN);
            currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
            if (isCandidate)
                candidateFile = currentCandidateFile;
            else if (currentCandidateFile.IsOk())
                return currentCandidateFile.GetFullPath();
        }
    }
    if (candidateFile.IsOk())
        return candidateFile.GetFullPath();
    return wxEmptyString;
}
Example #23
0
void Autosave::OnTimer(wxTimerEvent& e)
{
    if(e.GetId() == 10000)
    {
        int method = Manager::Get()->GetConfigManager(_T("autosave"))->ReadInt(_T("method"));
        bool allProjects = Manager::Get()->GetConfigManager(_T("autosave"))->ReadBool(_T("all_projects"), true);
        bool doWorkspace = Manager::Get()->GetConfigManager(_T("autosave"))->ReadBool(_T("do_workspace"), true);
        ProjectManager *pm = Manager::Get()->GetProjectManager();
        if(pm)// && pm->GetActiveProject())
        {
            if (allProjects)
            {
                ProjectsArray *projects = pm->GetProjects();
                for (size_t ii = 0; ii < projects->GetCount(); ++ii)
                    SaveProject((*projects)[ii], method);
            }
            else if(cbProject *p = pm->GetActiveProject())
                SaveProject(p, method);

            cbWorkspace *workspace = pm->GetWorkspace();
            if (doWorkspace && workspace && workspace->GetModified())
            {
                switch(method)
                {
                    case 0:
                        if(::wxRenameFile(workspace->GetFilename(), workspace->GetFilename() + _T(".bak")))
                            workspace->Save();
                        break;
                    case 1:
                        workspace->Save();
                        break;
                    case 2:
                    case 3:
                    {
                        WorkspaceLoader loader;
                        loader.Save(workspace->GetTitle(), workspace->GetFilename() + wxT(".save"));
                        workspace->SetModified(true);
                        break;
                    }
                    default:
                        break;
                }
            }
        }
    }
    else if(e.GetId() == 20000)
    {
        int method = Manager::Get()->GetConfigManager(_T("autosave"))->ReadInt(_T("method"));
        EditorManager* em = Manager::Get()->GetEditorManager();

        if(em)
        {
            for(int i = 0; i < em->GetEditorsCount(); ++i)
            {
                cbEditor* ed = em->GetBuiltinEditor(em->GetEditor(i));
                if(ed && ed->GetModified())
                {
                    wxFileName fn(ed->GetFilename());
                    switch(method)
                    {
                        case 0:
                        {
                            if(::wxRenameFile(fn.GetFullPath(), fn.GetFullPath() + _T(".bak")))
                                cbSaveToFile(fn.GetFullPath(), ed->GetControl()->GetText(), ed->GetEncoding(), ed->GetUseBom());
                            break;
                        }
                        case 1:
                        {
                            ed->Save();
                            break;
                        }
                        case 2:
                        {
                            cbSaveToFile(fn.GetFullPath() + _T(".save"), ed->GetControl()->GetText(), ed->GetEncoding(), ed->GetUseBom());
                            ed->SetModified(); // the "real" file has not been saved!
                            break;
                        }
                        case 3:
                        {
                            wxString tmp1;
                            wxString tmp2;

                            for(unsigned int revisions = 8; revisions; --revisions)
                            {
                                tmp1.Printf(_T("%s/%s.%u.%s"), fn.GetPath().c_str(), fn.GetName().c_str(), revisions,   fn.GetExt().c_str());
                                tmp2.Printf(_T("%s/%s.%u.%s"), fn.GetPath().c_str(), fn.GetName().c_str(), revisions+1, fn.GetExt().c_str());

                                if(::wxFileExists(tmp2))
                                    ::wxRemoveFile(tmp2);
                                if(::wxFileExists(tmp1))
                                    ::wxRenameFile(tmp1, tmp2);
                            }

                            tmp1.Printf(_T("%s/%s.1.%s"), fn.GetPath().c_str(), fn.GetName().c_str(), fn.GetExt().c_str());

                            cbSaveToFile(tmp1, ed->GetControl()->GetText(), ed->GetEncoding(), ed->GetUseBom());
                            ed->SetModified(); // the "real" file has not been saved!
                            break;
                        }
                        default:
                            break;
                    }
                }

            }
        }
    }

}
Example #24
0
void ClangPlugin::OnTimer(wxTimerEvent& event)
{
    if (!IsAttached())
        return;
    const int evId = event.GetId();
    if (evId == idEdOpenTimer)
    {
        cbEditor* ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
        if (!ed || !IsProviderFor(ed))
            return;
        else if (m_Proxy.GetTranslationUnitId(ed->GetFilename()) != wxNOT_FOUND)
        {
            m_DiagnosticTimer.Start(DIAGNOSTIC_DELAY, wxTIMER_ONE_SHOT);
            return;
        }
        wxString compileCommand;
        ProjectFile* pf = ed->GetProjectFile();
        ProjectBuildTarget* target = nullptr;
        Compiler* comp = nullptr;
        if (pf && pf->GetParentProject() && !pf->GetBuildTargets().IsEmpty() )
        {
            target = pf->GetParentProject()->GetBuildTarget(pf->GetBuildTargets()[0]);
            comp = CompilerFactory::GetCompiler(target->GetCompilerID());
            if (pf->GetUseCustomBuildCommand(target->GetCompilerID()))
            {
                compileCommand = pf->GetCustomBuildCommand(target->GetCompilerID()).AfterFirst(wxT(' '));
            }
        }
        if (compileCommand.IsEmpty())
            compileCommand = wxT("$options $includes");
        cbProject* proj = (pf ? pf->GetParentProject() : nullptr);
        if (!comp && proj)
            comp = CompilerFactory::GetCompiler(proj->GetCompilerID());
        if (!comp)
        {
            cbProject* tmpPrj = Manager::Get()->GetProjectManager()->GetActiveProject();
            if (tmpPrj)
                comp = CompilerFactory::GetCompiler(tmpPrj->GetCompilerID());
        }
        if (!comp)
            comp = CompilerFactory::GetDefaultCompiler();
        comp->GetCommandGenerator(proj)->GenerateCommandLine(compileCommand, target, pf, ed->GetFilename(),
                                                             g_InvalidStr, g_InvalidStr, g_InvalidStr );
        wxStringTokenizer tokenizer(compileCommand);
        compileCommand.Empty();
        wxString pathStr;
        while (tokenizer.HasMoreTokens())
        {
            wxString flag = tokenizer.GetNextToken();
            // make all include paths absolute, so clang does not choke if Code::Blocks switches directories
            if (flag.StartsWith(wxT("-I"), &pathStr))
            {
                wxFileName path(pathStr);
                if (path.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE))
                    flag = wxT("-I") + path.GetFullPath();
            }
            compileCommand += flag + wxT(" ");
        }
        compileCommand += GetCompilerInclDirs(comp->GetID());
        if (FileTypeOf(ed->GetFilename()) == ftHeader) // try to find the associated source
        {
            const wxString& source = GetSourceOf(ed);
            if (!source.IsEmpty())
            {
                m_Proxy.CreateTranslationUnit(source, compileCommand);
                if (m_Proxy.GetTranslationUnitId(ed->GetFilename()) != wxNOT_FOUND)
                    return; // got it
            }
        }
        m_Proxy.CreateTranslationUnit(ed->GetFilename(), compileCommand);
        m_DiagnosticTimer.Start(DIAGNOSTIC_DELAY, wxTIMER_ONE_SHOT);
    }
    else if (evId == idReparseTimer)
    {
        EditorManager* edMgr = Manager::Get()->GetEditorManager();
        cbEditor* ed = edMgr->GetBuiltinActiveEditor();
        if (!ed)
            return;
        if (ed != m_pLastEditor)
        {
            m_TranslUnitId = m_Proxy.GetTranslationUnitId(ed->GetFilename());
            m_pLastEditor = ed;
        }
        if (m_TranslUnitId == wxNOT_FOUND)
            return;
        std::map<wxString, wxString> unsavedFiles;
        for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
        {
            ed = edMgr->GetBuiltinEditor(i);
            if (ed && ed->GetModified())
                unsavedFiles.insert(std::make_pair(ed->GetFilename(), ed->GetControl()->GetText()));
        }
        m_Proxy.Reparse(m_TranslUnitId, unsavedFiles);
        DiagnoseEd(m_pLastEditor, dlMinimal);
    }
    else if (evId == idDiagnosticTimer)
    {
        cbEditor* ed = Manager::Get()->GetEditorManager()->GetBuiltinActiveEditor();
        if (!ed)
            return;
        if (ed != m_pLastEditor)
        {
            m_TranslUnitId = m_Proxy.GetTranslationUnitId(ed->GetFilename());
            m_pLastEditor = ed;
        }
        if (m_TranslUnitId == wxNOT_FOUND)
            return;
        DiagnoseEd(ed, dlFull);
    }
    else
        event.Skip();
}