File: workspace.cpp

package info (click to toggle)
codelite 17.0.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 136,204 kB
  • sloc: cpp: 491,547; ansic: 280,393; php: 10,259; sh: 8,930; lisp: 7,664; vhdl: 6,518; python: 6,020; lex: 4,920; yacc: 3,123; perl: 2,385; javascript: 1,715; cs: 1,193; xml: 1,110; makefile: 804; cobol: 741; sql: 709; ruby: 620; f90: 566; ada: 534; asm: 464; fortran: 350; objc: 289; tcl: 258; java: 157; erlang: 61; pascal: 51; ml: 49; awk: 44; haskell: 36
file content (1698 lines) | stat: -rw-r--r-- 54,513 bytes parent folder | download | duplicates (2)
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : workspace.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#include "workspace.h"

#include "StringUtils.h"
#include "build_settings_config.h"
#include "cl_command_event.h"
#include "codelite_events.h"
#include "compiler_command_line_parser.h"
#include "ctags_manager.h"
#include "environmentconfig.h"
#include "event_notifier.h"
#include "evnvarlist.h"
#include "file_logger.h"
#include "fileutils.h"
#include "globals.h"
#include "localworkspace.h"
#include "macromanager.h"
#include "macros.h"
#include "plugin.h"
#include "project.h"
#include "wx/regex.h"
#include "wx_xml_compatibility.h"
#include "xmlutils.h"

#include <wx/app.h>
#include <wx/log.h>
#include <wx/msgdlg.h>
#include <wx/sstream.h>
#include <wx/stc/stc.h>
#include <wx/thread.h>
#include <wx/tokenzr.h>

clCxxWorkspace::clCxxWorkspace()
    : m_saveOnExit(true)
{
    SetWorkspaceType(_("C++"));
    m_localWorkspace = new LocalWorkspace();
    EventNotifier::Get()->Bind(wxEVT_BUILD_OUTPUT_HOTSPOT_CLICKED, &clCxxWorkspace::OnBuildHotspotClicked, this);
}

clCxxWorkspace::~clCxxWorkspace()
{
    if(m_saveOnExit && m_doc.IsOk()) {
        SaveXmlFile();
    }
    delete m_localWorkspace;
    m_localWorkspace = nullptr;
    EventNotifier::Get()->Unbind(wxEVT_BUILD_OUTPUT_HOTSPOT_CLICKED, &clCxxWorkspace::OnBuildHotspotClicked, this);
}

wxString clCxxWorkspace::GetName() const
{
    if(m_doc.IsOk()) {
        return XmlUtils::ReadString(m_doc.GetRoot(), wxT("Name"));
    }
    return wxEmptyString;
}

void clCxxWorkspace::CloseWorkspace()
{
    m_buildMatrix.Reset(NULL);
    if(m_doc.IsOk()) {
        SaveXmlFile();
        m_doc = wxXmlDocument();
    }

    m_fileName.Clear();
    // reset the internal cache objects
    m_projects.clear();

    TagsManagerST::Get()->CloseDatabase();
}

bool clCxxWorkspace::OpenReadOnly(const wxString& fileName, wxString& errMsg)
{
    m_buildMatrix.Reset(NULL);
    wxFileName workSpaceFile(fileName);
    if(!workSpaceFile.FileExists()) {
        return false;
    }
    m_fileName = workSpaceFile;
    m_doc.Load(m_fileName.GetFullPath());
    if(!m_doc.IsOk()) {
        return false;
    }

    m_saveOnExit = false;

    // Make sure we have the WORKSPACE/.codelite folder exists
    {
        wxLogNull nolog;
        wxMkdir(GetPrivateFolder());
    }

    // Load all projects from the XML file
    std::vector<wxXmlNode*> removedChildren;
    DoLoadProjectsFromXml(m_doc.GetRoot(), "", removedChildren);

    DoUpdateBuildMatrix();
    return true;
}

bool clCxxWorkspace::OpenWorkspace(const wxString& fileName, wxString& errMsg)
{
    if(!DoLoadWorkspace(fileName, errMsg)) {
        return false;
    }

    // Notify about active project changed
    ProjectPtr activeProject = GetActiveProject();
    if(activeProject) {
        clProjectSettingsEvent evt(wxEVT_ACTIVE_PROJECT_CHANGED);
        evt.SetProjectName(activeProject->GetName());
        evt.SetFileName(activeProject->GetFileName().GetFullPath());
        EventNotifier::Get()->AddPendingEvent(evt);
    }
    return true;
}

BuildMatrixPtr clCxxWorkspace::GetBuildMatrix() const { return m_buildMatrix; }

wxXmlNode* clCxxWorkspace::GetWorkspaceEditorOptions() const
{
    return XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("Options"));
}

void clCxxWorkspace::SetWorkspaceEditorOptions(LocalOptionsConfigPtr opts)
{
    wxXmlNode* parent = m_doc.GetRoot();
    wxXmlNode* oldOptions = XmlUtils::FindFirstByTagName(parent, wxT("Options"));
    if(oldOptions) {
        oldOptions->GetParent()->RemoveChild(oldOptions);
        delete oldOptions;
    }
    parent->AddChild(opts->ToXml());
    SaveXmlFile();
}

void clCxxWorkspace::SetBuildMatrix(BuildMatrixPtr mapping)
{
    wxXmlNode* parent = m_doc.GetRoot();
    wxXmlNode* oldMapping = XmlUtils::FindFirstByTagName(parent, wxT("BuildMatrix"));
    if(oldMapping) {
        parent->RemoveChild(oldMapping);
        wxDELETE(oldMapping);
    }
    parent->AddChild(mapping->ToXml());
    SaveXmlFile();

    GetLocalWorkspace()->SetSelectedBuildConfiguration(mapping->GetSelectedConfigurationName());

    // force regeneration of makefiles for all projects
    for(ProjectMap_t::iterator iter = m_projects.begin(); iter != m_projects.end(); iter++) {
        iter->second->SetModified(true);
    }

    DoUpdateBuildMatrix();
}

bool clCxxWorkspace::CreateWorkspace(const wxString& name, const wxString& path, wxString& errMsg)
{
    // If we have an open workspace, close it
    if(m_doc.IsOk()) {
        if(!SaveXmlFile()) {
            errMsg = wxT("Failed to save current workspace");
            return false;
        }
    }

    if(name.IsEmpty()) {
        errMsg = wxT("Invalid workspace name");
        return false;
    }

    // Create new
    // Open workspace database
    m_fileName = wxFileName(path, name + wxT(".workspace"));

    // Make sure we have the WORKSPACE/.codelite folder exists
    {
        wxLogNull nolog;
        wxMkdir(GetPrivateFolder());
    }

    // This function sets the working directory to the workspace directory!
    ::wxSetWorkingDirectory(m_fileName.GetPath());
    m_buildMatrix.Reset(NULL);

    wxFileName dbFileName = GetTagsFileName();
    TagsManagerST::Get()->OpenDatabase(dbFileName);

    wxXmlNode* root = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("CodeLite_Workspace"));
    m_doc.SetRoot(root);
    m_doc.GetRoot()->AddAttribute(wxT("Name"), name);
    m_doc.GetRoot()->AddAttribute(wxT("Database"), dbFileName.GetFullPath(wxPATH_UNIX));

    m_doc.GetRoot()->DeleteAttribute(wxT("SWTLW"));
    if(GetLocalWorkspace()->GetParserFlags() & LocalWorkspace::EnableSWTLW) {
        m_doc.GetRoot()->AddAttribute(wxT("SWTLW"), "Yes");
    }

    SaveXmlFile();
    // create an empty build matrix
    DoUpdateBuildMatrix();
    return true;
}

