aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/languageclient/languageclientoutline.cpp
blob: 6928edeccfe42ce4d77ca87c0187b90f5a9a2163 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "languageclientoutline.h"

#include "documentsymbolcache.h"
#include "languageclientmanager.h"
#include "languageclientutils.h"

#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/find/itemviewfind.h>
#include <languageserverprotocol/languagefeatures.h>
#include <texteditor/outlinefactory.h>
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>
#include <utils/dropsupport.h>
#include <utils/itemviews.h>
#include <utils/navigationtreeview.h>
#include <utils/treemodel.h>
#include <utils/treeviewcombobox.h>
#include <utils/utilsicons.h>

#include <QAction>
#include <QBoxLayout>
#include <QSortFilterProxyModel>

using namespace LanguageServerProtocol;

namespace LanguageClient {

const QList<SymbolInformation> sortedSymbols(const QList<SymbolInformation> &symbols)
{
    auto result = symbols;
    Utils::sort(result, [](const SymbolInformation &a, const SymbolInformation &b){
        return a.location().range().start() < b.location().range().start();
    });
    return result;
}
const QList<DocumentSymbol> sortedSymbols(const QList<DocumentSymbol> &symbols)
{
    auto result = symbols;
    Utils::sort(result, [](const DocumentSymbol &a, const DocumentSymbol &b){
        return a.range().start() < b.range().start();
    });
    return result;
}

class LanguageClientOutlineItem : public Utils::TypedTreeItem<LanguageClientOutlineItem>
{
public:
    LanguageClientOutlineItem() = default;
    LanguageClientOutlineItem(const SymbolInformation &info)
        : m_name(info.name())
        , m_range(info.location().range())
        , m_type(info.kind())
    { }

    LanguageClientOutlineItem(const DocumentSymbol &info, const SymbolStringifier &stringifier)
        : m_name(info.name())
        , m_detail(info.detail().value_or(QString()))
        , m_range(info.range())
        , m_symbolStringifier(stringifier)
        , m_type(info.kind())
    {
        const QList<LanguageServerProtocol::DocumentSymbol> children = sortedSymbols(
                    info.children().value_or(QList<DocumentSymbol>()));
        for (const DocumentSymbol &child : children)
            appendChild(new LanguageClientOutlineItem(child, stringifier));
    }

    // TreeItem interface
    QVariant data(int column, int role) const override
    {
        switch (role) {
        case Qt::DecorationRole:
            return symbolIcon(m_type);
        case Qt::DisplayRole:
            return m_symbolStringifier
                    ? m_symbolStringifier(static_cast<SymbolKind>(m_type), m_name, m_detail)
                    : m_name;
        default:
            return Utils::TreeItem::data(column, role);
        }
    }

    Qt::ItemFlags flags(int column) const override
    {
        Q_UNUSED(column)
        return Utils::TypedTreeItem<LanguageClientOutlineItem>::flags(column)
               | Qt::ItemIsDragEnabled;
    }

    Range range() const { return m_range; }
    Position pos() const { return m_range.start(); }
    bool contains(const Position &pos) const { return m_range.contains(pos); }

private:
    QString m_name;
    QString m_detail;
    Range m_range;
    SymbolStringifier m_symbolStringifier;
    int m_type = -1;
};

class LanguageClientOutlineModel : public Utils::TreeModel<LanguageClientOutlineItem>
{
public:
    using Utils::TreeModel<LanguageClientOutlineItem>::TreeModel;
    void setFilePath(const Utils::FilePath &filePath) { m_filePath = filePath; }

    void setInfo(const QList<SymbolInformation> &info)
    {
        clear();
        for (const SymbolInformation &symbol : sortedSymbols(info))
            rootItem()->appendChild(new LanguageClientOutlineItem(symbol));
    }
    void setInfo(const QList<DocumentSymbol> &info)
    {
        clear();
        for (const DocumentSymbol &symbol : sortedSymbols(info))
            rootItem()->appendChild(new LanguageClientOutlineItem(symbol, m_symbolStringifier));
    }

    void setSymbolStringifier(const SymbolStringifier &stringifier)
    {
        m_symbolStringifier = stringifier;
    }

    Qt::DropActions supportedDragActions() const override
    {
        return Qt::MoveAction;
    }

