lspclientservermanager.cpp 28.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*  SPDX-License-Identifier: MIT

    Copyright (C) 2019 Mark Nauwelaerts <mark.nauwelaerts@gmail.com>

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
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
/*
 * Some explanation here on server configuration JSON, pending such ending up
 * in real user level documentation ...
 *
 * The default configuration in JSON format is roughly as follows;
{
    "global":
    {
        "root": null,
    },
    "servers":
    {
        "Python":
        {
            "command": "python3 -m pyls --check-parent-process"
        },
        "C":
        {
            "command": "clangd -log=verbose --background-index"
        },
        "C++":
        {
            "use": "C++"
        }
    }
}
 * (the "command" can be an array or a string, which is then split into array)
 *
 * From the above, the gist is presumably clear.  In addition, each server
 * entry object may also have an "initializationOptions" entry, which is passed
 * along to the server as part of the 'initialize' method.  A clangd-specific
 * HACK^Hfeature uses this to add "compilationDatabasePath".
 *
 * Various stages of override/merge are applied;
 * + user configuration (loaded from file) overrides (internal) default configuration
 * + "lspclient" entry in projectMap overrides the above
 * + the resulting "global" entry is used to supplement (not override) any server entry
 *
 * One server instance is used per (root, servertype) combination.
 * If "root" is not specified, it default to the $HOME directory.  If it is
 * specified as an absolute path, then it used as-is, otherwise it is relative
 * to the projectBase.  For any document, the resulting "root" then determines
 * whether or not a separate instance is needed. If so, the "root" is passed
 * as rootUri/rootPath.
 *
 * In general, it is recommended to leave root unspecified, as it is not that
 * important for a server (your mileage may vary though).  Fewer instances
 * are obviously more efficient, and they also have a 'wider' view than
 * the view of many separate instances.
 */

76
77
78
79
80
81
82
#include "lspclientservermanager.h"

#include "lspclient_debug.h"

#include <KTextEditor/Document>
#include <KTextEditor/MainWindow>
#include <KTextEditor/View>
83
84
#include <KTextEditor/Message>
#include <KLocalizedString>
85
#include <KTextEditor/MovingInterface>
86

87
#include <QDir>
88
89
#include <QEventLoop>
#include <QFileInfo>
90
91
92
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
93
94
95
#include <QTimer>

// helper to find a proper root dir for the given document & file name that indicate the root dir
96
97
static QString rootForDocumentAndRootIndicationFileName(KTextEditor::Document *document,
                                                        const QString &rootIndicationFileName)
98
99
100
101
102
103
104
105
106
107
108
109
110
{
    // search only feasible if document is local file
    if (!document->url().isLocalFile()) {
        return QString();
    }

    // search root upwards
    QDir dir(QFileInfo(document->url().toLocalFile()).absolutePath());
    QSet<QString> seenDirectories;
    while (!seenDirectories.contains(dir.absolutePath())) {
        // update guard
        seenDirectories.insert(dir.absolutePath());

Christoph Cullmann's avatar
Christoph Cullmann committed
111
        // the file that indicates the root dir is there => all fine
112
113
114
115
116
117
118
119
120
121
122
123
124
        if (dir.exists(rootIndicationFileName)) {
            return dir.absolutePath();
        }

        // else: cd up, if possible or abort
        if (!dir.cdUp()) {
            break;
        }
    }

    // no root found, bad luck
    return QString();
}
125

126
127
#include <memory>

128
129
// local helper;
// recursively merge top json top onto bottom json
130
static QJsonObject merge(const QJsonObject &bottom, const QJsonObject &top)
131
132
133
{
    QJsonObject result;
    for (auto item = top.begin(); item != top.end(); item++) {
134
135
        const auto &key = item.key();
        if (item.value().isObject()) {
136
137
138
139
140
141
142
143
144
145
146
147
148
            result.insert(key, merge(bottom.value(key).toObject(), item.value().toObject()));
        } else {
            result.insert(key, item.value());
        }
    }
    // parts only in bottom
    for (auto item = bottom.begin(); item != bottom.end(); item++) {
        if (!result.contains(item.key())) {
            result.insert(item.key(), item.value());
        }
    }
    return result;
}
149

