File: textdocument.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (842 lines) | stat: -rw-r--r-- 26,394 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
/***************************************************************************
 *   Copyright 2007 Alexander Dymo  <adymo@kdevelop.org>                   *
 *                                                                         *
 *   This program 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 program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/
#include "textdocument.h"

#include <QAction>
#include <QFile>
#include <QMenu>
#include <QMimeDatabase>
#include <QPointer>
#include <QWidget>

#include <KActionCollection>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KMessageBox>
#include <KTextEditor/View>
#include <KTextEditor/Document>
#include <KTextEditor/ModificationInterface>
#include <KTextEditor/CodeCompletionInterface>
#include <KTextEditor/MarkInterface>

#include <interfaces/context.h>
#include <interfaces/contextmenuextension.h>
#include <interfaces/ilanguagecontroller.h>
#include <interfaces/icompletionsettings.h>
#include <interfaces/iprojectcontroller.h>
#include <interfaces/iproject.h>

#include <vcs/interfaces/icontentawareversioncontrol.h>

#include <language/interfaces/editorcontext.h>
#include <language/backgroundparser/backgroundparser.h>

#include <util/foregroundlock.h>

#include "core.h"
#include "mainwindow.h"
#include "uicontroller.h"
#include "partcontroller.h"
#include "plugincontroller.h"
#include "documentcontroller.h"
#include "ktexteditorpluginintegration.h"
#include "debug.h"

#include <path.h>
#include <shellutils.h>

namespace KDevelop {

const int MAX_DOC_SETTINGS = 20;

// This sets cursor position and selection on the view to the given
// range. Selection is set only for non-empty ranges
// Factored into a function since its needed in 3 places already
static void selectAndReveal( KTextEditor::View* view, const KTextEditor::Range& range ) {
    Q_ASSERT(view);
    if (range.isValid()) {
        view->setCursorPosition(range.start());
        view->setSelection(range);
    }
}

class TextDocumentPrivate
{
public:
    explicit TextDocumentPrivate(TextDocument *textDocument)
        : q(textDocument)
    {
    }

    ~TextDocumentPrivate()
    {
        // Handle the case we are being deleted while the context menu is not yet hidden.
        // We want to remove all actions we added to it, especially those not owned by the document
        // but by the plugins (i.e. created on-the-fly during ContextMenuExtension::populateMenu
        // with ownership set to our addedContextMenu)
        cleanContextMenu();

        saveSessionConfig();
        delete document;
    }

    void setStatus(KTextEditor::Document* document, bool dirty)
    {
        QIcon statusIcon;

        if (document->isModified())
            if (dirty) {
                state = IDocument::DirtyAndModified;
                statusIcon = QIcon::fromTheme(QStringLiteral("edit-delete"));
            } else {
                state = IDocument::Modified;
                statusIcon = QIcon::fromTheme(QStringLiteral("document-save"));
            }
        else
            if (dirty) {
                state = IDocument::Dirty;
                statusIcon = QIcon::fromTheme(QStringLiteral("document-revert"));
            } else {
                state = IDocument::Clean;
            }

        q->notifyStateChanged();
        Core::self()->uiControllerInternal()->setStatusIcon(q, statusIcon);
    }

    inline KConfigGroup katePartSettingsGroup() const
    {
        return KSharedConfig::openConfig()->group("KatePart Settings");
    }

    inline QString docConfigGroupName() const
    {
        return document->url().toDisplayString(QUrl::PreferLocalFile);
    }

    inline KConfigGroup docConfigGroup() const
    {
        return katePartSettingsGroup().group(docConfigGroupName());
    }

    void saveSessionConfig()
    {
        if(document && document->url().isValid()) {
            // make sure only MAX_DOC_SETTINGS entries are stored
            KConfigGroup katePartSettings = katePartSettingsGroup();
            // ordered list of documents
            QStringList documents = katePartSettings.readEntry("documents", QStringList());
            // ensure this document is "new", i.e. at the end of the list
            documents.removeOne(docConfigGroupName());
            documents.append(docConfigGroupName());
            // remove "old" documents + their group
            while(documents.size() >= MAX_DOC_SETTINGS) {
                katePartSettings.group(documents.takeFirst()).deleteGroup();
            }
            // update order
            katePartSettings.writeEntry("documents", documents);

            // actually save session config
            KConfigGroup group = docConfigGroup();
            document->writeSessionConfig(group);
        }
    }

    void loadSessionConfig()
    {
        if (!document || !katePartSettingsGroup().hasGroup(docConfigGroupName())) {
            return;
        }

        document->readSessionConfig(docConfigGroup(), {QStringLiteral("SkipUrl")});
    }

    // Determines whether the current contents of this document in the editor
    // could be retrieved from the VCS if they were dismissed.
    void queryCanRecreateFromVcs(KTextEditor::Document* document) const {
        // Find projects by checking which one contains the file's parent directory,
        // to avoid issues with the cmake manager temporarily removing files from a project
        // during reloading.
        KDevelop::Path path(document->url());
        const auto projects = Core::self()->projectController()->projects();
        auto projectIt = std::find_if(projects.begin(), projects.end(), [&](KDevelop::IProject* project) {
            return project->path().isParentOf(path);
        });
        if (projectIt == projects.end()) {
            return;
        }
        IProject* project = *projectIt;

        IContentAwareVersionControl* iface;
        iface = qobject_cast< KDevelop::IContentAwareVersionControl* >(project->versionControlPlugin());
        if (!iface) {
            return;
        }
        if ( !qobject_cast<KTextEditor::ModificationInterface*>( document ) ) {
            return;
        }

        CheckInRepositoryJob* req = iface->isInRepository( document );
        if ( !req ) {
            return;
        }
        QObject::connect(req, &CheckInRepositoryJob::finished,
                            q, &TextDocument::repositoryCheckFinished);
        // Abort the request when the user edits the document
        QObject::connect(q->textDocument(), &KTextEditor::Document::textChanged,
                            req, &CheckInRepositoryJob::abort);
    }

    void modifiedOnDisk(KTextEditor::Document *document, bool /*isModified*/,
        KTextEditor::ModificationInterface::ModifiedOnDiskReason reason)
    {
        bool dirty = false;
        switch (reason)
        {
            case KTextEditor::ModificationInterface::OnDiskUnmodified:
                break;
            case KTextEditor::ModificationInterface::OnDiskModified:
            case KTextEditor::ModificationInterface::OnDiskCreated:
            case KTextEditor::ModificationInterface::OnDiskDeleted:
                dirty = true;
                break;
        }

        // In some cases, the VCS (e.g. git) can know whether the old contents are "valuable", i.e.
        // not retrieveable from the VCS. If that is not the case, then the document can safely be
        // reloaded without displaying a dialog asking the user.
        if ( dirty ) {
            queryCanRecreateFromVcs(document);
        }
        setStatus(document, dirty);
    }

    void cleanContextMenu()
    {
        if (!addedContextMenu) {
            return;
        }

        if (currentContextMenu) {
            const auto actions = addedContextMenu->actions();
            for (QAction* action : actions) {
                currentContextMenu->removeAction(action);
            }
            currentContextMenu.clear();
        }

        // The addedContextMenu owns those actions created on-the-fly for the context menu
        // (other than those actions only shared for the context menu, but also used elsewhere)
        // and thuse deletes then on its own destruction.
        // Some actions potentially could be connected to triggered-signal handlers
        // using Qt::QueuedConnection (at least SwitchToBuddyPlugin does so currently).
        // Deleting them here also would also delete the connection before the handler is triggered.
        // So we delay the menu's and thus their destruction to the next eventloop by default.
        addedContextMenu->deleteLater();
        addedContextMenu = nullptr;
    }

    TextDocument * const q;

    QPointer<KTextEditor::Document> document;
    IDocument::DocumentState state = IDocument::Clean;
    QString encoding;
    bool loaded = false;
    // we want to remove the added stuff when the menu hides
    QMenu* addedContextMenu = nullptr;
    QPointer<QMenu> currentContextMenu;
};