    QStringList mimeTypes() const override
    {
        return Utils::DropSupport::mimeTypesForFilePaths();
    }

    QMimeData *mimeData(const QModelIndexList &indexes) const override
    {
        auto mimeData = new Utils::DropMimeData;
        for (const QModelIndex &index : indexes) {
            if (LanguageClientOutlineItem *item = itemForIndex(index)) {
                const LanguageServerProtocol::Position pos = item->pos();
                mimeData->addFile(m_filePath, pos.line() + 1, pos.character());
            }
        }
        return mimeData;
    }

private:
    SymbolStringifier m_symbolStringifier;
    Utils::FilePath m_filePath;
};

class DragSortFilterProxyModel : public QSortFilterProxyModel
{
public:
    using QSortFilterProxyModel::QSortFilterProxyModel;

    Qt::DropActions supportedDragActions() const override
    {
        return sourceModel()->supportedDragActions();
    }
};

class LanguageClientOutlineWidget : public TextEditor::IOutlineWidget
{
public:
    LanguageClientOutlineWidget(Client *client, TextEditor::BaseTextEditor *editor);

    // IOutlineWidget interface
public:
    QList<QAction *> filterMenuActions() const override;
    void setCursorSynchronization(bool syncWithCursor) override;
    void setSorted(bool) override;
    bool isSorted() const override;
    void restoreSettings(const QVariantMap &map) override;
    QVariantMap settings() const override;

private:
    void handleResponse(const DocumentUri &uri, const DocumentSymbolsResult &response);
    void updateTextCursor(const QModelIndex &proxyIndex);
    void updateSelectionInTree(const QTextCursor &currentCursor);
    void onItemActivated(const QModelIndex &index);

