diff --git a/addons/lspclient/lspclientpluginview.cpp b/addons/lspclient/lspclientpluginview.cpp index f3d4b41f6..01201855b 100644 --- a/addons/lspclient/lspclientpluginview.cpp +++ b/addons/lspclient/lspclientpluginview.cpp @@ -1,1532 +1,1532 @@ /* SPDX-License-Identifier: MIT Copyright (C) 2019 Mark Nauwelaerts 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. */ #include "lspclientpluginview.h" #include "lspclientsymbolview.h" #include "lspclientplugin.h" #include "lspclientservermanager.h" #include "lspclientcompletion.h" #include "lspclienthover.h" #include "lspclient_debug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace RangeData { enum { // preserve UserRole for generic use where needed FileUrlRole = Qt::UserRole + 1, RangeRole, KindRole, }; class KindEnum { public: enum _kind { Text = (int) LSPDocumentHighlightKind::Text, Read = (int) LSPDocumentHighlightKind::Read, Write = (int) LSPDocumentHighlightKind::Write, Error = 10 + (int) LSPDiagnosticSeverity::Error, Warning = 10 + (int) LSPDiagnosticSeverity::Warning, Information = 10 + (int) LSPDiagnosticSeverity::Information, Hint = 10 + (int) LSPDiagnosticSeverity::Hint, Related }; KindEnum(int v) { m_value = (_kind) v; } KindEnum(LSPDocumentHighlightKind hl) : KindEnum((_kind) (hl)) {} KindEnum(LSPDiagnosticSeverity sev) : KindEnum(_kind(10 + (int) sev)) {} operator _kind() { return m_value; } private: _kind m_value; }; static constexpr KTextEditor::MarkInterface::MarkTypes markType = KTextEditor::MarkInterface::markType31; static constexpr KTextEditor::MarkInterface::MarkTypes markTypeDiagError = KTextEditor::MarkInterface::Error; static constexpr KTextEditor::MarkInterface::MarkTypes markTypeDiagWarning = KTextEditor::MarkInterface::Warning; static constexpr KTextEditor::MarkInterface::MarkTypes markTypeDiagOther = KTextEditor::MarkInterface::markType30; static constexpr KTextEditor::MarkInterface::MarkTypes markTypeDiagAll = KTextEditor::MarkInterface::MarkTypes (markTypeDiagError | markTypeDiagWarning | markTypeDiagOther); } static QIcon diagnosticsIcon(LSPDiagnosticSeverity severity) { #define RETURN_CACHED_ICON(name) \ { \ static QIcon icon(QIcon::fromTheme(QStringLiteral(name))); \ return icon; \ } switch (severity) { case LSPDiagnosticSeverity::Error: RETURN_CACHED_ICON("dialog-error") case LSPDiagnosticSeverity::Warning: RETURN_CACHED_ICON("dialog-warning") case LSPDiagnosticSeverity::Information: case LSPDiagnosticSeverity::Hint: RETURN_CACHED_ICON("dialog-information") default: break; } return QIcon(); } static QIcon codeActionIcon() { static QIcon icon(QIcon::fromTheme(QStringLiteral("insert-text"))); return icon; } KTextEditor::Document* findDocument(KTextEditor::MainWindow *mainWindow, const QUrl & url) { auto views = mainWindow->views(); for (const auto v: views) { auto doc = v->document(); if (doc && doc->url() == url) return doc; } return nullptr; } // helper to read lines from unopened documents // lightweight and does not require additional symbols class FileLineReader { QFile file; int lastLineNo = -1; QString lastLine; public: FileLineReader(const QUrl & url) : file(url.path()) { file.open(QIODevice::ReadOnly); } // called with non-descending lineno QString line(int lineno) { if (lineno == lastLineNo) { return lastLine; } while (file.isOpen() && !file.atEnd()) { auto line = file.readLine(); if (++lastLineNo == lineno) { QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QString text = codec->toUnicode(line.constData(), line.size(), &state); if (state.invalidChars > 0) { text = QString::fromLatin1(line); } while (text.size() && text.at(text.size() -1).isSpace()) text.chop(1); lastLine = text; return text; } } return QString(); } }; class LSPClientActionView : public QObject { Q_OBJECT typedef LSPClientActionView self_type; LSPClientPlugin *m_plugin; KTextEditor::MainWindow *m_mainWindow; KXMLGUIClient *m_client; QSharedPointer m_serverManager; QScopedPointer m_viewTracker; QScopedPointer m_completion; QScopedPointer m_hover; QScopedPointer m_symbolView; QPointer m_findDef; QPointer m_findDecl; QPointer m_findRef; QPointer m_triggerHighlight; QPointer m_triggerHover; QPointer m_triggerFormat; QPointer m_triggerRename; QPointer m_complDocOn; QPointer m_refDeclaration; QPointer m_diagnostics; QPointer m_diagnosticsHighlight; QPointer m_diagnosticsMark; QPointer m_restartServer; QPointer m_restartAll; // toolview QScopedPointer m_toolView; QPointer m_tabWidget; // applied search ranges typedef QMultiHash RangeCollection; RangeCollection m_ranges; // modelis either owned by tree added to tabwidget or owned here QScopedPointer m_ownedModel; // in either case, the model that directs applying marks/ranges QPointer m_markModel; // goto definition and declaration jump list is more a menu than a // search result, so let's not keep adding new tabs for those // previous tree for definition result QPointer m_defTree; // ... and for declaration QPointer m_declTree; // diagnostics tab QPointer m_diagnosticsTree; // tree widget is either owned here or by tab QScopedPointer m_diagnosticsTreeOwn; QScopedPointer m_diagnosticsModel; // diagnostics ranges RangeCollection m_diagnosticsRanges; // views on which completions have been registered QSet m_completionViews; // views on which hovers have been registered QSet m_hoverViews; // outstanding request LSPClientServer::RequestHandle m_handle; // timeout on request bool m_req_timeout = false; // accept incoming applyEdit bool m_accept_edit = false; KActionCollection *actionCollection() const { return m_client->actionCollection(); } public: LSPClientActionView(LSPClientPlugin *plugin, KTextEditor::MainWindow *mainWin, KXMLGUIClient *client, QSharedPointer serverManager) : QObject(mainWin), m_plugin(plugin), m_mainWindow(mainWin), m_client(client), m_serverManager(serverManager), m_completion(LSPClientCompletion::new_(m_serverManager)), m_hover(LSPClientHover::new_(m_serverManager)), m_symbolView(LSPClientSymbolView::new_(plugin, mainWin, m_serverManager)) { connect(m_mainWindow, &KTextEditor::MainWindow::viewChanged, this, &self_type::updateState); connect(m_mainWindow, &KTextEditor::MainWindow::unhandledShortcutOverride, this, &self_type::handleEsc); connect(m_serverManager.get(), &LSPClientServerManager::serverChanged, this, &self_type::updateState); m_findDef = actionCollection()->addAction(QStringLiteral("lspclient_find_definition"), this, &self_type::goToDefinition); m_findDef->setText(i18n("Go to Definition")); m_findDecl = actionCollection()->addAction(QStringLiteral("lspclient_find_declaration"), this, &self_type::goToDeclaration); m_findDecl->setText(i18n("Go to Declaration")); m_findRef = actionCollection()->addAction(QStringLiteral("lspclient_find_references"), this, &self_type::findReferences); m_findRef->setText(i18n("Find References")); m_triggerHighlight = actionCollection()->addAction(QStringLiteral("lspclient_highlight"), this, &self_type::highlight); m_triggerHighlight->setText(i18n("Highlight")); // perhaps hover suggests to do so on mouse-over, // but let's just use a (convenient) action/shortcut for it m_triggerHover = actionCollection()->addAction(QStringLiteral("lspclient_hover"), this, &self_type::hover); m_triggerHover->setText(i18n("Hover")); m_triggerFormat = actionCollection()->addAction(QStringLiteral("lspclient_format"), this, &self_type::format); m_triggerFormat->setText(i18n("Format")); m_triggerRename = actionCollection()->addAction(QStringLiteral("lspclient_rename"), this, &self_type::rename); m_triggerRename->setText(i18n("Rename")); // general options m_complDocOn = actionCollection()->addAction(QStringLiteral("lspclient_completion_doc"), this, &self_type::displayOptionChanged); m_complDocOn->setText(i18n("Show selected completion documentation")); m_complDocOn->setCheckable(true); m_refDeclaration = actionCollection()->addAction(QStringLiteral("lspclient_references_declaration"), this, &self_type::displayOptionChanged); m_refDeclaration->setText(i18n("Include declaration in references")); m_refDeclaration->setCheckable(true); // diagnostics m_diagnostics = actionCollection()->addAction(QStringLiteral("lspclient_diagnostics"), this, &self_type::displayOptionChanged); m_diagnostics->setText(i18n("Show diagnostics notifications")); m_diagnostics->setCheckable(true); m_diagnosticsHighlight = actionCollection()->addAction(QStringLiteral("lspclient_diagnostics_highlight"), this, &self_type::displayOptionChanged); m_diagnosticsHighlight->setText(i18n("Show diagnostics highlights")); m_diagnosticsHighlight->setCheckable(true); m_diagnosticsMark = actionCollection()->addAction(QStringLiteral("lspclient_diagnostics_mark"), this, &self_type::displayOptionChanged); m_diagnosticsMark->setText(i18n("Show diagnostics marks")); m_diagnosticsMark->setCheckable(true); // server control m_restartServer = actionCollection()->addAction(QStringLiteral("lspclient_restart_server"), this, &self_type::restartCurrent); m_restartServer->setText(i18n("Restart LSP Server")); m_restartAll = actionCollection()->addAction(QStringLiteral("lspclient_restart_all"), this, &self_type::restartAll); m_restartAll->setText(i18n("Restart All LSP Servers")); // popup menu auto menu = new KActionMenu(i18n("LSP Client"), this); actionCollection()->addAction(QStringLiteral("popup_lspclient"), menu); menu->addAction(m_findDef); menu->addAction(m_findDecl); menu->addAction(m_findRef); menu->addAction(m_triggerHighlight); menu->addAction(m_triggerHover); menu->addAction(m_triggerFormat); menu->addAction(m_triggerRename); menu->addSeparator(); menu->addAction(m_complDocOn); menu->addAction(m_refDeclaration); menu->addSeparator(); menu->addAction(m_diagnostics); menu->addAction(m_diagnosticsHighlight); menu->addAction(m_diagnosticsMark); menu->addSeparator(); menu->addAction(m_restartServer); menu->addAction(m_restartAll); // sync with plugin settings if updated connect(m_plugin, &LSPClientPlugin::update, this, &self_type::configUpdated); // toolview m_toolView.reset(mainWin->createToolView(plugin, QStringLiteral("kate_lspclient"), KTextEditor::MainWindow::Bottom, QIcon::fromTheme(QStringLiteral("application-x-ms-dos-executable")), i18n("LSP Client"))); m_tabWidget = new QTabWidget(m_toolView.get()); m_toolView->layout()->addWidget(m_tabWidget); m_tabWidget->setFocusPolicy(Qt::NoFocus); m_tabWidget->setTabsClosable(true); KAcceleratorManager::setNoAccel(m_tabWidget); connect(m_tabWidget, &QTabWidget::tabCloseRequested, this, &self_type::tabCloseRequested); // diagnostics tab m_diagnosticsTree = new QTreeView(); configureTreeView(m_diagnosticsTree); m_diagnosticsTree->setAlternatingRowColors(true); m_diagnosticsTreeOwn.reset(m_diagnosticsTree); m_diagnosticsModel.reset(new QStandardItemModel()); m_diagnosticsModel->setColumnCount(2); m_diagnosticsTree->setModel(m_diagnosticsModel.get()); connect(m_diagnosticsTree, &QTreeView::clicked, this, &self_type::goToItemLocation); connect(m_diagnosticsTree, &QTreeView::doubleClicked, this, &self_type::triggerCodeAction); // track position in view to sync diagnostics list m_viewTracker.reset(LSPClientViewTracker::new_(plugin, mainWin, 0, 500)); connect(m_viewTracker.get(), &LSPClientViewTracker::newState, this, &self_type::onViewState); configUpdated(); updateState(); } ~LSPClientActionView() { // unregister all code-completion providers, else we might crash for (auto view : qAsConst(m_completionViews)) { qobject_cast(view)->unregisterCompletionModel(m_completion.get()); } // unregister all text-hint providers, else we might crash for (auto view : qAsConst(m_hoverViews)) { qobject_cast(view)->unregisterTextHintProvider(m_hover.get()); } clearAllLocationMarks(); clearAllDiagnosticsMarks(); } void configureTreeView(QTreeView *treeView) { treeView->setHeaderHidden(true); treeView->setFocusPolicy(Qt::NoFocus); treeView->setLayoutDirection(Qt::LeftToRight); treeView->setSortingEnabled(false); treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); } void displayOptionChanged() { m_diagnosticsHighlight->setEnabled(m_diagnostics->isChecked()); m_diagnosticsMark->setEnabled(m_diagnostics->isChecked()); auto index = m_tabWidget->indexOf(m_diagnosticsTree); // setTabEnabled may still show it ... so let's be more forceful if (m_diagnostics->isChecked() && m_diagnosticsTreeOwn) { m_diagnosticsTreeOwn.take(); m_tabWidget->insertTab(0, m_diagnosticsTree, i18nc("@title:tab", "Diagnostics")); } else if (!m_diagnostics->isChecked() && !m_diagnosticsTreeOwn) { m_diagnosticsTreeOwn.reset(m_diagnosticsTree); m_tabWidget->removeTab(index); } updateState(); } void configUpdated() { if (m_complDocOn) m_complDocOn->setChecked(m_plugin->m_complDoc); if (m_refDeclaration) m_refDeclaration->setChecked(m_plugin->m_refDeclaration); if (m_diagnostics) m_diagnostics->setChecked(m_plugin->m_diagnostics); if (m_diagnosticsHighlight) m_diagnosticsHighlight->setChecked(m_plugin->m_diagnosticsHighlight); if (m_diagnosticsMark) m_diagnosticsMark->setChecked(m_plugin->m_diagnosticsMark); displayOptionChanged(); } void restartCurrent() { KTextEditor::View *activeView = m_mainWindow->activeView(); auto server = m_serverManager->findServer(activeView); if (server) m_serverManager->restart(server.get()); } void restartAll() { m_serverManager->restart(nullptr); } static void clearMarks(KTextEditor::Document *doc, RangeCollection & ranges, uint markType) { KTextEditor::MarkInterface* iface = qobject_cast(doc); if (iface) { const QHash marks = iface->marks(); QHashIterator i(marks); while (i.hasNext()) { i.next(); if (i.value()->type & markType) { iface->removeMark(i.value()->line, markType); } } } for (auto it = ranges.find(doc); it != ranges.end() && it.key() == doc;) { delete it.value(); it = ranges.erase(it); } } static void clearMarks(RangeCollection & ranges, uint markType) { while (!ranges.empty()) { clearMarks(ranges.begin().key(), ranges, markType); } } Q_SLOT void clearAllMarks(KTextEditor::Document *doc) { clearMarks(doc, m_ranges, RangeData::markType); clearMarks(doc, m_diagnosticsRanges, RangeData::markTypeDiagAll); } void clearAllLocationMarks() { clearMarks(m_ranges, RangeData::markType); // no longer add any again m_ownedModel.reset(); m_markModel.clear(); } void clearAllDiagnosticsMarks() { clearMarks(m_diagnosticsRanges, RangeData::markTypeDiagAll); } void addMarks(KTextEditor::Document *doc, QStandardItem *item, RangeCollection & ranges) { Q_ASSERT(item); KTextEditor::MovingInterface* miface = qobject_cast(doc); KTextEditor::MarkInterface* iface = qobject_cast(doc); KTextEditor::View* activeView = m_mainWindow->activeView(); KTextEditor::ConfigInterface* ciface = qobject_cast(activeView); if (!miface || !iface) return; auto url = item->data(RangeData::FileUrlRole).toUrl(); if (url != doc->url()) return; KTextEditor::Range range = item->data(RangeData::RangeRole).value(); auto line = range.start().line(); RangeData::KindEnum kind = (RangeData::KindEnum) item->data(RangeData::KindRole).toInt(); KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute()); bool enabled = m_diagnostics && m_diagnostics->isChecked() && m_diagnosticsHighlight && m_diagnosticsHighlight->isChecked(); KTextEditor::MarkInterface::MarkTypes markType = RangeData::markType; switch (kind) { case RangeData::KindEnum::Text: { // well, it's a bit like searching for something, so re-use that color QColor rangeColor = Qt::yellow; if (ciface) { rangeColor = ciface->configValue(QStringLiteral("search-highlight-color")).value(); } attr->setBackground(rangeColor); enabled = true; break; } // FIXME are there any symbolic/configurable ways to pick these colors? case RangeData::KindEnum::Read: attr->setBackground(Qt::green); enabled = true; break; case RangeData::KindEnum::Write: attr->setBackground(Qt::red); enabled = true; break; // use underlining for diagnostics to avoid lots of fancy flickering case RangeData::KindEnum::Error: markType = RangeData::markTypeDiagError; attr->setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); attr->setUnderlineColor(Qt::red); break; case RangeData::KindEnum::Warning: markType = RangeData::markTypeDiagWarning; attr->setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); attr->setUnderlineColor(QColor(255, 128, 0)); break; case RangeData::KindEnum::Information: case RangeData::KindEnum::Hint: case RangeData::KindEnum::Related: markType = RangeData::markTypeDiagOther; attr->setUnderlineStyle(QTextCharFormat::DashUnderline); attr->setUnderlineColor(Qt::blue); break; } if (activeView) { attr->setForeground(activeView->defaultStyleAttribute(KTextEditor::dsNormal)->foreground().color()); } // highlight the range if (enabled) { KTextEditor::MovingRange* mr = miface->newMovingRange(range); mr->setAttribute(attr); mr->setZDepth(-90000.0); // Set the z-depth to slightly worse than the selection mr->setAttributeOnlyForViews(true); ranges.insert(doc, mr); } // add match mark for range const int ps = 32; bool handleClick = true; enabled = m_diagnostics && m_diagnostics->isChecked() && m_diagnosticsMark && m_diagnosticsMark->isChecked(); switch (markType) { case RangeData::markType: iface->setMarkDescription(markType, i18n("RangeHighLight")); iface->setMarkPixmap(markType, QIcon().pixmap(0, 0)); handleClick = false; enabled = true; break; case RangeData::markTypeDiagError: iface->setMarkDescription(markType, i18n("Error")); iface->setMarkPixmap(markType, diagnosticsIcon(LSPDiagnosticSeverity::Error).pixmap(ps, ps)); break; case RangeData::markTypeDiagWarning: iface->setMarkDescription(markType, i18n("Warning")); iface->setMarkPixmap(markType, diagnosticsIcon(LSPDiagnosticSeverity::Warning).pixmap(ps, ps)); break; case RangeData::markTypeDiagOther: iface->setMarkDescription(markType, i18n("Information")); iface->setMarkPixmap(markType, diagnosticsIcon(LSPDiagnosticSeverity::Information).pixmap(ps, ps)); break; default: Q_ASSERT(false); break; } if (enabled) iface->addMark(line, markType); // ensure runtime match connect(doc, SIGNAL(aboutToInvalidateMovingInterfaceContent(KTextEditor::Document*)), this, SLOT(clearAllMarks(KTextEditor::Document*)), Qt::UniqueConnection); connect(doc, SIGNAL(aboutToDeleteMovingInterfaceContent(KTextEditor::Document*)), this, SLOT(clearAllMarks(KTextEditor::Document*)), Qt::UniqueConnection); if (handleClick) { connect(doc, SIGNAL(markClicked(KTextEditor::Document*, KTextEditor::Mark, bool&)), this, SLOT(onMarkClicked(KTextEditor::Document*,KTextEditor::Mark, bool&)), Qt::UniqueConnection); } } void addMarksRec(KTextEditor::Document *doc, QStandardItem *item, RangeCollection & ranges) { Q_ASSERT(item); addMarks(doc, item, ranges); for (int i = 0; i < item->rowCount(); ++i) { addMarksRec(doc, item->child(i), ranges); } } void addMarks(KTextEditor::Document *doc, QStandardItemModel *treeModel, RangeCollection & ranges) { // check if already added if (ranges.contains(doc)) return; Q_ASSERT(treeModel); addMarksRec(doc, treeModel->invisibleRootItem(), ranges); } void goToDocumentLocation(const QUrl & uri, int line, int column) { KTextEditor::View *activeView = m_mainWindow->activeView(); if (!activeView || uri.isEmpty() || line < 0 || column < 0) return; KTextEditor::Document *document = activeView->document(); KTextEditor::Cursor cdef(line, column); if (document && uri == document->url()) { activeView->setCursorPosition(cdef); } else { KTextEditor::View *view = m_mainWindow->openUrl(uri); if (view) { view->setCursorPosition(cdef); } } } void goToItemLocation(const QModelIndex & index) { auto url = index.data(RangeData::FileUrlRole).toUrl(); auto start = index.data(RangeData::RangeRole).value().start(); goToDocumentLocation(url, start.line(), start.column()); } // custom item subclass that captures additional attributes; // a bit more convenient than the variant/role way struct DiagnosticItem : public QStandardItem { LSPDiagnostic m_diagnostic; LSPCodeAction m_codeAction; QSharedPointer m_snapshot; DiagnosticItem(const LSPDiagnostic & d) : m_diagnostic(d) {} DiagnosticItem(const LSPCodeAction & c, QSharedPointer s) : m_codeAction(c), m_snapshot(s) { m_diagnostic.range = LSPRange::invalid(); } bool isCodeAction() { return !m_diagnostic.range.isValid() && m_codeAction.title.size(); } }; // double click on: // diagnostic item -> request and add actions (below item) // code action -> perform action (literal edit and/or execute command) // (execution of command may lead to an applyEdit request from server) void triggerCodeAction(const QModelIndex & index) { KTextEditor::View *activeView = m_mainWindow->activeView(); QPointer document = activeView->document(); auto server = m_serverManager->findServer(activeView); auto it = dynamic_cast(m_diagnosticsModel->itemFromIndex(index)); if (!server || !document || !it) return; // click on an action ? if (it->isCodeAction()) { auto& action = it->m_codeAction; // apply edit before command applyWorkspaceEdit(action.edit, it->m_snapshot.get()); const auto &command = action.command; if (command.command.size()) { // accept edit requests that may be sent to execute command m_accept_edit = true; // but only for a short time QTimer::singleShot(2000, this, [this] { m_accept_edit = false; }); server->executeCommand(command.command, command.arguments); } return; } // only engage action if // * active document matches diagnostic document // * if really clicked a diagnostic item // (which is the case as it != nullptr and not a code action) // * if no code action invoked and added already // (note; related items are also children) auto url = it->data(RangeData::FileUrlRole).toUrl(); if (url != document->url() || it->data(Qt::UserRole).toBool()) return; // store some things to find item safely later on QPersistentModelIndex pindex(index); QSharedPointer snapshot(m_serverManager->snapshot(server.get())); auto h = [this, url, snapshot, pindex] (const QList actions) { if (!pindex.isValid()) return; auto child = m_diagnosticsModel->itemFromIndex(pindex); if (!child) return; // add actions below diagnostic item for (const auto &action: actions) { auto item = new DiagnosticItem(action, snapshot); child->appendRow(item); auto text = action.kind.size() ? QStringLiteral("[%1] %2").arg(action.kind).arg(action.title) : action.title; item->setData(text, Qt::DisplayRole); item->setData(codeActionIcon(), Qt::DecorationRole); } m_diagnosticsTree->setExpanded(child->index(), true); // mark actions added child->setData(true, Qt::UserRole); }; auto range = activeView->selectionRange(); if (!range.isValid()) { range = document->documentRange(); } server->documentCodeAction(url, range, {}, {it->m_diagnostic}, this, h); } void tabCloseRequested(int index) { auto widget = m_tabWidget->widget(index); if (widget != m_diagnosticsTree) { if (widget == m_markModel->parent()) { clearAllLocationMarks(); } delete widget; } } // local helper to overcome some differences in LSP types struct RangeItem { QUrl uri; LSPRange range; LSPDocumentHighlightKind kind; }; static bool compareRangeItem(const RangeItem & a, const RangeItem & b) { return (a.uri < b.uri) || ((a.uri == b.uri) && a.range < b.range); } // provide Qt::DisplayRole (text) line lazily; // only find line's text content when so requested // This may then involve opening reading some file, at which time // all items for that file will be resolved in one go. struct LineItem : public QStandardItem { KTextEditor::MainWindow *m_mainWindow; LineItem(KTextEditor::MainWindow *mainWindow) : m_mainWindow(mainWindow) {} QVariant data(int role = Qt::UserRole + 1) const override { auto rootItem = this->parent(); if (role != Qt::DisplayRole || !rootItem) { return QStandardItem::data(role); } auto line = data(Qt::UserRole); // either of these mean we tried to obtain line already if (line.isValid() || rootItem->data(RangeData::KindRole).toBool()) { return QStandardItem::data(role).toString().append(line.toString()); } KTextEditor::Document *doc = nullptr; QScopedPointer fr; for (int i = 0; i < rootItem->rowCount(); i++) { auto child = rootItem->child(i); if (i == 0) { auto url = child->data(RangeData::FileUrlRole).toUrl(); doc = findDocument(m_mainWindow, url); if (!doc) { fr.reset(new FileLineReader(url)); } } auto lineno = child->data(RangeData::RangeRole).value().start().line(); auto line = doc ? doc->line(lineno) : fr->line(lineno); child->setData(line, Qt::UserRole); } // mark as processed rootItem->setData(RangeData::KindRole, true); // should work ok return data(role); } }; LSPRange transformRange(const QUrl & url, const LSPClientRevisionSnapshot & snapshot, const LSPRange & range) { KTextEditor::MovingInterface *miface; qint64 revision; auto result = range; snapshot.find(url, miface, revision); if (miface) { miface->transformRange(result, KTextEditor::MovingRange::DoNotExpand, KTextEditor::MovingRange::AllowEmpty, revision); } return result; } void fillItemRoles(QStandardItem * item, const QUrl & url, const LSPRange _range, RangeData::KindEnum kind, const LSPClientRevisionSnapshot * snapshot = nullptr) { auto range = snapshot ? transformRange(url, *snapshot, _range) : _range; item->setData(QVariant(url), RangeData::FileUrlRole); QVariant vrange; vrange.setValue(range); item->setData(vrange, RangeData::RangeRole); item->setData((int) kind, RangeData::KindRole); } void makeTree(const QVector & locations, const LSPClientRevisionSnapshot * snapshot) { // group by url, assuming input is suitably sorted that way auto treeModel = new QStandardItemModel(); treeModel->setColumnCount(1); QUrl lastUrl; QStandardItem *parent = nullptr; for (const auto & loc: locations) { if (loc.uri != lastUrl) { if (parent) { parent->setText(QStringLiteral("%1: %2").arg(lastUrl.path()).arg(parent->rowCount())); } lastUrl = loc.uri; parent = new QStandardItem(); treeModel->appendRow(parent); } auto item = new LineItem(m_mainWindow); parent->appendRow(item); // add partial display data; line will be added by item later on item->setText(i18n("Line: %1: ", loc.range.start().line() + 1)); fillItemRoles(item, loc.uri, loc.range, loc.kind, snapshot); } if (parent) parent->setText(QStringLiteral("%1: %2").arg(lastUrl.path()).arg(parent->rowCount())); // plain heuristic; mark for auto-expand all when safe and/or useful to do so if (treeModel->rowCount() <= 2 || locations.size() <= 20) { treeModel->invisibleRootItem()->setData(true, RangeData::KindRole); } m_ownedModel.reset(treeModel); m_markModel = treeModel; } void showTree(const QString & title, QPointer *targetTree) { // clean up previous target if any if (targetTree && *targetTree) { int index = m_tabWidget->indexOf(*targetTree); if (index >= 0) tabCloseRequested(index); } // setup view auto treeView = new QTreeView(); configureTreeView(treeView); // transfer model from owned to tree and that in turn to tabwidget auto treeModel = m_ownedModel.take(); treeView->setModel(treeModel); treeModel->setParent(treeView); int index = m_tabWidget->addTab(treeView, title); connect(treeView, &QTreeView::clicked, this, &self_type::goToItemLocation); if (treeModel->invisibleRootItem()->data(RangeData::KindRole).toBool()) { treeView->expandAll(); } // track for later cleanup if (targetTree) *targetTree = treeView; // activate the resulting tab m_tabWidget->setCurrentIndex(index); m_mainWindow->showToolView(m_toolView.get()); } void showMessage(const QString & text, KTextEditor::Message::MessageType level) { KTextEditor::View *view = m_mainWindow->activeView(); if (!view || !view->document()) return; auto kmsg = new KTextEditor::Message(text, level); kmsg->setPosition(KTextEditor::Message::BottomInView); kmsg->setAutoHide(500); kmsg->setView(view); view->document()->postMessage(kmsg); } void handleEsc(QEvent *e) { if (!m_mainWindow) return; QKeyEvent *k = static_cast(e); if (k->key() == Qt::Key_Escape && k->modifiers() == Qt::NoModifier) { if (!m_ranges.empty()) { clearAllLocationMarks(); } else if (m_toolView->isVisible()) { m_mainWindow->hideToolView(m_toolView.get()); } } } template using LocationRequest = std::function; template void positionRequest(const LocationRequest & req, const Handler & h, QScopedPointer * snapshot = nullptr) { KTextEditor::View *activeView = m_mainWindow->activeView(); auto server = m_serverManager->findServer(activeView); if (!server) return; // track revision if requested if (snapshot) { snapshot->reset(m_serverManager->snapshot(server.get())); } KTextEditor::Cursor cursor = activeView->cursorPosition(); clearAllLocationMarks(); m_req_timeout = false; QTimer::singleShot(1000, this, [this] { m_req_timeout = true; }); m_handle.cancel() = req(*server, activeView->document()->url(), {cursor.line(), cursor.column()}, this, h); } QString currentWord() { KTextEditor::View *activeView = m_mainWindow->activeView(); if (activeView) { KTextEditor::Cursor cursor = activeView->cursorPosition(); return activeView->document()->wordAt(cursor); } else { return QString(); } } // some template and function type trickery here, but at least that buck stops here then ... template>> void processLocations(const QString & title, const typename utils::identity>::type & req, bool onlyshow, const std::function & itemConverter, QPointer *targetTree = nullptr) { // no capture for move only using initializers available (yet), so shared outer type // the additional level of indirection is so it can be 'filled-in' after lambda creation QSharedPointer> s(new QScopedPointer); auto h = [this, title, onlyshow, itemConverter, targetTree, s] (const QList & defs) { if (defs.count() == 0) { showMessage(i18n("No results"), KTextEditor::Message::Information); } else { // convert to helper type QVector ranges; ranges.reserve(defs.size()); for (const auto & def: defs) { ranges.push_back(itemConverter(def)); } // ... so we can sort it also std::stable_sort(ranges.begin(), ranges.end(), compareRangeItem); makeTree(ranges, s.get()->get()); // assuming that reply ranges refer to revision when submitted // (not specified anyway in protocol/reply) if (defs.count() > 1 || onlyshow) { showTree(title, targetTree); } // it's not nice to jump to some location if we are too late if (!m_req_timeout && !onlyshow) { // assuming here that the first location is the best one const auto &item = itemConverter(defs.at(0)); const auto &pos = item.range.start(); goToDocumentLocation(item.uri, pos.line(), pos.column()); } // update marks updateState(); } }; positionRequest(req, h, s.get()); } static RangeItem locationToRangeItem(const LSPLocation & loc) { return {loc.uri, loc.range, LSPDocumentHighlightKind::Text}; } void goToDefinition() { auto title = i18nc("@title:tab", "Definition: %1", currentWord()); processLocations(title, &LSPClientServer::documentDefinition, false, &self_type::locationToRangeItem, &m_defTree); } void goToDeclaration() { auto title = i18nc("@title:tab", "Declaration: %1", currentWord()); processLocations(title, &LSPClientServer::documentDeclaration, false, &self_type::locationToRangeItem, &m_declTree); } void findReferences() { auto title = i18nc("@title:tab", "References: %1", currentWord()); bool decl = m_refDeclaration->isChecked(); auto req = [decl] (LSPClientServer & server, const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentDefinitionReplyHandler & h) { return server.documentReferences(document, pos, decl, context, h); }; processLocations(title, req, true, &self_type::locationToRangeItem); } void highlight() { // determine current url to capture and use later on QUrl url; const KTextEditor::View* viewForRequest(m_mainWindow->activeView()); if (viewForRequest && viewForRequest->document()) { url = viewForRequest->document()->url(); } auto title = i18nc("@title:tab", "Highlight: %1", currentWord()); auto converter = [url] (const LSPDocumentHighlight & hl) { return RangeItem {url, hl.range, hl.kind}; }; processLocations(title, &LSPClientServer::documentHighlight, true, converter); } void hover() { // trigger manually the normally automagic hover if (auto activeView = m_mainWindow->activeView()) { m_hover->textHint(activeView, activeView->cursorPosition()); } } void applyEdits(KTextEditor::Document * doc, const LSPClientRevisionSnapshot * snapshot, const QList & edits) { KTextEditor::MovingInterface* miface = qobject_cast(doc); if (!miface) return; // NOTE: // server might be pretty sloppy wrt edits (e.g. python-language-server) // e.g. send one edit for the whole document rather than 'surgical edits' // and that even when requesting format for a limited selection // ... but then we are but a client and do as we are told // all-in-all a low priority feature // all coordinates in edits are wrt original document, // so create moving ranges that will adjust to preceding edits as they are applied QVector ranges; for (const auto &edit: edits) { auto range = snapshot ? transformRange(doc->url(), *snapshot, edit.range) : edit.range; KTextEditor::MovingRange *mr = miface->newMovingRange(range); ranges.append(mr); } // now make one transaction (a.o. for one undo) and apply in sequence { KTextEditor::Document::EditingTransaction transaction(doc); for (int i = 0; i < ranges.length(); ++i) { doc->replaceText(ranges.at(i)->toRange(), edits.at(i).newText); } } qDeleteAll(ranges); } void applyWorkspaceEdit(const LSPWorkspaceEdit & edit, const LSPClientRevisionSnapshot * snapshot) { auto currentView = m_mainWindow->activeView(); for (auto it = edit.changes.begin(); it != edit.changes.end(); ++it) { auto document = findDocument(m_mainWindow, it.key()); if (!document) { KTextEditor::View *view = m_mainWindow->openUrl(it.key()); if (view) { document = view->document(); } } applyEdits(document, snapshot, it.value()); } if (currentView) { m_mainWindow->activateView(currentView->document()); } } void onApplyEdit(const LSPApplyWorkspaceEditParams & edit, const ApplyEditReplyHandler & h, bool &handled) { if (handled) return; handled = true; if (m_accept_edit) { qCInfo(LSPCLIENT) << "applying edit" << edit.label; applyWorkspaceEdit(edit.edit, nullptr); } else { qCInfo(LSPCLIENT) << "ignoring edit"; } h({m_accept_edit, QString()}); } template void checkEditResult(const Collection & c) { if (c.size() == 0) { showMessage(i18n("No edits"), KTextEditor::Message::Information); } } void delayCancelRequest(LSPClientServer::RequestHandle && h, int timeout_ms = 4000) { QTimer::singleShot(timeout_ms, this, [this, h] () mutable { h.cancel(); }); } void format() { KTextEditor::View *activeView = m_mainWindow->activeView(); QPointer document = activeView->document(); auto server = m_serverManager->findServer(activeView); if (!server || !document) return; int tabSize = 4; bool insertSpaces = true; auto cfgiface = qobject_cast(document); if (cfgiface) { tabSize = cfgiface->configValue(QStringLiteral("tab-width")).toInt(); insertSpaces = cfgiface->configValue(QStringLiteral("replace-tabs")).toBool(); } // sigh, no move initialization capture ... // (again) assuming reply ranges wrt revisions submitted at this time QSharedPointer snapshot(m_serverManager->snapshot(server.get())); auto h = [this, document, snapshot] (const QList & edits) { checkEditResult(edits); if (document) { applyEdits(document, snapshot.get(), edits); } }; auto handle = activeView->selection() ? server->documentRangeFormatting(document->url(), activeView->selectionRange(), - tabSize, insertSpaces, QJsonObject(), this, h) : + {tabSize, insertSpaces, QJsonObject()}, this, h) : server->documentFormatting(document->url(), - tabSize, insertSpaces, QJsonObject(), this, h); + {tabSize, insertSpaces, QJsonObject()}, this, h); delayCancelRequest(std::move(handle)); } void rename() { KTextEditor::View *activeView = m_mainWindow->activeView(); QPointer document = activeView->document(); auto server = m_serverManager->findServer(activeView); if (!server || !document) return; bool ok = false; // results are typically (too) limited // due to server implementation or limited view/scope // so let's add a disclaimer that it's not our fault QString newName = QInputDialog::getText(activeView, i18nc("@title:window", "Rename"), i18nc("@label:textbox", "New name (caution: not all references may be replaced)"), QLineEdit::Normal, QString(), &ok); if (!ok) { return; } QSharedPointer snapshot(m_serverManager->snapshot(server.get())); auto h = [this, snapshot] (const LSPWorkspaceEdit & edit) { checkEditResult(edit.changes); applyWorkspaceEdit(edit, snapshot.get()); }; auto handle = server->documentRename(document->url(), activeView->cursorPosition(), newName, this, h); delayCancelRequest(std::move(handle)); } static QStandardItem* getItem(const QStandardItemModel &model, const QUrl & url) { auto l = model.findItems(url.path()); if (l.length()) { return l.at(0); } return nullptr; } // select/scroll to diagnostics item for document and (optionally) line bool syncDiagnostics(KTextEditor::Document *document, int line, bool allowTop, bool doShow) { if (!m_diagnosticsTree) return false; auto hint = QAbstractItemView::PositionAtTop; QStandardItem *targetItem = nullptr; QStandardItem *topItem = getItem(*m_diagnosticsModel, document->url()); if (topItem) { int count = topItem->rowCount(); // let's not run wild on a linear search in a flood of diagnostics // user is already in enough trouble as it is ;-) if (count > 50) count = 0; for (int i = 0; i < count; ++i) { auto item = topItem->child(i); int itemline = item->data(RangeData::RangeRole).value().start().line(); if (line == itemline && m_diagnosticsTree) { targetItem = item; hint = QAbstractItemView::PositionAtCenter; break; } } } if (!targetItem && allowTop) { targetItem = topItem; } if (targetItem) { m_diagnosticsTree->blockSignals(true); m_diagnosticsTree->scrollTo(targetItem->index(), hint); m_diagnosticsTree->setCurrentIndex(targetItem->index()); m_diagnosticsTree->blockSignals(false); if (doShow) { m_tabWidget->setCurrentWidget(m_diagnosticsTree); m_mainWindow->showToolView(m_toolView.get()); } } return targetItem != nullptr; } void onViewState(KTextEditor::View *view, LSPClientViewTracker::State newState) { if (!view || !view->document()) return; // select top item on view change, // but otherwise leave selection unchanged if no match switch(newState) { case LSPClientViewTracker::ViewChanged: syncDiagnostics(view->document(), view->cursorPosition().line(), true, false); break; case LSPClientViewTracker::LineChanged: syncDiagnostics(view->document(), view->cursorPosition().line(), false, false); break; default: // should not happen break; } } Q_SLOT void onMarkClicked(KTextEditor::Document *document, KTextEditor::Mark mark, bool &handled) { if (syncDiagnostics(document, mark.line, false, true)) { handled = true; } } void onDiagnostics(const LSPPublishDiagnosticsParams & diagnostics) { if (!m_diagnosticsTree) return; QStandardItemModel *model = m_diagnosticsModel.get(); QStandardItem *topItem = getItem(*m_diagnosticsModel, diagnostics.uri); if (!topItem) { topItem = new QStandardItem(); model->appendRow(topItem); topItem->setText(diagnostics.uri.path()); } else { topItem->setRowCount(0); } for (const auto & diag : diagnostics.diagnostics) { auto item = new DiagnosticItem(diag); topItem->appendRow(item); QString source; if (diag.source.length()) { source = QStringLiteral("[%1] ").arg(diag.source); } item->setData(diagnosticsIcon(diag.severity), Qt::DecorationRole); item->setText(source + diag.message); fillItemRoles(item, diagnostics.uri, diag.range, diag.severity); const auto &related = diag.relatedInformation; if (!related.location.uri.isEmpty()) { auto relatedItemMessage = new QStandardItem(); relatedItemMessage->setText(related.message); fillItemRoles(relatedItemMessage, related.location.uri, related.location.range, RangeData::KindEnum::Related); auto relatedItemPath = new QStandardItem(); auto basename = QFileInfo(related.location.uri.path()).fileName(); relatedItemPath->setText(QStringLiteral("%1:%2").arg(basename).arg(related.location.range.start().line())); item->appendRow({relatedItemMessage, relatedItemPath}); m_diagnosticsTree->setExpanded(item->index(), true); } } // TODO perhaps add some custom delegate that only shows 1 line // and only the whole text when item selected ?? m_diagnosticsTree->setExpanded(topItem->index(), true); m_diagnosticsTree->setRowHidden(topItem->row(), QModelIndex(), topItem->rowCount() == 0); m_diagnosticsTree->scrollTo(topItem->index(), QAbstractItemView::PositionAtTop); auto header = m_diagnosticsTree->header(); header->setStretchLastSection(false); header->setMinimumSectionSize(0); header->setSectionResizeMode(0, QHeaderView::Stretch); header->setSectionResizeMode(1, QHeaderView::ResizeToContents); updateState(); } void updateState() { KTextEditor::View *activeView = m_mainWindow->activeView(); auto server = m_serverManager->findServer(activeView); bool defEnabled = false, declEnabled = false, refEnabled = false; bool hoverEnabled = false, highlightEnabled = false; bool formatEnabled = false; bool renameEnabled = false; if (server) { const auto& caps = server->capabilities(); defEnabled = caps.definitionProvider; // FIXME no real official protocol way to detect, so enable anyway declEnabled = caps.declarationProvider || true; refEnabled = caps.referencesProvider; hoverEnabled = caps.hoverProvider; highlightEnabled = caps.documentHighlightProvider; formatEnabled = caps.documentFormattingProvider || caps.documentRangeFormattingProvider; renameEnabled = caps.renameProvider; connect(server.get(), &LSPClientServer::publishDiagnostics, this, &self_type::onDiagnostics, Qt::UniqueConnection); connect(server.get(), &LSPClientServer::applyEdit, this, &self_type::onApplyEdit, Qt::UniqueConnection); } if (m_findDef) m_findDef->setEnabled(defEnabled); if (m_findDecl) m_findDecl->setEnabled(declEnabled); if (m_findRef) m_findRef->setEnabled(refEnabled); if (m_triggerHighlight) m_triggerHighlight->setEnabled(highlightEnabled); if (m_triggerHover) m_triggerHover->setEnabled(hoverEnabled); if (m_triggerFormat) m_triggerFormat->setEnabled(formatEnabled); if (m_triggerRename) m_triggerRename->setEnabled(renameEnabled); if (m_complDocOn) m_complDocOn->setEnabled(server); if (m_restartServer) m_restartServer->setEnabled(server); // update completion with relevant server m_completion->setServer(server); if (m_complDocOn) m_completion->setSelectedDocumentation(m_complDocOn->isChecked()); updateCompletion(activeView, server.get()); // update hover with relevant server m_hover->setServer(server); updateHover(activeView, server.get()); // update marks if applicable if (m_markModel && activeView) addMarks(activeView->document(), m_markModel, m_ranges); if (m_diagnosticsModel && activeView) { clearMarks(activeView->document(), m_diagnosticsRanges, RangeData::markTypeDiagAll); addMarks(activeView->document(), m_diagnosticsModel.get(), m_diagnosticsRanges); } // connect for cleanup stuff if (activeView) connect(activeView, &KTextEditor::View::destroyed, this, &self_type::viewDestroyed, Qt::UniqueConnection); } void viewDestroyed(QObject *view) { m_completionViews.remove(static_cast(view)); m_hoverViews.remove(static_cast(view)); } void updateCompletion(KTextEditor::View *view, LSPClientServer * server) { bool registered = m_completionViews.contains(view); KTextEditor::CodeCompletionInterface *cci = qobject_cast(view); if (!cci) { return; } if (!registered && server && server->capabilities().completionProvider.provider) { qCInfo(LSPCLIENT) << "registering cci"; cci->registerCompletionModel(m_completion.get()); m_completionViews.insert(view); } if (registered && !server) { qCInfo(LSPCLIENT) << "unregistering cci"; cci->unregisterCompletionModel(m_completion.get()); m_completionViews.remove(view); } } void updateHover(KTextEditor::View *view, LSPClientServer * server) { bool registered = m_hoverViews.contains(view); KTextEditor::TextHintInterface *cci = qobject_cast(view); if (!cci) { return; } if (!registered && server && server->capabilities().hoverProvider) { qCInfo(LSPCLIENT) << "registering cci"; cci->registerTextHintProvider(m_hover.get()); m_hoverViews.insert(view); } if (registered && !server) { qCInfo(LSPCLIENT) << "unregistering cci"; cci->unregisterTextHintProvider(m_hover.get()); m_hoverViews.remove(view); } } }; class LSPClientPluginViewImpl : public QObject, public KXMLGUIClient { Q_OBJECT typedef LSPClientPluginViewImpl self_type; LSPClientPlugin *m_plugin; KTextEditor::MainWindow *m_mainWindow; QSharedPointer m_serverManager; QScopedPointer m_actionView; public: LSPClientPluginViewImpl(LSPClientPlugin *plugin, KTextEditor::MainWindow *mainWin) : QObject(mainWin), m_plugin(plugin), m_mainWindow(mainWin), m_serverManager(LSPClientServerManager::new_(plugin, mainWin)), m_actionView(new LSPClientActionView(plugin, mainWin, this, m_serverManager)) { KXMLGUIClient::setComponentName(QStringLiteral("lspclient"), i18n("LSP Client")); setXMLFile(QStringLiteral("ui.rc")); m_mainWindow->guiFactory()->addClient(this); } ~LSPClientPluginViewImpl() { // minimize/avoid some surprises; // safe construction/destruction by separate (helper) objects; // signals are auto-disconnected when high-level "view" objects are broken down // so it only remains to clean up lowest level here then prior to removal m_actionView.reset(); m_serverManager.reset(); m_mainWindow->guiFactory()->removeClient(this); } }; QObject* LSPClientPluginView::new_(LSPClientPlugin *plugin, KTextEditor::MainWindow *mainWin) { return new LSPClientPluginViewImpl(plugin, mainWin); } #include "lspclientpluginview.moc" diff --git a/addons/lspclient/lspclientprotocol.h b/addons/lspclient/lspclientprotocol.h index 6bc6214fe..d9dc97668 100644 --- a/addons/lspclient/lspclientprotocol.h +++ b/addons/lspclient/lspclientprotocol.h @@ -1,320 +1,329 @@ /* SPDX-License-Identifier: MIT Copyright (C) 2019 Mark Nauwelaerts 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. */ #ifndef LSPCLIENTPROTOCOL_H #define LSPCLIENTPROTOCOL_H #include #include #include #include #include #include +#include #include #include // Following types roughly follow the types/interfaces as defined in LSP protocol spec // although some deviation may arise where it has been deemed useful // Moreover, to avoid introducing a custom 'optional' type, absence of an optional // part/member is usually signalled by some 'invalid' marker (empty, negative). enum class LSPErrorCode { // Defined by JSON RPC ParseError = -32700, InvalidRequest = -32600, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603, serverErrorStart = -32099, serverErrorEnd = -32000, ServerNotInitialized = -32002, UnknownErrorCode = -32001, // Defined by the protocol. RequestCancelled = -32800, ContentModified = -32801 }; enum class LSPDocumentSyncKind { None = 0, Full = 1, Incremental = 2 }; struct LSPCompletionOptions { bool provider = false; bool resolveProvider = false; QVector triggerCharacters; }; struct LSPSignatureHelpOptions { bool provider = false; QVector triggerCharacters; }; struct LSPServerCapabilities { LSPDocumentSyncKind textDocumentSync = LSPDocumentSyncKind::None; bool hoverProvider = false; LSPCompletionOptions completionProvider; LSPSignatureHelpOptions signatureHelpProvider; bool definitionProvider = false; // FIXME ? clangd unofficial extension bool declarationProvider = false; bool referencesProvider = false; bool documentSymbolProvider = false; bool documentHighlightProvider = false; bool documentFormattingProvider = false; bool documentRangeFormattingProvider = false; bool renameProvider = false; // CodeActionOptions not useful/considered at present bool codeActionProvider = false; }; enum class LSPMarkupKind { None = 0, PlainText = 1, MarkDown = 2 }; struct LSPMarkupContent { LSPMarkupKind kind = LSPMarkupKind::None; QString value; }; /** * Language Server Protocol Position * line + column, 0 based, negative for invalid * maps 1:1 to KTextEditor::Cursor */ using LSPPosition = KTextEditor::Cursor; /** * Language Server Protocol Range * start + end tuple of LSPPosition * maps 1:1 to KTextEditor::Range */ using LSPRange = KTextEditor::Range; struct LSPLocation { QUrl uri; LSPRange range; }; enum class LSPDocumentHighlightKind { Text = 1, Read = 2, Write = 3 }; struct LSPDocumentHighlight { LSPRange range; LSPDocumentHighlightKind kind; }; struct LSPHover { LSPMarkupContent contents; LSPRange range; }; enum class LSPSymbolKind { File = 1, Module = 2, Namespace = 3, Package = 4, Class = 5, Method = 6, Property = 7, Field = 8, Constructor = 9, Enum = 10, Interface = 11, Function = 12, Variable = 13, Constant = 14, String = 15, Number = 16, Boolean = 17, Array = 18, }; struct LSPSymbolInformation { LSPSymbolInformation(const QString & _name, LSPSymbolKind _kind, LSPRange _range, const QString & _detail) : name(_name), detail(_detail), kind(_kind), range(_range) {} QString name; QString detail; LSPSymbolKind kind; LSPRange range; QList children; }; enum class LSPCompletionItemKind { Text = 1, Method = 2, Function = 3, Constructor = 4, Field = 5, Variable = 6, Class = 7, Interface = 8, Module = 9, Property = 10, Unit = 11, Value = 12, Enum = 13, Keyword = 14, Snippet = 15, Color = 16, File = 17, Reference = 18, Folder = 19, EnumMember = 20, Constant = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25, }; struct LSPCompletionItem { QString label; LSPCompletionItemKind kind; QString detail; LSPMarkupContent documentation; QString sortText; QString insertText; }; struct LSPParameterInformation { // offsets into overall signature label // (-1 if invalid) int start; int end; }; struct LSPSignatureInformation { QString label; LSPMarkupContent documentation; QList parameters; }; struct LSPSignatureHelp { QList signatures; int activeSignature; int activeParameter; }; +struct LSPFormattingOptions +{ + int tabSize; + bool insertSpaces; + // additional fields + QJsonObject extra; +}; + struct LSPTextEdit { LSPRange range; QString newText; }; enum class LSPDiagnosticSeverity { Unknown = 0, Error = 1, Warning = 2, Information = 3, Hint = 4, }; struct LSPDiagnosticRelatedInformation { // empty url / invalid range when absent LSPLocation location; QString message; }; struct LSPDiagnostic { LSPRange range; LSPDiagnosticSeverity severity; QString code; QString source; QString message; LSPDiagnosticRelatedInformation relatedInformation; }; struct LSPPublishDiagnosticsParams { QUrl uri; QList diagnostics; }; struct LSPCommand { QString title; QString command; // pretty opaque QJsonArray arguments; }; struct LSPWorkspaceEdit { // supported part for now QHash> changes; }; struct LSPCodeAction { QString title; QString kind; QList diagnostics; LSPWorkspaceEdit edit; LSPCommand command; }; struct LSPApplyWorkspaceEditParams { QString label; LSPWorkspaceEdit edit; }; struct LSPApplyWorkspaceEditResponse { bool applied; QString failureReason; }; #endif diff --git a/addons/lspclient/lspclientserver.cpp b/addons/lspclient/lspclientserver.cpp index bfa48513b..1bf57569d 100644 --- a/addons/lspclient/lspclientserver.cpp +++ b/addons/lspclient/lspclientserver.cpp @@ -1,1302 +1,1301 @@ /* SPDX-License-Identifier: MIT Copyright (C) 2019 Mark Nauwelaerts 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. */ #include "lspclientserver.h" #include "lspclient_debug.h" #include #include #include #include #include #include #include #include #include // good/bad old school; allows easier concatenate #define CONTENT_LENGTH "Content-Length" static const QString MEMBER_ID = QStringLiteral("id"); static const QString MEMBER_METHOD = QStringLiteral("method"); static const QString MEMBER_ERROR = QStringLiteral("error"); static const QString MEMBER_CODE = QStringLiteral("code"); static const QString MEMBER_MESSAGE = QStringLiteral("message"); static const QString MEMBER_PARAMS = QStringLiteral("params"); static const QString MEMBER_RESULT = QStringLiteral("result"); static const QString MEMBER_URI = QStringLiteral("uri"); static const QString MEMBER_VERSION = QStringLiteral("version"); static const QString MEMBER_START = QStringLiteral("start"); static const QString MEMBER_END = QStringLiteral("end"); static const QString MEMBER_POSITION = QStringLiteral("position"); static const QString MEMBER_LOCATION = QStringLiteral("location"); static const QString MEMBER_RANGE = QStringLiteral("range"); static const QString MEMBER_LINE = QStringLiteral("line"); static const QString MEMBER_CHARACTER = QStringLiteral("character"); static const QString MEMBER_KIND = QStringLiteral("kind"); static const QString MEMBER_TEXT = QStringLiteral("text"); static const QString MEMBER_LANGID = QStringLiteral("languageId"); static const QString MEMBER_LABEL = QStringLiteral("label"); static const QString MEMBER_DOCUMENTATION = QStringLiteral("documentation"); static const QString MEMBER_DETAIL = QStringLiteral("detail"); static const QString MEMBER_COMMAND = QStringLiteral("command"); static const QString MEMBER_EDIT = QStringLiteral("edit"); static const QString MEMBER_TITLE = QStringLiteral("title"); static const QString MEMBER_ARGUMENTS = QStringLiteral("arguments"); static const QString MEMBER_DIAGNOSTICS = QStringLiteral("diagnostics"); // message construction helpers static QJsonObject to_json(const LSPPosition & pos) { return QJsonObject { { MEMBER_LINE, pos.line() }, { MEMBER_CHARACTER, pos.column() } }; } static QJsonObject to_json(const LSPRange & range) { return QJsonObject { { MEMBER_START, to_json(range.start()) }, { MEMBER_END, to_json(range.end()) } }; } static QJsonValue to_json(const LSPLocation & location) { if (location.uri.isValid()) { return QJsonObject { { MEMBER_URI, location.uri.toString() }, { MEMBER_RANGE, to_json(location.range) } }; } return QJsonValue(); } static QJsonValue to_json(const LSPDiagnosticRelatedInformation & related) { auto loc = to_json(related.location); if (loc.isObject()) { return QJsonObject { { MEMBER_LOCATION, to_json(related.location) }, { MEMBER_MESSAGE, related.message } }; } return QJsonValue(); } static QJsonObject to_json(const LSPDiagnostic & diagnostic) { // required auto result = QJsonObject(); result[MEMBER_RANGE] = to_json(diagnostic.range); result[MEMBER_MESSAGE] = diagnostic.message; // optional if (!diagnostic.code.isEmpty()) result[QStringLiteral("code")] = diagnostic.code; if (diagnostic.severity != LSPDiagnosticSeverity::Unknown) result[QStringLiteral("severity")] = (int) diagnostic.severity; if (!diagnostic.source.isEmpty()) result[QStringLiteral("source")] = diagnostic.source; auto related = to_json(diagnostic.relatedInformation); if (related.isObject()) { result[QStringLiteral("relatedInformation")] = related; } return result; } static QJsonObject versionedTextDocumentIdentifier(const QUrl & document, int version = -1) { QJsonObject map { { MEMBER_URI, document.toString() } }; if (version >= 0) map[MEMBER_VERSION] = version; return map; } static QJsonObject textDocumentItem(const QUrl & document, const QString & lang, const QString & text, int version) { auto map = versionedTextDocumentIdentifier(document, version); map[MEMBER_TEXT] = text; map[MEMBER_LANGID] = lang; return map; } static QJsonObject textDocumentParams(const QJsonObject & m) { return QJsonObject { { QStringLiteral("textDocument"), m} }; } static QJsonObject textDocumentParams(const QUrl & document, int version = -1) { return textDocumentParams(versionedTextDocumentIdentifier(document, version)); } static QJsonObject textDocumentPositionParams(const QUrl & document, LSPPosition pos) { auto params = textDocumentParams(document); params[MEMBER_POSITION] = to_json(pos); return params; } static QJsonObject referenceParams(const QUrl & document, LSPPosition pos, bool decl) { auto params = textDocumentPositionParams(document, pos); params[QStringLiteral("context")] = QJsonObject { { QStringLiteral("includeDeclaration"), decl } }; return params; } static QJsonObject documentRangeFormattingParams(const QUrl & document, const LSPRange *range, - int tabSize, bool insertSpaces, const QJsonObject & _options) + const LSPFormattingOptions & _options) { auto params = textDocumentParams(document); if (range) { params[MEMBER_RANGE] = to_json(*range); } - auto options = _options; - options[QStringLiteral("tabSize")] = tabSize; - options[QStringLiteral("insertSpaces")] = insertSpaces; + auto options = _options.extra; + options[QStringLiteral("tabSize")] = _options.tabSize; + options[QStringLiteral("insertSpaces")] = _options.insertSpaces; params[QStringLiteral("options")] = options; return params; } static QJsonObject renameParams(const QUrl & document, const LSPPosition & pos, const QString & newName) { auto params = textDocumentPositionParams(document, pos); params[QStringLiteral("newName")] = newName; return params; } static QJsonObject codeActionParams(const QUrl & document, const LSPRange & range, QList kinds, QList diagnostics) { auto params = textDocumentParams(document); params[MEMBER_RANGE] = to_json(range); QJsonObject context; QJsonArray diags; for (const auto& diagnostic: diagnostics) { diags.push_back(to_json(diagnostic)); } context[MEMBER_DIAGNOSTICS] = diags; if (kinds.length()) context[QStringLiteral("only")] = QJsonArray::fromStringList(kinds); params[QStringLiteral("context")] = context; return params; } static QJsonObject executeCommandParams(const QString & command, const QJsonValue & args) { return QJsonObject { { MEMBER_COMMAND, command }, { MEMBER_ARGUMENTS, args } }; } static QJsonObject applyWorkspaceEditResponse(const LSPApplyWorkspaceEditResponse & response) { return QJsonObject { { QStringLiteral("applied"), response.applied }, { QStringLiteral("failureReason"), response.failureReason } }; } static void from_json(QVector & trigger, const QJsonValue & json) { for (const auto & t : json.toArray()) { auto st = t.toString(); if (st.length()) trigger.push_back(st.at(0)); } } static void from_json(LSPCompletionOptions & options, const QJsonValue & json) { if (json.isObject()) { auto ob = json.toObject(); options.provider = true; options.resolveProvider = ob.value(QStringLiteral("resolveProvider")).toBool(); from_json(options.triggerCharacters, ob.value(QStringLiteral("triggerCharacters"))); } } static void from_json(LSPSignatureHelpOptions & options, const QJsonValue & json) { if (json.isObject()) { auto ob = json.toObject(); options.provider = true; from_json(options.triggerCharacters, ob.value(QStringLiteral("triggerCharacters"))); } } static void from_json(LSPServerCapabilities & caps, const QJsonObject & json) { auto sync = json.value(QStringLiteral("textDocumentSync")); caps.textDocumentSync = (LSPDocumentSyncKind) (sync.isObject() ? sync.toObject().value(QStringLiteral("change")) : sync).toInt((int)LSPDocumentSyncKind::None); caps.hoverProvider = json.value(QStringLiteral("hoverProvider")).toBool(); from_json(caps.completionProvider, json.value(QStringLiteral("completionProvider"))); from_json(caps.signatureHelpProvider, json.value(QStringLiteral("signatureHelpProvider"))); caps.definitionProvider = json.value(QStringLiteral("definitionProvider")).toBool(); caps.declarationProvider = json.value(QStringLiteral("declarationProvider")).toBool(); caps.referencesProvider = json.value(QStringLiteral("referencesProvider")).toBool(); caps.documentSymbolProvider = json.value(QStringLiteral("documentSymbolProvider")).toBool(); caps.documentHighlightProvider = json.value(QStringLiteral("documentHighlightProvider")).toBool(); caps.documentFormattingProvider = json.value(QStringLiteral("documentFormattingProvider")).toBool(); caps.documentRangeFormattingProvider = json.value(QStringLiteral("documentRangeFormattingProvider")).toBool(); caps.renameProvider = json.value(QStringLiteral("renameProvider")).toBool(); auto codeActionProvider = json.value(QStringLiteral("codeActionProvider")); caps.codeActionProvider = codeActionProvider.toBool() || codeActionProvider.isObject(); } // TODO move all parsing here static LSPPublishDiagnosticsParams parseDiagnostics(const QJsonObject & result); static LSPApplyWorkspaceEditParams parseApplyWorkspaceEditParams(const QJsonObject & result); using GenericReplyType = QJsonValue; using GenericReplyHandler = ReplyHandler; class LSPClientServer::LSPClientServerPrivate { typedef LSPClientServerPrivate self_type; LSPClientServer *q; // server cmd line QStringList m_server; // workspace root to pass along QUrl m_root; // user provided init QJsonValue m_init; // server process QProcess m_sproc; // server declared capabilites LSPServerCapabilities m_capabilities; // server state State m_state = State::None; // last msg id int m_id = 0; // receive buffer QByteArray m_receive; // registered reply handlers QHash m_handlers; // pending request responses static constexpr int MAX_REQUESTS = 5; QVector m_requests{MAX_REQUESTS + 1}; public: LSPClientServerPrivate(LSPClientServer * _q, const QStringList & server, const QUrl & root, const QJsonValue & init) : q(_q), m_server(server), m_root(root), m_init(init) { // setup async reading QObject::connect(&m_sproc, &QProcess::readyRead, utils::mem_fun(&self_type::read, this)); QObject::connect(&m_sproc, &QProcess::stateChanged, utils::mem_fun(&self_type::onStateChanged, this)); } ~LSPClientServerPrivate() { stop(TIMEOUT_SHUTDOWN, TIMEOUT_SHUTDOWN); } const QStringList& cmdline() const { return m_server; } State state() { return m_state; } const LSPServerCapabilities& capabilities() { return m_capabilities; } int cancel(int reqid) { if (m_handlers.remove(reqid) > 0) { auto params = QJsonObject { { MEMBER_ID, reqid } }; write(init_request(QStringLiteral("$/cancelRequest"), params)); } return -1; } private: void setState(State s) { if (m_state != s) { m_state = s; emit q->stateChanged(q); } } RequestHandle write(const QJsonObject & msg, const GenericReplyHandler & h = nullptr, const int * id = nullptr) { RequestHandle ret; ret.m_server = q; if (!running()) return ret; auto ob = msg; ob.insert(QStringLiteral("jsonrpc"), QStringLiteral("2.0")); // notification == no handler if (h) { ob.insert(MEMBER_ID, ++m_id); ret.m_id = m_id; m_handlers[m_id] = h; } else if (id) { ob.insert(MEMBER_ID, *id); } QJsonDocument json(ob); auto sjson = json.toJson(); qCInfo(LSPCLIENT) << "calling" << msg[MEMBER_METHOD].toString(); qCDebug(LSPCLIENT) << "sending message:\n" << QString::fromUtf8(sjson); // some simple parsers expect length header first auto hdr = QStringLiteral(CONTENT_LENGTH ": %1\r\n").arg(sjson.length()); // write is async, so no blocking wait occurs here m_sproc.write(hdr.toLatin1()); m_sproc.write("\r\n"); m_sproc.write(sjson); return ret; } RequestHandle send(const QJsonObject & msg, const GenericReplyHandler & h = nullptr) { if (m_state == State::Running) return write(msg, h); else qCWarning(LSPCLIENT) << "send for non-running server"; return RequestHandle(); } void read() { // accumulate in buffer m_receive.append(m_sproc.readAllStandardOutput()); // try to get one (or more) message QByteArray &buffer = m_receive; while (true) { qCDebug(LSPCLIENT) << "buffer size" << buffer.length(); auto header = QByteArray(CONTENT_LENGTH ":"); int index = buffer.indexOf(header); if (index < 0) { // avoid collecting junk if (buffer.length() > 1 << 20) buffer.clear(); break; } index += header.length(); int endindex = buffer.indexOf("\r\n", index); auto msgstart = buffer.indexOf("\r\n\r\n", index); if (endindex < 0 || msgstart < 0) break; msgstart += 4; bool ok = false; auto length = buffer.mid(index, endindex - index).toInt(&ok, 10); // FIXME perhaps detect if no reply for some time // then again possibly better left to user to restart in such case if (!ok) { qCWarning(LSPCLIENT) << "invalid " CONTENT_LENGTH; // flush and try to carry on to some next header buffer.remove(0, msgstart); continue; } // sanity check to avoid extensive buffering if (length > 1 << 29) { qCWarning(LSPCLIENT) << "excessive size"; buffer.clear(); continue; } if (msgstart + length > buffer.length()) break; // now onto payload auto payload = buffer.mid(msgstart, length); buffer.remove(0, msgstart + length); qCInfo(LSPCLIENT) << "got message payload size " << length; qCDebug(LSPCLIENT) << "message payload:\n" << payload; QJsonParseError error{}; auto msg = QJsonDocument::fromJson(payload, &error); if (error.error != QJsonParseError::NoError || !msg.isObject()) { qCWarning(LSPCLIENT) << "invalid response payload"; continue; } auto result = msg.object(); // check if it is the expected result int msgid = -1; if (result.contains(MEMBER_ID)) { msgid = result[MEMBER_ID].toInt(); } else { processNotification(result); continue; } // could be request if (result.contains(MEMBER_METHOD)) { processRequest(result); continue; } // a valid reply; what to do with it now auto it = m_handlers.find(msgid); if (it != m_handlers.end()) { (*it)(result.value(MEMBER_RESULT)); m_handlers.erase(it); } else { // could have been canceled qCDebug(LSPCLIENT) << "unexpected reply id"; } } } static QJsonObject init_error(const LSPErrorCode code, const QString & msg) { return QJsonObject { { MEMBER_ERROR, QJsonObject { { MEMBER_CODE, (int) code }, { MEMBER_MESSAGE, msg } } } }; } static QJsonObject init_request(const QString & method, const QJsonObject & params = QJsonObject()) { return QJsonObject { { MEMBER_METHOD, method }, { MEMBER_PARAMS, params } }; } static QJsonObject init_response(const QJsonValue & result = QJsonValue()) { return QJsonObject { { MEMBER_RESULT, result } }; } bool running() { return m_sproc.state() == QProcess::Running; } void onStateChanged(QProcess::ProcessState nstate) { if (nstate == QProcess::NotRunning) { setState(State::None); } } void shutdown() { if (m_state == State::Running) { qCInfo(LSPCLIENT) << "shutting down" << m_server; // cancel all pending m_handlers.clear(); // shutdown sequence send(init_request(QStringLiteral("shutdown"))); // maybe we will get/see reply on the above, maybe not // but not important or useful either way send(init_request(QStringLiteral("exit"))); // no longer fit for regular use setState(State::Shutdown); } } void onInitializeReply(const QJsonValue & value) { // only parse parts that we use later on from_json(m_capabilities, value.toObject().value(QStringLiteral("capabilities")).toObject()); // finish init initialized(); } void initialize() { QJsonObject codeAction { { QStringLiteral("codeActionLiteralSupport"), QJsonObject { { QStringLiteral("codeActionKind"), QJsonObject { { QStringLiteral("valueSet"), QJsonArray() } } } } } }; QJsonObject capabilities { { QStringLiteral("textDocument"), QJsonObject { { QStringLiteral("documentSymbol"), QJsonObject { { QStringLiteral("hierarchicalDocumentSymbolSupport"), true } }, }, { QStringLiteral("publishDiagnostics"), QJsonObject { { QStringLiteral("relatedInformation"), true } } }, { QStringLiteral("codeAction"), codeAction } } } }; // NOTE a typical server does not use root all that much, // other than for some corner case (in) requests QJsonObject params { { QStringLiteral("processId"), QCoreApplication::applicationPid() }, { QStringLiteral("rootPath"), m_root.path() }, { QStringLiteral("rootUri"), m_root.toString() }, { QStringLiteral("capabilities"), capabilities }, { QStringLiteral("initializationOptions"), m_init } }; // write(init_request(QStringLiteral("initialize"), params), utils::mem_fun(&self_type::onInitializeReply, this)); } void initialized() { write(init_request(QStringLiteral("initialized"))); setState(State::Running); } public: bool start() { if (m_state != State::None) return true; auto program = m_server.front(); auto args = m_server; args.pop_front(); qCInfo(LSPCLIENT) << "starting" << m_server; // at least we see some errors somewhere then m_sproc.setProcessChannelMode(QProcess::ForwardedErrorChannel); m_sproc.setReadChannel(QProcess::QProcess::StandardOutput); m_sproc.start(program, args); bool result = m_sproc.waitForStarted(); if (!result) { qCWarning(LSPCLIENT) << m_sproc.error(); } else { setState(State::Started); // perform initial handshake initialize(); } return result; } void stop(int to_term, int to_kill) { if (running()) { shutdown(); if ((to_term >= 0) && !m_sproc.waitForFinished(to_term)) m_sproc.terminate(); if ((to_kill >= 0) && !m_sproc.waitForFinished(to_kill)) m_sproc.kill(); } } RequestHandle documentSymbols(const QUrl & document, const GenericReplyHandler & h) { auto params = textDocumentParams(document); return send(init_request(QStringLiteral("textDocument/documentSymbol"), params), h); } RequestHandle documentDefinition(const QUrl & document, const LSPPosition & pos, const GenericReplyHandler & h) { auto params = textDocumentPositionParams(document, pos); return send(init_request(QStringLiteral("textDocument/definition"), params), h); } RequestHandle documentDeclaration(const QUrl & document, const LSPPosition & pos, const GenericReplyHandler & h) { auto params = textDocumentPositionParams(document, pos); return send(init_request(QStringLiteral("textDocument/declaration"), params), h); } RequestHandle documentHover(const QUrl & document, const LSPPosition & pos, const GenericReplyHandler & h) { auto params = textDocumentPositionParams(document, pos); return send(init_request(QStringLiteral("textDocument/hover"), params), h); } RequestHandle documentHighlight(const QUrl & document, const LSPPosition & pos, const GenericReplyHandler & h) { auto params = textDocumentPositionParams(document, pos); return send(init_request(QStringLiteral("textDocument/documentHighlight"), params), h); } RequestHandle documentReferences(const QUrl & document, const LSPPosition & pos, bool decl, const GenericReplyHandler & h) { auto params = referenceParams(document, pos, decl); return send(init_request(QStringLiteral("textDocument/references"), params), h); } RequestHandle documentCompletion(const QUrl & document, const LSPPosition & pos, const GenericReplyHandler & h) { auto params = textDocumentPositionParams(document, pos); return send(init_request(QStringLiteral("textDocument/completion"), params), h); } RequestHandle signatureHelp(const QUrl & document, const LSPPosition & pos, const GenericReplyHandler & h) { auto params = textDocumentPositionParams(document, pos); return send(init_request(QStringLiteral("textDocument/signatureHelp"), params), h); } - RequestHandle documentFormatting(const QUrl & document, int tabSize, bool insertSpaces, - const QJsonObject & options, const GenericReplyHandler & h) + RequestHandle documentFormatting(const QUrl & document, const LSPFormattingOptions & options, + const GenericReplyHandler & h) { - auto params = documentRangeFormattingParams(document, nullptr, tabSize, insertSpaces, options); + auto params = documentRangeFormattingParams(document, nullptr, options); return send(init_request(QStringLiteral("textDocument/formatting"), params), h); } RequestHandle documentRangeFormatting(const QUrl & document, const LSPRange & range, - int tabSize, bool insertSpaces, - const QJsonObject & options, const GenericReplyHandler & h) + const LSPFormattingOptions & options, const GenericReplyHandler & h) { - auto params = documentRangeFormattingParams(document, &range, tabSize, insertSpaces, options); + auto params = documentRangeFormattingParams(document, &range, options); return send(init_request(QStringLiteral("textDocument/rangeFormatting"), params), h); } RequestHandle documentRename(const QUrl & document, const LSPPosition & pos, const QString newName, const GenericReplyHandler & h) { auto params = renameParams(document, pos, newName); return send(init_request(QStringLiteral("textDocument/rename"), params), h); } RequestHandle documentCodeAction(const QUrl & document, const LSPRange & range, const QList & kinds, QList diagnostics, const GenericReplyHandler & h) { auto params = codeActionParams(document, range, kinds, diagnostics); return send(init_request(QStringLiteral("textDocument/codeAction"), params), h); } void executeCommand(const QString & command, const QJsonValue & args) { auto params = executeCommandParams(command, args); send(init_request(QStringLiteral("workspace/executeCommand"), params)); } void didOpen(const QUrl & document, int version, const QString & langId, const QString & text) { auto params = textDocumentParams(textDocumentItem(document, langId, text, version)); send(init_request(QStringLiteral("textDocument/didOpen"), params)); } void didChange(const QUrl & document, int version, const QString & text) { auto params = textDocumentParams(document, version); params[QStringLiteral("contentChanges")] = QJsonArray { QJsonObject {{MEMBER_TEXT, text}} }; send(init_request(QStringLiteral("textDocument/didChange"), params)); } void didSave(const QUrl & document, const QString & text) { auto params = textDocumentParams(document); params[QStringLiteral("text")] = text; send(init_request(QStringLiteral("textDocument/didSave"), params)); } void didClose(const QUrl & document) { auto params = textDocumentParams(document); send(init_request(QStringLiteral("textDocument/didClose"), params)); } void processNotification(const QJsonObject & msg) { auto method = msg[MEMBER_METHOD].toString(); if (method == QStringLiteral("textDocument/publishDiagnostics")) { emit q->publishDiagnostics(parseDiagnostics(msg[MEMBER_PARAMS].toObject())); } else { qCWarning(LSPCLIENT) << "discarding notification" << method; } } template static GenericReplyHandler make_handler(const ReplyHandler & h, const QObject *context, typename utils::identity>::type c) { QPointer ctx(context); return [ctx, h, c] (const GenericReplyType & m) { if (ctx) h(c(m)); }; } GenericReplyHandler prepareResponse(int msgid) { // allow limited number of outstanding requests auto ctx = QPointer(q); m_requests.push_back(msgid); if (m_requests.size() > MAX_REQUESTS) { m_requests.pop_front(); } auto h = [ctx, this, msgid] (const GenericReplyType & response) { if (!ctx) { return; } auto index = m_requests.indexOf(msgid); if (index >= 0) { m_requests.remove(index); write(init_response(response), nullptr, &msgid); } else { qCWarning(LSPCLIENT) << "discarding response" << msgid; } }; return h; } template static ReplyHandler responseHandler(const GenericReplyHandler & h, typename utils::identity>::type c) { return [h, c] (const ReplyType & m) { h(c(m)); }; } // pretty rare and limited use, but anyway void processRequest(const QJsonObject & msg) { auto method = msg[MEMBER_METHOD].toString(); auto msgid = msg[MEMBER_ID].toInt(); auto params = msg[MEMBER_PARAMS]; bool handled = false; if (method == QStringLiteral("workspace/applyEdit")) { auto h = responseHandler(prepareResponse(msgid), applyWorkspaceEditResponse); emit q->applyEdit(parseApplyWorkspaceEditParams(params.toObject()), h, handled); } else { write(init_error(LSPErrorCode::MethodNotFound, method), nullptr, &msgid); qCWarning(LSPCLIENT) << "discarding request" << method; } } }; // follow suit; as performed in kate docmanager // normalize at this stage/layer to avoid surprises elsewhere // sadly this is not a single QUrl method as one might hope ... static QUrl normalizeUrl(const QUrl & url) { // Resolve symbolic links for local files (done anyway in KTextEditor) if (url.isLocalFile()) { QString normalizedUrl = QFileInfo(url.toLocalFile()).canonicalFilePath(); if (!normalizedUrl.isEmpty()) { return QUrl::fromLocalFile(normalizedUrl); } } // else: cleanup only the .. stuff return url.adjusted(QUrl::NormalizePathSegments); } static LSPMarkupContent parseMarkupContent(const QJsonValue & v) { LSPMarkupContent ret; if (v.isObject()) { const auto& vm = v.toObject(); ret.value = vm.value(QStringLiteral("value")).toString(); auto kind = vm.value(MEMBER_KIND).toString(); if (kind == QStringLiteral("plaintext")) { ret.kind = LSPMarkupKind::PlainText; } else if (kind == QStringLiteral("markdown")) { ret.kind = LSPMarkupKind::MarkDown; } } else if (v.isString()) { ret.kind = LSPMarkupKind::PlainText; ret.value = v.toString(); } return ret; } static LSPPosition parsePosition(const QJsonObject & m) { auto line = m.value(MEMBER_LINE).toInt(-1); auto column = m.value(MEMBER_CHARACTER).toInt(-1); return {line, column}; } static bool isPositionValid(const LSPPosition & pos) { return pos.isValid(); } static LSPRange parseRange(const QJsonObject & range) { auto startpos = parsePosition(range.value(MEMBER_START).toObject()); auto endpos = parsePosition(range.value(MEMBER_END).toObject()); return {startpos, endpos}; } static LSPLocation parseLocation(const QJsonObject & loc) { auto uri = normalizeUrl(QUrl(loc.value(MEMBER_URI).toString())); auto range = parseRange(loc.value(MEMBER_RANGE).toObject()); return {QUrl(uri), range}; } static LSPDocumentHighlight parseDocumentHighlight(const QJsonValue & result) { auto hover = result.toObject(); auto range = parseRange(hover.value(MEMBER_RANGE).toObject()); auto kind = (LSPDocumentHighlightKind)hover.value(MEMBER_KIND).toInt((int)LSPDocumentHighlightKind::Text); // default is DocumentHighlightKind.Text return {range, kind}; } static QList parseDocumentHighlightList(const QJsonValue & result) { QList ret; // could be array if (result.isArray()) { for (const auto & def : result.toArray()) { ret.push_back(parseDocumentHighlight(def)); } } else if (result.isObject()) { // or a single value ret.push_back(parseDocumentHighlight(result)); } return ret; } static LSPHover parseHover(const QJsonValue & result) { LSPHover ret; auto hover = result.toObject(); // normalize content which can be of many forms ret.range = parseRange(hover.value(MEMBER_RANGE).toObject()); auto contents = hover.value(QStringLiteral("contents")); if (contents.isString()) { ret.contents.value = contents.toString(); } else { // should be object, pretend so auto cont = contents.toObject(); auto text = cont.value(QStringLiteral("value")).toString(); if (text.isEmpty()) { // nothing to lose, try markdown ret.contents = parseMarkupContent(contents); } else { ret.contents.value = text; } } if (ret.contents.value.length()) ret.contents.kind = LSPMarkupKind::PlainText; return ret; } static QList parseDocumentSymbols(const QJsonValue & result) { // the reply could be old SymbolInformation[] or new (hierarchical) DocumentSymbol[] // try to parse it adaptively in any case // if new style, hierarchy is specified clearly in reply // if old style, it is assumed the values enter linearly, that is; // * a parent/container is listed before its children // * if a name is defined/declared several times and then used as a parent, // then it is the last instance that is used as a parent QList ret; QMap index; std::function parseSymbol = [&] (const QJsonObject & symbol, LSPSymbolInformation *parent) { // if flat list, try to find parent by name if (!parent) { auto container = symbol.value(QStringLiteral("containerName")).toString(); parent = index.value(container, nullptr); } auto list = parent ? &parent->children : &ret; const auto& location = symbol.value(MEMBER_LOCATION).toObject(); const auto& mrange = symbol.contains(MEMBER_RANGE) ? symbol.value(MEMBER_RANGE) : location.value(MEMBER_RANGE); auto range = parseRange(mrange.toObject()); if (isPositionValid(range.start()) && isPositionValid(range.end())) { auto name = symbol.value(QStringLiteral("name")).toString(); auto kind = (LSPSymbolKind) symbol.value(MEMBER_KIND).toInt(); auto detail = symbol.value(MEMBER_DETAIL).toString(); list->push_back({name, kind, range, detail}); index[name] = &list->back(); // proceed recursively for (const auto &child : symbol.value(QStringLiteral("children")).toArray()) parseSymbol(child.toObject(), &list->back()); } }; for (const auto& info : result.toArray()) { parseSymbol(info.toObject(), nullptr); } return ret; } static QList parseDocumentLocation(const QJsonValue & result) { QList ret; // could be array if (result.isArray()) { for (const auto & def : result.toArray()) { ret.push_back(parseLocation(def.toObject())); } } else if (result.isObject()) { // or a single value ret.push_back(parseLocation(result.toObject())); } return ret; } static QList parseDocumentCompletion(const QJsonValue & result) { QList ret; QJsonArray items = result.toArray(); // might be CompletionList if (items.size() == 0) { items = result.toObject().value(QStringLiteral("items")).toArray(); } for (const auto & vitem : items) { const auto & item = vitem.toObject(); auto label = item.value(MEMBER_LABEL).toString(); auto detail = item.value(MEMBER_DETAIL).toString(); auto doc = parseMarkupContent(item.value(MEMBER_DOCUMENTATION)); auto sortText = item.value(QStringLiteral("sortText")).toString(); if (sortText.isEmpty()) sortText = label; auto insertText = item.value(QStringLiteral("insertText")).toString(); if (insertText.isEmpty()) insertText = label; auto kind = (LSPCompletionItemKind) item.value(MEMBER_KIND).toInt(); ret.push_back({label, kind, detail, doc, sortText, insertText}); } return ret; } static LSPSignatureInformation parseSignatureInformation(const QJsonObject & json) { LSPSignatureInformation info; info.label = json.value(MEMBER_LABEL).toString(); info.documentation = parseMarkupContent(json.value(MEMBER_DOCUMENTATION)); for (const auto & rpar : json.value(QStringLiteral("parameters")).toArray()) { auto par = rpar.toObject(); auto label = par.value(MEMBER_LABEL); int begin = -1, end = -1; if (label.isArray()) { auto range = label.toArray(); if (range.size() == 2) { begin = range.at(0).toInt(-1); end = range.at(1).toInt(-1); if (begin > info.label.length()) begin = -1; if (end > info.label.length()) end = -1; } } else { auto sub = label.toString(); if (sub.length()) { begin = info.label.indexOf(sub); if (begin >= 0) { end = begin + sub.length(); } } } info.parameters.push_back({begin, end}); } return info; } static LSPSignatureHelp parseSignatureHelp(const QJsonValue & result) { LSPSignatureHelp ret; QJsonObject sig = result.toObject(); for (const auto & info: sig.value(QStringLiteral("signatures")).toArray()) { ret.signatures.push_back(parseSignatureInformation(info.toObject())); } ret.activeSignature = sig.value(QStringLiteral("activeSignature")).toInt(0); ret.activeParameter = sig.value(QStringLiteral("activeParameter")).toInt(0); ret.activeSignature = qMin(qMax(ret.activeSignature, 0), ret.signatures.size()); ret.activeParameter = qMin(qMax(ret.activeParameter, 0), ret.signatures.size()); return ret; } static QList parseTextEdit(const QJsonValue & result) { QList ret; for (const auto &redit: result.toArray()) { auto edit = redit.toObject(); auto text = edit.value(QStringLiteral("newText")).toString(); auto range = parseRange(edit.value(MEMBER_RANGE).toObject()); ret.push_back({range, text}); } return ret; } static LSPWorkspaceEdit parseWorkSpaceEdit(const QJsonValue & result) { QHash> ret; auto changes = result.toObject().value(QStringLiteral("changes")).toObject(); for (auto it = changes.begin(); it != changes.end(); ++it) { ret.insert(normalizeUrl(QUrl(it.key())), parseTextEdit(it.value())); } return {ret}; } static LSPCommand parseCommand(const QJsonObject & result) { auto title = result.value(MEMBER_TITLE).toString(); auto command = result.value(MEMBER_COMMAND).toString(); auto args = result.value(MEMBER_ARGUMENTS).toArray(); return { title, command, args }; } static QList parseDiagnostics(const QJsonArray &result) { QList ret; for (const auto & vdiag : result) { auto diag = vdiag.toObject(); auto range = parseRange(diag.value(MEMBER_RANGE).toObject()); auto severity = (LSPDiagnosticSeverity) diag.value(QStringLiteral("severity")).toInt(); auto code = diag.value(QStringLiteral("code")).toString(); auto source = diag.value(QStringLiteral("source")).toString(); auto message = diag.value(MEMBER_MESSAGE).toString(); auto related = diag.value(QStringLiteral("relatedInformation")).toObject(); auto relLocation = parseLocation(related.value(MEMBER_LOCATION).toObject()); auto relMessage = related.value(MEMBER_MESSAGE).toString(); ret.push_back({range, severity, code, source, message, relLocation, relMessage}); } return ret; } static QList parseCodeAction(const QJsonValue & result) { QList ret; for (const auto &vaction: result.toArray()) { auto action = vaction.toObject(); // entry could be Command or CodeAction if (!action.value(MEMBER_COMMAND).isString()) { // CodeAction auto title = action.value(MEMBER_TITLE).toString(); auto kind = action.value(MEMBER_KIND).toString(); auto command = parseCommand(action.value(MEMBER_COMMAND).toObject()); auto edit = parseWorkSpaceEdit(action.value(MEMBER_EDIT)); auto diagnostics = parseDiagnostics(action.value(MEMBER_DIAGNOSTICS).toArray()); ret.push_back({title, kind, diagnostics, edit, command}); } else { // Command auto command = parseCommand(action); ret.push_back({command.title, QString(), {}, {}, command}); } } return ret; } static LSPPublishDiagnosticsParams parseDiagnostics(const QJsonObject & result) { LSPPublishDiagnosticsParams ret; ret.uri = normalizeUrl(QUrl(result.value(MEMBER_URI).toString())); ret.diagnostics = parseDiagnostics(result.value(MEMBER_DIAGNOSTICS).toArray()); return ret; } static LSPApplyWorkspaceEditParams parseApplyWorkspaceEditParams(const QJsonObject & result) { LSPApplyWorkspaceEditParams ret; ret.label = result.value(MEMBER_LABEL).toString(); ret.edit = parseWorkSpaceEdit(result.value(MEMBER_EDIT)); return ret; } // generic convert handler // sprinkle some connection-like context safety // not so likely relevant/needed due to typical sequence of events, // but in case the latter would be changed in surprising ways ... template static GenericReplyHandler make_handler(const ReplyHandler & h, const QObject *context, typename utils::identity>::type c) { QPointer ctx(context); return [ctx, h, c] (const GenericReplyType & m) { if (ctx) h(c(m)); }; } LSPClientServer::LSPClientServer(const QStringList & server, const QUrl & root, const QJsonValue & init) : d(new LSPClientServerPrivate(this, server, root, init)) {} LSPClientServer::~LSPClientServer() { delete d; } const QStringList& LSPClientServer::cmdline() const { return d->cmdline(); } LSPClientServer::State LSPClientServer::state() const { return d->state(); } const LSPServerCapabilities& LSPClientServer::capabilities() const { return d->capabilities(); } bool LSPClientServer::start() { return d->start(); } void LSPClientServer::stop(int to_t, int to_k) { return d->stop(to_t, to_k); } int LSPClientServer::cancel(int reqid) { return d->cancel(reqid); } LSPClientServer::RequestHandle LSPClientServer::documentSymbols(const QUrl & document, const QObject *context, const DocumentSymbolsReplyHandler & h) { return d->documentSymbols(document, make_handler(h, context, parseDocumentSymbols)); } LSPClientServer::RequestHandle LSPClientServer::documentDefinition(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentDefinitionReplyHandler & h) { return d->documentDefinition(document, pos, make_handler(h, context, parseDocumentLocation)); } LSPClientServer::RequestHandle LSPClientServer::documentDeclaration(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentDefinitionReplyHandler & h) { return d->documentDeclaration(document, pos, make_handler(h, context, parseDocumentLocation)); } LSPClientServer::RequestHandle LSPClientServer::documentHover(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentHoverReplyHandler & h) { return d->documentHover(document, pos, make_handler(h, context, parseHover)); } LSPClientServer::RequestHandle LSPClientServer::documentHighlight(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentHighlightReplyHandler & h) { return d->documentHighlight(document, pos, make_handler(h, context, parseDocumentHighlightList)); } LSPClientServer::RequestHandle LSPClientServer::documentReferences(const QUrl & document, const LSPPosition & pos, bool decl, const QObject *context, const DocumentDefinitionReplyHandler & h) { return d->documentReferences(document, pos, decl, make_handler(h, context, parseDocumentLocation)); } LSPClientServer::RequestHandle LSPClientServer::documentCompletion(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentCompletionReplyHandler & h) { return d->documentCompletion(document, pos, make_handler(h, context, parseDocumentCompletion)); } LSPClientServer::RequestHandle LSPClientServer::signatureHelp(const QUrl & document, const LSPPosition & pos, const QObject *context, const SignatureHelpReplyHandler & h) { return d->signatureHelp(document, pos, make_handler(h, context, parseSignatureHelp)); } LSPClientServer::RequestHandle -LSPClientServer::documentFormatting(const QUrl & document, int tabSize, bool insertSpaces, - const QJsonObject & options, const QObject *context, const FormattingReplyHandler & h) -{ return d->documentFormatting(document, tabSize, insertSpaces, options, make_handler(h, context, parseTextEdit)); } +LSPClientServer::documentFormatting(const QUrl & document, const LSPFormattingOptions & options, + const QObject *context, const FormattingReplyHandler & h) +{ return d->documentFormatting(document, options, make_handler(h, context, parseTextEdit)); } LSPClientServer::RequestHandle LSPClientServer::documentRangeFormatting(const QUrl & document, const LSPRange & range, - int tabSize, bool insertSpaces, const QJsonObject & options, + const LSPFormattingOptions & options, const QObject *context, const FormattingReplyHandler & h) -{ return d->documentRangeFormatting(document, range, tabSize, insertSpaces, options, make_handler(h, context, parseTextEdit)); } +{ return d->documentRangeFormatting(document, range, options, make_handler(h, context, parseTextEdit)); } LSPClientServer::RequestHandle LSPClientServer::documentRename(const QUrl & document, const LSPPosition & pos, const QString newName, const QObject *context, const WorkspaceEditReplyHandler & h) { return d->documentRename(document, pos, newName, make_handler(h, context, parseWorkSpaceEdit)); } LSPClientServer::RequestHandle LSPClientServer::documentCodeAction(const QUrl & document, const LSPRange & range, const QList & kinds, QList diagnostics, const QObject *context, const CodeActionReplyHandler & h) { return d->documentCodeAction(document, range, kinds, diagnostics, make_handler(h, context, parseCodeAction)); } void LSPClientServer::executeCommand(const QString & command, const QJsonValue & args) { return d->executeCommand(command, args); } void LSPClientServer::didOpen(const QUrl & document, int version, const QString & langId, const QString & text) { return d->didOpen(document, version, langId, text); } void LSPClientServer::didChange(const QUrl & document, int version, const QString & text) { return d->didChange(document, version, text); } void LSPClientServer::didSave(const QUrl & document, const QString & text) { return d->didSave(document, text); } void LSPClientServer::didClose(const QUrl & document) { return d->didClose(document); } diff --git a/addons/lspclient/lspclientserver.h b/addons/lspclient/lspclientserver.h index 7e1f26769..4d3c02380 100644 --- a/addons/lspclient/lspclientserver.h +++ b/addons/lspclient/lspclientserver.h @@ -1,182 +1,182 @@ /* SPDX-License-Identifier: MIT Copyright (C) 2019 Mark Nauwelaerts 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. */ #ifndef LSPCLIENTSERVER_H #define LSPCLIENTSERVER_H #include "lspclientprotocol.h" #include #include #include #include #include #include #include #include namespace utils { // template helper // function bind helpers template inline std::function mem_fun(R (T::*pm)(Args ...), Tp object) { return [object, pm](Args... args) { return (object->*pm)(std::forward(args)...); }; } template inline std::function mem_fun(R (T::*pm)(Args ...) const, Tp object) { return [object, pm](Args... args) { return (object->*pm)(std::forward(args)...); }; } // prevent argument deduction template struct identity { typedef T type; }; } // namespace utils static const int TIMEOUT_SHUTDOWN = 200; template using ReplyHandler = std::function; using DocumentSymbolsReplyHandler = ReplyHandler>; using DocumentDefinitionReplyHandler = ReplyHandler>; using DocumentHighlightReplyHandler = ReplyHandler>; using DocumentHoverReplyHandler = ReplyHandler; using DocumentCompletionReplyHandler = ReplyHandler>; using SignatureHelpReplyHandler = ReplyHandler; using FormattingReplyHandler = ReplyHandler>; using CodeActionReplyHandler = ReplyHandler>; using WorkspaceEditReplyHandler = ReplyHandler; using ApplyEditReplyHandler = ReplyHandler; class LSPClientServer : public QObject { Q_OBJECT public: enum class State { None, Started, Running, Shutdown }; class LSPClientServerPrivate; class RequestHandle { friend class LSPClientServerPrivate; QPointer m_server; int m_id = -1; public: RequestHandle& cancel() { if (m_server) m_server->cancel(m_id); return *this; } }; LSPClientServer(const QStringList & server, const QUrl & root, const QJsonValue & init = QJsonValue()); ~LSPClientServer(); // server management // request start bool start(); // request shutdown/stop // if to_xxx >= 0 -> send signal if not exit'ed after timeout void stop(int to_term_ms, int to_kill_ms); int cancel(int id); // properties const QStringList& cmdline() const; State state() const; Q_SIGNAL void stateChanged(LSPClientServer * server); const LSPServerCapabilities& capabilities() const; // language RequestHandle documentSymbols(const QUrl & document, const QObject *context, const DocumentSymbolsReplyHandler & h); RequestHandle documentDefinition(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentDefinitionReplyHandler & h); RequestHandle documentDeclaration(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentDefinitionReplyHandler & h); RequestHandle documentHighlight(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentHighlightReplyHandler & h); RequestHandle documentHover(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentHoverReplyHandler & h); RequestHandle documentReferences(const QUrl & document, const LSPPosition & pos, bool decl, const QObject *context, const DocumentDefinitionReplyHandler & h); RequestHandle documentCompletion(const QUrl & document, const LSPPosition & pos, const QObject *context, const DocumentCompletionReplyHandler & h); RequestHandle signatureHelp(const QUrl & document, const LSPPosition & pos, const QObject *context, const SignatureHelpReplyHandler & h); - RequestHandle documentFormatting(const QUrl & document, int tabSize, bool insertSpaces, - const QJsonObject & options, const QObject *context, const FormattingReplyHandler & h); + RequestHandle documentFormatting(const QUrl & document, const LSPFormattingOptions & options, + const QObject *context, const FormattingReplyHandler & h); RequestHandle documentRangeFormatting(const QUrl & document, const LSPRange & range, - int tabSize, bool insertSpaces, const QJsonObject & options, + const LSPFormattingOptions & options, const QObject *context, const FormattingReplyHandler & h); RequestHandle documentRename(const QUrl & document, const LSPPosition & pos, const QString newName, const QObject *context, const WorkspaceEditReplyHandler & h); RequestHandle documentCodeAction(const QUrl & document, const LSPRange & range, const QList & kinds, QList diagnostics, const QObject *context, const CodeActionReplyHandler & h); void executeCommand(const QString & command, const QJsonValue & args); // sync void didOpen(const QUrl & document, int version, const QString & langId, const QString & text); void didChange(const QUrl & document, int version, const QString & text); void didSave(const QUrl & document, const QString & text); void didClose(const QUrl & document); // notifcation = signal Q_SIGNALS: void publishDiagnostics(const LSPPublishDiagnosticsParams & ); // request = signal void applyEdit(const LSPApplyWorkspaceEditParams &req, const ApplyEditReplyHandler &h, bool &handled); private: // pimpl data holder LSPClientServerPrivate * const d; }; #endif diff --git a/addons/lspclient/tests/lsptestapp.cpp b/addons/lspclient/tests/lsptestapp.cpp index 0bc3fdda5..7cce4b01b 100644 --- a/addons/lspclient/tests/lsptestapp.cpp +++ b/addons/lspclient/tests/lsptestapp.cpp @@ -1,129 +1,129 @@ /* SPDX-License-Identifier: MIT Copyright (C) 2019 Mark Nauwelaerts 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. */ #include "../lspclientserver.h" #include #include #include #include #include #include int main(int argc, char ** argv) { if (argc < 5) return -1; LSPClientServer lsp(QString::fromLatin1(argv[1]).split(QStringLiteral(" ")), QUrl(QString::fromLatin1(argv[2]))); QCoreApplication app(argc, argv); QEventLoop q; auto state_h = [&lsp, &q] () { if (lsp.state() == LSPClientServer::State::Running) q.quit(); }; auto conn = QObject::connect(&lsp, &LSPClientServer::stateChanged, state_h); lsp.start(); q.exec(); QObject::disconnect(conn); auto diagnostics_h = [] (const LSPPublishDiagnosticsParams & diag) { std::cout << "diagnostics " << diag.uri.path().toUtf8().toStdString() << " count: " << diag.diagnostics.length(); }; QObject::connect(&lsp, &LSPClientServer::publishDiagnostics, diagnostics_h); auto document = QUrl(QString::fromLatin1(argv[3])); QFile file(document.path()); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return -1; QTextStream in(&file); QString content = in.readAll(); lsp.didOpen(document, 0, QString(), content); auto ds_h = [&q] (const QList & syms) { std::cout << "symbol count: " << syms.length() << std::endl; q.quit(); }; lsp.documentSymbols(document, &app, ds_h); q.exec(); auto position = QString::fromLatin1(argv[4]).split(QStringLiteral(" ")); auto def_h = [&q] (const QList & defs) { std::cout << "definition count: " << defs.length() << std::endl; q.quit(); }; lsp.documentDefinition(document, {position[0].toInt(), position[1].toInt()}, &app, def_h); q.exec(); auto comp_h = [&q] (const QList & completions) { std::cout << "completion count: " << completions.length() << std::endl; q.quit(); }; lsp.documentCompletion(document, {position[0].toInt(), position[1].toInt()}, &app, comp_h); q.exec(); auto sig_h = [&q] (const LSPSignatureHelp & help) { std::cout << "signature help count: " << help.signatures.length() << std::endl; q.quit(); }; lsp.signatureHelp(document, {position[0].toInt(), position[1].toInt()}, &app, sig_h); q.exec(); auto hover_h = [&q] (const LSPHover & hover) { std::cout << "hover: " << hover.contents.value.toStdString() << std::endl; q.quit(); }; lsp.documentHover(document, {position[0].toInt(), position[1].toInt()}, &app, hover_h); q.exec(); auto ref_h = [&q] (const QList & refs) { std::cout << "refs: " << refs.length() << std::endl; q.quit(); }; lsp.documentReferences(document, {position[0].toInt(), position[1].toInt()}, true, &app, ref_h); q.exec(); auto hl_h = [&q] (const QList & hls) { std::cout << "highlights: " << hls.length() << std::endl; q.quit(); }; lsp.documentHighlight(document, {position[0].toInt(), position[1].toInt()}, &app, hl_h); q.exec(); auto fmt_h = [&q] (const QList & edits) { std::cout << "edits: " << edits.length() << std::endl; q.quit(); }; - lsp.documentFormatting(document, 2, true, QJsonObject(), &app, fmt_h); + lsp.documentFormatting(document, {2, true, QJsonObject()}, &app, fmt_h); q.exec(); // lsp.didOpen(document, 0, QStringLiteral("blah")); lsp.didChange(document, 1, QStringLiteral("foo")); lsp.didClose(document); }