File: mainbook.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 (1276 lines) | stat: -rw-r--r-- 43,293 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
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
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2008 by Eran Ifrah
// file name            : mainbook.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 <wx/xrc/xmlres.h>
#include "new_quick_watch_dlg.h"
#include "event_notifier.h"
#include "globals.h"
#include "ctags_manager.h"
#include "frame.h"
#include <wx/wupdlock.h>
#include "manager.h"
#include "clang_code_completion.h"
#include "close_all_dlg.h"
#include "filechecklist.h"
#include "editor_config.h"
#include "mainbook.h"
#include "message_pane.h"
#include "theme_handler.h"
#include "editorframe.h"
#include "FilesModifiedDlg.h"
#include <wx/regex.h>

#if CL_USE_NATIVEBOOK
#ifdef __WXGTK20__
// We need this ugly hack to workaround a gtk2-wxGTK name-clash
// See http://trac.wxwidgets.org/ticket/10883
#define GSocket GlibGSocket
#include <gtk/gtk.h>
#undef GSocket
#endif
#endif

MainBook::MainBook(wxWindow* parent)
    : wxPanel(parent)
    , m_navBar(NULL)
    , m_book(NULL)
    , m_quickFindBar(NULL)
    , m_useBuffereLimit(true)
    , m_isWorkspaceReloading(false)
    , m_reloadingDoRaise(true)
    , m_filesModifiedDlg(NULL)
{
    CreateGuiControls();
    ConnectEvents();
}

void MainBook::CreateGuiControls()
{
    wxBoxSizer* sz = new wxBoxSizer(wxVERTICAL);
    SetSizer(sz);

    m_messagePane = new MessagePane(this);
    sz->Add(m_messagePane, 0, wxALL | wxEXPAND, 5, NULL);

    m_navBar = new NavBar(this);
    sz->Add(m_navBar, 0, wxEXPAND);
    long style = wxVB_HAS_X | wxVB_MOUSE_MIDDLE_CLOSE_TAB;

#if !CL_USE_NATIVEBOOK
    style |= wxAUI_NB_WINDOWLIST_BUTTON | wxAUI_NB_SCROLL_BUTTONS;
#endif

    // load the notebook style from the configuration settings
    m_book = new Notebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, style);

    wxMenu* contextMenu = wxXmlResource::Get()->LoadMenu(wxT("editor_tab_right_click"));
    m_book->SetRightClickMenu(contextMenu);

    sz->Add(m_book, 1, wxEXPAND);

    m_quickFindBar = new QuickFindBar(this);
    DoPositionFindBar(2);

    sz->Layout();
}

void MainBook::ConnectEvents()
{
    m_book->Connect(wxEVT_COMMAND_BOOK_PAGE_CLOSING, NotebookEventHandler(MainBook::OnPageClosing), NULL, this);
    m_book->Connect(wxEVT_COMMAND_BOOK_PAGE_CLOSED, NotebookEventHandler(MainBook::OnPageClosed), NULL, this);
    m_book->Connect(wxEVT_COMMAND_BOOK_PAGE_CHANGED, NotebookEventHandler(MainBook::OnPageChanged), NULL, this);
    m_book->Connect(wxEVT_COMMAND_BOOK_PAGE_CHANGING, NotebookEventHandler(MainBook::OnPageChanging), NULL, this);
    m_book->Connect(wxEVT_COMMAND_BOOK_PAGE_X_CLICKED, NotebookEventHandler(MainBook::OnClosePage), NULL, this);
    m_book->Connect(wxEVT_COMMAND_BOOK_PAGE_MIDDLE_CLICKED, NotebookEventHandler(MainBook::OnClosePage), NULL, this);
    m_book->Connect(wxEVT_COMMAND_BOOK_BG_DCLICK, NotebookEventHandler(MainBook::OnMouseDClick), NULL, this);

    EventNotifier::Get()->Connect(
        wxEVT_WORKSPACE_LOADED, wxCommandEventHandler(MainBook::OnWorkspaceLoaded), NULL, this);
    EventNotifier::Get()->Connect(
        wxEVT_PROJ_FILE_ADDED, clCommandEventHandler(MainBook::OnProjectFileAdded), NULL, this);
    EventNotifier::Get()->Connect(
        wxEVT_PROJ_FILE_REMOVED, clCommandEventHandler(MainBook::OnProjectFileRemoved), NULL, this);
    EventNotifier::Get()->Connect(
        wxEVT_WORKSPACE_CLOSED, wxCommandEventHandler(MainBook::OnWorkspaceClosed), NULL, this);
    EventNotifier::Get()->Connect(wxEVT_DEBUG_ENDED, wxCommandEventHandler(MainBook::OnDebugEnded), NULL, this);
    EventNotifier::Get()->Connect(wxEVT_INIT_DONE, wxCommandEventHandler(MainBook::OnInitDone), NULL, this);

    EventNotifier::Get()->Bind(wxEVT_DETACHED_EDITOR_CLOSED, &MainBook::OnDetachedEditorClosed, this);

    // Highlight Job
    Connect(wxEVT_CMD_JOB_STATUS_VOID_PTR, wxCommandEventHandler(MainBook::OnStringHighlight), NULL, this);
}

