summaryrefslogtreecommitdiff
path: root/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
blob: 4918b93f92e9f04f465d0619a3282fe9c202e844 (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
/****************************************************************************
**
** Copyright (C) 2016 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 "functionhintproposalwidget.h"
#include "ifunctionhintproposalmodel.h"
#include "codeassistant.h"

#include <utils/algorithm.h>
#include <utils/faketooltip.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>

#include <QDebug>
#include <QApplication>
#include <QLabel>
#include <QToolButton>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QPointer>
#include <QScreen>

namespace TextEditor {

static const int maxSelectedFunctionHints = 20;

class SelectedFunctionHints
{
public:
    void insert(int basePosition, const QString &hintId)
    {
        if (basePosition < 0 || hintId.isEmpty())
            return;

        const int index = indexOf(basePosition);

        // Add new item
        if (index == -1) {
            if (m_items.size() + 1 > maxSelectedFunctionHints)
                m_items.removeLast();
            m_items.prepend(FunctionHintItem(basePosition, hintId));
            return;
        }

        // Update existing item
        m_items[index].hintId = hintId;
    }

    QString hintId(int basePosition) const
    {
        const int index = indexOf(basePosition);
        return index == -1 ? QString() : m_items.at(index).hintId;
    }

private:
    int indexOf(int basePosition) const
    {
        return Utils::indexOf(m_items, [&](const FunctionHintItem &item) {
            return item.basePosition == basePosition;
        });
    }

private:
    struct FunctionHintItem {
        FunctionHintItem(int basePosition, const QString &hintId)
            : basePosition(basePosition), hintId(hintId) {}

        int basePosition = -1;
        QString hintId;
    };

    QList<FunctionHintItem> m_items;
};

// -------------------------
// HintProposalWidgetPrivate
// -------------------------
struct FunctionHintProposalWidgetPrivate
{
    FunctionHintProposalWidgetPrivate();

    const QWidget *m_underlyingWidget = nullptr;
    CodeAssistant *m_assistant = nullptr;
    FunctionHintProposalModelPtr m_model;
    QPointer<Utils::FakeToolTip> m_popupFrame; // guard WA_DeleteOnClose widget
    QLabel *m_numberLabel = nullptr;
    QLabel *m_hintLabel = nullptr;
    QWidget *m_pager = nullptr;
    QRect m_displayRect;
    int m_currentHint = -1;
    int m_totalHints = 0;
    int m_currentArgument = -1;
    bool m_escapePressed = false;
};

FunctionHintProposalWidgetPrivate::FunctionHintProposalWidgetPrivate()
    : m_popupFrame(new Utils::FakeToolTip)
    , m_numberLabel(new QLabel)
    , m_hintLabel(new QLabel)
    , m_pager(new QWidget)
{
    m_hintLabel->setTextFormat(Qt::RichText);
}

// ------------------
// HintProposalWidget
// ------------------
FunctionHintProposalWidget::FunctionHintProposalWidget()
    : d(new FunctionHintProposalWidgetPrivate)
{
    auto downArrow = new QToolButton;
    downArrow->setArrowType(Qt::DownArrow);
    downArrow->setFixedSize(16, 16);
    downArrow->setAutoRaise(true);

    auto upArrow = new QToolButton;
    upArrow->setArrowType(Qt::UpArrow);
    upArrow->setFixedSize(16, 16);
    upArrow->setAutoRaise(true);

    auto pagerLayout = new QHBoxLayout(d->m_pager);
    pagerLayout->setContentsMargins(0, 0, 0, 0);
    pagerLayout->setSpacing(0);
    pagerLayout->addWidget(upArrow);
    pagerLayout->addWidget(d->m_numberLabel);
    pagerLayout->addWidget(downArrow);

    auto popupLayout = new QHBoxLayout(d->m_popupFrame);
    popupLayout->setContentsMargins(0, 0, 0, 0);
    popupLayout->setSpacing(0);
    popupLayout->addWidget(d->m_pager);
    popupLayout->addWidget(d->m_hintLabel);

    connect(upArrow, &QAbstractButton::clicked, this, &FunctionHintProposalWidget::previousPage);
    connect(downArrow, &QAbstractButton::clicked, this, &FunctionHintProposalWidget::nextPage);
    connect(d->m_popupFrame.data(), &QObject::destroyed, this, [this] {
        qApp->removeEventFilter(this);
        deleteLater();
    });

    setFocusPolicy(Qt::NoFocus);
}

FunctionHintProposalWidget::~FunctionHintProposalWidget()
{
    delete d;
}

void FunctionHintProposalWidget::setAssistant(CodeAssistant *assistant)
{
    d->m_assistant = assistant;
}

void FunctionHintProposalWidget::setReason(AssistReason)
{}

void FunctionHintProposalWidget::setKind(AssistKind)
{}

void FunctionHintProposalWidget::setUnderlyingWidget(const QWidget *underlyingWidget)
{
    d->m_underlyingWidget = underlyingWidget;
}

void FunctionHintProposalWidget::setModel(ProposalModelPtr model)
{
    d->m_model = model.staticCast<IFunctionHintProposalModel>();
}

void FunctionHintProposalWidget::setDisplayRect(const QRect &rect)
{
    d->m_displayRect = rect;
}

void FunctionHintProposalWidget::setIsSynchronized(bool)
{}

void FunctionHintProposalWidget::showProposal(const QString &prefix)
{
    QTC_ASSERT(d->m_model && d->m_assistant, abort(); return; );

    d->m_totalHints = d->m_model->size();
    QTC_ASSERT(d->m_totalHints != 0, abort(); return; );

    d->m_pager->setVisible(d->m_totalHints > 1);
    d->m_currentHint = loadSelectedHint();
    if (!updateAndCheck(prefix))
        return;

    qApp->installEventFilter(this);
    d->m_popupFrame->show();
}

void FunctionHintProposalWidget::updateProposal(const QString &prefix)
{
    updateAndCheck(prefix);
}

void FunctionHintProposalWidget::closeProposal()
{
    abort();
}

bool FunctionHintProposalWidget::proposalIsVisible() const
{
    return d->m_popupFrame && d->m_popupFrame->isVisible();
}

void FunctionHintProposalWidget::abort()
{
    qApp->removeEventFilter(this);
    if (proposalIsVisible())
        d->m_popupFrame->close();
    deleteLater();
}

static SelectedFunctionHints selectedFunctionHints(CodeAssistant &codeAssistant)
{
    const QVariant variant = codeAssistant.userData();
    return variant.value<SelectedFunctionHints>();
}

int FunctionHintProposalWidget::loadSelectedHint() const
{
    const QString hintId = selectedFunctionHints(*d->m_assistant).hintId(basePosition());

    for (int i = 0; i < d->m_model->size(); ++i) {
        if (d->m_model->id(i) == hintId)
            return i;
    }

    return 0;
}

void FunctionHintProposalWidget::storeSelectedHint()
{
    SelectedFunctionHints table = selectedFunctionHints(*d->m_assistant);
    table.insert(basePosition(), d->m_model->id(d->m_currentHint));

    d->m_assistant->setUserData(QVariant::fromValue(table));
}

bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e)
{
    switch (e->type()) {
    case QEvent::ShortcutOverride:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            d->m_escapePressed = true;
            e->accept();
        }
        break;
    case QEvent::KeyPress:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            d->m_escapePressed = true;
            e->accept();
        }
        QTC_CHECK(d->m_model);
        if (d->m_model && d->m_model->size() > 1) {
            auto ke = static_cast<QKeyEvent*>(e);
            if (ke->key() == Qt::Key_Up) {
                previousPage();
                return true;
            } else if (ke->key() == Qt::Key_Down) {
                nextPage();
                return true;
            }
            return false;
        }
        break;
    case QEvent::KeyRelease: {
            auto ke = static_cast<QKeyEvent*>(e);
            if (ke->key() == Qt::Key_Escape && d->m_escapePressed) {
                abort();
                emit explicitlyAborted();
                return false;
            } else if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) {
                QTC_CHECK(d->m_model);
                if (d->m_model && d->m_model->size() > 1)
                    return false;
            }
        }
        break;
    case QEvent::WindowDeactivate:
    case QEvent::FocusOut:
        if (obj != d->m_underlyingWidget)
            break;
        abort();
        break;
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
    case QEvent::Wheel:
        if (QWidget *widget = qobject_cast<QWidget *>(obj)) {
            if (d->m_popupFrame && !d->m_popupFrame->isAncestorOf(widget)) {
                abort();
            } else if (e->type() == QEvent::Wheel) {
                if (static_cast<QWheelEvent*>(e)->angleDelta().y() > 0)
                    previousPage();
                else
                    nextPage();
                return true;
            }
        }
        break;
    default:
        break;
    }
    return false;
}

void FunctionHintProposalWidget::nextPage()
{
    d->m_currentHint = (d->m_currentHint + 1) % d->m_totalHints;

    storeSelectedHint();
    updateContent();
}

void FunctionHintProposalWidget::previousPage()
{
    if (d->m_currentHint == 0)
        d->m_currentHint = d->m_totalHints - 1;
    else
        --d->m_currentHint;

    storeSelectedHint();
    updateContent();
}

bool FunctionHintProposalWidget::updateAndCheck(const QString &prefix)
{
    const int activeArgument = d->m_model->activeArgument(prefix);
    if (activeArgument == -1) {
        abort();
        return false;
    } else if (activeArgument != d->m_currentArgument) {
        d->m_currentArgument = activeArgument;
        updateContent();
    }

    return true;
}

void FunctionHintProposalWidget::updateContent()
{
    d->m_hintLabel->setText(d->m_model->text(d->m_currentHint));
    d->m_numberLabel->setText(tr("%1 of %2").arg(d->m_currentHint + 1).arg(d->m_totalHints));
    updatePosition();
}

void FunctionHintProposalWidget::updatePosition()
{
    auto widgetScreen = d->m_underlyingWidget->screen();
    const QRect &screen = Utils::HostOsInfo::isMacHost()
        ? widgetScreen->availableGeometry() : widgetScreen->geometry();

    d->m_pager->setFixedWidth(d->m_pager->minimumSizeHint().width());

    d->m_hintLabel->setWordWrap(false);
    const int maxDesiredWidth = screen.width() - 10;
    const QSize &minHint = d->m_popupFrame->minimumSizeHint();
    if (minHint.width() > maxDesiredWidth) {
        d->m_hintLabel->setWordWrap(true);
        d->m_popupFrame->setFixedWidth(maxDesiredWidth);
        const int extra = d->m_popupFrame->contentsMargins().bottom() +
            d->m_popupFrame->contentsMargins().top();
        d->m_popupFrame->setFixedHeight(
            d->m_hintLabel->heightForWidth(maxDesiredWidth - d->m_pager->width()) + extra);
    } else {
        d->m_popupFrame->setFixedSize(minHint);
    }

    const QSize &sz = d->m_popupFrame->size();
    QPoint pos = d->m_displayRect.topLeft();
    pos.setY(pos.y() - sz.height() - 1);
    if (pos.x() + sz.width() > screen.right())
        pos.setX(screen.right() - sz.width());
    d->m_popupFrame->move(pos);
}

} // TextEditor

Q_DECLARE_METATYPE(TextEditor::SelectedFunctionHints)