wxString clCxxWorkspace::GetStringProperty(const wxString& propName, wxString& errMsg)
{
    if(!m_doc.IsOk()) {
        errMsg = wxT("No workspace open");
        return wxEmptyString;
    }

    wxXmlNode* rootNode = m_doc.GetRoot();
    if(!rootNode) {
        errMsg = wxT("Corrupted workspace file");
        return wxEmptyString;
    }

    return rootNode->GetAttribute(propName, wxEmptyString);
}

void clCxxWorkspace::AddProjectToBuildMatrix(ProjectPtr prj)
{
    if(!prj) {
        wxMessageBox(_("AddProjectToBuildMatrix was called with NULL project"), _("CodeLite"), wxICON_WARNING | wxOK);
        return;
    }

    BuildMatrixPtr matrix = GetBuildMatrix();
    wxString selConfName = matrix->GetSelectedConfigurationName();

    std::list<WorkspaceConfigurationPtr> wspList = matrix->GetConfigurations();
    std::list<WorkspaceConfigurationPtr>::iterator iter = wspList.begin();
    for(; iter != wspList.end(); iter++) {
        WorkspaceConfigurationPtr workspaceConfig = (*iter);
        WorkspaceConfiguration::ConfigMappingList prjList = workspaceConfig->GetMapping();
        wxString wspCnfName = workspaceConfig->GetName();

        ProjectSettingsCookie cookie;

        // getSettings is a bit misleading, since it actually create new instance which represents the layout
        // of the XML
        ProjectSettingsPtr settings = prj->GetSettings();
        BuildConfigPtr prjBldConf = settings->GetFirstBuildConfiguration(cookie);
        BuildConfigPtr matchConf;

        if(!prjBldConf) {
            // the project does not have any settings, create new one and add it
            prj->SetSettings(settings);

            settings = prj->GetSettings();
            prjBldConf = settings->GetFirstBuildConfiguration(cookie);
            matchConf = prjBldConf;

        } else {

            matchConf = prjBldConf;

            // try to locate the best match to add to the workspace
            while(prjBldConf) {
                wxString projBldConfName = prjBldConf->GetName();
                if(wspCnfName == projBldConfName) {
                    // we found a suitable match use it instead of the default one
                    matchConf = prjBldConf;
                    break;
                }
                prjBldConf = settings->GetNextBuildConfiguration(cookie);
            }
        }

        ConfigMappingEntry entry(prj->GetName(), matchConf->GetName());
        prjList.push_back(entry);
        (*iter)->SetConfigMappingList(prjList);
        matrix->SetConfiguration((*iter));
    }

    // and set the configuration name
    matrix->SetSelectedConfigurationName(selConfName);

    // this will also reset the build matrix pointer
    SetBuildMatrix(matrix);
}

void clCxxWorkspace::RemoveProjectFromBuildMatrix(ProjectPtr prj)
{
    BuildMatrixPtr matrix = GetBuildMatrix();
    wxString selConfName = matrix->GetSelectedConfigurationName();

    std::list<WorkspaceConfigurationPtr> wspList = matrix->GetConfigurations();
    std::list<WorkspaceConfigurationPtr>::iterator iter = wspList.begin();
    for(; iter != wspList.end(); iter++) {
        WorkspaceConfiguration::ConfigMappingList prjList = (*iter)->GetMapping();

        WorkspaceConfiguration::ConfigMappingList::iterator it = prjList.begin();
        for(; it != prjList.end(); it++) {
            if((*it).m_project == prj->GetName()) {
                prjList.erase(it);
                break;
            }
        }

        (*iter)->SetConfigMappingList(prjList);
        matrix->SetConfiguration((*iter));
    }

    // and set the configuration name
    matrix->SetSelectedConfigurationName(selConfName);

    // this will also reset the build matrix pointer
    SetBuildMatrix(matrix);
}

bool clCxxWorkspace::CreateProject(const wxString& name, const wxString& path, const wxString& type,
                                   const wxString& workspaceFolder, bool addToBuildMatrix, wxString& errMsg)
{
    if(!m_doc.IsOk()) {
        errMsg = wxT("No workspace open");
        return false;
    }

    ProjectPtr proj(new Project());
    proj->Create(name, wxEmptyString, path, type);
    proj->AssociateToWorkspace(this);
    proj->SetWorkspaceFolder(workspaceFolder);
    m_projects[name] = proj;

    // make the project path to be relative to the workspace, if it's sensible to do so
    wxFileName tmp(path + wxFileName::GetPathSeparator() + name + wxT(".project"));
    tmp.MakeRelativeTo(m_fileName.GetPath());

    // Add an entry to the workspace file
    wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("Project"));
    node->AddAttribute(wxT("Name"), name);
    node->AddAttribute(wxT("Path"), tmp.GetFullPath(wxPATH_UNIX));

    // Create the workspace folder and add the project
    wxXmlNode* parentNode = DoCreateWorkspaceFolder(workspaceFolder);
    parentNode->AddChild(node);

    if(m_projects.size() == 1) {
        SetActiveProject(name);
    }

    SaveXmlFile();
    if(addToBuildMatrix) {
        AddProjectToBuildMatrix(proj);
    }
    return true;
}

bool clCxxWorkspace::AddProject(const wxString& path, // fullpath
                                const wxString& workspaceFolder, wxString& errMsg)
{
    if(!m_doc.IsOk()) {
        errMsg = _("No workspace open");
        return false;
    }

    ProjectPtr proj(new Project());
    if(!proj->Load(path)) {
        errMsg << _("Failed to load project file: ") << path;
        return false;
    }
    proj->AssociateToWorkspace(this);
    proj->SetWorkspaceFolder(workspaceFolder);
    m_projects[proj->GetName()] = proj;

    // make the project path to be relative to the workspace, if it's sensible to do so
    wxFileName tmp(path);
    tmp.MakeRelativeTo(m_fileName.GetPath());

    // Add an entry to the workspace file
    wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("Project"));
    node->AddAttribute(wxT("Name"), proj->GetName());
    node->AddAttribute(wxT("Path"), tmp.GetFullPath(wxPATH_UNIX));

    // Create the workspace folder and add the project
    wxXmlNode* parentNode = DoCreateWorkspaceFolder(workspaceFolder);
    parentNode->AddChild(node);

    if(m_projects.size() == 1) {
        SetActiveProject(proj->GetName());
    }

    SaveXmlFile();
    AddProjectToBuildMatrix(proj);
    return true;
}

ProjectPtr clCxxWorkspace::FindProjectByName(const wxString& projName, wxString& errMsg) const
{
    if(!m_doc.IsOk()) {
        errMsg = wxT("No workspace open");
        return NULL;
    }

    ProjectMap_t::const_iterator iter = m_projects.find(projName);
    if(iter == m_projects.end()) {
        errMsg = wxT("Invalid project name '");
        errMsg << projName << wxT("'");
        return NULL;
    }
    return iter->second;
}