    QPointer<Client> m_client;
    QPointer<TextEditor::BaseTextEditor> m_editor;
    LanguageClientOutlineModel m_model;
    DragSortFilterProxyModel m_proxyModel;
    Utils::NavigationTreeView m_view;
    DocumentUri m_uri;
    bool m_sync = false;
    bool m_sorted = false;
};

LanguageClientOutlineWidget::LanguageClientOutlineWidget(Client *client,
                                                         TextEditor::BaseTextEditor *editor)
    : m_client(client)
    , m_editor(editor)
    , m_view(this)
    , m_uri(DocumentUri::fromFilePath(editor->textDocument()->filePath()))
{
    connect(client->documentSymbolCache(),
            &DocumentSymbolCache::gotSymbols,
            this,
            &LanguageClientOutlineWidget::handleResponse);
    connect(client, &Client::documentUpdated, this, [this](TextEditor::TextDocument *document) {
        if (m_client && m_uri == DocumentUri::fromFilePath(document->filePath()))
            m_client->documentSymbolCache()->requestSymbols(m_uri, Schedule::Delayed);
    });

    client->documentSymbolCache()->requestSymbols(m_uri, Schedule::Delayed);

    auto *layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    layout->addWidget(Core::ItemViewFind::createSearchableWrapper(&m_view));
    setLayout(layout);
    m_model.setSymbolStringifier(m_client->symbolStringifier());
    m_model.setFilePath(editor->textDocument()->filePath());
    m_proxyModel.setSourceModel(&m_model);
    m_view.setModel(&m_proxyModel);
    m_view.setHeaderHidden(true);
    m_view.setExpandsOnDoubleClick(false);
    m_view.setFrameStyle(QFrame::NoFrame);
    m_view.setDragEnabled(true);
    m_view.setDragDropMode(QAbstractItemView::DragOnly);
    connect(&m_view, &QAbstractItemView::activated,
            this, &LanguageClientOutlineWidget::onItemActivated);
    connect(m_editor->editorWidget(), &TextEditor::TextEditorWidget::cursorPositionChanged,
            this, [this](){
        if (m_sync)
            updateSelectionInTree(m_editor->textCursor());
    });
    setFocusProxy(&m_view);
}

QList<QAction *> LanguageClientOutlineWidget::filterMenuActions() const
{
    return {};
}

void LanguageClientOutlineWidget::setCursorSynchronization(bool syncWithCursor)
{
    m_sync = syncWithCursor;
    if (m_sync && m_editor)
        updateSelectionInTree(m_editor->textCursor());
}

void LanguageClientOutlineWidget::setSorted(bool sorted)
{
    m_sorted = sorted;
    m_proxyModel.sort(sorted ? 0 : -1);
}

bool LanguageClientOutlineWidget::isSorted() const
{
    return m_sorted;
}

void LanguageClientOutlineWidget::restoreSettings(const QVariantMap &map)
{
    setSorted(map.value(QString("LspOutline.Sort"), false).toBool());
}

QVariantMap LanguageClientOutlineWidget::settings() const
{
    return {{QString("LspOutline.Sort"), m_sorted}};
}

void LanguageClientOutlineWidget::handleResponse(const DocumentUri &uri,
                                                 const DocumentSymbolsResult &result)
{
    if (uri != m_uri)
        return;
    if (Utils::holds_alternative<QList<SymbolInformation>>(result))
        m_model.setInfo(Utils::get<QList<SymbolInformation>>(result));
    else if (Utils::holds_alternative<QList<DocumentSymbol>>(result))
        m_model.setInfo(Utils::get<QList<DocumentSymbol>>(result));
    else
        m_model.clear();

    // The list has changed, update the current items
    updateSelectionInTree(m_editor->textCursor());
}

void LanguageClientOutlineWidget::updateTextCursor(const QModelIndex &proxyIndex)
{
    LanguageClientOutlineItem *item = m_model.itemForIndex(m_proxyModel.mapToSource(proxyIndex));
    const Position &pos = item->pos();
    // line has to be 1 based, column 0 based!
    m_editor->editorWidget()->gotoLine(pos.line() + 1, pos.character(), true, true);
}

static LanguageClientOutlineItem *itemForCursor(const LanguageClientOutlineModel &m_model,
                                                const QTextCursor &cursor)
{
    const Position pos(cursor);
    LanguageClientOutlineItem *result = nullptr;
    m_model.forAllItems([&](LanguageClientOutlineItem *candidate){
        if (!candidate->contains(pos))
            return;
        if (result && candidate->range().contains(result->range()))
            return; // skip item if the range is equal or bigger than the previous found range
        result = candidate;
    });
    return result;
}

void LanguageClientOutlineWidget::updateSelectionInTree(const QTextCursor &currentCursor)
{
    if (LanguageClientOutlineItem *item = itemForCursor(m_model, currentCursor)) {
        const QModelIndex index = m_proxyModel.mapFromSource(m_model.indexForItem(item));
        m_view.setCurrentIndex(index);
        m_view.scrollTo(index);
    } else {
        m_view.clearSelection();
    }
}

void LanguageClientOutlineWidget::onItemActivated(const QModelIndex &index)
{
    if (!index.isValid() || !m_editor)
        return;

    updateTextCursor(index);
    m_editor->widget()->setFocus();
}

bool LanguageClientOutlineWidgetFactory::supportsEditor(Core::IEditor *editor) const
{
    if (auto doc = qobject_cast<TextEditor::TextDocument *>(editor->document())) {
        if (Client *client = LanguageClientManager::clientForDocument(doc))
            return client->supportsDocumentSymbols(doc);
    }
    return false;
}

TextEditor::IOutlineWidget *LanguageClientOutlineWidgetFactory::createWidget(Core::IEditor *editor)
{
    auto textEditor = qobject_cast<TextEditor::BaseTextEditor *>(editor);
    QTC_ASSERT(textEditor, return nullptr);
    if (Client *client = LanguageClientManager::clientForDocument(textEditor->textDocument())) {
        if (client->supportsDocumentSymbols(textEditor->textDocument()))
            return new LanguageClientOutlineWidget(client, textEditor);
    }
    return nullptr;
}

class OutlineComboBox : public Utils::TreeViewComboBox
{
    Q_DECLARE_TR_FUNCTIONS(LanguageClient::OutlineComboBox)
public:
    OutlineComboBox(Client *client, TextEditor::BaseTextEditor *editor);

private:
    void updateModel(const DocumentUri &resultUri, const DocumentSymbolsResult &result);
    void updateEntry();
    void activateEntry();
    void documentUpdated(TextEditor::TextDocument *document);
    void setSorted(bool sorted);

