/
documentcontroller.cpp
1243 lines (1067 loc) · 48.2 KB
/
documentcontroller.cpp
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
/* This file is part of the KDE project
Copyright 2002 Matthias Hoelzer-Kluepfel <hoelzer@kde.org>
Copyright 2002 Bernd Gehrmann <bernd@kdevelop.org>
Copyright 2003 Roberto Raggi <roberto@kdevelop.org>
Copyright 2003-2008 Hamish Rodda <rodda@kde.org>
Copyright 2003 Harald Fernengel <harry@kdevelop.org>
Copyright 2003 Jens Dagerbo <jens.dagerbo@swipnet.se>
Copyright 2005 Adam Treat <treat@kde.org>
Copyright 2004-2007 Alexander Dymo <adymo@kdevelop.org>
Copyright 2007 Andreas Pakulat <apaku@gmx.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "documentcontroller.h"
#include <QApplication>
#include <QDBusConnection>
#include <QFileInfo>
#include <QMimeDatabase>
#include <QRegularExpression>
#include <QTemporaryFile>
#include <KActionCollection>
#include <KEncodingFileDialog>
#include <KIO/StatJob>
#include <KJobWidgets>
#include <KLocalizedString>
#include <KMessageBox>
#include <KProtocolInfo>
#include <KRecentFilesAction>
#include <KTextEditor/Document>
#include <KTextEditor/View>
#include <KTextEditor/AnnotationInterface>
#include <sublime/area.h>
#include <sublime/view.h>
#include <interfaces/iplugincontroller.h>
#include <interfaces/iprojectcontroller.h>
#include <interfaces/ibuddydocumentfinder.h>
#include <interfaces/iproject.h>
#include <interfaces/iselectioncontroller.h>
#include <interfaces/context.h>
#include <project/projectmodel.h>
#include <util/path.h>
#include "core.h"
#include "mainwindow.h"
#include "textdocument.h"
#include "uicontroller.h"
#include "partcontroller.h"
#include "savedialog.h"
#include "debug.h"
#include <vcs/interfaces/ibasicversioncontrol.h>
#include <vcs/models/vcsannotationmodel.h>
#include <vcs/vcsjob.h>
#include <vcs/vcspluginhelper.h>
#define EMPTY_DOCUMENT_URL i18n("Untitled")
namespace KDevelop
{
struct DocumentControllerPrivate
{
struct OpenFileResult
{
QList<QUrl> urls;
QString encoding;
};
explicit DocumentControllerPrivate(DocumentController* c)
: controller(c)
, fileOpenRecent(nullptr)
, globalTextEditorInstance(nullptr)
{
}
~DocumentControllerPrivate()
{
//delete temporary files so they are removed from disk
foreach (QTemporaryFile *temp, tempFiles)
delete temp;
}
// used to map urls to open docs
QHash< QUrl, IDocument* > documents;
QHash< QString, IDocumentFactory* > factories;
QList<QTemporaryFile*> tempFiles;
struct HistoryEntry
{
HistoryEntry() {}
HistoryEntry( const QUrl & u, const KTextEditor::Cursor& cursor );
QUrl url;
KTextEditor::Cursor cursor;
int id;
};
void removeDocument(Sublime::Document *doc)
{
QList<QUrl> urlsForDoc = documents.keys(dynamic_cast<KDevelop::IDocument*>(doc));
foreach (const QUrl &url, urlsForDoc)
{
qCDebug(SHELL) << "destroying document" << doc;
documents.remove(url);
}
}
OpenFileResult showOpenFile() const
{
QUrl dir;
if ( controller->activeDocument() ) {
dir = controller->activeDocument()->url().adjusted(QUrl::RemoveFilename);
} else {
const auto cfg = KSharedConfig::openConfig()->group("Open File");
dir = cfg.readEntry( "Last Open File Directory", Core::self()->projectController()->projectsBaseDirectory() );
}
const auto caption = i18n("Open File");
const auto filter = i18n("*|Text File\n");
auto parent = Core::self()->uiControllerInternal()->defaultMainWindow();
// use special dialogs in a KDE session, native dialogs elsewhere
if (qEnvironmentVariableIsSet("KDE_FULL_SESSION")) {
const auto result = KEncodingFileDialog::getOpenUrlsAndEncoding(QString(), dir,
filter, parent, caption);
return {result.URLs, result.encoding};
}
// note: can't just filter on text files using the native dialog, just display all files
// see https://phabricator.kde.org/D622#11679
const auto urls = QFileDialog::getOpenFileUrls(parent, caption, dir);
return {urls, QString()};
}
void chooseDocument()
{
const auto res = showOpenFile();
if( !res.urls.isEmpty() ) {
QString encoding = res.encoding;
foreach( const QUrl& u, res.urls ) {
openDocumentInternal(u, QString(), KTextEditor::Range::invalid(), encoding );
}
}
}
void changeDocumentUrl(KDevelop::IDocument* document)
{
QMutableHashIterator<QUrl, IDocument*> it = documents;
while (it.hasNext()) {
if (it.next().value() == document) {
if (documents.contains(document->url())) {
// Weird situation (saving as a file that is aready open)
IDocument* origDoc = documents[document->url()];
if (origDoc->state() & IDocument::Modified) {
// given that the file has been saved, close the saved file as the other instance will become conflicted on disk
document->close();
controller->activateDocument( origDoc );
break;
}
// Otherwise close the original document
origDoc->close();
} else {
// Remove the original document
it.remove();
}
documents.insert(document->url(), document);
if (!controller->isEmptyDocumentUrl(document->url()))
{
fileOpenRecent->addUrl(document->url());
}
break;
}
}
}
KDevelop::IDocument* findBuddyDocument(const QUrl &url, IBuddyDocumentFinder* finder)
{
QList<KDevelop::IDocument*> allDocs = controller->openDocuments();
foreach( KDevelop::IDocument* doc, allDocs ) {
if(finder->areBuddies(url, doc->url())) {
return doc;
}
}
return nullptr;
}
static bool fileExists(const QUrl& url)
{
if (url.isLocalFile()) {
return QFile::exists(url.toLocalFile());
} else {
auto job = KIO::stat(url, KIO::StatJob::SourceSide, 0);
KJobWidgets::setWindow(job, ICore::self()->uiController()->activeMainWindow());
return job->exec();
}
};
IDocument* openDocumentInternal( const QUrl & inputUrl, const QString& prefName = QString(),
const KTextEditor::Range& range = KTextEditor::Range::invalid(), const QString& encoding = QString(),
DocumentController::DocumentActivationParams activationParams = nullptr,
IDocument* buddy = nullptr)
{
Q_ASSERT(!inputUrl.isRelative());
Q_ASSERT(!inputUrl.fileName().isEmpty() || !inputUrl.isLocalFile());
QString _encoding = encoding;
QUrl url = inputUrl;
if ( url.isEmpty() && (!activationParams.testFlag(IDocumentController::DoNotCreateView)) )
{
const auto res = showOpenFile();
if( !res.urls.isEmpty() )
url = res.urls.first();
_encoding = res.encoding;
if ( url.isEmpty() )
//still no url
return nullptr;
}
KSharedConfig::openConfig()->group("Open File").writeEntry( "Last Open File Directory", url.adjusted(QUrl::RemoveFilename) );
// clean it and resolve possible symlink
url = url.adjusted( QUrl::NormalizePathSegments );
if ( url.isLocalFile() )
{
QString path = QFileInfo( url.toLocalFile() ).canonicalFilePath();
if ( !path.isEmpty() )
url = QUrl::fromLocalFile( path );
}
//get a part document
IDocument* doc = documents.value(url);
if (!doc)
{
QMimeType mimeType;
if (DocumentController::isEmptyDocumentUrl(url))
{
mimeType = QMimeDatabase().mimeTypeForName(QStringLiteral("text/plain"));
}
else if (!url.isValid())
{
// Exit if the url is invalid (should not happen)
// If the url is valid and the file does not already exist,
// kate creates the file and gives a message saying so
qCDebug(SHELL) << "invalid URL:" << url.url();
return nullptr;
}
else if (KProtocolInfo::isKnownProtocol(url.scheme()) && !fileExists(url))
{
//Don't create a new file if we are not in the code mode.
if (ICore::self()->uiController()->activeArea()->objectName() != QLatin1String("code")) {
return nullptr;
}
// enfore text mime type in order to create a kate part editor which then can be used to create the file
// otherwise we could end up opening e.g. okteta which then crashes, see: https://bugs.kde.org/id=326434
mimeType = QMimeDatabase().mimeTypeForName(QStringLiteral("text/plain"));
}
else
{
mimeType = QMimeDatabase().mimeTypeForUrl(url);
if(!url.isLocalFile() && mimeType.isDefault())
{
// fall back to text/plain, for remote files without extension, i.e. COPYING, LICENSE, ...
// using a synchronous KIO::MimetypeJob is hazardous and may lead to repeated calls to
// this function without it having returned in the first place
// and this function is *not* reentrant, see assert below:
// Q_ASSERT(!documents.contains(url) || documents[url]==doc);
mimeType = QMimeDatabase().mimeTypeForName(QStringLiteral("text/plain"));
}
}
// is the URL pointing to a directory?
if (mimeType.inherits(QStringLiteral("inode/directory")))
{
qCDebug(SHELL) << "cannot open directory:" << url.url();
return nullptr;
}
if( prefName.isEmpty() )
{
// Try to find a plugin that handles this mimetype
QVariantMap constraints;
constraints.insert(QStringLiteral("X-KDevelop-SupportedMimeTypes"), mimeType.name());
Core::self()->pluginController()->pluginForExtension(QString(), QString(), constraints);
}
if( IDocumentFactory* factory = factories.value(mimeType.name()))
{
doc = factory->create(url, Core::self());
}
if(!doc) {
if( !prefName.isEmpty() )
{
doc = new PartDocument(url, Core::self(), prefName);
} else if ( Core::self()->partControllerInternal()->isTextType(mimeType))
{
doc = new TextDocument(url, Core::self(), _encoding);
} else if( Core::self()->partControllerInternal()->canCreatePart(url) )
{
doc = new PartDocument(url, Core::self());
} else
{
int openAsText = KMessageBox::questionYesNo(nullptr, i18n("KDevelop could not find the editor for file '%1' of type %2.\nDo you want to open it as plain text?", url.fileName(), mimeType.name()), i18nc("@title:window", "Could Not Find Editor"),
KStandardGuiItem::yes(), KStandardGuiItem::no(), QStringLiteral("AskOpenWithTextEditor"));
if (openAsText == KMessageBox::Yes)
doc = new TextDocument(url, Core::self(), _encoding);
else
return nullptr;
}
}
}
// The url in the document must equal the current url, else the housekeeping will get broken
Q_ASSERT(!doc || doc->url() == url);
if(doc && openDocumentInternal(doc, range, activationParams, buddy))
return doc;
else
return nullptr;
}
bool openDocumentInternal(IDocument* doc,
const KTextEditor::Range& range,
DocumentController::DocumentActivationParams activationParams,
IDocument* buddy = nullptr)
{
IDocument* previousActiveDocument = controller->activeDocument();
KTextEditor::View* previousActiveTextView = ICore::self()->documentController()->activeTextDocumentView();
KTextEditor::Cursor previousActivePosition;
if(previousActiveTextView)
previousActivePosition = previousActiveTextView->cursorPosition();
QUrl url=doc->url();
UiController *uiController = Core::self()->uiControllerInternal();
Sublime::Area *area = uiController->activeArea();
//We can't have the same url in many documents
//so we check it's already the same if it exists
//contains=>it's the same
Q_ASSERT(!documents.contains(url) || documents[url]==doc);
Sublime::Document *sdoc = dynamic_cast<Sublime::Document*>(doc);
if( !sdoc )
{
documents.remove(url);
delete doc;
return false;
}
//react on document deletion - we need to cleanup controller structures
QObject::connect(sdoc, &Sublime::Document::aboutToDelete, controller, &DocumentController::notifyDocumentClosed);
//We check if it was already opened before
bool emitOpened = !documents.contains(url);
if(emitOpened)
documents[url]=doc;
if (!activationParams.testFlag(IDocumentController::DoNotCreateView))
{
//find a view if there's one already opened in this area
Sublime::View *partView = nullptr;
Sublime::AreaIndex* activeViewIdx = area->indexOf(uiController->activeSublimeWindow()->activeView());
foreach (Sublime::View *view, sdoc->views())
{
Sublime::AreaIndex* areaIdx = area->indexOf(view);
if (areaIdx && areaIdx == activeViewIdx)
{
partView = view;
break;
}
}
bool addView = false;
if (!partView)
{
//no view currently shown for this url
partView = sdoc->createView();
addView = true;
}
if(addView) {
// This code is never executed when restoring session on startup,
// only when opening a file manually
Sublime::View* buddyView = nullptr;
bool placeAfterBuddy = true;
if(Core::self()->uiControllerInternal()->arrangeBuddies() && !buddy && doc->mimeType().isValid()) {
// If buddy is not set, look for a (usually) plugin which handles this URL's mimetype
// and use its IBuddyDocumentFinder, if available, to find a buddy document
QString mime = doc->mimeType().name();
IBuddyDocumentFinder* buddyFinder = IBuddyDocumentFinder::finderForMimeType(mime);
if(buddyFinder) {
buddy = findBuddyDocument(url, buddyFinder);
if(buddy) {
placeAfterBuddy = buddyFinder->buddyOrder(buddy->url(), doc->url());
}
}
}
if(buddy) {
Sublime::Document* sublimeDocBuddy = dynamic_cast<Sublime::Document*>(buddy);
if(sublimeDocBuddy) {
Sublime::AreaIndex *pActiveViewIndex = area->indexOf(uiController->activeSublimeWindow()->activeView());
if(pActiveViewIndex) {
// try to find existing View of buddy document in current active view's tab
foreach (Sublime::View *pView, pActiveViewIndex->views()) {
if(sublimeDocBuddy->views().contains(pView)) {
buddyView = pView;
break;
}
}
}
}
}
// add view to the area
if(buddyView && area->indexOf(buddyView)) {
if(placeAfterBuddy) {
// Adding new view after buddy view, simple case
area->addView(partView, area->indexOf(buddyView), buddyView);
}
else {
// First new view, then buddy view
area->addView(partView, area->indexOf(buddyView), buddyView);
// move buddyView tab after the new document
area->removeView(buddyView);
area->addView(buddyView, area->indexOf(partView), partView);
}
}
else {
// no buddy found for new document / plugin does not support buddies / buddy feature disabled
Sublime::View *activeView = uiController->activeSublimeWindow()->activeView();
Sublime::UrlDocument *activeDoc = nullptr;
IBuddyDocumentFinder *buddyFinder = nullptr;
if(activeView)
activeDoc = dynamic_cast<Sublime::UrlDocument *>(activeView->document());
if(activeDoc && Core::self()->uiControllerInternal()->arrangeBuddies()) {
QString mime = QMimeDatabase().mimeTypeForUrl(activeDoc->url()).name();
buddyFinder = IBuddyDocumentFinder::finderForMimeType(mime);
}
if(Core::self()->uiControllerInternal()->openAfterCurrent() &&
Core::self()->uiControllerInternal()->arrangeBuddies() &&
buddyFinder)
{
// Check if active document's buddy is directly next to it.
// For example, we have the already-open tabs | *foo.h* | foo.cpp | , foo.h is active.
// When we open a new document here (and the buddy feature is enabled),
// we do not want to separate foo.h and foo.cpp, so we take care and avoid this.
Sublime::AreaIndex *activeAreaIndex = area->indexOf(activeView);
int pos = activeAreaIndex->views().indexOf(activeView);
Sublime::View *afterActiveView = activeAreaIndex->views().value(pos+1, nullptr);
Sublime::UrlDocument *activeDoc = nullptr, *afterActiveDoc = nullptr;
if(activeView && afterActiveView) {
activeDoc = dynamic_cast<Sublime::UrlDocument *>(activeView->document());
afterActiveDoc = dynamic_cast<Sublime::UrlDocument *>(afterActiveView->document());
}
if(activeDoc && afterActiveDoc &&
buddyFinder->areBuddies(activeDoc->url(), afterActiveDoc->url()))
{
// don't insert in between of two buddies, but after them
area->addView(partView, activeAreaIndex, afterActiveView);
}
else {
// The active document's buddy is not directly after it
// => no ploblem, insert after active document
area->addView(partView, activeView);
}
}
else {
// Opening as last tab won't disturb our buddies
// Same, if buddies are disabled, we needn't care about them.
// this method places the tab according to openAfterCurrent()
area->addView(partView, activeView);
}
}
}
if (!activationParams.testFlag(IDocumentController::DoNotActivate))
{
uiController->activeSublimeWindow()->activateView(
partView, !activationParams.testFlag(IDocumentController::DoNotFocus));
}
if (!activationParams.testFlag(IDocumentController::DoNotAddToRecentOpen) && !controller->isEmptyDocumentUrl(url))
{
fileOpenRecent->addUrl( url );
}
if( range.isValid() )
{
if (range.isEmpty())
doc->setCursorPosition( range.start() );
else
doc->setTextSelection( range );
}
}
// Deferred signals, wait until it's all ready first
if( emitOpened ) {
emit controller->documentOpened( doc );
}
if (!activationParams.testFlag(IDocumentController::DoNotActivate) && doc != controller->activeDocument())
emit controller->documentActivated( doc );
saveAll->setEnabled(true);
revertAll->setEnabled(true);
close->setEnabled(true);
closeAll->setEnabled(true);
closeAllOthers->setEnabled(true);
KTextEditor::Cursor activePosition;
if(range.isValid())
activePosition = range.start();
else if(KTextEditor::View* v = doc->activeTextView())
activePosition = v->cursorPosition();
if (doc != previousActiveDocument || activePosition != previousActivePosition)
emit controller->documentJumpPerformed(doc, activePosition, previousActiveDocument, previousActivePosition);
return true;
}
DocumentController* controller;
QList<HistoryEntry> backHistory;
QList<HistoryEntry> forwardHistory;
bool isJumping;
QPointer<QAction> saveAll;
QPointer<QAction> revertAll;
QPointer<QAction> close;
QPointer<QAction> closeAll;
QPointer<QAction> closeAllOthers;
KRecentFilesAction* fileOpenRecent;
KTextEditor::Document* globalTextEditorInstance;
};
DocumentController::DocumentController( QObject *parent )
: IDocumentController( parent )
{
setObjectName(QStringLiteral("DocumentController"));
d = new DocumentControllerPrivate(this);
QDBusConnection::sessionBus().registerObject( QStringLiteral("/org/kdevelop/DocumentController"),
this, QDBusConnection::ExportScriptableSlots );
connect(this, &DocumentController::documentUrlChanged, this, [&] (IDocument* document) { d->changeDocumentUrl(document); });
if(!(Core::self()->setupFlags() & Core::NoUi)) setupActions();
}
void DocumentController::initialize()
{
}
void DocumentController::cleanup()
{
if (d->fileOpenRecent)
d->fileOpenRecent->saveEntries( KConfigGroup(KSharedConfig::openConfig(), "Recent Files" ) );
// Close all documents without checking if they should be saved.
// This is because the user gets a chance to save them during MainWindow::queryClose.
foreach (IDocument* doc, openDocuments())
doc->close(IDocument::Discard);
}
DocumentController::~DocumentController()
{
delete d;
}
void DocumentController::setupActions()
{
KActionCollection* ac = Core::self()->uiControllerInternal()->defaultMainWindow()->actionCollection();
QAction* action;
action = ac->addAction( QStringLiteral("file_open") );
action->setIcon(QIcon::fromTheme(QStringLiteral("document-open")));
ac->setDefaultShortcut(action, Qt::CTRL + Qt::Key_O );
action->setText(i18n( "&Open..." ) );
connect( action, &QAction::triggered, this, [&] { d->chooseDocument(); } );
action->setToolTip( i18n( "Open file" ) );
action->setWhatsThis( i18n( "Opens a file for editing." ) );
d->fileOpenRecent = KStandardAction::openRecent(this,
SLOT(slotOpenDocument(QUrl)), ac);
d->fileOpenRecent->setWhatsThis(i18n("This lists files which you have opened recently, and allows you to easily open them again."));
d->fileOpenRecent->loadEntries( KConfigGroup(KSharedConfig::openConfig(), "Recent Files" ) );
action = d->saveAll = ac->addAction( QStringLiteral("file_save_all") );
action->setIcon(QIcon::fromTheme(QStringLiteral("document-save")));
action->setText(i18n( "Save Al&l" ) );
connect( action, &QAction::triggered, this, &DocumentController::slotSaveAllDocuments );
action->setToolTip( i18n( "Save all open documents" ) );
action->setWhatsThis( i18n( "Save all open documents, prompting for additional information when necessary." ) );
ac->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_L) );
action->setEnabled(false);
action = d->revertAll = ac->addAction( QStringLiteral("file_revert_all") );
action->setIcon(QIcon::fromTheme(QStringLiteral("document-revert")));
action->setText(i18n( "Reload All" ) );
connect( action, &QAction::triggered, this, &DocumentController::reloadAllDocuments );
action->setToolTip( i18n( "Revert all open documents" ) );
action->setWhatsThis( i18n( "Revert all open documents, returning to the previously saved state." ) );
action->setEnabled(false);
action = d->close = ac->addAction( QStringLiteral("file_close") );
action->setIcon(QIcon::fromTheme(QStringLiteral("window-close")));
ac->setDefaultShortcut(action, Qt::CTRL + Qt::Key_W );
action->setText( i18n( "&Close" ) );
connect( action, &QAction::triggered, this, &DocumentController::fileClose );
action->setToolTip( i18n( "Close file" ) );
action->setWhatsThis( i18n( "Closes current file." ) );
action->setEnabled(false);
action = d->closeAll = ac->addAction( QStringLiteral("file_close_all") );
action->setIcon(QIcon::fromTheme(QStringLiteral("window-close")));
action->setText(i18n( "Clos&e All" ) );
connect( action, &QAction::triggered, this, &DocumentController::closeAllDocuments );
action->setToolTip( i18n( "Close all open documents" ) );
action->setWhatsThis( i18n( "Close all open documents, prompting for additional information when necessary." ) );
action->setEnabled(false);
action = d->closeAllOthers = ac->addAction( QStringLiteral("file_closeother") );
action->setIcon(QIcon::fromTheme(QStringLiteral("window-close")));
ac->setDefaultShortcut(action, Qt::CTRL + Qt::SHIFT + Qt::Key_W );
action->setText(i18n( "Close All Ot&hers" ) );
connect( action, &QAction::triggered, this, &DocumentController::closeAllOtherDocuments );
action->setToolTip( i18n( "Close all other documents" ) );
action->setWhatsThis( i18n( "Close all open documents, with the exception of the currently active document." ) );
action->setEnabled(false);
action = ac->addAction( QStringLiteral("vcsannotate_current_document") );
connect( action, &QAction::triggered, this, &DocumentController::vcsAnnotateCurrentDocument );
action->setText( i18n( "Show Annotate on current document") );
action->setIconText( i18n( "Annotate" ) );
action->setIcon( QIcon::fromTheme(QStringLiteral("user-properties")) );
}
void DocumentController::slotOpenDocument(const QUrl &url)
{
openDocument(url);
}
IDocument* DocumentController::openDocumentFromText( const QString& data )
{
IDocument* d = openDocument(nextEmptyDocumentUrl());
Q_ASSERT(d->textDocument());
d->textDocument()->setText( data );
return d;
}
bool DocumentController::openDocumentFromTextSimple( QString text )
{
return (bool)openDocumentFromText( text );
}
bool DocumentController::openDocumentSimple( QString url, int line, int column )
{
return (bool)openDocument( QUrl::fromUserInput(url), KTextEditor::Cursor( line, column ) );
}
IDocument* DocumentController::openDocument( const QUrl& inputUrl, const QString& prefName )
{
return d->openDocumentInternal( inputUrl, prefName );
}
IDocument* DocumentController::openDocument( const QUrl & inputUrl,
const KTextEditor::Range& range,
DocumentActivationParams activationParams,
const QString& encoding, IDocument* buddy)
{
return d->openDocumentInternal( inputUrl, QLatin1String(""), range, encoding, activationParams, buddy);
}
bool DocumentController::openDocument(IDocument* doc,
const KTextEditor::Range& range,
DocumentActivationParams activationParams,
IDocument* buddy)
{
return d->openDocumentInternal( doc, range, activationParams, buddy);
}
void DocumentController::fileClose()
{
IDocument *activeDoc = activeDocument();
if (activeDoc)
{
UiController *uiController = Core::self()->uiControllerInternal();
Sublime::View *activeView = uiController->activeSublimeWindow()->activeView();
uiController->activeArea()->closeView(activeView);
}
}
bool DocumentController::closeDocument( const QUrl &url )
{
if( !d->documents.contains(url) )
return false;
//this will remove all views and after the last view is removed, the
//document will be self-destructed and removeDocument() slot will catch that
//and clean up internal data structures
d->documents[url]->close();
return true;
}
void DocumentController::notifyDocumentClosed(Sublime::Document* doc_)
{
IDocument* doc = dynamic_cast<IDocument*>(doc_);
Q_ASSERT(doc);
d->removeDocument(doc_);
if (d->documents.isEmpty()) {
if (d->saveAll)
d->saveAll->setEnabled(false);
if (d->revertAll)
d->revertAll->setEnabled(false);
if (d->close)
d->close->setEnabled(false);
if (d->closeAll)
d->closeAll->setEnabled(false);
if (d->closeAllOthers)
d->closeAllOthers->setEnabled(false);
}
emit documentClosed(doc);
}
IDocument * DocumentController::documentForUrl( const QUrl & dirtyUrl ) const
{
if (dirtyUrl.isEmpty()) {
return nullptr;
}
Q_ASSERT(!dirtyUrl.isRelative());
Q_ASSERT(!dirtyUrl.fileName().isEmpty() || !dirtyUrl.isLocalFile());
//Fix urls that might not be normalized
return d->documents.value( dirtyUrl.adjusted( QUrl::NormalizePathSegments ), nullptr );
}
QList<IDocument*> DocumentController::openDocuments() const
{
QList<IDocument*> opened;
foreach (IDocument *doc, d->documents)
{
Sublime::Document *sdoc = dynamic_cast<Sublime::Document*>(doc);
if( !sdoc )
{
continue;
}
if (!sdoc->views().isEmpty())
opened << doc;
}
return opened;
}
void DocumentController::activateDocument( IDocument * document, const KTextEditor::Range& range )
{
// TODO avoid some code in openDocument?
Q_ASSERT(document);
openDocument(document->url(), range, IDocumentController::DoNotAddToRecentOpen);
}
void DocumentController::slotSaveAllDocuments()
{
saveAllDocuments(IDocument::Silent);
}
bool DocumentController::saveAllDocuments(IDocument::DocumentSaveMode mode)
{
return saveSomeDocuments(openDocuments(), mode);
}
bool KDevelop::DocumentController::saveSomeDocuments(const QList< IDocument * > & list, IDocument::DocumentSaveMode mode)
{
if (mode & IDocument::Silent) {
foreach (IDocument* doc, modifiedDocuments(list)) {
if( !DocumentController::isEmptyDocumentUrl(doc->url()) && !doc->save(mode) )
{
if( doc )
qWarning() << "!! Could not save document:" << doc->url();
else
qWarning() << "!! Could not save document as its NULL";
}
// TODO if (!ret) showErrorDialog() ?
}
} else {
// Ask the user which documents to save
QList<IDocument*> checkSave = modifiedDocuments(list);
if (!checkSave.isEmpty()) {
KSaveSelectDialog dialog(checkSave, qApp->activeWindow());
if (dialog.exec() == QDialog::Rejected)
return false;
}
}
return true;
}
QList< IDocument * > KDevelop::DocumentController::visibleDocumentsInWindow(MainWindow * mw) const
{
// Gather a list of all documents which do have a view in the given main window
// Does not find documents which are open in inactive areas
QList<IDocument*> list;
foreach (IDocument* doc, openDocuments()) {
if (Sublime::Document* sdoc = dynamic_cast<Sublime::Document*>(doc)) {
foreach (Sublime::View* view, sdoc->views()) {
if (view->hasWidget() && view->widget()->window() == mw) {
list.append(doc);
break;
}
}
}
}
return list;
}
QList< IDocument * > KDevelop::DocumentController::documentsExclusivelyInWindow(MainWindow * mw, bool currentAreaOnly) const
{
// Gather a list of all documents which have views only in the given main window
QList<IDocument*> checkSave;
foreach (IDocument* doc, openDocuments()) {
if (Sublime::Document* sdoc = dynamic_cast<Sublime::Document*>(doc)) {
bool inOtherWindow = false;
foreach (Sublime::View* view, sdoc->views()) {
foreach(Sublime::MainWindow* window, Core::self()->uiControllerInternal()->mainWindows())
if(window->containsView(view) && (window != mw || (currentAreaOnly && window == mw && !mw->area()->views().contains(view))))
inOtherWindow = true;
}
if (!inOtherWindow)
checkSave.append(doc);
}
}
return checkSave;
}
QList< IDocument * > KDevelop::DocumentController::modifiedDocuments(const QList< IDocument * > & list) const
{
QList< IDocument * > ret;
foreach (IDocument* doc, list)
if (doc->state() == IDocument::Modified || doc->state() == IDocument::DirtyAndModified)
ret.append(doc);
return ret;
}
bool DocumentController::saveAllDocumentsForWindow(KParts::MainWindow* mw, KDevelop::IDocument::DocumentSaveMode mode, bool currentAreaOnly)
{
QList<IDocument*> checkSave = documentsExclusivelyInWindow(dynamic_cast<KDevelop::MainWindow*>(mw), currentAreaOnly);
return saveSomeDocuments(checkSave, mode);
}
void DocumentController::reloadAllDocuments()
{
if (Sublime::MainWindow* mw = Core::self()->uiControllerInternal()->activeSublimeWindow()) {
QList<IDocument*> views = visibleDocumentsInWindow(dynamic_cast<KDevelop::MainWindow*>(mw));
if (!saveSomeDocuments(views, IDocument::Default))
// User cancelled or other error
return;
foreach (IDocument* doc, views)
if(!isEmptyDocumentUrl(doc->url()))
doc->reload();
}
}
bool DocumentController::closeAllDocuments()
{
if (Sublime::MainWindow* mw = Core::self()->uiControllerInternal()->activeSublimeWindow()) {
QList<IDocument*> views = visibleDocumentsInWindow(dynamic_cast<KDevelop::MainWindow*>(mw));
if (!saveSomeDocuments(views, IDocument::Default))
// User cancelled or other error
return false;
foreach (IDocument* doc, views)
doc->close(IDocument::Discard);
}
return true;
}
void DocumentController::closeAllOtherDocuments()
{
if (Sublime::MainWindow* mw = Core::self()->uiControllerInternal()->activeSublimeWindow()) {
Sublime::View* activeView = mw->activeView();
if (!activeView) {
qWarning() << "Shouldn't there always be an active view when this function is called?";
return;
}
// Deal with saving unsaved solo views
QList<IDocument*> soloViews = documentsExclusivelyInWindow(dynamic_cast<KDevelop::MainWindow*>(mw));
soloViews.removeAll(dynamic_cast<IDocument*>(activeView->document()));
if (!saveSomeDocuments(soloViews, IDocument::Default))
// User cancelled or other error
return;
foreach (Sublime::View* view, mw->area()->views()) {
if (view != activeView)
mw->area()->closeView(view);
}
activeView->widget()->setFocus();
}
}
IDocument* DocumentController::activeDocument() const
{
UiController *uiController = Core::self()->uiControllerInternal();
Sublime::MainWindow* mw = uiController->activeSublimeWindow();
if( !mw || !mw->activeView() ) return nullptr;
return dynamic_cast<IDocument*>(mw->activeView()->document());
}
KTextEditor::View* DocumentController::activeTextDocumentView() const
{
UiController *uiController = Core::self()->uiControllerInternal();
Sublime::MainWindow* mw = uiController->activeSublimeWindow();
if( !mw || !mw->activeView() )
return nullptr;
TextView* view = qobject_cast<TextView*>(mw->activeView());
if(!view)
return nullptr;
return view->textView();
}
QString DocumentController::activeDocumentPath( QString target ) const
{
if(!target.isEmpty()) {
foreach(IProject* project, Core::self()->projectController()->projects()) {
if(project->name().startsWith(target, Qt::CaseInsensitive)) {
return project->path().pathOrUrl() + "/.";
}
}
}
IDocument* doc = activeDocument();
if(!doc || target == QStringLiteral("[selection]"))
{
Context* selection = ICore::self()->selectionController()->currentSelection();
if(selection && selection->type() == Context::ProjectItemContext && !static_cast<ProjectItemContext*>(selection)->items().isEmpty())
{
QString ret = static_cast<ProjectItemContext*>(selection)->items().at(0)->path().pathOrUrl();
if(static_cast<ProjectItemContext*>(selection)->items().at(0)->folder())
ret += QStringLiteral("/.");
return ret;
}
return QString();
}
return doc->url().toString();
}
QStringList DocumentController::activeDocumentPaths() const
{
UiController *uiController = Core::self()->uiControllerInternal();
if( !uiController->activeSublimeWindow() ) return QStringList();
QSet<QString> documents;
foreach(Sublime::View* view, uiController->activeSublimeWindow()->area()->views())
documents.insert(view->document()->documentSpecifier());
return documents.toList();