MainBook::~MainBook()
{
    wxDELETE(m_filesModifiedDlg);
    m_book->Disconnect(wxEVT_COMMAND_BOOK_PAGE_CLOSING, NotebookEventHandler(MainBook::OnPageClosing), NULL, this);
    m_book->Disconnect(wxEVT_COMMAND_BOOK_PAGE_CLOSED, NotebookEventHandler(MainBook::OnPageClosed), NULL, this);
    m_book->Disconnect(wxEVT_COMMAND_BOOK_PAGE_CHANGED, NotebookEventHandler(MainBook::OnPageChanged), NULL, this);
    m_book->Disconnect(wxEVT_COMMAND_BOOK_PAGE_X_CLICKED, NotebookEventHandler(MainBook::OnClosePage), NULL, this);
    m_book->Disconnect(wxEVT_COMMAND_BOOK_PAGE_MIDDLE_CLICKED, NotebookEventHandler(MainBook::OnClosePage), NULL, this);
    m_book->Disconnect(wxEVT_COMMAND_BOOK_BG_DCLICK, NotebookEventHandler(MainBook::OnMouseDClick), NULL, this);

    EventNotifier::Get()->Disconnect(
        wxEVT_WORKSPACE_LOADED, wxCommandEventHandler(MainBook::OnWorkspaceLoaded), NULL, this);
    EventNotifier::Get()->Disconnect(
        wxEVT_PROJ_FILE_ADDED, clCommandEventHandler(MainBook::OnProjectFileAdded), NULL, this);
    EventNotifier::Get()->Disconnect(
        wxEVT_PROJ_FILE_REMOVED, clCommandEventHandler(MainBook::OnProjectFileRemoved), NULL, this);
    EventNotifier::Get()->Disconnect(
        wxEVT_WORKSPACE_CLOSED, wxCommandEventHandler(MainBook::OnWorkspaceClosed), NULL, this);
    EventNotifier::Get()->Disconnect(wxEVT_DEBUG_ENDED, wxCommandEventHandler(MainBook::OnDebugEnded), NULL, this);
    EventNotifier::Get()->Disconnect(wxEVT_INIT_DONE, wxCommandEventHandler(MainBook::OnInitDone), NULL, this);

    EventNotifier::Get()->Unbind(wxEVT_DETACHED_EDITOR_CLOSED, &MainBook::OnDetachedEditorClosed, this);
    Disconnect(wxEVT_CMD_JOB_STATUS_VOID_PTR, wxCommandEventHandler(MainBook::OnStringHighlight), NULL, this);
}

void MainBook::OnMouseDClick(NotebookEvent& e)
{
    wxUnusedVar(e);
    NewEditor();
}

void MainBook::OnPageClosing(NotebookEvent& e)
{
    e.Skip();

    LEditor* editor = dynamic_cast<LEditor*>(m_book->GetPage(e.GetSelection()));
    if(editor) {
        if(AskUserToSave(editor)) {
            SendCmdEvent(wxEVT_EDITOR_CLOSING, (IEditor*)editor);
        } else {
            e.Veto();
        }

    } else {

        // Unknow type, ask the plugins - maybe they know about this type
        wxNotifyEvent closeEvent(wxEVT_NOTIFY_PAGE_CLOSING);
        closeEvent.SetClientData(m_book->GetPage(e.GetSelection()));
        EventNotifier::Get()->ProcessEvent(closeEvent);
        if(!closeEvent.IsAllowed()) {
            e.Veto();
        }
    }
}

void MainBook::OnPageClosed(NotebookEvent& e)
{
    SelectPage(m_book->GetCurrentPage());
    m_quickFindBar->SetEditor(GetActiveEditor());

    // any editors left open?
    LEditor* editor = NULL;
    for(size_t i = 0; i < m_book->GetPageCount() && editor == NULL; i++) {
        editor = dynamic_cast<LEditor*>(m_book->GetPage(i));
    }

    if(m_book->GetPageCount() == 0) {
        SendCmdEvent(wxEVT_ALL_EDITORS_CLOSED);
        ShowQuickBar(false);
    }
}

void MainBook::OnProjectFileAdded(clCommandEvent& e)
{
    e.Skip();
    const wxArrayString& files = e.GetStrings();
    for(size_t i = 0; i < files.GetCount(); i++) {
        LEditor* editor = FindEditor(files.Item(i));
        if(editor) {
            wxString fileName = editor->GetFileName().GetFullPath();
            if(files.Index(fileName) != wxNOT_FOUND) {
                editor->SetProject(ManagerST::Get()->GetProjectNameByFile(fileName));
            }
        }
    }
}

void MainBook::OnProjectFileRemoved(clCommandEvent& e)
{
    e.Skip();
    const wxArrayString& files = e.GetStrings();
    for(size_t i = 0; i < files.GetCount(); ++i) {
        LEditor* editor = FindEditor(files.Item(i));
        if(editor && files.Index(editor->GetFileName().GetFullPath()) != wxNOT_FOUND) {
            editor->SetProject(wxEmptyString);
        }
    }
}

void MainBook::OnWorkspaceLoaded(wxCommandEvent& e)
{
    e.Skip();
    CloseAll(false); // get ready for session to be restored by clearing out existing pages
}

void MainBook::OnWorkspaceClosed(wxCommandEvent& e)
{
    e.Skip();
    CloseAll(false); // make sure no unsaved files
}

bool MainBook::AskUserToSave(LEditor* editor)
{
    if(!editor || !editor->GetModify() || editor->GetFileName().FileExists() == false) return true;

    // unsaved changes
    wxString msg;
    msg << _("Save changes to '") << editor->GetFileName().GetFullName() << wxT("' ?");
    long style = wxYES_NO;
    if(!ManagerST::Get()->IsShutdownInProgress()) {
        style |= wxCANCEL;
    }

    int answer = wxMessageBox(msg, _("Confirm"), style, clMainFrame::Get());
    switch(answer) {
    case wxYES:
        return editor->SaveFile();
    case wxNO:
        editor->SetSavePoint();
        return true;
    case wxCANCEL:
        return false;
    }

    return true; // to avoid compiler warnings
}

