-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocumentManager.cpp
More file actions
1052 lines (897 loc) · 33.9 KB
/
Copy pathDocumentManager.cpp
File metadata and controls
1052 lines (897 loc) · 33.9 KB
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
#include "editor/DocumentManager.h"
#include "editor/Document.h"
#include "editor/EditorWidget.h"
#include "editor/FileIo.h"
#include "editor/FileLimits.h"
#include "editor/LargeFileBanner.h"
#include "layout/EditorPaneItem.h"
#include "layout/LayoutTree.h"
#include "layout/PaneItem.h"
#include "layout/PaneWidget.h"
#include "lsp/LspClient.h"
#include "settings/EditorSettings.h"
#include "settings/SettingsService.h"
#include "syntax/HighlightService.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QFutureWatcher>
#include <QJsonArray>
#include <QMessageBox>
#include <QProgressDialog>
#include <QTextDocument>
#include <QTimer>
#include <QVBoxLayout>
#include <QVariant>
#include <QtConcurrent>
#include <algorithm>
namespace cold {
namespace {
struct FileReadResult {
QString content;
QString error;
bool ok = false;
};
constexpr auto kLayoutVersion = 1;
} // namespace
DocumentManager::DocumentManager(LayoutTree* layoutTree, QObject* parent)
: QObject(parent), m_layoutTree(layoutTree) {
if (!m_layoutTree) {
return;
}
connect(m_layoutTree, &LayoutTree::itemCloseRequested, this, &DocumentManager::closePaneTab);
connect(m_layoutTree, &LayoutTree::currentItemChanged, this,
[this](PaneId, int) { emit currentChanged(); });
connect(m_layoutTree, &LayoutTree::paneFocusChanged, this,
[this](PaneId) { emit currentChanged(); });
connect(m_layoutTree, &LayoutTree::itemMoved, this,
[this](const QString& itemId, PaneId paneId, int) {
const int entryIndex = findEntryByItem(itemId);
if (entryIndex >= 0) {
m_entries[static_cast<size_t>(entryIndex)].paneId = paneId;
emit currentChanged();
}
});
}
void DocumentManager::newDocument() {
++m_untitledCounter;
auto document = std::make_shared<Document>();
document->setUntitledName(QStringLiteral("Untitled-%1").arg(m_untitledCounter));
connectDocumentSignals(document.get());
TabEntry entry = createView(document);
addEntryToPane(std::move(entry), m_layoutTree->activePaneId());
TabEntry& stored = m_entries.back();
notifyLanguageServices(stored.editor, stored.document.get(), true);
focusEditor(stored.editor);
emit statusMessage(QStringLiteral("New document"));
emit currentChanged();
}
void DocumentManager::openFile() {
const QString path = QFileDialog::getOpenFileName(m_layoutTree, QStringLiteral("Open File"),
QString(), QStringLiteral("All Files (*)"));
if (path.isEmpty()) {
return;
}
open(path);
}
bool DocumentManager::open(const QString& path) {
return openInPane(path, m_layoutTree ? m_layoutTree->activePaneId() : -1, true);
}
bool DocumentManager::openInPane(const QString& path, PaneId paneId, bool reuseExisting) {
if (!m_layoutTree) {
return false;
}
const QString canonical = QFileInfo(path).canonicalFilePath();
if (canonical.isEmpty()) {
emit statusMessage(QStringLiteral("Cannot open: %1").arg(path));
return false;
}
const int existing = findEntryByPath(canonical);
if (existing >= 0 && reuseExisting) {
focusEntry(existing);
emit statusMessage(QStringLiteral("Already open: %1").arg(canonical));
return true;
}
if (existing >= 0 && !reuseExisting) {
const TabEntry& source = m_entries[static_cast<size_t>(existing)];
TabEntry splitEntry = createView(source.document, source.editor->document());
splitEntry.document->setLargeFile(source.document->isLargeFile());
if (splitEntry.document->isLargeFile() && splitEntry.banner) {
splitEntry.banner->showBanner();
}
addEntryToPane(std::move(splitEntry), paneId);
TabEntry& stored = m_entries.back();
notifyLanguageServices(stored.editor, stored.document.get(), false);
focusEditor(stored.editor);
emit statusMessage(QStringLiteral("Opened additional view: %1").arg(canonical));
emit currentChanged();
return true;
}
const qint64 fileSize = QFileInfo(canonical).size();
const bool largeOnDisk = isLargeFile(fileSize);
auto document = std::make_shared<Document>();
document->setPath(canonical);
connectDocumentSignals(document.get());
TabEntry entry = createView(document);
EditorWidget* loadingEditor = entry.editor;
addEntryToPane(std::move(entry), paneId);
TabEntry& stored = m_entries.back();
stored.editor->setEnabled(!largeOnDisk);
if (largeOnDisk) {
emit statusMessage(QStringLiteral("Loading %1…").arg(canonical));
}
if (!largeOnDisk) {
bool large = false;
QString error;
if (!loadFileIntoEditor(canonical, stored.editor, &large, &error)) {
removeEntryAt(static_cast<int>(m_entries.size()) - 1, false);
emit statusMessage(error);
QMessageBox::warning(m_layoutTree, QStringLiteral("Open Failed"), error);
return false;
}
stored.document->markClean();
stored.editor->setDocKey(makeDocKey(stored.document.get()));
finishOpenTab(stored, large, true);
focusEditor(stored.editor);
emit statusMessage(QStringLiteral("Opened %1").arg(canonical));
emit currentChanged();
return true;
}
auto* watcher = new QFutureWatcher<FileReadResult>(this);
QTimer* progressTimer = new QTimer(watcher);
progressTimer->setSingleShot(true);
progressTimer->setInterval(500);
connect(progressTimer, &QTimer::timeout, this, [this, watcher, canonical]() {
auto* dlg = new QProgressDialog(QStringLiteral("Loading large file…"), QString(), 0, 0,
m_layoutTree);
dlg->setWindowModality(Qt::WindowModal);
dlg->setMinimumDuration(0);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setLabelText(QStringLiteral("Loading %1…").arg(QFileInfo(canonical).fileName()));
dlg->show();
watcher->setProperty("coldProgress", QVariant::fromValue<QObject*>(dlg));
});
connect(watcher, &QFutureWatcher<FileReadResult>::finished, this,
[this, watcher, progressTimer, canonical, loadingEditor]() {
progressTimer->stop();
progressTimer->deleteLater();
if (QObject* dlg = watcher->property("coldProgress").value<QObject*>()) {
dlg->deleteLater();
}
const FileReadResult result = watcher->result();
watcher->deleteLater();
const int entryIndex = findEntryByEditor(loadingEditor);
if (entryIndex < 0) {
return;
}
TabEntry& entry = m_entries[static_cast<size_t>(entryIndex)];
if (!entry.document || entry.document->path() != canonical) {
return;
}
entry.editor->setEnabled(true);
if (!result.ok) {
removeEntryAt(entryIndex, false);
emit statusMessage(result.error);
QMessageBox::warning(m_layoutTree, QStringLiteral("Open Failed"), result.error);
return;
}
entry.editor->loadText(result.content);
entry.document->markClean();
entry.editor->setDocKey(makeDocKey(entry.document.get()));
finishOpenTab(entry, true, true);
focusEditor(entry.editor);
emit statusMessage(QStringLiteral("Opened %1").arg(canonical));
emit currentChanged();
});
connect(watcher, &QFutureWatcher<FileReadResult>::started, progressTimer,
QOverload<>::of(&QTimer::start));
watcher->setFuture(QtConcurrent::run([canonical]() -> FileReadResult {
FileReadResult out;
if (!FileIo::readTextFile(canonical, &out.content, &out.error)) {
out.ok = false;
return out;
}
out.ok = true;
return out;
}));
return true;
}
bool DocumentManager::openAt(const QString& path, int line, int column) {
const QString canonical = QFileInfo(path).canonicalFilePath();
if (canonical.isEmpty()) {
emit statusMessage(QStringLiteral("Cannot open: %1").arg(path));
return false;
}
const int editorLine = qMax(0, line - 1);
int existing = findEntryByPath(canonical);
if (existing < 0) {
if (!open(canonical)) {
return false;
}
existing = findEntryByPath(canonical);
}
if (existing >= 0) {
focusEntry(existing);
if (EditorWidget* editor = m_entries[static_cast<size_t>(existing)].editor) {
if (editor->isEnabled()) {
editor->setCursorPosition(editorLine, column);
editor->centerCursor();
focusEditor(editor);
}
}
}
emit statusMessage(QStringLiteral("Opened %1:%2").arg(canonical).arg(line));
return true;
}
void DocumentManager::saveActive() {
const int index = currentIndex();
if (index < 0) {
return;
}
TabEntry& entry = m_entries[static_cast<size_t>(index)];
if (!entry.document) {
return;
}
if (entry.document->isUntitled()) {
saveActiveAs();
return;
}
QString error;
if (!saveEditorToPath(entry.editor, entry.document->path(), &error)) {
QMessageBox::warning(m_layoutTree, QStringLiteral("Save Failed"), error);
emit statusMessage(error);
return;
}
entry.document->markClean();
updateTitlesForDocument(entry.document.get());
emit statusMessage(QStringLiteral("Saved %1").arg(entry.document->path()));
emit fileSaved(entry.document->path());
}
void DocumentManager::saveActiveAs() {
const int index = currentIndex();
if (index < 0) {
return;
}
TabEntry& entry = m_entries[static_cast<size_t>(index)];
if (!entry.document) {
return;
}
QString suggested = entry.document->path();
if (suggested.isEmpty()) {
suggested = entry.document->displayName();
}
const QString path = QFileDialog::getSaveFileName(m_layoutTree, QStringLiteral("Save As"),
suggested, QStringLiteral("All Files (*)"));
if (path.isEmpty()) {
return;
}
const QString canonical = QFileInfo(path).canonicalFilePath().isEmpty()
? QFileInfo(path).absoluteFilePath()
: QFileInfo(path).canonicalFilePath();
QString error;
if (!saveEditorToPath(entry.editor, canonical, &error)) {
QMessageBox::warning(m_layoutTree, QStringLiteral("Save Failed"), error);
emit statusMessage(error);
return;
}
const QString oldDocKey = makeDocKey(entry.document.get());
const QString oldPath = entry.document->path();
entry.document->setPath(canonical);
entry.document->markClean();
setDocKeyForDocumentViews(entry.document.get());
updateTitlesForDocument(entry.document.get());
if (!entry.document->isLargeFile()) {
if (m_highlight) {
m_highlight->removeDocument(oldDocKey);
}
if (m_lsp && !oldPath.isEmpty()) {
m_lsp->documentClosed(oldDocKey);
}
bool opened = false;
for (TabEntry& view : m_entries) {
if (view.document.get() != entry.document.get()) {
continue;
}
notifyLanguageServices(view.editor, view.document.get(), !opened);
opened = true;
}
}
emit statusMessage(QStringLiteral("Saved %1").arg(canonical));
emit fileSaved(canonical);
}
void DocumentManager::closeTab(int index) {
removeEntryAt(index, true);
}
void DocumentManager::closePaneTab(PaneId paneId, int tabIndex) {
const int entryIndex = findEntry(paneId, tabIndex);
if (entryIndex >= 0) {
removeEntryAt(entryIndex, true);
}
}
void DocumentManager::closeCurrentTab() {
closeTab(currentIndex());
}
bool DocumentManager::closeAllTabs() {
while (!m_entries.empty()) {
if (!removeEntryAt(static_cast<int>(m_entries.size()) - 1, true)) {
return false;
}
}
if (m_layoutTree) {
m_layoutTree->reset();
}
return true;
}
Document* DocumentManager::documentForIndex(int index) const {
if (index < 0 || index >= static_cast<int>(m_entries.size())) {
return nullptr;
}
return m_entries[static_cast<size_t>(index)].document.get();
}
EditorWidget* DocumentManager::editorForIndex(int index) const {
if (index < 0 || index >= static_cast<int>(m_entries.size())) {
return nullptr;
}
return m_entries[static_cast<size_t>(index)].editor;
}
int DocumentManager::currentIndex() const {
if (!m_layoutTree) {
return -1;
}
const std::shared_ptr<PaneItem> item = m_layoutTree->currentItem();
return item ? findEntryByItem(item->itemId()) : -1;
}
QVector<SessionTabState> DocumentManager::captureSession() const {
QVector<SessionTabState> states;
for (int i = 0; i < static_cast<int>(m_entries.size()); ++i) {
const TabEntry& entry = m_entries[static_cast<size_t>(i)];
if (!entry.document || entry.document->isUntitled()) {
continue;
}
SessionTabState state;
state.path = entry.document->path();
state.sortOrder = i;
state.paneId = entry.paneId;
if (entry.editor) {
state.cursorLine = entry.editor->cursorLine();
state.cursorCol = entry.editor->cursorColumn();
state.scrollY = entry.editor->scrollPosition();
}
states.push_back(state);
}
return states;
}
void DocumentManager::restoreSession(const QVector<SessionTabState>& tabs) {
if (tabs.isEmpty()) {
return;
}
QVector<SessionTabState> ordered = tabs;
std::sort(ordered.begin(), ordered.end(),
[](const SessionTabState& a, const SessionTabState& b) {
return a.sortOrder < b.sortOrder;
});
int firstRestoredIndex = -1;
for (const SessionTabState& state : ordered) {
if (state.path.isEmpty()) {
continue;
}
if (!open(state.path)) {
continue;
}
const int index = currentIndex();
if (index < 0) {
continue;
}
if (firstRestoredIndex < 0) {
firstRestoredIndex = index;
}
EditorWidget* editor = editorForIndex(index);
if (!editor || !editor->isEnabled()) {
continue;
}
editor->setCursorPosition(state.cursorLine, state.cursorCol);
editor->setScrollPosition(state.scrollY);
}
if (firstRestoredIndex >= 0) {
focusEntry(firstRestoredIndex);
}
}
QJsonObject DocumentManager::captureLayoutState() const {
QJsonObject state;
state.insert(QStringLiteral("version"), kLayoutVersion);
state.insert(QStringLiteral("panelPosition"), QStringLiteral("bottom"));
state.insert(QStringLiteral("sidebarVisible"), true);
state.insert(QStringLiteral("sidebarActivePanel"), QStringLiteral("explorer"));
state.insert(QStringLiteral("panelVisible"), true);
state.insert(QStringLiteral("layout"), layoutNodeWithTabs(m_layoutTree->toJson()));
state.insert(QStringLiteral("activePaneId"), m_layoutTree->activePaneId());
return state;
}
bool DocumentManager::restoreLayoutState(const QJsonObject& state) {
if (!m_layoutTree || state.isEmpty()) {
return false;
}
const QJsonObject layout = state.value(QStringLiteral("layout")).toObject();
if (layout.isEmpty()) {
return false;
}
closeAllTabs();
if (!m_entries.empty()) {
return false;
}
if (!m_layoutTree->restoreLayout(layout)) {
return false;
}
restoreTabsFromLayoutNode(layout);
const PaneId activePane = state.value(QStringLiteral("activePaneId")).toInt(-1);
if (activePane >= 0) {
m_layoutTree->setActivePane(activePane);
}
emit currentChanged();
return true;
}
void DocumentManager::setHighlightService(HighlightService* highlight) {
m_highlight = highlight;
}
void DocumentManager::setLspClient(LspClient* lsp) {
m_lsp = lsp;
}
void DocumentManager::setSettingsService(SettingsService* settings) {
m_settings = settings;
}
QString DocumentManager::docKeyForDocument(const Document* document) const {
return makeDocKey(document);
}
EditorWidget* DocumentManager::currentEditor() const {
const int index = currentIndex();
return index >= 0 ? editorForIndex(index) : nullptr;
}
Document* DocumentManager::currentDocument() const {
const int index = currentIndex();
return index >= 0 ? documentForIndex(index) : nullptr;
}
void DocumentManager::focusEditor(EditorWidget* editor) {
if (editor && editor->isEnabled()) {
editor->setFocus(Qt::OtherFocusReason);
}
}
void DocumentManager::showLargeFileBanner(const QString& docKey) {
for (TabEntry& entry : m_entries) {
if (makeDocKey(entry.document.get()) == docKey && entry.banner) {
entry.document->setLargeFile(true);
entry.banner->showBanner();
}
}
}
void DocumentManager::forEachEditor(const std::function<void(EditorWidget*)>& callback) const {
for (const TabEntry& entry : m_entries) {
if (entry.editor) {
callback(entry.editor);
}
}
}
void DocumentManager::splitActiveView(SplitDirection direction) {
const int index = currentIndex();
if (index < 0 || !m_layoutTree) {
return;
}
const TabEntry& source = m_entries[static_cast<size_t>(index)];
if (!source.editor || !source.document) {
return;
}
const PaneId sourcePaneId = source.paneId;
const bool sourceLarge = source.document->isLargeFile();
TabEntry splitEntry = createView(source.document, source.editor->document());
splitEntry.document->setLargeFile(sourceLarge);
if (splitEntry.document->isLargeFile() && splitEntry.banner) {
splitEntry.banner->showBanner();
}
std::shared_ptr<EditorPaneItem> item = splitEntry.paneItem;
QWidget* page = splitEntry.page;
m_entries.push_back(std::move(splitEntry));
const PaneId newPane = m_layoutTree->splitPane(sourcePaneId, direction, item);
if (newPane < 0) {
m_entries.pop_back();
delete page;
return;
}
TabEntry& stored = m_entries.back();
stored.paneId = newPane;
notifyLanguageServices(stored.editor, stored.document.get(), false);
updateTitlesForDocument(stored.document.get());
focusEditor(stored.editor);
emit statusMessage(QStringLiteral("Split view"));
emit currentChanged();
}
void DocumentManager::onEditorTextChanged() {
auto* editor = qobject_cast<EditorWidget*>(sender());
if (!editor) {
return;
}
Document* document =
qobject_cast<Document*>(editor->property("coldDocument").value<QObject*>());
if (!document) {
return;
}
if (!document->isDirty()) {
document->setDirty(true);
}
const QString docKey = makeDocKey(document);
setDocKeyForDocumentViews(document);
const QString text = editor->textContent();
const QString path = document->path();
const bool wasLarge = document->isLargeFile();
if (!wasLarge && static_cast<qint64>(text.toUtf8().size()) > kLargeFileBytes) {
document->setLargeFile(true);
showLargeFileBanner(docKey);
if (m_highlight) {
m_highlight->removeDocument(docKey);
}
if (m_lsp && !path.isEmpty()) {
m_lsp->documentClosed(docKey);
}
return;
}
if (document->isLargeFile()) {
return;
}
if (m_lsp && !path.isEmpty()) {
m_lsp->documentChanged(docKey, text);
}
}
int DocumentManager::findEntryByPath(const QString& path) const {
const QString canonical = QFileInfo(path).canonicalFilePath();
for (int i = 0; i < static_cast<int>(m_entries.size()); ++i) {
const auto& entry = m_entries[static_cast<size_t>(i)];
if (entry.document && entry.document->path() == canonical) {
return i;
}
}
return -1;
}
int DocumentManager::findEntryByItem(const QString& itemId) const {
for (int i = 0; i < static_cast<int>(m_entries.size()); ++i) {
if (m_entries[static_cast<size_t>(i)].itemId == itemId) {
return i;
}
}
return -1;
}
int DocumentManager::findEntryByEditor(EditorWidget* editor) const {
for (int i = 0; i < static_cast<int>(m_entries.size()); ++i) {
if (m_entries[static_cast<size_t>(i)].editor == editor) {
return i;
}
}
return -1;
}
int DocumentManager::findEntry(PaneId paneId, int tabIndex) const {
if (!m_layoutTree) {
return -1;
}
const std::shared_ptr<PaneItem> item = m_layoutTree->itemAt(paneId, tabIndex);
return item ? findEntryByItem(item->itemId()) : -1;
}
int DocumentManager::viewCountForDocument(const Document* document) const {
int count = 0;
for (const TabEntry& entry : m_entries) {
if (entry.document.get() == document) {
++count;
}
}
return count;
}
bool DocumentManager::loadFileIntoEditor(const QString& path, EditorWidget* editor, bool* largeOut,
QString* errorOut) {
QString content;
if (!FileIo::readTextFile(path, &content, errorOut)) {
return false;
}
editor->loadText(content);
const bool large = isLargeFile(QFileInfo(path).size()) ||
static_cast<qint64>(content.toUtf8().size()) > kLargeFileBytes;
if (largeOut) {
*largeOut = large;
}
return true;
}
bool DocumentManager::saveEditorToPath(EditorWidget* editor, const QString& path,
QString* errorOut) {
return FileIo::writeTextAtomic(path, editor->textContent(), errorOut);
}
QWidget* DocumentManager::createEditorPage(EditorWidget* editor, LargeFileBanner** bannerOut) {
auto* page = new QWidget();
auto* layout = new QVBoxLayout(page);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(0);
auto* banner = new LargeFileBanner(page);
layout->addWidget(banner);
layout->addWidget(editor, 1);
if (bannerOut) {
*bannerOut = banner;
}
return page;
}
TabEntry DocumentManager::createView(std::shared_ptr<Document> document,
QTextDocument* sharedTextDocument) {
auto* editor = new EditorWidget();
editor->setSharedTextDocument(sharedTextDocument ? sharedTextDocument
: document->textDocument());
LargeFileBanner* banner = nullptr;
QWidget* page = createEditorPage(editor, &banner);
connectEditor(editor, document.get());
if (m_settings) {
EditorSettings::applyTo(editor, *m_settings);
}
const QString itemId = QStringLiteral("pane-item-%1").arg(++m_itemCounter);
TabEntry entry;
entry.document = std::move(document);
entry.page = page;
entry.banner = banner;
entry.editor = editor;
entry.itemId = itemId;
entry.paneItem = std::make_shared<EditorPaneItem>(itemId, page, editor, entry.document.get());
editor->setProperty("coldDocument", QVariant::fromValue<QObject*>(entry.document.get()));
editor->setDocKey(makeDocKey(entry.document.get()));
return entry;
}
void DocumentManager::finishOpenTab(TabEntry& entry, bool largeFile, bool openedForLsp) {
entry.document->setLargeFile(largeFile);
entry.editor->setDocKey(makeDocKey(entry.document.get()));
if (largeFile && entry.banner) {
entry.banner->showBanner();
}
notifyLanguageServices(entry.editor, entry.document.get(), openedForLsp);
}
void DocumentManager::connectEditor(EditorWidget* editor, Document* document) {
connect(editor, &EditorWidget::textChanged, this, &DocumentManager::onEditorTextChanged);
if (m_lsp) {
connect(editor, &EditorWidget::completionRequested, this,
[this, editor](int line, int col) {
Document* doc =
qobject_cast<Document*>(editor->property("coldDocument").value<QObject*>());
if (doc && doc->isLargeFile()) {
return;
}
m_lsp->requestCompletion(editor->docKey(), line, col);
});
connect(editor, &EditorWidget::hoverRequested, this, [this, editor](int line, int col) {
Document* doc =
qobject_cast<Document*>(editor->property("coldDocument").value<QObject*>());
if (doc && doc->isLargeFile()) {
return;
}
m_lsp->requestHover(editor->docKey(), line, col);
});
connect(editor, &EditorWidget::definitionRequested, this,
[this, editor](int line, int col) {
Document* doc =
qobject_cast<Document*>(editor->property("coldDocument").value<QObject*>());
if (doc && doc->isLargeFile()) {
return;
}
m_lsp->requestDefinition(editor->docKey(), line, col);
});
}
Q_UNUSED(document);
}
void DocumentManager::connectDocumentSignals(Document* document) {
if (!document || document->property("coldSignalsConnected").toBool()) {
return;
}
document->setProperty("coldSignalsConnected", true);
connect(document, &Document::documentModified, this,
[this, document](bool) { updateTitlesForDocument(document); });
connect(document, &Document::displayNameChanged, this,
[this, document]() { updateTitlesForDocument(document); });
}
void DocumentManager::updateTitlesForDocument(Document* document) {
if (!document || !m_layoutTree) {
return;
}
for (TabEntry& entry : m_entries) {
if (entry.document.get() != document) {
continue;
}
int tabIndex = -1;
const PaneId paneId = m_layoutTree->paneForItem(entry.itemId, &tabIndex);
if (PaneWidget* pane = m_layoutTree->pane(paneId)) {
pane->updateItemTitle(tabIndex);
}
}
}
bool DocumentManager::removeEntryAt(int entryIndex, bool promptIfLastView) {
if (entryIndex < 0 || entryIndex >= static_cast<int>(m_entries.size())) {
return false;
}
TabEntry& entry = m_entries[static_cast<size_t>(entryIndex)];
const bool lastView = viewCountForDocument(entry.document.get()) <= 1;
if (promptIfLastView && lastView && entry.document->isDirty()) {
const QMessageBox::StandardButton choice = QMessageBox::warning(
m_layoutTree, QStringLiteral("Unsaved Changes"),
QStringLiteral("Save changes to \"%1\" before closing?")
.arg(entry.document->displayName()),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Save);
if (choice == QMessageBox::Cancel) {
return false;
}
if (choice == QMessageBox::Save) {
focusEntry(entryIndex);
saveActive();
if (entry.document->isDirty()) {
return false;
}
}
}
const QString docKey = makeDocKey(entry.document.get());
PaneId paneId = entry.paneId;
int paneIndex = -1;
if (m_layoutTree) {
paneId = m_layoutTree->paneForItem(entry.itemId, &paneIndex);
}
closeLanguageServicesForView(docKey, entry.editor, lastView);
if (m_layoutTree && paneId >= 0 && paneIndex >= 0) {
m_layoutTree->takeItem(paneId, paneIndex);
}
std::shared_ptr<Document> keepDocumentAlive = entry.document;
QWidget* page = entry.page;
m_entries.erase(m_entries.begin() + entryIndex);
delete page;
if (m_layoutTree) {
if (PaneWidget* pane = m_layoutTree->pane(paneId)) {
if (pane->count() == 0) {
m_layoutTree->closePane(paneId);
}
}
}
focusEditor(currentEditor());
emit statusMessage(QStringLiteral("Tab closed"));
emit currentChanged();
return true;
}
void DocumentManager::focusEntry(int entryIndex) {
if (!m_layoutTree || entryIndex < 0 || entryIndex >= static_cast<int>(m_entries.size())) {
return;
}
const TabEntry& entry = m_entries[static_cast<size_t>(entryIndex)];
int tabIndex = -1;
const PaneId paneId = m_layoutTree->paneForItem(entry.itemId, &tabIndex);
if (paneId >= 0 && tabIndex >= 0) {
m_layoutTree->setCurrentItem(paneId, tabIndex);
}
focusEditor(entry.editor);
}
QString DocumentManager::makeDocKey(const Document* document) const {
if (!document) {
return {};
}
if (document->isUntitled() || document->path().isEmpty()) {
return document->displayName();
}
return QFileInfo(document->path()).canonicalFilePath();
}
void DocumentManager::setDocKeyForDocumentViews(Document* document) {
const QString docKey = makeDocKey(document);
for (TabEntry& entry : m_entries) {
if (entry.document.get() == document && entry.editor) {
entry.editor->setDocKey(docKey);
}
}
}
void DocumentManager::notifyLanguageServices(EditorWidget* editor, Document* document,
bool opened) {
if (!editor || !document || document->isLargeFile()) {
return;
}
const QString docKey = makeDocKey(document);
const QString path = document->path();
const QString text = editor->textContent();
if (m_highlight) {
m_highlight->bindEditor(docKey, editor);
}
if (m_lsp && opened && !path.isEmpty()) {
m_lsp->documentOpened(docKey, path, text, document->isUntitled());
}
}
void DocumentManager::closeLanguageServicesForView(const QString& docKey, EditorWidget* editor,
bool lastView) {
if (m_highlight) {
if (lastView) {
m_highlight->removeDocument(docKey);
} else {
m_highlight->unbindEditor(docKey, editor);
}
}
if (lastView && m_lsp && editor) {
Document* doc = qobject_cast<Document*>(editor->property("coldDocument").value<QObject*>());
if (doc && !doc->path().isEmpty()) {
m_lsp->documentClosed(docKey);
}
}
}
void DocumentManager::addEntryToPane(TabEntry&& entry, PaneId paneId, int index) {
if (!m_layoutTree) {
return;
}
if (paneId < 0 || !m_layoutTree->pane(paneId)) {
paneId = m_layoutTree->activePaneId();
}
m_entries.push_back(std::move(entry));
TabEntry& stored = m_entries.back();
stored.paneId = paneId;
const int inserted = m_layoutTree->addItemToPane(paneId, stored.paneItem, index);
stored.paneId = paneId;
if (inserted >= 0) {
m_layoutTree->setCurrentItem(paneId, inserted);
}
updateTitlesForDocument(stored.document.get());
}
QJsonObject DocumentManager::layoutNodeWithTabs(const QJsonObject& node) const {
QJsonObject out = node;
const QString type = node.value(QStringLiteral("type")).toString();
if (type == QStringLiteral("pane")) {
const PaneId paneId = node.value(QStringLiteral("paneId")).toInt(-1);
QJsonArray tabs;
if (PaneWidget* pane = m_layoutTree->pane(paneId)) {
for (int i = 0; i < pane->count(); ++i) {
const std::shared_ptr<PaneItem> item = pane->itemAt(i);
const int entryIndex = item ? findEntryByItem(item->itemId()) : -1;
if (entryIndex < 0) {
continue;
}
const TabEntry& entry = m_entries[static_cast<size_t>(entryIndex)];
if (!entry.document || entry.document->isUntitled()) {
continue;
}
QJsonObject tab;
tab.insert(QStringLiteral("path"), entry.document->path());
tab.insert(QStringLiteral("cursorLine"), entry.editor->cursorLine());
tab.insert(QStringLiteral("cursorCol"), entry.editor->cursorColumn());
tab.insert(QStringLiteral("scrollY"), entry.editor->scrollPosition());