class TextViewPrivate
{
public:
    explicit TextViewPrivate(TextView* q) : q(q) {}

    TextView* const q;
    QPointer<KTextEditor::View> view;
    KTextEditor::Range initialRange;
};

TextDocument::TextDocument(const QUrl &url, ICore* core, const QString& encoding)
    : PartDocument(url, core)
    , d_ptr(new TextDocumentPrivate(this))
{
    Q_D(TextDocument);

    d->encoding = encoding;
}

TextDocument::~TextDocument() = default;

bool TextDocument::isTextDocument() const
{
    Q_D(const TextDocument);

    if( !d->document )
    {
        /// @todo Somehow it can happen that d->document is zero, which makes
        /// code relying on "isTextDocument() == (bool)textDocument()" crash
        qCWarning(SHELL) << "Broken text-document: " << url();
        return false;
    }

    return true;
}

KTextEditor::Document *TextDocument::textDocument() const
{
    Q_D(const TextDocument);

    return d->document;
}

QWidget *TextDocument::createViewWidget(QWidget *parent)
{
    Q_D(TextDocument);

    KTextEditor::View* view = nullptr;

    if (!d->document)
    {
        d->document = Core::self()->partControllerInternal()->createTextPart();

        // Connect to the first text changed signal, it occurs before the completed() signal
        connect(d->document.data(), &KTextEditor::Document::textChanged, this, &TextDocument::slotDocumentLoaded);
        // Also connect to the completed signal, sometimes the first text changed signal is missed because the part loads too quickly (? TODO - confirm this is necessary)
        connect(d->document.data(), QOverload<>::of(&KTextEditor::Document::completed),
                this, &TextDocument::slotDocumentLoaded);

        // force a reparse when a document gets reloaded
        connect(d->document.data(), &KTextEditor::Document::reloaded,
                this, [] (KTextEditor::Document* document) {
            ICore::self()->languageController()->backgroundParser()->addDocument(IndexedString(document->url()),
                    (TopDUContext::Features) ( TopDUContext::AllDeclarationsContextsAndUses | TopDUContext::ForceUpdate ),
                    BackgroundParser::BestPriority, nullptr);
        });

        // Set encoding passed via constructor
        // Needs to be done before openUrl, else katepart won't use the encoding
        // @see KTextEditor::Document::setEncoding
        if (!d->encoding.isEmpty())
            d->document->setEncoding(d->encoding);

        if (!url().isEmpty() && !DocumentController::isEmptyDocumentUrl(url()))
            d->document->openUrl( url() );

        d->setStatus(d->document, false);

        /* It appears, that by default a part will be deleted the
           first view containing it is deleted.  Since we do want
           to have several views, disable that behaviour.  */
        d->document->setAutoDeletePart(false);

        Core::self()->partController()->addPart(d->document, false);

        d->loadSessionConfig();

        connect(d->document.data(), &KTextEditor::Document::modifiedChanged,
                 this, &TextDocument::newDocumentStatus);
        connect(d->document.data(), &KTextEditor::Document::textChanged,
                 this, &TextDocument::textChanged);
        connect(d->document.data(), &KTextEditor::Document::documentUrlChanged,
                 this, &TextDocument::documentUrlChanged);
        connect(d->document.data(), &KTextEditor::Document::documentSavedOrUploaded,
                 this, &TextDocument::documentSaved );

        if (qobject_cast<KTextEditor::MarkInterface*>(d->document)) {
            // can't use new signal/slot syntax here, MarkInterface is not a QObject
            connect(d->document.data(), SIGNAL(marksChanged(KTextEditor::Document*)),
                    this, SLOT(saveSessionConfig()));
        }

        if (auto iface = qobject_cast<KTextEditor::ModificationInterface*>(d->document)) {
            iface->setModifiedOnDiskWarning(true);
            // can't use new signal/slot syntax here, ModificationInterface is not a QObject
            connect(d->document.data(), SIGNAL(modifiedOnDisk(KTextEditor::Document*,bool,KTextEditor::ModificationInterface::ModifiedOnDiskReason)),
                this, SLOT(modifiedOnDisk(KTextEditor::Document*,bool,KTextEditor::ModificationInterface::ModifiedOnDiskReason)));
        }

        notifyTextDocumentCreated();
    }

    view = d->document->createView(parent, Core::self()->uiControllerInternal()->defaultMainWindow()->kateWrapper()->interface());

    // get rid of some actions regarding the config dialog, we merge that one into the kdevelop menu already
    delete view->actionCollection()->action(QStringLiteral("set_confdlg"));
    delete view->actionCollection()->action(QStringLiteral("editor_options"));

    view->setStatusBarEnabled(Core::self()->partControllerInternal()->showTextEditorStatusBar());

    connect(view, &KTextEditor::View::contextMenuAboutToShow, this, &TextDocument::populateContextMenu);

    if (auto* cc = qobject_cast<KTextEditor::CodeCompletionInterface*>(view))
        cc->setAutomaticInvocationEnabled(core()->languageController()->completionSettings()->automaticCompletionEnabled());

    return view;
}