void MainBook::ClearFileHistory()
{
    size_t count = m_recentFiles.GetCount();
    for(size_t i = 0; i < count; i++) {
        m_recentFiles.RemoveFileFromHistory(0);
    }
    wxArrayString files;
    EditorConfigST::Get()->SetRecentItems(files, wxT("RecentFiles"));
}

void MainBook::GetRecentlyOpenedFiles(wxArrayString& files)
{
    EditorConfigST::Get()->GetRecentItems(files, wxT("RecentFiles"));
}

void MainBook::UpdateNavBar(LEditor* editor)
{
    if(m_navBar->IsShown()) {
        TagEntryPtr tag = NULL;
        if(editor && !editor->GetProject().IsEmpty()) {
            tag = TagsManagerST::Get()->FunctionFromFileLine(editor->GetFileName(), editor->GetCurrentLine() + 1);
        }
        m_navBar->UpdateScope(tag);
    }
}

void MainBook::ShowNavBar(bool s)
{
    m_navBar->DoShow(s);
    UpdateNavBar(GetActiveEditor());
}

void MainBook::SaveSession(SessionEntry& session, wxArrayInt& intArr)
{
    std::vector<LEditor*> editors;
    bool retain_order(true);
    GetAllEditors(editors, retain_order);

    session.SetSelectedTab(0);
    std::vector<TabInfo> vTabInfoArr;
    for(size_t i = 0; i < editors.size(); i++) {
        if((intArr.GetCount() > i) && (!intArr.Item(i))) {
            // If we're saving only selected editors, and this isn't one of them...
            continue;
        }
        if(editors[i] == GetActiveEditor()) {
            session.SetSelectedTab(vTabInfoArr.size());
        }
        TabInfo oTabInfo;
        oTabInfo.SetFileName(editors[i]->GetFileName().GetFullPath());
        oTabInfo.SetFirstVisibleLine(editors[i]->GetFirstVisibleLine());
        oTabInfo.SetCurrentLine(editors[i]->GetCurrentLine());

        wxArrayString astrBookmarks;
        editors[i]->StoreMarkersToArray(astrBookmarks);
        oTabInfo.SetBookmarks(astrBookmarks);

        std::vector<int> folds;
        editors[i]->StoreCollapsedFoldsToArray(folds);
        oTabInfo.SetCollapsedFolds(folds);

        vTabInfoArr.push_back(oTabInfo);
    }
    session.SetTabInfoArr(vTabInfoArr);
}

void MainBook::RestoreSession(SessionEntry& session)
{
    size_t sel = session.GetSelectedTab();
    const std::vector<TabInfo>& vTabInfoArr = session.GetTabInfoArr();
    for(size_t i = 0; i < vTabInfoArr.size(); i++) {
        const TabInfo& ti = vTabInfoArr[i];
        m_reloadingDoRaise = (i == vTabInfoArr.size() - 1); // Raise() when opening only the last editor
        LEditor* editor = OpenFile(ti.GetFileName());
        if(!editor) {
            if(i < sel) {
                // have to adjust selected tab number because couldn't open tab
                sel--;
            }
            continue;
        }

        editor->ScrollToLine(ti.GetFirstVisibleLine());
        editor->SetEnsureCaretIsVisible(editor->PositionFromLine(ti.GetCurrentLine()));
        editor->LoadMarkersFromArray(ti.GetBookmarks());
        editor->LoadCollapsedFoldsFromArray(ti.GetCollapsedFolds());
    }
    // We can't just use SelectPane() here.
    // Notebook::DoPageChangedEvent has posted events to us,
    // which have the effect of selecting back to page 0
    // So post ourselves an event, so that it arrives after that one
    NotebookEvent event(wxEVT_COMMAND_BOOK_PAGE_CHANGED, GetId());
    event.SetSelection(sel);
    m_book->GetEventHandler()->AddPendingEvent(event);
}

LEditor* MainBook::GetActiveEditor(bool includeDetachedEditors)
{
    if(includeDetachedEditors) {
        EditorFrame::List_t::iterator iter = m_detachedEditors.begin();
        for(; iter != m_detachedEditors.end(); ++iter) {
            if((*iter)->GetEditor()->IsFocused()) {
                return (*iter)->GetEditor();
            }
        }
    }

    if(!GetCurrentPage()) {
        return NULL;
    }
    return dynamic_cast<LEditor*>(GetCurrentPage());
}

void MainBook::GetAllEditors(LEditor::Vec_t& editors, size_t flags)
{
    editors.clear();
    if(!(flags & kGetAll_DetachedOnly)) {
        // Collect booked editors
        if(!(flags & kGetAll_RetainOrder)) {
            // Most of the time we don't care about the order the tabs are stored in
            for(size_t i = 0; i < m_book->GetPageCount(); i++) {
                LEditor* editor = dynamic_cast<LEditor*>(m_book->GetPage(i));
                if(editor) {
                    editors.push_back(editor);
                }
            }
        } else {
            std::vector<wxWindow*> windows;
#if !CL_USE_NATIVEBOOK
            m_book->GetEditorsInOrder(windows);
            for(size_t i = 0; i < windows.size(); i++) {
                LEditor* editor = dynamic_cast<LEditor*>(windows.at(i));
                if(editor) {
                    editors.push_back(editor);
                }
            }
#else
            for(size_t i = 0; i < m_book->GetPageCount(); i++) {
                LEditor* editor = dynamic_cast<LEditor*>(m_book->GetPage(i));
                if(editor) {
                    editors.push_back(editor);
                }
            }
#endif
        }
    }
    if((flags & kGetAll_IncludeDetached) || (flags & kGetAll_DetachedOnly)) {
        // Add the detached editors
        EditorFrame::List_t::iterator iter = m_detachedEditors.begin();
        for(; iter != m_detachedEditors.end(); ++iter) {
            editors.push_back((*iter)->GetEditor());
        }
    }
}