void clCxxWorkspace::GetProjectList(wxArrayString& list) const
{
    list.reserve(m_projects.size());
    ProjectMap_t::const_iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); iter++) {
        wxString name;
        name = iter->first;
        list.Add(name);
    }
}

bool clCxxWorkspace::AddProject(const wxString& path, wxString& errMsg)
{
    if(!m_doc.IsOk()) {
        errMsg = wxT("No workspace open");
        return false;
    }

    wxFileName fn(path);
    if(!fn.FileExists()) {
        errMsg = wxT("File does not exist");
        return false;
    }

    // Load the project into
    ProjectPtr newProject(new Project());
    if(!newProject->Load(path)) {
        errMsg = wxT("Corrupted project file '");
        errMsg << path << wxT("'");
        return false;
    }

    // Try first to find a project with similar name in the workspace
    ProjectPtr proj = FindProjectByName(newProject->GetName(), errMsg);
    if(!proj) {

        // No project could be find, add it to the workspace
        DoAddProject(newProject);

        // Add an entry to the workspace file
        fn.MakeRelativeTo(m_fileName.GetPath());

        wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("Project"));
        node->AddAttribute(wxT("Name"), fn.GetName());
        node->AddAttribute(wxT("Path"), fn.GetFullPath(wxPATH_UNIX));
        node->AddAttribute(wxT("Active"), m_projects.size() == 1 ? wxT("Yes") : wxT("No"));
        m_doc.GetRoot()->AddChild(node);
        if(!SaveXmlFile()) {
            wxMessageBox(
                _("Failed to save workspace file to disk. Please check that you have permission to write to disk"),
                _("CodeLite"), wxICON_ERROR | wxOK);
            return false;
        }

        AddProjectToBuildMatrix(newProject);
        return true;

    } else {
        errMsg = wxString::Format(wxT("A project with a similar name '%s' already exists in the workspace"),
                                  proj->GetName().c_str());
        return false;
    }
}

ProjectPtr clCxxWorkspace::DoAddProject(ProjectPtr proj)
{
    if(!proj) {
        return NULL;
    }

    m_projects.insert(std::make_pair(proj->GetName(), proj));
    proj->AssociateToWorkspace(this);
    return proj;
}

ProjectPtr clCxxWorkspace::DoAddProject(const wxString& path, const wxString& projectVirtualFolder, wxString& errMsg)
{
    // Add the project
    ProjectPtr proj(new Project());

    // Convert the path to absolute path
    wxFileName projectFile(path);
    if(projectFile.IsRelative()) {
        projectFile.MakeAbsolute(m_fileName.GetPath());
    }

    if(!proj->Load(projectFile.GetFullPath())) {
        errMsg = wxT("Corrupted project file '");
        errMsg << projectFile.GetFullPath() << wxT("'");
        return NULL;
    }

    // Add an entry to the projects map
    m_projects.insert(std::make_pair(proj->GetName(), proj));
    proj->AssociateToWorkspace(this);
    proj->SetWorkspaceFolder(projectVirtualFolder);
    return proj;
}

bool clCxxWorkspace::RemoveProject(const wxString& name, wxString& errMsg, const wxString& workspaceFolder)
{
    ProjectPtr proj = FindProjectByName(name, errMsg);
    if(!proj) {
        return false;
    }

    // remove the associated build configuration with this
    // project
    RemoveProjectFromBuildMatrix(proj);

    // remove the project from the internal map
    ProjectMap_t::iterator iter = m_projects.find(proj->GetName());
    if(iter != m_projects.end()) {
        m_projects.erase(iter);
    }

    // update the xml file
    // Incase we got a workspace folder, the project node will exists under the
    // workspace folder node and not under the root
    wxXmlNode* root = m_doc.GetRoot();
    if(!workspaceFolder.IsEmpty()) {
        wxXmlNode* node = DoGetWorkspaceFolderXmlNode(workspaceFolder);
        if(node) {
            root = node;
        }
    }

    wxXmlNode* child = root->GetChildren();
    while(child) {
        if(child->GetName() == wxT("Project") && child->GetAttribute(wxT("Name"), wxEmptyString) == name) {
            if(child->GetAttribute(wxT("Active"), wxEmptyString).CmpNoCase(wxT("Yes")) == 0) {
                // the removed project was active,
                // select new project to be active
                if(!m_projects.empty()) {
                    ProjectMap_t::iterator iter = m_projects.begin();
                    SetActiveProject(iter->first);
                }
            }
            root->RemoveChild(child);
            delete child;
            break;
        }
        child = child->GetNext();
    }

    // go over the dependencies list of each project and remove the project
    iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        ProjectPtr p = iter->second;
        if(p) {
            wxArrayString configs;
            // populate the choice control with the list of available configurations for this project
            ProjectSettingsPtr settings = p->GetSettings();
            if(settings) {
                ProjectSettingsCookie cookie;
                BuildConfigPtr bldConf = settings->GetFirstBuildConfiguration(cookie);
                while(bldConf) {
                    configs.Add(bldConf->GetName());
                    bldConf = settings->GetNextBuildConfiguration(cookie);
                }
            }

            // update each configuration of this project
            for(size_t i = 0; i < configs.GetCount(); i++) {

                wxArrayString deps = p->GetDependencies(configs.Item(i));
                int where = deps.Index(name);
                if(where != wxNOT_FOUND) {
                    deps.RemoveAt((size_t)where);
                }

                // update the configuration
                p->SetDependencies(deps, configs.Item(i));
            }
        }
    }
    return SaveXmlFile();
}

wxString clCxxWorkspace::GetActiveProjectName() const
{
    if(!m_doc.IsOk()) {
        return wxEmptyString;
    }

    std::list<wxXmlNode*> xmls = DoGetProjectsXmlNodes();
    std::list<wxXmlNode*>::iterator iter = std::find_if(xmls.begin(), xmls.end(), [&](wxXmlNode* node) {
        return (node->GetAttribute("Active", wxEmptyString).CmpNoCase("yes") == 0);
    });

    if(iter == xmls.end())
        return "";
    return (*iter)->GetAttribute("Name", wxEmptyString);
}

void clCxxWorkspace::SetActiveProject(const wxString& name)
{
    if(!m_doc.IsOk())
        return;

    // Clear all other projects
    DoUnselectActiveProject();

    std::list<wxXmlNode*> xmls = DoGetProjectsXmlNodes();
    std::for_each(xmls.begin(), xmls.end(), [&](wxXmlNode* node) {
        XmlUtils::UpdateProperty(node, "Active",
                                 (node->GetAttribute(wxT("Name"), wxEmptyString) == name) ? "Yes" : "No");
    });

    SaveXmlFile();

    // Notify about the change
    ProjectPtr activeProject = GetProject(name);
    if(activeProject) {
        clProjectSettingsEvent evt(wxEVT_ACTIVE_PROJECT_CHANGED);
        evt.SetProjectName(name);
        evt.SetFileName(activeProject->GetFileName().GetFullPath());
        EventNotifier::Get()->AddPendingEvent(evt);
    }
}

