File: ColoursAndFontsManager.cpp

package info (click to toggle)
codelite 6.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 48,992 kB
  • ctags: 43,502
  • sloc: cpp: 334,263; ansic: 18,441; xml: 4,713; yacc: 2,653; lex: 2,449; python: 1,188; sh: 385; makefile: 40
file content (427 lines) | stat: -rw-r--r-- 13,536 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
#include "ColoursAndFontsManager.h"
#include "cl_standard_paths.h"
#include <wx/filename.h>
#include <wx/dir.h>
#include "xmlutils.h"
#include <wx/xml/xml.h>
#include "editor_config.h"
#include "globals.h"
#include "event_notifier.h"
#include <codelite_events.h>
#include "cl_command_event.h"
#include "json_node.h"
#include "file_logger.h"
#include <algorithm>
#include "macros.h"
#include <wx/settings.h>
#include <wx/tokenzr.h>
#include "EclipseCXXThemeImporter.h"

class clCommandEvent;
ColoursAndFontsManager::ColoursAndFontsManager()
    : m_initialized(false)
{
    m_globalBgColour = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
    m_globalFgColour = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
}

ColoursAndFontsManager::~ColoursAndFontsManager()
{
}

ColoursAndFontsManager& ColoursAndFontsManager::Get()
{
    static ColoursAndFontsManager s_theManager;
    return s_theManager;
}

void ColoursAndFontsManager::Load()
{
    if(m_initialized) return;

    m_lexersMap.clear();
    m_initialized = true;

    // Always load first the installation lexers
    wxFileName defaultLexersPath(clStandardPaths::Get().GetDataDir(), "");
    defaultLexersPath.AppendDir("lexers");
    LoadNewXmls(defaultLexersPath.GetPath());

    //+++----------------------------------
    // Now handle user lexers
    //+++----------------------------------

    // Check to see if we have the new configuration files format (we break them from the unified XML file)
    // The naming convention used is:
    // lexer_<language>_<theme-name>.xml
    wxFileName cppLexerDefault(clStandardPaths::Get().GetUserDataDir(), "lexers_default.xml");
    cppLexerDefault.AppendDir("lexers");

    if(cppLexerDefault.FileExists()) {
        // We found the old lexer style here (single XML file for all the lexers)
        // Merge them with the installation lexers
        CL_DEBUG("Migrating old lexers XML files ...");
        LoadOldXmls(cppLexerDefault.GetPath());

    } else {
        // search for the new format in the user data folder
        cppLexerDefault.SetName("lexer_c++_default");
        if(cppLexerDefault.FileExists()) {
            CL_DEBUG("Using user lexer XML files from %s ...", cppLexerDefault.GetPath());
            // this function loads and delete the old xml files so they won't be located
            // next time we search for them
            LoadNewXmls(cppLexerDefault.GetPath());
        }
    }

    // Load the global settings
    if(GetConfigFile().FileExists()) {
        JSONRoot root(GetConfigFile());
        if(root.isOk()) {
            m_globalBgColour = root.toElement().namedObject("m_globalBgColour").toColour(m_globalBgColour);
            m_globalFgColour = root.toElement().namedObject("m_globalFgColour").toColour(m_globalFgColour);
        }
    }
}

void ColoursAndFontsManager::LoadNewXmls(const wxString& path)
{
    // load all XML files
    wxArrayString files;
    wxDir::GetAllFiles(path, &files, "lexer_*.xml");

    // Each XMl represents a single lexer
    for(size_t i = 0; i < files.GetCount(); ++i) {
        wxXmlDocument doc;
        if(!doc.Load(files.Item(i))) {
            continue;
        }
        DoAddLexer(doc.GetRoot());
    }
}

void ColoursAndFontsManager::LoadOldXmls(const wxString& path)
{
    // Convert the old XML format to a per lexer format
    wxArrayString files;
    wxDir::GetAllFiles(path, &files, "lexers_*.xml");

    wxString activeTheme = EditorConfigST::Get()->GetStringValue("LexerTheme");
    if(activeTheme.IsEmpty()) activeTheme = "Default";

    // Each XMl represents a single lexer
    for(size_t i = 0; i < files.GetCount(); ++i) {
        wxXmlDocument doc;
        if(!doc.Load(files.Item(i))) continue;

        wxXmlNode* lexers = doc.GetRoot();
        wxXmlNode* child = lexers->GetChildren();
        wxString themeName = XmlUtils::ReadString(lexers, "Theme", "Default");
        themeName = themeName.Capitalize();
        
        while(child) {
            if(child->GetName() == "Lexer") {
                // Assign theme to this lexer
                child->AddAttribute("Theme", themeName);
                child->AddAttribute("IsActive", themeName == activeTheme ? "Yes" : "No");
                DoAddLexer(child);
            }
            child = child->GetNext();
        }
    }

    for(size_t i = 0; i < files.GetCount(); ++i) {
        wxLogNull nl;
        ::wxRenameFile(files.Item(i), files.Item(i) + ".back");
    }

    // Since we just created the lexers, store them (migrating from old format)
    Save();
}