KParts::Part *TextDocument::partForView(QWidget *view) const
{
    Q_D(const TextDocument);

    if (d->document && d->document->views().contains(qobject_cast<KTextEditor::View*>(view)))
        return d->document;
    return nullptr;
}



// KDevelop::IDocument implementation

void TextDocument::reload()
{
    Q_D(TextDocument);

    if (!d->document)
        return;

    KTextEditor::ModificationInterface* modif=nullptr;
    if(d->state ==Dirty) {
        modif = qobject_cast<KTextEditor::ModificationInterface*>(d->document);
        modif->setModifiedOnDiskWarning(false);
    }
    d->document->documentReload();
    if(modif)
        modif->setModifiedOnDiskWarning(true);
}

bool TextDocument::save(DocumentSaveMode mode)
{
    Q_D(TextDocument);

    if (!d->document)
        return true;

    if (mode & Discard)
        return true;

    switch (d->state)
    {
        case IDocument::Clean:
            return true;

        case IDocument::Modified:
            break;

        case IDocument::Dirty:
        case IDocument::DirtyAndModified:
            if (!(mode & Silent))
            {
                int code = KMessageBox::warningYesNoCancel(
                    Core::self()->uiController()->activeMainWindow(),
                    i18n("The file \"%1\" is modified on disk.\n\nAre "
                        "you sure you want to overwrite it? (External "
                        "changes will be lost.)", d->document->url().toLocalFile()),
                    i18nc("@title:window", "Document Externally Modified"));
                if (code != KMessageBox::Yes)
                    return false;
            }
            break;
    }

    if (!KDevelop::ensureWritable(QList<QUrl>() << url())) {
        return false;
    }

    QUrl urlBeforeSave = d->document->url();
    if (d->document->documentSave())
    {
        if (d->document->url() != urlBeforeSave)
            notifyUrlChanged();
        return true;
    }
    return false;
}