bool clCxxWorkspace::CreateVirtualDirectory(const wxString& vdFullPath, wxString& errMsg, bool mkPath)
{
    wxStringTokenizer tkz(vdFullPath, wxT(":"));
    wxString projName = tkz.GetNextToken();

    wxString fixedPath;
    // Construct new path excluding the first token
    size_t count = tkz.CountTokens();

    for(size_t i = 0; i < count - 1; i++) {
        fixedPath += tkz.GetNextToken();
        fixedPath += wxT(":");
    }
    fixedPath += tkz.GetNextToken();

    ProjectPtr proj = FindProjectByName(projName, errMsg);
    return proj->CreateVirtualDir(fixedPath, mkPath);
}

bool clCxxWorkspace::RemoveVirtualDirectory(const wxString& vdFullPath, wxString& errMsg)
{
    wxStringTokenizer tkz(vdFullPath, wxT(":"));
    wxString projName = tkz.GetNextToken();

    wxString fixedPath;
    // Construct new path excluding the first token
    size_t count = tkz.CountTokens();

    for(size_t i = 0; i < count - 1; i++) {
        fixedPath += tkz.GetNextToken();
        fixedPath += wxT(":");
    }
    fixedPath += tkz.GetNextToken();

    ProjectPtr proj = FindProjectByName(projName, errMsg);
    return proj->DeleteVirtualDir(fixedPath);
}

bool clCxxWorkspace::SaveXmlFile()
{
    // We first remove the Save Workspace To Local Workspace (SWTLW) attribute
    // and then check the current state in the Code Completion tab. Then
    // we read new path values from the LW and set the appropiate attribute value.
    if(m_doc.GetRoot()->GetAttribute(wxT("SWTLW")) != wxEmptyString) {
        m_doc.GetRoot()->DeleteAttribute(wxT("SWTLW"));
    }

    if(GetLocalWorkspace()->GetParserFlags() & LocalWorkspace::EnableSWTLW) {
        m_doc.GetRoot()->AddAttribute(wxT("SWTLW"), "Yes");
        SyncFromLocalWorkspaceSTParserPaths();
        SyncFromLocalWorkspaceSTParserMacros();
    }

    // Set the workspace XML version
    wxString version;
    if(!m_doc.GetRoot()->GetAttribute("Version", &version)) {
        m_doc.GetRoot()->AddAttribute("Version", DEFAULT_CURRENT_WORKSPACE_VERSION_STR);
    }

    wxString content;
    wxStringOutputStream sos(&content);
    m_doc.Save(sos);

    bool ok = FileUtils::WriteFileContent(m_fileName, content);
    SetWorkspaceLastModifiedTime(GetFileLastModifiedTime());
    EventNotifier::Get()->PostFileSavedEvent(m_fileName.GetFullPath());
    DoUpdateBuildMatrix();
    return ok;
}

void clCxxWorkspace::SyncToLocalWorkspaceSTParserPaths()
{
    wxArrayString inclduePaths;
    wxArrayString excludePaths;
    wxXmlNode* workspaceInclPaths = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("WorkspaceParserPaths"));
    if(workspaceInclPaths) {
        wxXmlNode* child = workspaceInclPaths->GetChildren();
        while(child) {
            if(child->GetName() == wxT("Exclude")) {
                wxString path = child->GetAttribute(wxT("Path"), wxT(""));
                path.Trim().Trim(false);
                if(path.IsEmpty() == false) {
                    excludePaths.Add(path);
                }
            }

            else if(child->GetName() == wxT("Include")) {
                wxString path = child->GetAttribute(wxT("Path"), wxT(""));
                path.Trim().Trim(false);
                if(path.IsEmpty() == false) {
                    inclduePaths.Add(path);
                }
            }

            child = child->GetNext();
        }
        GetLocalWorkspace()->SetParserPaths(inclduePaths, excludePaths);
    }
}

void clCxxWorkspace::SyncFromLocalWorkspaceSTParserPaths()
{
    //
    // Here we just get the parser paths from the LocalWorkspaceST and write it into the worspace project file.
    //
    wxXmlNode* workspaceInclPaths = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("WorkspaceParserPaths"));
    if(workspaceInclPaths) {
        m_doc.GetRoot()->RemoveChild(workspaceInclPaths);
        delete workspaceInclPaths;
    }

    //
    // Get workspace parse paths from local workspace file.
    //
    wxArrayString inclduePaths;
    wxArrayString excludePaths;
    GetLocalWorkspace()->GetParserPaths(inclduePaths, excludePaths);

    workspaceInclPaths = new wxXmlNode(m_doc.GetRoot(), wxXML_ELEMENT_NODE, wxT("WorkspaceParserPaths"));
    for(size_t i = 0; i < inclduePaths.GetCount(); i++) {
        wxXmlNode* child = new wxXmlNode(workspaceInclPaths, wxXML_ELEMENT_NODE, wxT("Include"));
        child->AddAttribute(wxT("Path"), inclduePaths.Item(i));
    }

    for(size_t i = 0; i < excludePaths.GetCount(); i++) {
        wxXmlNode* child = new wxXmlNode(workspaceInclPaths, wxXML_ELEMENT_NODE, wxT("Exclude"));
        child->AddAttribute(wxT("Path"), excludePaths.Item(i));
    }
}

void clCxxWorkspace::SyncToLocalWorkspaceSTParserMacros()
{
    wxString macros;
    wxXmlNode* workspaceMacros = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("WorkspaceParserMacros"));
    if(workspaceMacros) {
        macros = workspaceMacros->GetNodeContent();
        macros.Trim().Trim(false);
        GetLocalWorkspace()->SetParserMacros(macros);
    }
}

void clCxxWorkspace::SyncFromLocalWorkspaceSTParserMacros()
{
    //
    // Here we just get the parser macros from the LocalWorkspaceST and write it into the worspace project file.
    //
    wxXmlNode* workspaceMacros = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("WorkspaceParserMacros"));
    if(workspaceMacros) {
        m_doc.GetRoot()->RemoveChild(workspaceMacros);
        delete workspaceMacros;
    }

    //
    // Get workspace parse macros from local workspace file.
    //
    wxString macros;
    GetLocalWorkspace()->GetParserMacros(macros);
    workspaceMacros = new wxXmlNode(m_doc.GetRoot(), wxXML_ELEMENT_NODE, wxT("WorkspaceParserMacros"));
    if(!macros.IsEmpty()) {
        wxXmlNode* contentNode = new wxXmlNode(wxXML_CDATA_SECTION_NODE, wxEmptyString, macros);
        workspaceMacros->AddChild(contentNode);
    }
}

void clCxxWorkspace::Save()
{
    if(m_doc.IsOk()) {
        ProjectMap_t::iterator iter = m_projects.begin();
        for(; iter != m_projects.end(); iter++) {
            iter->second->Save();
        }
        SaveXmlFile();
    }
}

bool clCxxWorkspace::AddNewFile(const wxString& vdFullPath, const wxString& fileName, wxString& errMsg)
{
    wxStringTokenizer tkz(vdFullPath, wxT(":"));

    // We should have at least 2 tokens:
    // project:virtual directory
    if(tkz.CountTokens() < 2)
        return false;

    wxString projName = tkz.GetNextToken();
    wxString fixedPath;
    // Construct new path excluding the first token
    size_t count = tkz.CountTokens();

    for(size_t i = 0; i < count - 1; i++) {
        fixedPath += tkz.GetNextToken();
        fixedPath += wxT(":");
    }
    fixedPath += tkz.GetNextToken();

    ProjectPtr proj = FindProjectByName(projName, errMsg);
    if(!proj) {
        errMsg = wxT("No such project");
        return false;
    }

    return proj->AddFile(fileName, fixedPath);
}