LEditor* MainBook::FindEditor(const wxString& fileName)
{
    wxString unixStyleFile(fileName);
#ifdef __WXMSW__
    unixStyleFile.Replace(wxT("\\"), wxT("/"));
#endif
    // On gtk either fileName or the editor filepath (or both) may be (or their paths contain) symlinks
    wxString fileNameDest = CLRealPath(fileName);

    for(size_t i = 0; i < m_book->GetPageCount(); i++) {
        LEditor* editor = dynamic_cast<LEditor*>(m_book->GetPage(i));
        if(editor) {
            wxString unixStyleFile(editor->GetFileName().GetFullPath());
            wxString nativeFile(unixStyleFile);
#ifdef __WXMSW__
            unixStyleFile.Replace(wxT("\\"), wxT("/"));
#endif
            if(nativeFile.CmpNoCase(fileName) == 0 || unixStyleFile.CmpNoCase(fileName) == 0 ||
               unixStyleFile.CmpNoCase(fileNameDest) == 0) {
                return editor;
            }

#if defined(__WXGTK__)
            // Try again, dereferencing the editor fpath
            wxString editorDest = CLRealPath(unixStyleFile);
            if(editorDest.CmpNoCase(fileName) == 0 || editorDest.CmpNoCase(fileNameDest) == 0) {
                return editor;
            }
#endif
        }
    }

    // try the detached editors
    EditorFrame::List_t::iterator iter = m_detachedEditors.begin();
    for(; iter != m_detachedEditors.end(); ++iter) {
        if((*iter)->GetEditor()->GetFileName().GetFullPath() == fileName) {
            return (*iter)->GetEditor();
        }
    }
    return NULL;
}

wxWindow* MainBook::FindPage(const wxString& text)
{
    for(size_t i = 0; i < m_book->GetPageCount(); i++) {
        LEditor* editor = dynamic_cast<LEditor*>(m_book->GetPage(i));
        if(editor && editor->GetFileName().GetFullPath().CmpNoCase(text) == 0) {
            return editor;
        }

        if(m_book->GetPageText(i) == text) return m_book->GetPage(i);
    }
    return NULL;
}

LEditor* MainBook::NewEditor()
{
    static int fileCounter = 0;

    wxString fileNameStr(_("Untitled"));
    fileNameStr << ++fileCounter;
    wxFileName fileName(fileNameStr);

    // A Nice trick: hide the notebook, open the editor
    // and then show it
    bool hidden(false);
    if(m_book->GetPageCount() == 0) hidden = GetSizer()->Hide(m_book);

    LEditor* editor = new LEditor(m_book);
    editor->SetFileName(fileName);
    AddPage(editor, fileName.GetFullName(), wxNullBitmap, true);

#ifdef __WXMAC__
    m_book->GetSizer()->Layout();
#endif

    // SHow the notebook
    if(hidden) GetSizer()->Show(m_book);

    editor->SetActive();
    return editor;
}

static bool IsFileExists(const wxFileName& filename)
{
#ifdef __WXMSW__
    /*    wxString drive  = filename.GetVolume();
        if(drive.Length()>1)
            return false;*/

    return filename.FileExists();
#else
    return filename.FileExists();
#endif
}