IDocument::DocumentState TextDocument::state() const
{
    Q_D(const TextDocument);

    return d->state;
}

KTextEditor::Cursor KDevelop::TextDocument::cursorPosition() const
{
    Q_D(const TextDocument);

    if (!d->document) {
        return KTextEditor::Cursor::invalid();
    }

    KTextEditor::View *view = activeTextView();

    if (view)
        return view->cursorPosition();

    return KTextEditor::Cursor::invalid();
}

void TextDocument::setCursorPosition(const KTextEditor::Cursor &cursor)
{
    Q_D(TextDocument);

    if (!cursor.isValid() || !d->document)
        return;

    KTextEditor::View *view = activeTextView();

    // Rodda: Cursor must be accurate here, to the definition of accurate for KTextEditor::Cursor.
    // ie, starting from 0,0

    if (view)
        selectAndReveal(view, {cursor, cursor});
}

KTextEditor::Range TextDocument::textSelection() const
{
    Q_D(const TextDocument);

    if (!d->document) {
        return KTextEditor::Range::invalid();
    }

    KTextEditor::View *view = activeTextView();

    if (view && view->selection()) {
        return view->selectionRange();
    }

    return PartDocument::textSelection();
}

QString TextDocument::text(const KTextEditor::Range &range) const
{
    VERIFY_FOREGROUND_LOCKED
    Q_D(const TextDocument);

    if (!d->document) {
        return QString();
    }

    return d->document->text( range );
}