150
// map (highlight)mode to lsp languageId
151
static QString languageId(const QString &mode)
152
{
153
    // lookup in cache first
154
155
156
157
158
    static QHash<QString, QString> m;
    auto it = m.find(mode);
    if (it != m.end()) {
        return *it;
    }
159
160
161
162
163
164

    /**
     * try to normalize the highlighting name
     * - lower-case
     * - transform some special characters
     */
165
166
    QString result = mode.toLower();
    result = result.replace(QStringLiteral("++"), QStringLiteral("pp"));
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    result = result.replace(QStringLiteral("#"), QStringLiteral("sharp"));

    /**
     * we still need to take care of some languages that have "very" different names than the normalized lsp names
     */
    if (result.contains(QLatin1String("fortran"))) {
        result = QStringLiteral("fortran");
    }

    /**
     * now, cache the resulting mapping and be done
     */
    m[mode] = result;
    return result;
181
182
}

183
// helper guard to handle revision (un)lock
184
struct RevisionGuard {
185
186
187
188
    QPointer<KTextEditor::Document> m_doc;
    KTextEditor::MovingInterface *m_movingInterface = nullptr;
    qint64 m_revision = -1;

189
190
    RevisionGuard(KTextEditor::Document *doc = nullptr)
        : m_doc(doc),
191
          m_movingInterface(qobject_cast<KTextEditor::MovingInterface *>(doc))
192
193
194
195
196
197
198
199
    {
        if (m_movingInterface) {
            m_revision = m_movingInterface->revision();
            m_movingInterface->lockRevision(m_revision);
        }
    }

    // really only need/allow this one (out of 5)
200
    RevisionGuard(RevisionGuard &&other) : RevisionGuard(nullptr)
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
    {
        std::swap(m_doc, other.m_doc);
        std::swap(m_movingInterface, other.m_movingInterface);
        std::swap(m_revision, other.m_revision);
    }

    void release()
    {
        m_movingInterface = nullptr;
        m_revision = -1;
    }

    ~RevisionGuard()
    {
        // NOTE: hopefully the revision is still valid at this time
        if (m_doc && m_movingInterface && m_revision >= 0) {
            m_movingInterface->unlockRevision(m_revision);
        }
    }
};

class LSPClientRevisionSnapshotImpl : public LSPClientRevisionSnapshot
{
    Q_OBJECT

    typedef LSPClientRevisionSnapshotImpl self_type;

    // std::map has more relaxed constraints on value_type
    std::map<QUrl, RevisionGuard> m_guards;

    Q_SLOT
    void clearRevisions(KTextEditor::Document *doc)
    {
234
        for (auto &item : m_guards) {
235
236
237
238
239
240
241
242
243
244
245
            if (item.second.m_doc == doc) {
                item.second.release();
            }
        }
    }

public:
    void add(KTextEditor::Document *doc)
    {
        Q_ASSERT(doc);

246
247
        // make sure revision is cleared when needed and no longer used (to unlock or otherwise)
        // see e.g. implementation in katetexthistory.cpp and assert's in place there
248
249
250
        auto conn = connect(
                doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document *)), this,
                SLOT(clearRevisions(KTextEditor::Document *)));
251
        Q_ASSERT(conn);
252
253
        conn = connect(doc, SIGNAL(aboutToDeleteMovingInterfaceContent(KTextEditor::Document *)),
                       this, SLOT(clearRevisions(KTextEditor::Document *)));
254
        Q_ASSERT(conn);
255
256
257
        m_guards.emplace(doc->url(), doc);
    }

258
259
    void find(const QUrl &url, KTextEditor::MovingInterface *&miface,
              qint64 &revision) const override
260
261
262
263
264
265
266
267
268
269
270
271
    {
        auto it = m_guards.find(url);
        if (it != m_guards.end()) {
            miface = it->second.m_movingInterface;
            revision = it->second.m_revision;
        } else {
            miface = nullptr;
            revision = -1;
        }
    }
};