bool clCxxWorkspace::RemoveFile(const wxString& vdFullPath, const wxString& fileName, wxString& errMsg)
{
    wxStringTokenizer tkz(vdFullPath, wxT(":"));
    wxString projName = tkz.GetNextToken();
    wxString fixedPath;

    // Construct new path excluding the first token
    size_t count = tkz.CountTokens();
    if(!count) {
        errMsg = _("Malformed project name");
        return false;
    }

    for(size_t i = 0; i < count - 1; i++) {
        fixedPath += tkz.GetNextToken();
        fixedPath += wxT(":");
    }
    fixedPath += tkz.GetNextToken();

    ProjectPtr proj = FindProjectByName(projName, errMsg);
    if(!proj) {
        errMsg = _("No such project");
        return false;
    }

    bool result = proj->RemoveFile(fileName, fixedPath);
    if(!result) {
        errMsg = _("File removal failed");
    }
    return result;
}

BuildConfigPtr clCxxWorkspace::GetProjBuildConf(const wxString& projectName, const wxString& confName) const
{
    BuildMatrixPtr matrix = GetBuildMatrix();
    if(!matrix) {
        return NULL;
    }

    wxString projConf(confName);

    if(projConf.IsEmpty()) {
        wxString workspaceConfig = matrix->GetSelectedConfigurationName();
        projConf = matrix->GetProjectSelectedConf(workspaceConfig, projectName);
    }

    // Get the project setting and retrieve the selected configuration
    wxString errMsg;
    ProjectPtr proj = FindProjectByName(projectName, errMsg);
    if(proj) {
        ProjectSettingsPtr settings = proj->GetSettings();
        if(settings) {
            return settings->GetBuildConfiguration(projConf, true);
        }
    }
    return NULL;
}

void clCxxWorkspace::ReloadWorkspace()
{
    m_doc = wxXmlDocument();

    wxLogNull noLog;
    // reset the internal cache objects
    m_projects.clear();

    TagsManager* mgr = TagsManagerST::Get();
    mgr->CloseDatabase();

    wxString err_msg;
    if(!OpenWorkspace(m_fileName.GetFullPath(), err_msg)) {
        clDEBUG() << "Reload workspace:" << err_msg;
    }
}

time_t clCxxWorkspace::GetFileLastModifiedTime() const { return GetFileModificationTime(GetWorkspaceFileName()); }

// Singelton access
static clCxxWorkspace* gs_Workspace = NULL;
void clCxxWorkspaceST::Free()
{
    if(gs_Workspace) {
        delete gs_Workspace;
    }
    gs_Workspace = NULL;
}

clCxxWorkspace* clCxxWorkspaceST::Get()
{
    if(gs_Workspace == NULL)
        gs_Workspace = new clCxxWorkspace;
    return gs_Workspace;
}

wxString clCxxWorkspace::GetParserMacros()
{
    if(!m_doc.IsOk())
        return wxEmptyString;

    wxXmlNode* node = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("WorkspaceParserMacros"));
    if(node) {
        wxString nodeContent = node->GetNodeContent();
        nodeContent.Trim().Trim(false);
        return nodeContent;
    }
    return wxEmptyString;
}

wxString clCxxWorkspace::GetEnvironmentVariabels()
{
    if(!m_doc.IsOk())
        return wxEmptyString;

    // Use the environment variables set in the build matrix ("workspace configuration")
    wxString env;
    if(GetSelectedConfig()) {
        env = GetSelectedConfig()->GetEnvironmentVariables();
        if(!env.IsEmpty()) {
            return env;
        }
    }

    wxXmlNode* node = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("Environment"));
    if(node) {
        wxString nodeContent = node->GetNodeContent();
        nodeContent.Trim().Trim(false);
        return nodeContent;
    }
    return wxEmptyString;
}

void clCxxWorkspace::SetEnvironmentVariabels(const wxString& envvars)
{
    if(!m_doc.IsOk())
        return;
    if(GetSelectedConfig()) {
        GetSelectedConfig()->SetEnvironmentVariables(envvars);
        SetBuildMatrix(GetBuildMatrix()); // force an XML update
        SaveXmlFile();
        return;
    }

    wxXmlNode* node = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), wxT("Environment"));
    if(node) {
        m_doc.GetRoot()->RemoveChild(node);
        delete node;
    }

    node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("Environment"));
    m_doc.GetRoot()->AddChild(node);

    wxString nodeContent = envvars;
    nodeContent.Trim().Trim(false);

    wxXmlNode* contentNode = new wxXmlNode(wxXML_CDATA_SECTION_NODE, wxEmptyString, nodeContent);
    node->AddChild(contentNode);
    SaveXmlFile();
}

wxArrayString clCxxWorkspace::GetAllProjectPaths()
{
    wxArrayString projects;
    ProjectMap_t::iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); iter++) {
        projects.Add(iter->second->GetFileName().GetFullPath());
    }
    return projects;
}

bool clCxxWorkspace::IsOpen() const { return m_doc.IsOk(); }

bool clCxxWorkspace::IsVirtualDirectoryExists(const wxString& vdFullPath)
{
    wxStringTokenizer tkz(vdFullPath, wxT(":"));
    wxString projName = tkz.GetNextToken();

    wxString fixedPath;
    // Construct new path excluding the first token
    size_t count = tkz.CountTokens();

    for(size_t i = 0; i < count - 1; i++) {
        fixedPath += tkz.GetNextToken();
        fixedPath += wxT(":");
    }
    fixedPath += tkz.GetNextToken();

    wxString errMsg;
    ProjectPtr proj = FindProjectByName(projName, errMsg);
    if(!proj) {
        return false;
    }

    wxXmlNode* vdNode = proj->GetVirtualDir(fixedPath);
    return vdNode != NULL;
}

wxString clCxxWorkspace::GetPrivateFolder() const
{
    wxFileName workspacePath;
    if(IsOpen()) {
        workspacePath = GetWorkspaceFileName();
    } else {
        // try maybe the workspace is opened by a plugin
        clCommandEvent event(wxEVT_CMD_IS_WORKSPACE_OPEN);
        event.SetAnswer(false);
        EventNotifier::Get()->ProcessEvent(event);
        if(event.IsAnswer()) {
            workspacePath = event.GetFileName();
        }
    }
    if(workspacePath.Exists()) {
        // append the .codelite folder
        workspacePath.AppendDir(".codelite");

        // ensure the path exists
        workspacePath.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);

        return workspacePath.GetPath();
    }
    return "";
}

wxFileName clCxxWorkspace::GetTagsFileName() const
{
    if(!IsOpen()) {
        return wxFileName();
    }

    wxFileName fn_tags(GetPrivateFolder(), GetWorkspaceFileName().GetFullName());
    fn_tags.SetName(fn_tags.GetName() + "-" + ::clGetUserName());
    fn_tags.SetExt("tags");
    return fn_tags;
}