    LanguageClientOutlineModel m_model;
    QSortFilterProxyModel m_proxyModel;
    QPointer<Client> m_client;
    TextEditor::TextEditorWidget *m_editorWidget;
    const DocumentUri m_uri;
};

Utils::TreeViewComboBox *LanguageClientOutlineWidgetFactory::createComboBox(
    Client *client, TextEditor::BaseTextEditor *editor)
{
    if (client && client->supportsDocumentSymbols(editor->textDocument()))
        return new OutlineComboBox(client, editor);
    return nullptr;
}

OutlineComboBox::OutlineComboBox(Client *client, TextEditor::BaseTextEditor *editor)
    : m_client(client)
    , m_editorWidget(editor->editorWidget())
    , m_uri(DocumentUri::fromFilePath(editor->document()->filePath()))
{
    m_model.setSymbolStringifier(client->symbolStringifier());
    m_proxyModel.setSourceModel(&m_model);
    const bool sorted = LanguageClientSettings::outlineComboBoxIsSorted();
    m_proxyModel.sort(sorted ? 0 : -1);
    setModel(&m_proxyModel);
    setMinimumContentsLength(13);
    QSizePolicy policy = sizePolicy();
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    setSizePolicy(policy);
    setMaxVisibleItems(40);

    setContextMenuPolicy(Qt::ActionsContextMenu);
    const QString sortActionText
        = QCoreApplication::translate("TextEditor::Internal::OutlineWidgetStack",
                                      "Sort Alphabetically");
    auto sortAction = new QAction(sortActionText, this);
    sortAction->setCheckable(true);
    sortAction->setChecked(sorted);
    addAction(sortAction);

    connect(client->documentSymbolCache(),
            &DocumentSymbolCache::gotSymbols,
            this,
            &OutlineComboBox::updateModel);
    connect(client, &Client::documentUpdated, this, &OutlineComboBox::documentUpdated);
    connect(m_editorWidget, &TextEditor::TextEditorWidget::cursorPositionChanged,
            this, &OutlineComboBox::updateEntry);
    connect(this, &QComboBox::activated, this, &OutlineComboBox::activateEntry);
    connect(sortAction, &QAction::toggled, this, &OutlineComboBox::setSorted);

    documentUpdated(editor->textDocument());
}

void OutlineComboBox::updateModel(const DocumentUri &resultUri, const DocumentSymbolsResult &result)
{
    if (m_uri != resultUri)
        return;
    if (Utils::holds_alternative<QList<SymbolInformation>>(result))
        m_model.setInfo(Utils::get<QList<SymbolInformation>>(result));
    else if (Utils::holds_alternative<QList<DocumentSymbol>>(result))
        m_model.setInfo(Utils::get<QList<DocumentSymbol>>(result));
    else
        m_model.clear();

    view()->expandAll();
    // The list has changed, update the current item
    updateEntry();
}

void OutlineComboBox::updateEntry()
{
    if (LanguageClientOutlineItem *item = itemForCursor(m_model, m_editorWidget->textCursor()))
        setCurrentIndex(m_proxyModel.mapFromSource(m_model.indexForItem(item)));
}

void OutlineComboBox::activateEntry()
{
    const QModelIndex modelIndex = m_proxyModel.mapToSource(view()->currentIndex());
    if (modelIndex.isValid()) {
        const Position &pos = m_model.itemForIndex(modelIndex)->pos();
        Core::EditorManager::cutForwardNavigationHistory();
        Core::EditorManager::addCurrentPositionToNavigationHistory();
        // line has to be 1 based, column 0 based!
        m_editorWidget->gotoLine(pos.line() + 1, pos.character(), true, true);
        emit m_editorWidget->activateEditor();
    }
}

void OutlineComboBox::documentUpdated(TextEditor::TextDocument *document)
{
    if (document == m_editorWidget->textDocument())
        m_client->documentSymbolCache()->requestSymbols(m_uri, Schedule::Delayed);
}

void OutlineComboBox::setSorted(bool sorted)
{
    LanguageClientSettings::setOutlineComboBoxSorted(sorted);
    m_proxyModel.sort(sorted ? 0 : -1);
}

} // namespace LanguageClient