272
273
274
275
276
277
278
// helper class to sync document changes to LSP server
class LSPClientServerManagerImpl : public LSPClientServerManager
{
    Q_OBJECT

    typedef LSPClientServerManagerImpl self_type;

279
    struct DocumentInfo {
280
        QSharedPointer<LSPClientServer> server;
281
        KTextEditor::MovingInterface *movingInterface;
282
        QUrl url;
283
        qint64 version;
284
285
        bool open : 1;
        bool modified : 1;
286
287
        // used for incremental update (if non-empty)
        QList<LSPTextDocumentContentChangeEvent> changes;
288
289
290
291
    };

    LSPClientPlugin *m_plugin;
    KTextEditor::MainWindow *m_mainWindow;
292
293
    // merged default and user config
    QJsonObject m_serverConfig;
294
295
    // root -> (mode -> server)
    QMap<QUrl, QMap<QString, QSharedPointer<LSPClientServer>>> m_servers;
296
    QHash<KTextEditor::Document *, DocumentInfo> m_docs;
297
    bool m_incrementalSync = false;
298

299
300
    typedef QVector<QSharedPointer<LSPClientServer>> ServerList;

301
302
public:
    LSPClientServerManagerImpl(LSPClientPlugin *plugin, KTextEditor::MainWindow *mainWin)
303
        : m_plugin(plugin), m_mainWindow(mainWin)
304
305
306
307
    {
        connect(plugin, &LSPClientPlugin::update, this, &self_type::updateServerConfig);
        QTimer::singleShot(100, this, &self_type::updateServerConfig);
    }
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

    ~LSPClientServerManagerImpl()
    {
        // stop everything as we go down
        // several stages;
        // stage 1; request shutdown of all servers (in parallel)
        // (give that some time)
        // stage 2; send TERM
        // stage 3; send KILL

        // stage 1
        QEventLoop q;
        QTimer t;
        connect(&t, &QTimer::timeout, &q, &QEventLoop::quit);

323
        auto run = [&q, &t](int ms) {
324
325
326
327
328
329
            t.setSingleShot(true);
            t.start(ms);
            q.exec();
        };

        int count = 0;
330
331
        for (const auto &el : m_servers) {
            for (const auto &s : el) {
332
                disconnect(s.data(), nullptr, this, nullptr);
Christoph Cullmann's avatar
Christoph Cullmann committed
333
                if (s->state() != LSPClientServer::State::None) {
334
                    auto handler = [&q, &count, s]() {
Christoph Cullmann's avatar
Christoph Cullmann committed
335
                        if (s->state() != LSPClientServer::State::None) {
336
337
338
339
340
                            if (--count == 0) {
                                q.quit();
                            }
                        }
                    };
341
                    connect(s.data(), &LSPClientServer::stateChanged, this, handler);
342
343
344
345
346
347
348
349
350
351
                    ++count;
                    s->stop(-1, -1);
                }
            }
        }
        run(500);

        // stage 2 and 3
        count = 0;
        for (count = 0; count < 2; ++count) {
352
353
            for (const auto &el : m_servers) {
                for (const auto &s : el) {
354
355
356
357
358
359
360
                    s->stop(count == 0 ? 1 : -1, count == 0 ? -1 : 1);
                }
            }
            run(100);
        }
    }

361
    void setIncrementalSync(bool inc) override { m_incrementalSync = inc; }
362

363
364
    QSharedPointer<LSPClientServer> findServer(KTextEditor::Document *document,
                                               bool updatedoc = true) override
365
366
367
368
369
370
371
372
373
374
375
376
    {
        if (!document || document->url().isEmpty())
            return nullptr;

        auto it = m_docs.find(document);
        auto server = it != m_docs.end() ? it->server : nullptr;
        if (!server) {
            if ((server = _findServer(document)))
                trackDocument(document, server);
        }

        if (server && updatedoc)
377
            update(server.data(), false);
378
379
380
        return server;
    }

381
382
383
384
385
    QSharedPointer<LSPClientServer> findServer(KTextEditor::View *view,
                                               bool updatedoc = true) override
    {
        return view ? findServer(view->document(), updatedoc) : nullptr;
    }
386

387
    // restart a specific server or all servers if server == nullptr
388
    void restart(LSPClientServer *server) override
389
390
391
    {
        ServerList servers;
        // find entry for server(s) and move out
392
393
        for (auto &m : m_servers) {
            for (auto it = m.begin(); it != m.end();) {
394
                if (!server || it->data() == server) {
395
396
397
398
399
400
401
402
403
404
                    servers.push_back(*it);
                    it = m.erase(it);
                } else {
                    ++it;
                }
            }
        }
        restart(servers);
    }

405
406
407
408
409
410
    virtual qint64 revision(KTextEditor::Document *doc) override
    {
        auto it = m_docs.find(doc);
        return it != m_docs.end() ? it->version : -1;
    }

411
    virtual LSPClientRevisionSnapshot *snapshot(LSPClientServer *server) override
412
413
414
415
416
417
418
419
420
421
422
423
    {
        auto result = new LSPClientRevisionSnapshotImpl;
        for (auto it = m_docs.begin(); it != m_docs.end(); ++it) {
            if (it->server == server) {
                // sync server to latest revision that will be recorded
                update(it.key(), false);
                result->add(it.key());
            }
        }
        return result;
    }

424
private:
425
426
427
    void showMessage(const QString &msg, KTextEditor::Message::MessageType level)
    {
        KTextEditor::View *view = m_mainWindow->activeView();
428
429
        if (!view || !view->document())
            return;
430
431
432
433
434
435
436
437
438
439

        auto kmsg = new KTextEditor::Message(xi18nc("@info", "<b>LSP Client:</b> %1", msg), level);
        kmsg->setPosition(KTextEditor::Message::AboveView);
        kmsg->setAutoHide(5000);
        kmsg->setAutoHideMode(KTextEditor::Message::Immediate);
        kmsg->setView(view);
        view->document()->postMessage(kmsg);
    }