LexerConf::Ptr_t ColoursAndFontsManager::DoAddLexer(wxXmlNode* node)
{
    wxString lexerName = XmlUtils::ReadString(node, "Name");
    lexerName.MakeLower();
    if(lexerName.IsEmpty()) return NULL;

    LexerConf::Ptr_t lexer(new LexerConf);
    lexer->FromXml(node);
    
    // ensure that the theme name is capitalized - this helps
    // when displaying the content in a wxListBox sorted
    wxString themeName = lexer->GetThemeName();
    themeName = themeName.Mid(0, 1).Capitalize() + themeName.Mid(1);
    lexer->SetThemeName( themeName );
    
    // Hack: fix Java lexer which is using the same
    // file extensions as C++...
    if(lexer->GetName() == "java" && lexer->GetFileSpec().Contains(".cpp")) {
        lexer->SetFileSpec("*.java");
    }

    if(m_lexersMap.count(lexerName) == 0) {
        m_lexersMap.insert(std::make_pair(lexerName, ColoursAndFontsManager::Vec_t()));
    }

    ColoursAndFontsManager::Vec_t& vec = m_lexersMap.find(lexerName)->second;

    // Locate an instance with this name and theme in
    // both the m_alllexers and vector for this lexer
    // name
    ColoursAndFontsManager::Vec_t::iterator iter =
        std::find_if(vec.begin(), vec.end(), LexerConf::FindByNameAndTheme(lexer->GetName(), lexer->GetThemeName()));
    if(iter != vec.end()) {
        vec.erase(iter);
    }
    iter = std::find_if(
        m_allLexers.begin(), m_allLexers.end(), LexerConf::FindByNameAndTheme(lexer->GetName(), lexer->GetThemeName()));
    if(iter != m_allLexers.end()) {
        m_allLexers.erase(iter);
    }
    vec.push_back(lexer);
    m_allLexers.push_back(lexer);
    return lexer;
}

wxArrayString ColoursAndFontsManager::GetAvailableThemesForLexer(const wxString& lexerName) const
{
    ColoursAndFontsManager::Map_t::const_iterator iter = m_lexersMap.find(lexerName.Lower());
    if(iter == m_lexersMap.end()) return wxArrayString();

    wxArrayString themes;
    const ColoursAndFontsManager::Vec_t& lexers = iter->second;
    for(size_t i = 0; i < lexers.size(); ++i) {
        themes.Add(lexers.at(i)->GetThemeName());
    }
    
    // sort the list
    themes.Sort();
    return themes;
}

LexerConf::Ptr_t ColoursAndFontsManager::GetLexer(const wxString& lexerName, const wxString& theme) const
{
    ColoursAndFontsManager::Map_t::const_iterator iter = m_lexersMap.find(lexerName.Lower());
    if(iter == m_lexersMap.end()) return NULL;

    // Locate the requested theme
    LexerConf::Ptr_t firstLexer(NULL);
    LexerConf::Ptr_t defaultLexer(NULL);

    if(theme.IsEmpty()) {
        // return the active theme
        const ColoursAndFontsManager::Vec_t& lexers = iter->second;
        for(size_t i = 0; i < lexers.size(); ++i) {

            if(!firstLexer) {
                firstLexer = lexers.at(i);
            }

            if(!defaultLexer && lexers.at(i)->GetThemeName() == "Default") {
                defaultLexer = lexers.at(i);
            }

            if(lexers.at(i)->IsActive()) return lexers.at(i);
        }

        // No match
        if(defaultLexer)
            return defaultLexer;
        else if(firstLexer)
            return firstLexer;
        else
            return NULL;

    } else {
        const ColoursAndFontsManager::Vec_t& lexers = iter->second;
        for(size_t i = 0; i < lexers.size(); ++i) {
            if(lexers.at(i)->GetThemeName() == theme) {
                return lexers.at(i);
            }
        }
        return NULL;
    }
}

void ColoursAndFontsManager::Save()
{
    ColoursAndFontsManager::Map_t::const_iterator iter = m_lexersMap.begin();
    for(; iter != m_lexersMap.end(); ++iter) {
        const ColoursAndFontsManager::Vec_t& lexers = iter->second;
        for(size_t i = 0; i < lexers.size(); ++i) {
            Save(lexers.at(i));
        }
    }

    SaveGlobalSettings();
    clCommandEvent event(wxEVT_CMD_COLOURS_FONTS_UPDATED);
    EventNotifier::Get()->AddPendingEvent(event);
}

wxArrayString ColoursAndFontsManager::GetAllLexersNames() const
{
    wxArrayString names;
    for(size_t i = 0; i < m_allLexers.size(); ++i) {
        LexerConf::Ptr_t lexer = m_allLexers.at(i);
        if(names.Index(lexer->GetName()) == wxNOT_FOUND) {
            names.Add(lexer->GetName());
        }
    }
    names.Sort();
    return names;
}