QString TextDocument::textLine() const
{
    VERIFY_FOREGROUND_LOCKED
    Q_D(const TextDocument);

    if (!d->document) {
        return QString();
    }

    KTextEditor::View *view = activeTextView();

    if (view) {
        return d->document->line( view->cursorPosition().line() );
    }

    return PartDocument::textLine();
}

QString TextDocument::textWord() const
{
    VERIFY_FOREGROUND_LOCKED
    Q_D(const TextDocument);

    if (!d->document) {
        return QString();
    }

    KTextEditor::View *view = activeTextView();

    if (view) {
        KTextEditor::Cursor start = view->cursorPosition();
        qCDebug(SHELL) << "got start position from view:" << start.line() << start.column();
        QString linestr = textLine();
        int startPos = qMax( qMin( start.column(), linestr.length() - 1 ), 0 );
        int endPos = startPos;
        startPos --;
        while (startPos >= 0 &&
               (linestr[startPos].isLetterOrNumber() || linestr[startPos] == QLatin1Char('_') || linestr[startPos] == QLatin1Char('~'))) {
            --startPos;
        }

        while (endPos < linestr.length() &&
               (linestr[endPos].isLetterOrNumber() || linestr[endPos] == QLatin1Char('_') || linestr[endPos] == QLatin1Char('~'))) {
            ++endPos;
        }
        if( startPos != endPos )
        {
            qCDebug(SHELL) << "found word" << startPos << endPos << linestr.mid( startPos+1, endPos - startPos - 1 );
            return linestr.mid( startPos + 1, endPos - startPos - 1 );
        }
    }

    return PartDocument::textWord();
}

void TextDocument::setTextSelection(const KTextEditor::Range &range)
{
    Q_D(TextDocument);

    if (!range.isValid() || !d->document)
        return;

    KTextEditor::View *view = activeTextView();

    if (view) {
        selectAndReveal(view, range);
    }
}

Sublime::View* TextDocument::newView(Sublime::Document* doc)
{
    Q_UNUSED(doc);
    return new TextView(this);
}

}

KDevelop::TextView::TextView(TextDocument * doc)
    : View(doc, View::TakeOwnership)
    , d_ptr(new TextViewPrivate(this))
{
}

KDevelop::TextView::~TextView() = default;

QWidget * KDevelop::TextView::createWidget(QWidget * parent)
{
    Q_D(TextView);

    auto textDocument = qobject_cast<TextDocument*>(document());
    Q_ASSERT(textDocument);
    QWidget* widget = textDocument->createViewWidget(parent);
    d->view = qobject_cast<KTextEditor::View*>(widget);
    Q_ASSERT(d->view);
    connect(d->view.data(), &KTextEditor::View::cursorPositionChanged, this, &KDevelop::TextView::sendStatusChanged);
    return widget;
}

void KDevelop::TextView::setInitialRange(const KTextEditor::Range& range)
{
    Q_D(TextView);

    if (d->view) {
        selectAndReveal(d->view, range);
    } else {
        d->initialRange = range;
    }
}

KTextEditor::Range KDevelop::TextView::initialRange() const
{
    Q_D(const TextView);

    return d->initialRange;
}

void KDevelop::TextView::readSessionConfig(KConfigGroup& config)
{
    Q_D(TextView);

    if (!d->view) {
        return;
    }
    d->view->readSessionConfig(config);
}

void KDevelop::TextView::writeSessionConfig(KConfigGroup& config)
{
    Q_D(TextView);

    if (!d->view) {
        return;
    }
    d->view->writeSessionConfig(config);
}

QString KDevelop::TextDocument::documentType() const
{
    return QStringLiteral("Text");
}

QIcon KDevelop::TextDocument::defaultIcon() const
{
    Q_D(const TextDocument);

    if (d->document) {
        QMimeType mime = QMimeDatabase().mimeTypeForName(d->document->mimeType());
        QIcon icon = QIcon::fromTheme(mime.iconName());
        if (!icon.isNull()) {
            return icon;
        }
    }
    return PartDocument::defaultIcon();
}

KTextEditor::View *KDevelop::TextView::textView() const
{
    Q_D(const TextView);

    return d->view;
}