    // caller ensures that servers are no longer present in m_servers
440
    void restart(const ServerList &servers)
441
442
    {
        // close docs
443
        for (const auto &server : servers) {
444
            // controlling server here, so disable usual state tracking response
445
            disconnect(server.data(), nullptr, this, nullptr);
446
            for (auto it = m_docs.begin(); it != m_docs.end();) {
447
448
449
450
451
452
453
454
455
456
457
458
459
460
                auto &item = it.value();
                if (item.server == server) {
                    // no need to close if server not in proper state
                    if (server->state() != LSPClientServer::State::Running) {
                        item.open = false;
                    }
                    it = _close(it, true);
                } else {
                    ++it;
                }
            }
        }

        // helper captures servers
461
462
        auto stopservers = [servers](int t, int k) {
            for (const auto &server : servers) {
463
464
465
466
467
468
469
470
471
                server->stop(t, k);
            }
        };

        // trigger server shutdown now
        stopservers(-1, -1);

        // initiate delayed stages (TERM and KILL)
        // async, so give a bit more time
472
473
        QTimer::singleShot(2 * TIMEOUT_SHUTDOWN, this, [stopservers]() { stopservers(1, -1); });
        QTimer::singleShot(4 * TIMEOUT_SHUTDOWN, this, [stopservers]() { stopservers(-1, 1); });
474
475
476
477

        // as for the start part
        // trigger interested parties, which will again request a server as needed
        // let's delay this; less chance for server instances to trip over each other
478
        QTimer::singleShot(6 * TIMEOUT_SHUTDOWN, this, [this]() { emit serverChanged(); });
479
480
481
482
483
484
485
486
487
    }