cJSON* clCxxWorkspace::CreateCompileCommandsJSON(bool createCompileFlagsTxt, wxArrayString* generated_paths) const
{
    // Build the global compiler paths, we will need this later on...
    wxStringMap_t compilersGlobalPaths;
    std::unordered_map<wxString, wxArrayString> pathsMap = BuildSettingsConfigST::Get()->GetCompilersGlobalPaths();
    for(const auto& vt : pathsMap) {
        wxString compiler_name = vt.first;
        wxArrayString pathsArr = vt.second;
        wxString paths;
        std::for_each(pathsArr.begin(), pathsArr.end(), [&](wxString& path) {
            path.Trim().Trim(false);
            if(path.EndsWith("\\")) {
                path.RemoveLast();
            }
            paths << path << ";";
        });
        compilersGlobalPaths.insert({ compiler_name, paths });
    }

    // Check if the active project is using custom build
    ProjectPtr activeProject = GetActiveProject();
    if(activeProject) {
        BuildConfigPtr buildConf = activeProject->GetBuildConfiguration();
        if(buildConf && buildConf->IsCustomBuild()) {
            return nullptr;
        }
    }

    JSONItem compile_commands = JSONItem::createArray();
    clCxxWorkspace::ProjectMap_t::const_iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        BuildConfigPtr buildConf = iter->second->GetBuildConfiguration();
        if(buildConf && buildConf->IsProjectEnabled() && !buildConf->IsCustomBuild() &&
           buildConf->IsCompilerRequired()) {
            iter->second->CreateCompileCommandsJSON(compile_commands, compilersGlobalPaths, createCompileFlagsTxt);
            if(createCompileFlagsTxt && generated_paths) {
                // compile_flags.txt files are created under the same path as the project
                wxFileName project_fn = iter->second->GetFileName();
                project_fn.SetFullName("compile_flags.txt");
                generated_paths->Add(project_fn.GetFullPath());
            }
        }
    }

    if(!createCompileFlagsTxt && generated_paths) {
        wxFileName path = GetFileName();
        path.SetFullName("compile_commands.json");
        generated_paths->Add(path.GetFullPath());
    }
    return createCompileFlagsTxt ? nullptr : compile_commands.release();
}

ProjectPtr clCxxWorkspace::GetActiveProject() const { return GetProject(GetActiveProjectName()); }

ProjectPtr clCxxWorkspace::GetProject(const wxString& name) const
{
    clCxxWorkspace::ProjectMap_t::const_iterator iter = m_projects.find(name);
    if(iter == m_projects.end()) {
        return NULL;
    }
    return iter->second;
}

void clCxxWorkspace::GetCompilers(wxStringSet_t& compilers)
{
    clCxxWorkspace::ProjectMap_t::iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        iter->second->GetCompilers(compilers);
    }
}

void clCxxWorkspace::ReplaceCompilers(const wxStringMap_t& compilers)
{
    clCxxWorkspace::ProjectMap_t::iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        iter->second->ReplaceCompilers(compilers);
    }
}

void clCxxWorkspace::DoUpdateBuildMatrix()
{
    m_buildMatrix.Reset(new BuildMatrix(XmlUtils::FindFirstByTagName(m_doc.GetRoot(), "BuildMatrix"),
                                        GetLocalWorkspace()->GetSelectedBuildConfiguration()));
}

void clCxxWorkspace::RenameProject(const wxString& oldname, const wxString& newname)
{
    // Update the build matrix (we work on the XML directly here)
    wxXmlNode* buildMatrixNode = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), "BuildMatrix");
    if(buildMatrixNode) {
        wxXmlNode* child = buildMatrixNode->GetChildren();
        while(child) {
            if(child->GetName() == "WorkspaceConfiguration") {
                wxXmlNode* projectNode = child->GetChildren();
                while(projectNode) {
                    if(projectNode->GetName() == "Project") {
                        wxString name = projectNode->GetAttribute("Name");
                        if(name == oldname) {
                            XmlUtils::UpdateProperty(projectNode, "Name", newname);
                        }
                    }
                    projectNode = projectNode->GetNext();
                }
            }
            child = child->GetNext();
        }
    }

    // Update the list of projects in the workspace
    wxXmlNode* projectNode = XmlUtils::FindFirstByTagName(m_doc.GetRoot(), "Project");
    while(projectNode) {
        if(projectNode->GetAttribute("Name") == oldname) {
            XmlUtils::UpdateProperty(projectNode, "Name", newname);
        }
        projectNode = projectNode->GetNext();
    }
    // Update dependenices for each project
    clCxxWorkspace::ProjectMap_t::iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        iter->second->ProjectRenamed(oldname, newname);
    }

    clCxxWorkspace::ProjectMap_t tmpProjects;
    iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        tmpProjects.insert(std::make_pair(iter->first, iter->second));
    }
    m_projects.swap(tmpProjects);

    // Save everything
    Save();

    // Notify about this change
    clCommandEvent event(wxEVT_PROJ_RENAMED);
    event.SetOldName(oldname);
    event.SetString(newname);
    EventNotifier::Get()->AddPendingEvent(event);
}

bool clCxxWorkspace::IsBuildSupported() const { return true; }
bool clCxxWorkspace::IsProjectSupported() const { return true; }

wxString clCxxWorkspace::GetFilesMask() const
{
    wxString findInFilesMask = "*.c;*.cpp;*.cxx;*.cc;*.h;*.hpp;*.inc;*.mm;*.m;*.xrc;*.ini;*.xml";
    if(IsOpen()) {
        wxString fifMask;
        GetLocalWorkspace()->GetSearchInFilesMask(fifMask, findInFilesMask);
        if(fifMask.IsEmpty()) {
            fifMask = findInFilesMask;
        }
    }
    return findInFilesMask;
}
wxString clCxxWorkspace::GetProjectFromFile(const wxFileName& filename) const
{
    wxString filenameFP = filename.GetFullPath();
    clCxxWorkspace::ProjectMap_t::const_iterator iter = m_projects.begin();
    for(; iter != m_projects.end(); ++iter) {
        if(iter->second->GetFiles().count(filenameFP)) {
            return iter->first;
        }
    }
    return "";
}

void clCxxWorkspace::GetProjectFiles(const wxString& projectName, wxArrayString& files) const
{
    ProjectPtr p = GetProject(projectName.IsEmpty() ? GetActiveProjectName() : projectName);
    CHECK_PTR_RET(p);

    const Project::FilesMap_t& filesMap = p->GetFiles();
    if(filesMap.empty()) {
        return;
    }
    files.Alloc(filesMap.size());
    std::for_each(filesMap.begin(), filesMap.end(),
                  [&](const Project::FilesMap_t::value_type& vt) { files.Add(vt.first); });
}

void clCxxWorkspace::GetWorkspaceFiles(wxArrayString& files) const
{
    size_t totalFiles = 0;
    std::for_each(m_projects.begin(), m_projects.end(), [&](const clCxxWorkspace::ProjectMap_t::value_type& v) {
        totalFiles += v.second->GetFiles().size();
    });

    if(totalFiles) {
        files.Alloc(totalFiles);
        std::for_each(m_projects.begin(), m_projects.end(), [&](const clCxxWorkspace::ProjectMap_t::value_type& v) {
            const Project::FilesMap_t& filesMap = v.second->GetFiles();

            // Convert the set wxArrayString
            std::for_each(filesMap.begin(), filesMap.end(),
                          [&](const Project::FilesMap_t::value_type& vt) { files.Add(vt.first); });
        });
    }
}