LEditor* MainBook::OpenFile(const wxString& file_name,
                            const wxString& projectName,
                            int lineno,
                            long position,
                            OF_extra extra /*=OF_AddJump*/,
                            bool preserveSelection /*=true*/)
{
    wxFileName fileName(file_name);
    fileName.MakeAbsolute();

#ifdef __WXMSW__
    // Handle cygwin paths
    wxString curpath = fileName.GetFullPath();
    static wxRegEx reCygdrive("/cygdrive/([A-Za-z])");
    if(reCygdrive.Matches(curpath)) {
        // Replace the /cygdrive/c with volume C:
        wxString volume = reCygdrive.GetMatch(curpath, 1);
        volume << ":";
        reCygdrive.Replace(&curpath, volume);
        fileName = curpath;
    }
#endif

    if(IsFileExists(fileName) == false) {
        wxLogMessage(wxT("Failed to open: %s: No such file or directory"), fileName.GetFullPath().c_str());
        return NULL;
    }

    wxString projName = projectName;
    if(projName.IsEmpty()) {
        // try to match a project name to the file. otherwise, CC may not work
        projName = ManagerST::Get()->GetProjectNameByFile(fileName.GetFullPath());
    }

    LEditor* editor = GetActiveEditor(true);
    BrowseRecord jumpfrom = editor ? editor->CreateBrowseRecord() : BrowseRecord();

    editor = FindEditor(fileName.GetFullPath());
    if(editor) {
        editor->SetProject(projName);
    } else if(fileName.IsOk() == false) {
        wxLogMessage(wxT("Invalid file name: ") + fileName.GetFullPath());
        return NULL;

    } else if(!fileName.FileExists()) {
        wxLogMessage(wxT("File: ") + fileName.GetFullPath() + wxT(" does not exist!"));
        return NULL;

    } else {

        // A Nice trick: hide the notebook, open the editor
        // and then show it
        bool hidden(false);
        if(m_book->GetPageCount() == 0) hidden = GetSizer()->Hide(m_book);

        editor = new LEditor(m_book);
        editor->Create(projName, fileName);

// If we're here from 'Swap Header/Implementation file', insert the new page next door
#if !CL_USE_NATIVEBOOK
        size_t sel = m_book->GetVisibleEditorIndex();
#else
        size_t sel = (size_t)m_book->GetSelection();
#endif

        if((extra & OF_PlaceNextToCurrent) && (sel != Notebook::npos)) {
            AddPage(editor, fileName.GetFullName(), wxNullBitmap, false, sel + 1);
        } else {
            AddPage(editor, fileName.GetFullName());
        }
        editor->SetSyntaxHighlight();

        // mark the editor as read only if needed
        MarkEditorReadOnly(editor, IsFileReadOnly(editor->GetFileName()));

        // SHow the notebook
        if(hidden) GetSizer()->Show(m_book);

        if(position == wxNOT_FOUND && lineno == wxNOT_FOUND && editor->GetContext()->GetName() == wxT("C++")) {
            // try to find something interesting in the file to put the caret at
            // for now, just skip past initial blank lines and comments
            for(lineno = 0; lineno < editor->GetLineCount(); lineno++) {
                switch(editor->GetStyleAt(editor->PositionFromLine(lineno))) {
                case wxSTC_C_DEFAULT:
                case wxSTC_C_COMMENT:
                case wxSTC_C_COMMENTDOC:
                case wxSTC_C_COMMENTLINE:
                case wxSTC_C_COMMENTLINEDOC:
                    continue;
                }
                // if we got here, it's a line to stop on
                break;
            }
            if(lineno == editor->GetLineCount()) {
                lineno = 1; // makes sure a navigation record gets saved
            }
        }
    }

    if(position != wxNOT_FOUND) {
        editor->SetEnsureCaretIsVisible(position, preserveSelection);
        editor->SetLineVisible(editor->LineFromPosition(position));

    } else if(lineno != wxNOT_FOUND) {
        editor->SetEnsureCaretIsVisible(editor->PositionFromLine(lineno), preserveSelection);
        editor->SetLineVisible(lineno);
    }

    if(m_reloadingDoRaise) {
        if(GetActiveEditor() == editor) {
            editor->SetActive();
        } else {
            SelectPage(editor);
        }
    }

    // Add this file to the history. Don't check for uniqueness:
    // if it's already on the list, wxFileHistory will move it to the top
    // Also, sync between the history object and the configuration file
    m_recentFiles.AddFileToHistory(fileName.GetFullPath());
    wxArrayString files;
    m_recentFiles.GetFiles(files);
    EditorConfigST::Get()->SetRecentItems(files, wxT("RecentFiles"));

    if(extra & OF_AddJump) {
        BrowseRecord jumpto = editor->CreateBrowseRecord();
        NavMgr::Get()->AddJump(jumpfrom, jumpto);
    }
#if !CL_USE_NATIVEBOOK
    if(m_book->GetPageCount() == 1) {
        m_book->GetSizer()->Layout();
    }
#endif
    return editor;
}

bool MainBook::AddPage(wxWindow* win,
                       const wxString& text,
                       const wxBitmap& bmp,
                       bool selected,
                       size_t insert_at_index /*=wxNOT_FOUND*/)
{
    if(m_book->GetPageIndex(win) != Notebook::npos) return false;

    long MaxBuffers = clConfig::Get().Read("MaxOpenedTabs", 15);
    bool closeLastTab = ((long)(m_book->GetPageCount()) >= MaxBuffers) && GetUseBuffereLimit();
    if((insert_at_index == (size_t)wxNOT_FOUND) || (insert_at_index >= m_book->GetPageCount())) {

#if CL_USE_NATIVEBOOK
        // There seems to be a bug in wxGTK where we can't change
        // the selection programtically
        int next_pos = m_book->GetPageCount();
#endif
        m_book->AddPage(win, text, closeLastTab ? true : selected, bmp);

#if CL_USE_NATIVEBOOK
        // If the newly added page is expected to be the selected one
        // and it is NOT of type IEditor we provide a workaround that
        // uses direct gtk calls
        bool shouldSelect = (closeLastTab ? true : selected);
        IEditor* editor = dynamic_cast<IEditor*>(win);
        if(shouldSelect && (m_book->GetSelection() != (size_t)next_pos) && !editor) {
            // failed to insert the page AND the page is not of type
            // IEditor
            gtk_widget_show_all(win->m_widget);
            m_book->SetSelection(next_pos);
        }
#endif
    } else {
        m_book->InsertPage(insert_at_index, win, text, closeLastTab ? true : selected, bmp);
    }

    if(closeLastTab) {
        // We have reached the limit of the number of open buffers
        // Close the last used buffer
        const wxArrayPtrVoid& arr = m_book->GetHistory();
        if(arr.GetCount()) {
            // We got at least one page, close the last used
            wxWindow* tab = static_cast<wxWindow*>(arr.Item(arr.GetCount() - 1));
            ClosePage(tab);
        }
    }

#if !CL_USE_NATIVEBOOK
    if(m_book->GetPageCount() == 1) {
        m_book->GetSizer()->Layout();
    }
#endif
    return true;
}

bool MainBook::SelectPage(wxWindow* win)
{
    size_t index = m_book->GetPageIndex(win);
    if(index != Notebook::npos && m_book->GetSelection() != (int)index) {
        m_book->SetSelection(index);
    }

    return DoSelectPage(win);
}

bool MainBook::UserSelectFiles(std::vector<std::pair<wxFileName, bool> >& files,
                               const wxString& title,
                               const wxString& caption,
                               bool cancellable)
{
    if(files.empty()) return true;

    FileCheckList dlg(clMainFrame::Get(), wxID_ANY, title);
    dlg.SetCaption(caption);
    dlg.SetFiles(files);
    dlg.SetCancellable(cancellable);
    bool res = dlg.ShowModal() == wxID_OK;
    files = dlg.GetFiles();
    return res;
}