    void onStateChanged(LSPClientServer *server)
    {
        if (server->state() == LSPClientServer::State::Running) {
            // clear for normal operation
            emit serverChanged();
        } else if (server->state() == LSPClientServer::State::None) {
            // went down
488
489
490
            showMessage(i18n("Server terminated unexpectedly: %1",
                             server->cmdline().join(QLatin1Char(' '))),
                        KTextEditor::Message::Warning);
491
492
493
494
            restart(server);
        }
    }

495
    QSharedPointer<LSPClientServer> _findServer(KTextEditor::Document *document)
496
497
    {
        QObject *projectView = m_mainWindow->pluginView(QStringLiteral("kateprojectplugin"));
498
499
500
501
        const auto projectBase =
                QDir(projectView ? projectView->property("projectBaseDir").toString() : QString());
        const auto &projectMap =
                projectView ? projectView->property("projectMap").toMap() : QVariantMap();
502

503
504
505
        // compute the LSP standardized language id
        auto langId = languageId(document->highlightingMode());

506
        // merge with project specific
507
508
509
510
        auto projectConfig = QJsonDocument::fromVariant(projectMap)
                                     .object()
                                     .value(QStringLiteral("lspclient"))
                                     .toObject();
511
512
513
514
515
516
        auto serverConfig = merge(m_serverConfig, projectConfig);

        // locate server config
        QJsonValue config;
        QSet<QString> used;
        while (true) {
517
518
519
            qCInfo(LSPCLIENT) << "language id " << langId;
            used << langId;
            config = serverConfig.value(QStringLiteral("servers")).toObject().value(langId);
520
            if (config.isObject()) {
521
                const auto &base = config.toObject().value(QStringLiteral("use")).toString();
522
523
                // basic cycle detection
                if (!base.isEmpty() && !used.contains(base)) {
524
                    langId = base;
525
526
527
528
529
530
531
532
533
534
                    continue;
                }
            }
            break;
        }

        if (!config.isObject())
            return nullptr;

        // merge global settings
535
536
        serverConfig =
                merge(serverConfig.value(QStringLiteral("global")).toObject(), config.toObject());
537
538
539
540
541
542
543
544
545
546
547

        QString rootpath;
        auto rootv = serverConfig.value(QStringLiteral("root"));
        if (rootv.isString()) {
            auto sroot = rootv.toString();
            if (QDir::isAbsolutePath(sroot)) {
                rootpath = sroot;
            } else if (!projectBase.isEmpty()) {
                rootpath = QDir(projectBase).absoluteFilePath(sroot);
            }
        }
548
549
550

        /**
         * no explicit set root dir? search for a matching root based on some name filters
551
552
         * this is required for some LSP servers like rls that don't handle that on their own like
         * clangd does
553
554
         */
        if (rootpath.isEmpty()) {
555
556
            const auto fileNamesForDetection =
                    serverConfig.value(QStringLiteral("rootIndicationFileNames"));
557
558
559
560
561
            if (fileNamesForDetection.isArray()) {
                // we try each file name alternative in the listed order
                // this allows to have preferences
                for (auto name : fileNamesForDetection.toArray()) {
                    if (name.isString()) {
562
563
                        rootpath =
                                rootForDocumentAndRootIndicationFileName(document, name.toString());
564
565
566
567
568
569
570
571
572
                        if (!rootpath.isEmpty()) {
                            break;
                        }
                    }
                }
            }
        }

        // last fallback: home directory
573
574
575
576
577
        if (rootpath.isEmpty()) {
            rootpath = QDir::homePath();
        }

        auto root = QUrl::fromLocalFile(rootpath);
578
        auto server = m_servers.value(root).value(langId);
579
        if (!server) {
580
            QStringList cmdline;
581
582

            // choose debug command line for debug mode, fallback to command
583
584
585
            auto vcmdline =
                    serverConfig.value(m_plugin->m_debugMode ? QStringLiteral("commandDebug")
                                                             : QStringLiteral("command"));
586
587
588
589
            if (vcmdline.isUndefined()) {
                vcmdline = serverConfig.value(QStringLiteral("command"));
            }

590
591
592
            auto scmdline = vcmdline.toString();
            if (!scmdline.isEmpty()) {
                cmdline = scmdline.split(QLatin1Char(' '));
593
            } else {
594
                for (const auto &c : vcmdline.toArray()) {
595
596
597
598
                    cmdline.push_back(c.toString());
                }
            }
            if (cmdline.length() > 0) {
599
600
601
                server.reset(new LSPClientServer(
                        cmdline, root,
                        serverConfig.value(QStringLiteral("initializationOptions"))));
602
                m_servers[root][langId] = server;
603
604
                connect(server.data(), &LSPClientServer::stateChanged, this,
                        &self_type::onStateChanged, Qt::UniqueConnection);
605
606
                if (!server->start()) {
                    showMessage(i18n("Failed to start server: %1", cmdline.join(QLatin1Char(' '))),
607
                                KTextEditor::Message::Error);
608
                }
609
610
611
612
613
            }
        }
        return (server && server->state() == LSPClientServer::State::Running) ? server : nullptr;
    }

614
615
    void updateServerConfig()
    {
616
617
618
619
620
        // default configuration, compiled into plugin resource, reading can't fail
        QFile defaultConfigFile(QStringLiteral(":/lspclient/settings.json"));
        defaultConfigFile.open(QIODevice::ReadOnly);
        Q_ASSERT(defaultConfigFile.isOpen());
        m_serverConfig = QJsonDocument::fromJson(defaultConfigFile.readAll()).object();
621
622

        // consider specified configuration
623
        const auto &configPath = m_plugin->m_configPath.path();
624
625
626
627
628
629
630
631
632
        if (!configPath.isEmpty()) {
            QFile f(configPath);
            if (f.open(QIODevice::ReadOnly)) {
                auto data = f.readAll();
                auto json = QJsonDocument::fromJson(data);
                if (json.isObject()) {
                    m_serverConfig = merge(m_serverConfig, json.object());
                } else {
                    showMessage(i18n("Failed to parse server configuration: %1", configPath),
633
                                KTextEditor::Message::Error);
634
635
636
                }
            } else {
                showMessage(i18n("Failed to read server configuration: %1", configPath),
637
                            KTextEditor::Message::Error);
638
639
640
641
642
643
644
645
646
            }
        }

        // we could (but do not) perform restartAll here;
        // for now let's leave that up to user
        // but maybe we do have a server now where not before, so let's signal
        emit serverChanged();
    }

Filip Gawin's avatar
Filip Gawin committed
647
    void trackDocument(KTextEditor::Document *doc, const QSharedPointer<LSPClientServer>& server)
648
649
650
    {
        auto it = m_docs.find(doc);
        if (it == m_docs.end()) {
651
652
653
            KTextEditor::MovingInterface *miface =
                    qobject_cast<KTextEditor::MovingInterface *>(doc);
            it = m_docs.insert(doc, { server, miface, doc->url(), 0, false, false, {} });
654
            // track document
655
656
657
658
659
660
661
662
663
664
            connect(doc, &KTextEditor::Document::documentUrlChanged, this, &self_type::untrack,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::highlightingModeChanged, this, &self_type::untrack,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::aboutToClose, this, &self_type::untrack,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::destroyed, this, &self_type::untrack,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::textChanged, this, &self_type::onTextChanged,
                    Qt::UniqueConnection);
665
            // in case of incremental change
666
667
668
669
670
671
672
673
            connect(doc, &KTextEditor::Document::textInserted, this, &self_type::onTextInserted,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::textRemoved, this, &self_type::onTextRemoved,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::lineWrapped, this, &self_type::onLineWrapped,
                    Qt::UniqueConnection);
            connect(doc, &KTextEditor::Document::lineUnwrapped, this, &self_type::onLineUnwrapped,
                    Qt::UniqueConnection);
674
675
676
677
678
        } else {
            it->server = server;
        }
    }

679
    decltype(m_docs)::iterator _close(decltype(m_docs)::iterator it, bool remove)
680
681
682
683
684
685
686
687
    {
        if (it != m_docs.end()) {
            if (it->open) {
                // release server side (use url as registered with)
                (it->server)->didClose(it->url);
                it->open = false;
            }
            if (remove) {
688
689
                disconnect(it.key(), nullptr, this, nullptr);
                it = m_docs.erase(it);
690
691
            }
        }
692
        return it;
693
694
    }

695
696
697
698
699
700
701
702
703
704
    void _close(KTextEditor::Document *doc, bool remove)
    {
        auto it = m_docs.find(doc);
        if (it != m_docs.end()) {
            _close(it, remove);
        }
    }