WorkspaceConfigurationPtr clCxxWorkspace::GetSelectedConfig() const
{
    if(!GetBuildMatrix())
        return NULL;
    wxString buildConf = GetBuildMatrix()->GetSelectedConfigurationName();
    return GetBuildMatrix()->GetConfigurationByName(buildConf);
}

void clCxxWorkspace::ClearIncludePathCache()
{
    std::for_each(m_projects.begin(), m_projects.end(),
                  [&](const clCxxWorkspace::ProjectMap_t::value_type& v) { v.second->ClearIncludePathCache(); });
}

void clCxxWorkspace::DoUnselectActiveProject()
{
    if(!m_doc.IsOk())
        return;

    std::list<wxXmlNode*> xmls = DoGetProjectsXmlNodes();
    std::for_each(xmls.begin(), xmls.end(), [&](wxXmlNode* node) { XmlUtils::UpdateProperty(node, "Active", "No"); });
}

void clCxxWorkspace::DoLoadProjectsFromXml(wxXmlNode* parentNode, const wxString& folder,
                                           std::vector<wxXmlNode*>& removedChildren)
{
    wxXmlNode* child = parentNode->GetChildren();
    while(child) {
        if(child->GetName() == wxT("Project")) {
            wxString projectPath = child->GetAttribute(wxT("Path"), wxEmptyString);
            wxString errmsg;
            if(!DoAddProject(projectPath, folder, errmsg)) {
                removedChildren.push_back(child);
            }
        } else if(child->GetName() == wxT("VirtualDirectory")) {
            // Virtual directory
            wxString currentFolder = folder;
            wxString vdName = child->GetAttribute("Name", wxEmptyString);
            if(!currentFolder.IsEmpty()) {
                currentFolder << "/";
            }
            currentFolder << vdName;
            DoLoadProjectsFromXml(child, currentFolder, removedChildren);
        } else if((child->GetName() == wxT("WorkspaceParserPaths")) ||
                  (child->GetName() == wxT("WorkspaceParserMacros"))) {
            wxString swtlw = XmlUtils::ReadString(m_doc.GetRoot(), "SWTLW");
            if(swtlw.CmpNoCase("yes") == 0) {
                GetLocalWorkspace()->SetParserFlags(GetLocalWorkspace()->GetParserFlags() |
                                                    LocalWorkspace::EnableSWTLW);
                SyncToLocalWorkspaceSTParserPaths();
                SyncToLocalWorkspaceSTParserMacros();
            }
        }
        child = child->GetNext();
    }
}

wxXmlNode* clCxxWorkspace::DoGetWorkspaceFolderXmlNode(const wxString& path)
{
    wxArrayString parts = ::wxStringTokenize(path, "/", wxTOKEN_STRTOK);
    if(parts.IsEmpty())
        return m_doc.GetRoot();

    wxXmlNode* parent = m_doc.GetRoot();
    for(size_t i = 0; i < parts.size(); ++i) {
        parent = XmlUtils::FindNodeByName(parent, "VirtualDirectory", parts.Item(i));
        if(!parent)
            return NULL;
    }
    return parent;
}

wxXmlNode* clCxxWorkspace::DoCreateWorkspaceFolder(const wxString& path)
{
    wxXmlNode* node = DoGetWorkspaceFolderXmlNode(path);
    if(node)
        return node; // already exists

    // Create it
    wxArrayString parts = ::wxStringTokenize(path, "/", wxTOKEN_STRTOK);
    if(parts.IsEmpty())
        return m_doc.GetRoot();

    // Starting from the root node
    wxXmlNode* parent = m_doc.GetRoot();
    for(size_t i = 0; i < parts.size(); ++i) {
        wxXmlNode* child = XmlUtils::FindNodeByName(parent, "VirtualDirectory", parts.Item(i));
        if(!child) {
            // add this child
            child = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, "VirtualDirectory");
            child->AddAttribute("Name", parts.Item(i));
            parent->AddChild(child);
        }
        parent = child;
    }
    return parent;
}

bool clCxxWorkspace::MoveProjectToFolder(const wxString& projectName, const wxString& folderPath, bool saveAndReload)
{
    wxXmlNode* folderXml = DoGetWorkspaceFolderXmlNode(folderPath);
    if(!folderXml) {
        folderXml = DoCreateWorkspaceFolder(folderPath);
        if(!folderXml) {
            return false;
        }
    }

    // Locate the project XML node
    wxXmlNode* projectXml = DoGetProjectXmlNode(projectName);
    if(!projectXml || !projectXml->GetParent()) {
        return false;
    }

    projectXml->GetParent()->RemoveChild(projectXml);
    folderXml->AddChild(projectXml);

    if(!saveAndReload)
        return true;

    // Store the XML file and reload the workspace
    if(!SaveXmlFile()) {
        return false;
    }

    // Reload the workspace XML file
    wxString errMsg;
    return DoLoadWorkspace(m_fileName.GetFullPath(), errMsg);
}

void clCxxWorkspace::DeleteWorkspaceFolder(const wxString& path)
{
    wxXmlNode* node = DoGetWorkspaceFolderXmlNode(path);
    if(!node || !node->GetParent())
        return;

    node->GetParent()->RemoveChild(node);
    wxDELETE(node);

    wxString errMsg;
    DoLoadWorkspace(m_fileName.GetFullPath(), errMsg);
}

bool clCxxWorkspace::CreateWorkspaceFolder(const wxString& path) { return (DoCreateWorkspaceFolder(path) != NULL); }

bool clCxxWorkspace::DoLoadWorkspace(const wxString& fileName, wxString& errMsg)
{
    CloseWorkspace();
    m_buildMatrix.Reset(NULL);
    wxFileName workSpaceFile(fileName);
    if(workSpaceFile.FileExists() == false) {
        errMsg = wxString::Format(_("Could not open workspace file: '%s'"), fileName.c_str());
        return false;
    }

    m_fileName = workSpaceFile;
    m_doc.Load(m_fileName.GetFullPath());
    if(!m_doc.IsOk()) {
        errMsg = _("Corrupted workspace file");
        return false;
    }

    // Make sure we have the WORKSPACE/.codelite folder exists
    {
        wxLogNull nolog;
        wxMkdir(GetPrivateFolder());
    }

    SetWorkspaceLastModifiedTime(GetFileLastModifiedTime());

    // This function sets the working directory to the workspace directory!
    ::wxSetWorkingDirectory(m_fileName.GetPath());

    // Load all projects from the XML file
    std::vector<wxXmlNode*> removedChildren;
    DoLoadProjectsFromXml(m_doc.GetRoot(), wxEmptyString, removedChildren);

    // Delete the faulty projects
    for(size_t i = 0; i < removedChildren.size(); i++) {
        wxXmlNode* ch = removedChildren.at(i);
        ch->GetParent()->RemoveChild(ch);
        wxDELETE(ch);
    }

    errMsg.Clear();
    TagsManager* mgr = TagsManagerST::Get();
    mgr->CloseDatabase();
    mgr->OpenDatabase(GetTagsFileName().GetFullPath());

    // Update the build matrix
    DoUpdateBuildMatrix();
    return true;
}