bool MainBook::SaveAll(bool askUser, bool includeUntitled)
{
    // turn the 'saving all' flag on so we could 'Veto' all focus events
    LEditor::Vec_t editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);

    std::vector<std::pair<wxFileName, bool> > files;
    size_t n = 0;
    for(size_t i = 0; i < editors.size(); i++) {
        if(!editors[i]->GetModify()) continue;

        if(!includeUntitled && !editors[i]->GetFileName().FileExists())
            continue; // don't save new documents that have not been saved to disk yet

        files.push_back(std::make_pair(editors[i]->GetFileName(), true));
        editors[n++] = editors[i];
    }
    editors.resize(n);

    bool res = !askUser || UserSelectFiles(files,
                                           _("Save Modified Files"),
                                           _("Some files are modified.\nChoose the files you would like to save."));
    if(res) {
        for(size_t i = 0; i < files.size(); i++) {
            if(files[i].second) {
                editors[i]->SaveFile();
            }
        }
    }
    // And notify the plugins to save their tabs (this function only cover editors)
    clCommandEvent saveAllEvent(wxEVT_SAVE_ALL_EDITORS);
    EventNotifier::Get()->AddPendingEvent(saveAllEvent);
    return res;
}

void MainBook::ReloadExternallyModified(bool prompt)
{
    if(m_isWorkspaceReloading) return;

    LEditor::Vec_t editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);

    time_t workspaceModifiedTimeBefore = WorkspaceST::Get()->GetFileLastModifiedTime();

    // filter list of editors for any whose files have been modified
    std::vector<std::pair<wxFileName, bool> > files;
    size_t n = 0;
    for(size_t i = 0; i < editors.size(); i++) {
        time_t diskTime = editors[i]->GetFileLastModifiedTime();
        time_t editTime = editors[i]->GetEditorLastModifiedTime();
        if(diskTime != editTime) {
            // update editor last mod time so that we don't keep bugging the user over the same file,
            // unless it gets changed again
            editors[i]->SetEditorLastModifiedTime(diskTime);

            // A last check: see if the content of the file has actually changed. This avoids unnecessary reload offers
            // after e.g. git stash
            if(!CompareFileWithString(editors[i]->GetFileName().GetFullPath(), editors[i]->GetText())) {
                files.push_back(std::make_pair(editors[i]->GetFileName(), !editors[i]->GetModify()));
                editors[n++] = editors[i];
            }
        }
    }
    editors.resize(n);
    if(n == 0) return;

    if(prompt) {

        int res = clConfig::Get().GetAnnoyingDlgAnswer("FilesModifiedDlg", wxNOT_FOUND);
        if(res == wxNOT_FOUND) {
            // User did not ticked the 'Remember my answer' checkbox
            // Show the dialog
            res = GetFilesModifiedDlg()->ShowModal();

            if(res == wxID_CANCEL) {
                return;
            }

            if(GetFilesModifiedDlg()->GetRememberMyAnswer()) {
                clConfig::Get().SetAnnoyingDlgAnswer("FilesModifiedDlg", res);
            }
        }

        if(res == FilesModifiedDlg::kID_BUTTON_CHOOSE) {
            UserSelectFiles(
                files,
                _("Reload Modified Files"),
                _("Files have been modified outside the editor.\nChoose which files you would like to reload."),
                false);
        }
    }

    time_t workspaceModifiedTimeAfter = WorkspaceST::Get()->GetFileLastModifiedTime();
    if(workspaceModifiedTimeBefore != workspaceModifiedTimeAfter) {
        // a workspace reload occured between the "Reload Modified Files" and
        // the "Reload WOrkspace" dialog, cancel this it's not needed anymore
        return;
    }

    std::vector<wxFileName> filesToRetag;
    for(size_t i = 0; i < files.size(); i++) {
        if(files[i].second) {
            editors[i]->ReloadFile();
            filesToRetag.push_back(files[i].first);
        }
    }
    if(filesToRetag.size() > 1) {
        TagsManagerST::Get()->RetagFiles(filesToRetag, TagsManager::Retag_Quick);
        SendCmdEvent(wxEVT_FILE_RETAGGED, (void*)&filesToRetag);

    } else if(filesToRetag.size() == 1) {
        ManagerST::Get()->RetagFile(filesToRetag.at(0).GetFullPath());
        SendCmdEvent(wxEVT_FILE_RETAGGED, (void*)&filesToRetag);
    }
}

bool MainBook::ClosePage(wxWindow* page)
{
    size_t pos = m_book->GetPageIndex(page);
    return pos != Notebook::npos && m_book->DeletePage(pos);
}

bool MainBook::CloseAllButThis(wxWindow* page)
{
    wxString text;

    clWindowUpdateLocker locker(this);

    size_t pos = m_book->GetPageIndex(page);
    if(pos != Notebook::npos) {
        text = m_book->GetPageText(pos);
        m_book->RemovePage(pos, false);
    }
    bool res = CloseAll(true);
    if(pos != Notebook::npos) {
        m_book->AddPage(page, text, true);
    }

#ifdef __WXMAC__
    m_book->GetSizer()->Layout();
#endif

    return res;
}