    void untrack(QObject *doc)
    {
705
        _close(qobject_cast<KTextEditor::Document *>(doc), true);
706
707
708
        emit serverChanged();
    }

709
    void close(KTextEditor::Document *doc) { _close(doc, false); }
710

711
    void update(const decltype(m_docs)::iterator &it, bool force)
712
    {
713
        auto doc = it.key();
714
        if (it != m_docs.end() && it->server) {
715
716
717
718
719
            if (it->movingInterface) {
                it->version = it->movingInterface->revision();
            } else if (it->modified) {
                ++it->version;
            }
720
721
722
            if (!m_incrementalSync) {
                it->changes.clear();
            }
723
            if (it->open) {
724
                if (it->modified || force) {
725
726
727
728
                    (it->server)
                            ->didChange(it->url, it->version,
                                        (it->changes.size() == 0) ? doc->text() : QString(),
                                        it->changes);
729
                }
730
            } else {
731
732
733
                (it->server)
                        ->didOpen(it->url, it->version, languageId(doc->highlightingMode()),
                                  doc->text());
734
735
                it->open = true;
            }
736
737
            it->modified = false;
            it->changes.clear();
738
739
        }
    }
740

741
742
743
744
745
    void update(KTextEditor::Document *doc, bool force) override
    {
        update(m_docs.find(doc), force);
    }

746
    void update(LSPClientServer *server, bool force)
747
748
749
    {
        for (auto it = m_docs.begin(); it != m_docs.end(); ++it) {
            if (it->server == server) {
750
                update(it, force);
751
752
753
754
755
756
757
758
759
760
761
            }
        }
    }