QString KDevelop::TextView::viewStatus() const
{
    Q_D(const TextView);

    // only show status when KTextEditor's own status bar isn't already enabled
    const bool showStatus = !Core::self()->partControllerInternal()->showTextEditorStatusBar();
    if (!showStatus) {
        return QString();
    }

    const KTextEditor::Cursor pos = d->view ? d->view->cursorPosition() : KTextEditor::Cursor::invalid();
    return i18n(" Line: %1 Col: %2 ", pos.line() + 1, pos.column() + 1);
}

void KDevelop::TextView::sendStatusChanged()
{
    emit statusChanged(this);
}

KTextEditor::View* KDevelop::TextDocument::activeTextView() const
{
    KTextEditor::View* fallback = nullptr;
    for (auto view : views()) {
        auto textView = qobject_cast<TextView*>(view)->textView();
        if (!textView) {
            continue;
        }
        if (textView->hasFocus()) {
            return textView;
        } else if (textView->isVisible()) {
            fallback = textView;
        } else if (!fallback) {
            fallback = textView;
        }
    }
    return fallback;
}

void KDevelop::TextDocument::newDocumentStatus(KTextEditor::Document *document)
{
    Q_D(TextDocument);

    bool dirty = (d->state == IDocument::Dirty || d->state == IDocument::DirtyAndModified);

    d->setStatus(document, dirty);
}

void KDevelop::TextDocument::textChanged(KTextEditor::Document *document)
{
    Q_UNUSED(document);
    notifyContentChanged();
}

void KDevelop::TextDocument::unpopulateContextMenu()
{
    Q_D(TextDocument);

    auto* menu = qobject_cast<QMenu*>(sender());

    disconnect(menu, &QMenu::aboutToHide, this, &TextDocument::unpopulateContextMenu);

    d->cleanContextMenu();
}

void KDevelop::TextDocument::populateContextMenu( KTextEditor::View* v, QMenu* menu )
{
    Q_D(TextDocument);

    if (d->addedContextMenu) {
        qCWarning(SHELL) << "populateContextMenu() called while we still handled another menu.";
        d->cleanContextMenu();
    }

    d->currentContextMenu = menu;
    connect(menu, &QMenu::aboutToHide, this, &TextDocument::unpopulateContextMenu);

    d->addedContextMenu = new QMenu();

    EditorContext c(v, v->cursorPosition());
    auto extensions = Core::self()->pluginController()->queryPluginsForContextMenuExtensions(&c, d->addedContextMenu);

    ContextMenuExtension::populateMenu(d->addedContextMenu, extensions);

    const auto actions = d->addedContextMenu->actions();
    for (QAction* action : actions) {
        menu->addAction(action);
    }
}

void KDevelop::TextDocument::repositoryCheckFinished(bool canRecreate) {
    Q_D(TextDocument);

    if ( d->state != IDocument::Dirty && d->state != IDocument::DirtyAndModified ) {
        // document is not dirty for whatever reason, nothing to do.
        return;
    }
    if ( ! canRecreate ) {
        return;
    }
    KTextEditor::ModificationInterface* modIface = qobject_cast<KTextEditor::ModificationInterface*>( d->document );
    Q_ASSERT(modIface);
    // Ok, all safe, we can clean up the document. Close it if the file is gone,
    // and reload if it's still there.
    d->setStatus(d->document, false);
    modIface->setModifiedOnDisk(KTextEditor::ModificationInterface::OnDiskUnmodified);
    if ( QFile::exists(d->document->url().path()) ) {
        reload();
    } else {
        close(KDevelop::IDocument::Discard);
    }
}

void KDevelop::TextDocument::slotDocumentLoaded()
{
    Q_D(TextDocument);

    if (d->loaded)
        return;
    // Tell the editor integrator first
    d->loaded = true;
    notifyLoaded();
}

void KDevelop::TextDocument::documentSaved(KTextEditor::Document* document, bool saveAs)
{
    Q_UNUSED(document);
    Q_UNUSED(saveAs);
    notifySaved();
    notifyStateChanged();
}

void KDevelop::TextDocument::documentUrlChanged(KTextEditor::Document* document)
{
    Q_D(TextDocument);

    Q_UNUSED(document);
    if (url() != d->document->url())
        setUrl(d->document->url());
}

#include "moc_textdocument.cpp"