wxXmlNode* clCxxWorkspace::DoGetProjectXmlNode(const wxString& projectName)
{
    std::list<wxXmlNode*> xmls = DoGetProjectsXmlNodes();
    std::list<wxXmlNode*>::iterator iter = std::find_if(xmls.begin(), xmls.end(), [&](wxXmlNode* node) {
        return (node->GetAttribute("Name", wxEmptyString) == projectName);
    });

    if(iter == xmls.end())
        return NULL;
    return (*iter);
}

std::list<wxXmlNode*> clCxxWorkspace::DoGetProjectsXmlNodes() const
{
    std::list<wxXmlNode*> queue;
    queue.push_back(m_doc.GetRoot());

    std::list<wxXmlNode*> projectsXmls;

    while(!queue.empty()) {
        wxXmlNode* node = queue.back();
        queue.pop_back();

        wxXmlNode* child = node->GetChildren();
        while(child) {
            if(child->GetName() == "VirtualDirectory") {
                queue.push_back(child);
            } else if(child->GetName() == "Project") {
                projectsXmls.push_back(child);
            }
            child = child->GetNext();
        }
    }
    return projectsXmls;
}

wxArrayString clCxxWorkspace::GetWorkspaceFolders() const
{
    wxArrayString arr;
    DoVisitWorkspaceFolders(m_doc.GetRoot(), "", arr);
    return arr;
}

void clCxxWorkspace::DoVisitWorkspaceFolders(wxXmlNode* parent, const wxString& curpath, wxArrayString& paths) const
{
    if((XmlUtils::FindFirstByTagName(parent, "VirtualDirectory") == NULL) && !curpath.IsEmpty()) {
        paths.Add(curpath);
        return;
    }

    wxXmlNode* child = parent->GetChildren();
    while(child) {
        if(child->GetName() == "VirtualDirectory") {
            wxString tmppath = curpath;
            if(!tmppath.IsEmpty()) {
                tmppath << "/";
            }
            tmppath << child->GetAttribute("Name", "");
            DoVisitWorkspaceFolders(child, tmppath, paths);
        }
        child = child->GetNext();
    }
}

wxString clCxxWorkspace::GetVersion() const
{
    if(!m_doc.IsOk() || m_doc.GetRoot())
        return wxEmptyString;
    return m_doc.GetRoot()->GetAttribute("Version");
}

wxFileName clCxxWorkspace::GetProjectFileName(const wxString& projectName) const
{
    ProjectPtr p = GetProject(projectName);
    if(!p) {
        return wxFileName();
    }
    return p->GetFileName();
}

wxArrayString clCxxWorkspace::GetWorkspaceProjects() const
{
    wxArrayString projects;
    GetProjectList(projects);
    return projects;
}

size_t clCxxWorkspace::GetExcludeFilesForConfig(std::vector<wxString>& files, const wxString& workspaceConfigName)
{
    std::for_each(m_projects.begin(), m_projects.end(), [&](const ProjectMap_t::value_type& vt) {
        ProjectPtr proj = vt.second;
        BuildConfigPtr conf = GetProjBuildConf(proj->GetName(), workspaceConfigName);
        if(conf) {
            const wxString& confname = conf->GetName();
            const wxStringSet_t& excludeFiles = proj->GetExcludeFiles();
            for(const wxString& filename : excludeFiles) {
                clProjectFile::Ptr_t file = proj->GetFile(filename);
                if(file && file->IsExcludeFromConfiguration(confname)) {
                    files.push_back(filename);
                }
            }
        }
    });
    return files.size();
}

void clCxxWorkspace::CreateCompileFlags() const
{
    // Build the global compiler paths, we will need this later on...
    wxStringMap_t compilersGlobalPaths;
    std::unordered_map<wxString, wxArrayString> pathsMap = BuildSettingsConfigST::Get()->GetCompilersGlobalPaths();
    for(const std::unordered_map<wxString, wxArrayString>::value_type& vt : pathsMap) {
        wxString compiler_name = vt.first;
        wxArrayString pathsArr = vt.second;
        wxString paths;
        std::for_each(pathsArr.begin(), pathsArr.end(), [&](wxString& path) {
            path.Trim().Trim(false);
            if(path.EndsWith("\\")) {
                path.RemoveLast();
            }
            paths << path << ";";
        });
        compilersGlobalPaths.insert({ compiler_name, paths });
    }

    for(const ProjectMap_t::value_type& vt : m_projects) {
        vt.second->CreateCompileFlags(compilersGlobalPaths);
    }
}

void clCxxWorkspace::ClearBacktickCache() { m_backticks.clear(); }

bool clCxxWorkspace::HasBacktick(const wxString& backtick) const { return m_backticks.count(backtick) != 0; }

void clCxxWorkspace::SetBacktickValue(const wxString& backtick, const wxString& value)
{
    m_backticks.erase(backtick);
    m_backticks.insert({ backtick, value });
}

bool clCxxWorkspace::GetBacktickValue(const wxString& backtick, wxString& value) const
{
    if(!HasBacktick(backtick)) {
        return false;
    }
    value = m_backticks.find(backtick)->second;
    return true;
}

void clCxxWorkspace::OnBuildHotspotClicked(clBuildEvent& event)
{
    if(!IsOpen()) {
        event.Skip();
        return;
    }

    wxFileName fn(event.GetFileName());
    if(fn.IsAbsolute()) {
        // there is a built in mechansim to handle full path files, let it process it
        event.Skip();
        return;
    }

    clDEBUG() << "Handling OnBuildHotspotClicked event" << endl;
    clDEBUG() << "File:" << event.GetFileName() << endl;
    clDEBUG() << "Line:" << event.GetLineNumber() << endl;
    clDEBUG() << "Project:" << event.GetProjectName() << endl;

    event.Skip(false);
    const wxString& project_name = event.GetProjectName();
    auto p = GetProject(project_name);
    if(!p) {
        clDEBUG() << "Could not find project:" << project_name << "." << endl;
        return;
    }

    fn.MakeAbsolute(p->GetFileName().GetPath());
    clDEBUG() << "Path made abs:" << event.GetFileName() << "->" << fn.GetFullPath() << endl;
    // attempt to open this file

    auto editor = clGetManager()->FindEditor(fn.GetFullPath());
    if(!editor) {
        editor = clGetManager()->OpenFile(fn.GetFullPath(), wxEmptyString, event.GetLineNumber());
    }
    if(editor) {
        clGetManager()->SelectPage(editor->GetCtrl());
        editor->CenterLine(event.GetLineNumber());
    }
}

void clCxxWorkspace::SetProjectActive(const wxString& project) { SetActiveProject(project); }

wxString clCxxWorkspace::GetDebuggerName() const
{
    auto proj = GetActiveProject();
    if(!proj) {
        return wxEmptyString;
    }

    auto build_conf = proj->GetBuildConfiguration();
    if(!build_conf) {
        return wxEmptyString;
    }
    return build_conf->GetDebuggerType();
}

clEnvList_t clCxxWorkspace::GetEnvironment() const
{
    clEnvList_t env_list;
    auto active_project = GetActiveProject();
    if(active_project && active_project->GetBuildConfiguration()) {
        const wxString& envstr = active_project->GetBuildConfiguration()->GetEnvvars();
        env_list = StringUtils::BuildEnvFromString(envstr);
    }
    return env_list;
}