    void onTextChanged(KTextEditor::Document *doc)
    {
        auto it = m_docs.find(doc);
        if (it != m_docs.end()) {
            it->modified = true;
        }
    }
762

763
    DocumentInfo *getDocumentInfo(KTextEditor::Document *doc)
764
765
766
767
768
769
    {
        if (!m_incrementalSync)
            return nullptr;

        auto it = m_docs.find(doc);
        if (it != m_docs.end() && it->server) {
770
            const auto &caps = it->server->capabilities();
771
772
773
774
775
776
777
            if (caps.textDocumentSync == LSPDocumentSyncKind::Incremental) {
                return &(*it);
            }
        }
        return nullptr;
    }

778
779
    void onTextInserted(KTextEditor::Document *doc, const KTextEditor::Cursor &position,
                        const QString &text)
780
781
782
    {
        auto info = getDocumentInfo(doc);
        if (info) {
783
            info->changes.push_back({ LSPRange { position, position }, text });
784
785
786
        }
    }

787
788
    void onTextRemoved(KTextEditor::Document *doc, const KTextEditor::Range &range,
                       const QString &text)
789
790
791
792
    {
        (void)text;
        auto info = getDocumentInfo(doc);
        if (info) {
793
            info->changes.push_back({ range, QString() });
794
795
796
797
798
799
800
        }
    }

    void onLineWrapped(KTextEditor::Document *doc, const KTextEditor::Cursor &position)
    {
        // so a 'newline' has been inserted at position
        // could have been UNIX style or other kind, let's ask the document
801
        auto text = doc->text({ position, { position.line() + 1, 0 } });
802
803
804
805
806
807
808
809
810
        onTextInserted(doc, position, text);
    }

    void onLineUnwrapped(KTextEditor::Document *doc, int line)
    {
        // lines line-1 and line got replaced by current content of line-1
        Q_ASSERT(line > 0);
        auto info = getDocumentInfo(doc);
        if (info) {
811
812
            LSPRange oldrange { { line - 1, 0 }, { line + 1, 0 } };
            LSPRange newrange { { line - 1, 0 }, { line, 0 } };
813
            auto text = doc->text(newrange);
814
            info->changes.push_back({ oldrange, text });
815
816
        }
    }
817
818
819
820
821
822
823
824
825
};

QSharedPointer<LSPClientServerManager>
LSPClientServerManager::new_(LSPClientPlugin *plugin, KTextEditor::MainWindow *mainWin)
{
    return QSharedPointer<LSPClientServerManager>(new LSPClientServerManagerImpl(plugin, mainWin));
}

#include "lspclientservermanager.moc"