LexerConf::Ptr_t ColoursAndFontsManager::GetLexerForFile(const wxString& filename) const
{
    wxFileName fnFileName(filename);
    wxString fileNameLowercase = fnFileName.GetFullName();
    fileNameLowercase.MakeLower();

    LexerConf::Ptr_t defaultLexer(NULL);
    LexerConf::Ptr_t firstLexer(NULL);

    // Scan the list of lexers, locate the active lexer for it and return it
    ColoursAndFontsManager::Vec_t::const_iterator iter = m_allLexers.begin();
    for(; iter != m_allLexers.end(); ++iter) {
        wxString fileMask = (*iter)->GetFileSpec().Lower();
        wxArrayString masks = ::wxStringTokenize(fileMask, ";", wxTOKEN_STRTOK);
        for(size_t i = 0; i < masks.GetCount(); ++i) {
            if(::wxMatchWild(masks.Item(i), fileNameLowercase)) {
                if((*iter)->IsActive()) {
                    return *iter;

                } else if(!firstLexer) {
                    firstLexer = *iter;

                } else if(!defaultLexer && (*iter)->GetThemeName() == "Default") {
                    defaultLexer = *iter;
                }
            }
        }
    }

    // If we reached here, it means we could not locate an active lexer for this file type
    if(defaultLexer) {
        return defaultLexer;
    } else if(firstLexer) {
        return firstLexer;
    } else {
        // Return the "Text" lexer
        return GetLexer("text");
    }
}

void ColoursAndFontsManager::Reload()
{
    Clear();
    Load();
}

void ColoursAndFontsManager::Clear()
{
    m_allLexers.clear();
    m_lexersMap.clear();
    m_initialized = false;
}

void ColoursAndFontsManager::Save(LexerConf::Ptr_t lexer)
{
    wxXmlDocument doc;
    doc.SetRoot(lexer->ToXml());

    wxString filename;
    wxString themeName = lexer->GetThemeName().Lower();
    themeName.Replace(" ", "_");
    themeName.Replace("::", "_");
    themeName.Replace("(", "_");
    themeName.Replace(")", "_");
    themeName.Replace(":", "_");
    themeName.Replace(",", "_");
    themeName.Replace(".", "_");
    themeName.Replace(";", "_");

    filename << "lexer_" << lexer->GetName().Lower() << "_" << themeName << ".xml";
    wxFileName xmlFile(clStandardPaths::Get().GetUserDataDir(), filename);
    xmlFile.AppendDir("lexers");
    ::SaveXmlToFile(&doc, xmlFile.GetFullPath());
}

void ColoursAndFontsManager::SetActiveTheme(const wxString& lexerName, const wxString& themeName)
{
    wxArrayString themes = GetAvailableThemesForLexer(lexerName);
    for(size_t i = 0; i < themes.GetCount(); ++i) {
        LexerConf::Ptr_t lexer = GetLexer(lexerName, themes.Item(i));
        if(lexer && lexer->GetName() == lexerName) {
            lexer->SetIsActive(lexer->GetThemeName() == themeName);
            Save(lexer);
        }
    }
}

wxFileName ColoursAndFontsManager::GetConfigFile() const
{
    wxFileName fnSettings(clStandardPaths::Get().GetUserDataDir(), "ColoursAndFonts.conf");
    fnSettings.AppendDir("config");
    return fnSettings;
}

void ColoursAndFontsManager::SaveGlobalSettings()
{
    // save the global settings
    JSONRoot root(cJSON_Object);
    root.toElement().addProperty("m_globalBgColour", m_globalBgColour).addProperty("m_globalFgColour",
                                                                                   m_globalFgColour);
    wxFileName fnSettings = GetConfigFile();
    root.save(fnSettings.GetFullPath());

    wxCommandEvent evtThemeChanged(wxEVT_CL_THEME_CHANGED);
    EventNotifier::Get()->AddPendingEvent(evtThemeChanged);
}

LexerConf::Ptr_t
ColoursAndFontsManager::CopyTheme(const wxString& lexerName, const wxString& themeName, const wxString& sourceTheme)
{
    LexerConf::Ptr_t sourceLexer = GetLexer(lexerName, sourceTheme);
    CHECK_PTR_RET_NULL(sourceLexer);

    wxXmlNode* sourceLexerXml = sourceLexer->ToXml();
    LexerConf::Ptr_t newLexer(new LexerConf());
    newLexer->FromXml(sourceLexerXml);

    // Update the theme name
    newLexer->SetThemeName(themeName);

    // Add it
    return DoAddLexer(newLexer->ToXml());
}

void ColoursAndFontsManager::RestoreDefaults()
{
    wxArrayString files;
    wxDir::GetAllFiles(clStandardPaths::Get().GetUserLexersDir(), &files, "lexer_*.xml");

    // First we delete the user settings
    {
        wxLogNull noLog;
        for(size_t i = 0; i < files.GetCount(); ++i) {
            ::wxRemoveFile(files.Item(i));
        }
    }

    // Now, we simply reload the settings
    Reload();
}

bool ColoursAndFontsManager::ImportEclipseTheme(const wxString& eclipseXml, wxString& outputFile)
{
    bool res = false;
    if(!eclipseXml.IsEmpty()) {
        EclipseCXXThemeImporter importer;
        res = importer.Import(eclipseXml, outputFile);
        if(res) {
            Reload();
        }
    }
    return res;
}