bool MainBook::CloseAll(bool cancellable)
{
    LEditor::Vec_t editors;
    GetAllEditors(editors, kGetAll_IncludeDetached);

    // filter list of editors for any that need to be saved
    std::vector<std::pair<wxFileName, bool> > files;
    size_t n = 0;
    for(size_t i = 0; i < editors.size(); i++) {
        if(editors[i]->GetModify()) {
            files.push_back(std::make_pair(editors[i]->GetFileName(), true));
            editors[n++] = editors[i];
        }
    }
    editors.resize(n);

    if(!UserSelectFiles(files,
                        _("Save Modified Files"),
                        _("Some files are modified.\nChoose the files you would like to save."),
                        cancellable))
        return false;

    for(size_t i = 0; i < files.size(); i++) {
        if(files[i].second) {
            editors[i]->SaveFile();
        } else {
            editors[i]->SetSavePoint();
        }
    }

    // Delete the files without notifications (it will be faster)
    clWindowUpdateLocker locker(this);
#if HAS_LIBCLANG
    ClangCodeCompletion::Instance()->CancelCodeComplete();
#endif

    SendCmdEvent(wxEVT_ALL_EDITORS_CLOSING);

    m_reloadingDoRaise = false;
    m_book->DeleteAllPages(false);
    m_reloadingDoRaise = true;

    // Delete all detached editors
    EditorFrame::List_t::iterator iter = m_detachedEditors.begin();
    for(; iter != m_detachedEditors.end(); ++iter) {
        (*iter)->Destroy(); // Destroying the frame will release the editor
    }

    // Since we got no more editors opened,
    // send a wxEVT_ALL_EDITORS_CLOSED event
    SendCmdEvent(wxEVT_ALL_EDITORS_CLOSED);

    // Update the quick-find-bar
    m_quickFindBar->SetEditor(NULL);
    ShowQuickBar(false);

    // Clear the Navigation Bar if it is not empty
    TagEntryPtr tag = NULL;
    m_navBar->UpdateScope(tag);

    // Update the frame's title
    clMainFrame::Get()->SetFrameTitle(NULL);

    DoHandleFrameMenu(NULL);

    // OutputTabWindow::OnEditUI will crash on >=wxGTK-2.9.3 if we don't set the focus somewhere that still exists
    // This workaround doesn't seem to work if applied earlier in the function :/
    m_book->SetFocus();

    return true;
}

wxString MainBook::GetPageTitle(wxWindow* page) const
{
    size_t selection = m_book->GetPageIndex(page);
    if(selection != Notebook::npos) return m_book->GetPageText(selection);
    return wxEmptyString;
}

void MainBook::SetPageTitle(wxWindow* page, const wxString& name)
{
    size_t selection = m_book->GetPageIndex(page);
    if(selection != Notebook::npos) {
        // LEditor *editor = dynamic_cast<LEditor*>(page);
        m_book->SetPageText(selection, name);
    }
}

void MainBook::ApplySettingsChanges()
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->SetSyntaxHighlight(editors[i]->GetContext()->GetName());
    }

    clMainFrame::Get()->UpdateAUI();
    clMainFrame::Get()->ShowOrHideCaptions();

    // Last: reposition the findBar
    DoPositionFindBar(2);
}

void MainBook::UnHighlightAll()
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->UnHighlightAll();
    }
}

void MainBook::DelAllBreakpointMarkers()
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->DelAllBreakpointMarkers();
    }
}

void MainBook::SetViewEOL(bool visible)
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->SetViewEOL(visible);
    }
}

void MainBook::HighlightWord(bool hl)
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->HighlightWord(hl);
    }
}

void MainBook::ShowWhitespace(int ws)
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->SetViewWhiteSpace(ws);
    }
}

void MainBook::UpdateColours()
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->UpdateColours();
    }
}

void MainBook::UpdateBreakpoints()
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_IncludeDetached);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->UpdateBreakpoints();
    }
    ManagerST::Get()->GetBreakpointsMgr()->RefreshBreakpointMarkers();
}

void MainBook::MarkEditorReadOnly(LEditor* editor, bool ro)
{
    if(!editor) {
        return;
    }
#if !CL_USE_NATIVEBOOK
    for(size_t i = 0; i < m_book->GetPageCount(); i++) {
        if(editor == m_book->GetPage(i)) {
            m_book->SetPageBitmap(i, ro ? wxXmlResource::Get()->LoadBitmap(wxT("read_only")) : wxNullBitmap);
            break;
        }
    }
#endif
}

long MainBook::GetBookStyle() { return 0; }

bool MainBook::DoSelectPage(wxWindow* win)
{
    LEditor* editor = dynamic_cast<LEditor*>(win);
    if(editor) {
        editor->SetActive();
        m_quickFindBar->SetEditor(editor);

    } else {
        m_quickFindBar->ShowForPlugins();
    }

    // Remove context menu if needed
    DoHandleFrameMenu(editor);

    if(!editor) {
        clMainFrame::Get()->SetFrameTitle(NULL);
        clMainFrame::Get()->SetStatusMessage(wxEmptyString, 1); // clear line & column indicator
        UpdateNavBar(NULL);
        SendCmdEvent(wxEVT_CMD_PAGE_CHANGED, win);

    } else {
        if(editor->GetContext()->GetName() == wxT("C++")) {
            if(clMainFrame::Get()->GetMenuBar()->FindMenu(wxT("C++")) == wxNOT_FOUND) {
                clMainFrame::Get()->GetMenuBar()->Append(wxXmlResource::Get()->LoadMenu(wxT("editor_right_click")),
                                                         wxT("C++"));
            }
        }
        SendCmdEvent(wxEVT_ACTIVE_EDITOR_CHANGED, (IEditor*)editor);
    }

    return true;
}

void MainBook::ShowMessage(const wxString& message,
                           bool showHideButton,
                           const wxBitmap& bmp,
                           const ButtonDetails& btn1,
                           const ButtonDetails& btn2,
                           const ButtonDetails& btn3,
                           const CheckboxDetails& cb)
{
    m_messagePane->ShowMessage(message, showHideButton, bmp, btn1, btn2, btn3, cb);
    clMainFrame::Get()->SendSizeEvent();
}

void MainBook::OnPageChanged(NotebookEvent& e)
{
    int newSel = e.GetSelection();
    if(newSel != wxNOT_FOUND && m_reloadingDoRaise) {
        wxWindow* win = m_book->GetPage((size_t)newSel);
        if(win) {
            SelectPage(win);
            // LEditor *editor = dynamic_cast<LEditor*>(win);
            // if(editor) {
            //	ManagerST::Get()->UpdatePreprocessorFile(editor);
            //}
        }
    }
    e.Skip();
}

wxWindow* MainBook::GetCurrentPage() { return m_book->GetCurrentPage(); }

void MainBook::OnClosePage(NotebookEvent& e)
{
    clWindowUpdateLocker locker(this);
    int where = e.GetSelection();
    if(where == wxNOT_FOUND) {
        return;
    }
    wxWindow* page = m_book->GetPage((size_t)where);
    if(page) ClosePage(page);
}

void MainBook::DoPositionFindBar(int where)
{
    clWindowUpdateLocker locker(this);
    // the find bar is already placed on the MainBook, detach it
    GetSizer()->Detach(m_quickFindBar);

    bool placeAtBottom = EditorConfigST::Get()->GetOptions()->GetFindBarAtBottom();
    if(placeAtBottom)
        GetSizer()->Add(m_quickFindBar, 0, wxTOP | wxBOTTOM | wxEXPAND);
    else
        GetSizer()->Insert(where, m_quickFindBar, 0, wxTOP | wxBOTTOM | wxEXPAND);

    GetSizer()->Layout();
}

void MainBook::OnDebugEnded(wxCommandEvent& e)
{
    // ManagerST::Get()->GetDebuggerTip()->HideDialog();
    e.Skip();
}

void MainBook::DoHandleFrameMenu(LEditor* editor)
{
    // Incase of no editor or an editor with context other than C++
    // remove the context menu from the main frame
    if(!editor || editor->GetContext()->GetName() != wxT("C++")) {
        int idx = clMainFrame::Get()->GetMenuBar()->FindMenu(wxT("C++"));
        if(idx != wxNOT_FOUND) {
            clMainFrame::Get()->GetMenuBar()->EnableTop(idx, false);
        }

    } else if(editor && editor->GetContext()->GetName() == wxT("C++")) {

        int idx = clMainFrame::Get()->GetMenuBar()->FindMenu(wxT("C++"));
        if(idx != wxNOT_FOUND) {
            clMainFrame::Get()->GetMenuBar()->EnableTop(idx, true);
        }
    }
}

void MainBook::OnStringHighlight(wxCommandEvent& e)
{
    StringHighlightOutput* result = reinterpret_cast<StringHighlightOutput*>(e.GetClientData());
    if(result) {

        // Locate the editor
        LEditor* editor = FindEditor(result->filename);
        if(editor) {
            editor->HighlightWord(result);
        }
        delete result;
    }
}

void MainBook::OnPageChanging(NotebookEvent& e)
{
    LEditor* editor = GetActiveEditor();
    if(editor) {
        editor->HideCompletionBox();
        editor->CallTipCancel();
    }
#if HAS_LIBCLANG
    ClangCodeCompletion::Instance()->CancelCodeComplete();
#endif
    e.Skip();
}

void MainBook::SetViewWordWrap(bool b)
{
    std::vector<LEditor*> editors;
    GetAllEditors(editors, MainBook::kGetAll_Default);
    for(size_t i = 0; i < editors.size(); i++) {
        editors[i]->SetWrapMode(b ? wxSTC_WRAP_WORD : wxSTC_WRAP_NONE);
    }
}

void MainBook::OnInitDone(wxCommandEvent& e) { e.Skip(); }

wxWindow* MainBook::GetPage(size_t page) { return m_book->GetPage(page); }

bool MainBook::ClosePage(const wxString& text)
{
    int numPageClosed(0);
    bool closed = ClosePage(FindPage(text));
    while(closed) {
        ++numPageClosed;
        closed = ClosePage(FindPage(text));
    }
    return numPageClosed > 0;
}

size_t MainBook::GetPageCount() const { return m_book->GetPageCount(); }

void MainBook::DetachActiveEditor()
{
    if(GetActiveEditor()) {
        LEditor* editor = GetActiveEditor();
        m_book->RemovePage(m_book->GetSelection(), true);
        EditorFrame* frame = new EditorFrame(clMainFrame::Get(), editor);
        frame->Show();
        m_detachedEditors.push_back(frame);
    }
}

void MainBook::OnDetachedEditorClosed(clCommandEvent& e)
{
    e.Skip();
    DoEraseDetachedEditor((IEditor*)e.GetClientData());
}

void MainBook::DoEraseDetachedEditor(IEditor* editor)
{
    EditorFrame::List_t::iterator iter = m_detachedEditors.begin();
    for(; iter != m_detachedEditors.end(); ++iter) {
        if((*iter)->GetEditor() == editor) {
            m_detachedEditors.erase(iter);
            break;
        }
    }
}

void MainBook::OnWorkspaceReloadEnded(clCommandEvent& e)
{
    e.Skip();
    m_isWorkspaceReloading = false;
}

void MainBook::OnWorkspaceReloadStarted(clCommandEvent& e)
{
    e.Skip();
    m_isWorkspaceReloading = true;
}

void MainBook::ClosePageVoid(wxWindow* win) { ClosePage(win); }

void MainBook::CloseAllButThisVoid(wxWindow* win) { CloseAllButThis(win); }

void MainBook::CloseAllVoid(bool cancellable) { CloseAll(cancellable); }

FilesModifiedDlg* MainBook::GetFilesModifiedDlg()
{
    if(!m_filesModifiedDlg) m_filesModifiedDlg = new FilesModifiedDlg(clMainFrame::Get());
    return m_filesModifiedDlg;
}