genericproposalwidget.cpp 20.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Leandro Melo's avatar
Leandro Melo committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Leandro Melo's avatar
Leandro Melo committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Leandro Melo's avatar
Leandro Melo committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
Leandro Melo's avatar
Leandro Melo committed
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
Leandro Melo's avatar
Leandro Melo committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
Leandro Melo's avatar
Leandro Melo committed
29 30 31 32 33 34 35 36

#include "genericproposalwidget.h"
#include "igenericproposalmodel.h"
#include "iassistproposalitem.h"
#include "codeassistant.h"

#include <texteditor/texteditorsettings.h>
#include <texteditor/completionsettings.h>
37
#include <texteditor/texteditorconstants.h>
Leandro Melo's avatar
Leandro Melo committed
38 39

#include <utils/faketooltip.h>
40
#include <utils/hostosinfo.h>
Leandro Melo's avatar
Leandro Melo committed
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include <QRect>
#include <QLatin1String>
#include <QAbstractListModel>
#include <QPointer>
#include <QDebug>
#include <QTimer>
#include <QApplication>
#include <QVBoxLayout>
#include <QListView>
#include <QAbstractItemView>
#include <QScrollBar>
#include <QKeyEvent>
#include <QDesktopWidget>
#include <QLabel>
Leandro Melo's avatar
Leandro Melo committed
56

57
using namespace Utils;
58

Leandro Melo's avatar
Leandro Melo committed
59 60
namespace TextEditor {

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
namespace {

QString cleanText(const QString &original)
{
    QString clean = original;
    int ignore = 0;
    for (int i = clean.length() - 1; i >= 0; --i, ++ignore) {
        const QChar &c = clean.at(i);
        if (c.isLetterOrNumber() || c == QLatin1Char('_'))
            break;
    }
    if (ignore)
        clean.chop(ignore);
    return clean;
}

77
bool isPerfectMatch(const QString &prefix, const IGenericProposalModel *model)
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
{
    if (prefix.isEmpty())
        return false;

    for (int i = 0; i < model->size(); ++i) {
        const QString &current = cleanText(model->text(i));
        if (!current.isEmpty()) {
            TextEditor::CaseSensitivity cs =
                TextEditor::TextEditorSettings::instance()->completionSettings().m_caseSensitivity;
            if (cs == TextEditor::CaseSensitive) {
                if (prefix == current)
                    return true;
            } else if (cs == TextEditor::CaseInsensitive) {
                if (prefix.compare(current, Qt::CaseInsensitive) == 0)
                    return true;
            } else if (cs == TextEditor::FirstLetterCaseSensitive) {
                if (prefix.at(0) == current.at(0)
                        && prefix.midRef(1).compare(current.midRef(1), Qt::CaseInsensitive) == 0)
                    return true;
            }
        }
    }
    return false;
}

}

Leandro Melo's avatar
Leandro Melo committed
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
// ------------
// ModelAdapter
// ------------
class ModelAdapter : public QAbstractListModel
{
    Q_OBJECT

public:
    ModelAdapter(IGenericProposalModel *completionModel, QWidget *parent);

    virtual int rowCount(const QModelIndex &) const;
    virtual QVariant data(const QModelIndex &index, int role) const;

private:
    IGenericProposalModel *m_completionModel;
};

ModelAdapter::ModelAdapter(IGenericProposalModel *completionModel, QWidget *parent)
    : QAbstractListModel(parent)
    , m_completionModel(completionModel)
{}

int ModelAdapter::rowCount(const QModelIndex &) const
{
    return m_completionModel->size();
}

QVariant ModelAdapter::data(const QModelIndex &index, int role) const
{
    if (index.row() >= m_completionModel->size())
        return QVariant();

137
    if (role == Qt::DisplayRole)
Leandro Melo's avatar
Leandro Melo committed
138
        return m_completionModel->text(index.row());
139
    else if (role == Qt::DecorationRole)
Leandro Melo's avatar
Leandro Melo committed
140
        return m_completionModel->icon(index.row());
141
    else if (role == Qt::WhatsThisRole)
Leandro Melo's avatar
Leandro Melo committed
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
        return m_completionModel->detail(index.row());

    return QVariant();
}

// ------------------------
// GenericProposalInfoFrame
// ------------------------
class GenericProposalInfoFrame : public Utils::FakeToolTip
{
public:
    GenericProposalInfoFrame(QWidget *parent = 0)
        : Utils::FakeToolTip(parent), m_label(new QLabel(this))
    {
        QVBoxLayout *layout = new QVBoxLayout(this);
        layout->setMargin(0);
        layout->setSpacing(0);
        layout->addWidget(m_label);

        m_label->setForegroundRole(QPalette::ToolTipText);
        m_label->setBackgroundRole(QPalette::ToolTipBase);
    }

    void setText(const QString &text)
    {
        m_label->setText(text);
    }

private:
    QLabel *m_label;
};

// -----------------------
// GenericProposalListView
// -----------------------
class GenericProposalListView : public QListView
{
public:
180
    GenericProposalListView(QWidget *parent);
Leandro Melo's avatar
Leandro Melo committed
181 182 183 184 185 186 187 188 189 190 191 192

    QSize calculateSize() const;
    QPoint infoFramePos() const;

    int rowSelected() const { return currentIndex().row(); }
    bool isFirstRowSelected() const { return rowSelected() == 0; }
    bool isLastRowSelected() const { return rowSelected() == model()->rowCount() - 1; }
    void selectRow(int row) { setCurrentIndex(model()->index(row, 0)); }
    void selectFirstRow() { selectRow(0); }
    void selectLastRow() { selectRow(model()->rowCount() - 1); }
};

193 194 195 196 197 198
GenericProposalListView::GenericProposalListView(QWidget *parent)
    : QListView(parent)
{
    setVerticalScrollMode(QAbstractItemView::ScrollPerItem);
}

Leandro Melo's avatar
Leandro Melo committed
199 200 201 202 203
QSize GenericProposalListView::calculateSize() const
{
    static const int maxVisibleItems = 10;

    // Determine size by calculating the space of the visible items
204 205
    const int visibleItems = qMin(model()->rowCount(), maxVisibleItems);
    const int firstVisibleRow = verticalScrollBar()->value();
Leandro Melo's avatar
Leandro Melo committed
206 207 208 209

    const QStyleOptionViewItem &option = viewOptions();
    QSize shint;
    for (int i = 0; i < visibleItems; ++i) {
210
        QSize tmp = itemDelegate()->sizeHint(option, model()->index(i + firstVisibleRow, 0));
Leandro Melo's avatar
Leandro Melo committed
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
        if (shint.width() < tmp.width())
            shint = tmp;
    }
    shint.rheight() *= visibleItems;

    return shint;
}

QPoint GenericProposalListView::infoFramePos() const
{
    const QRect &r = rectForIndex(currentIndex());
    QPoint p((parentWidget()->mapToGlobal(
                    parentWidget()->rect().topRight())).x() + 3,
            mapToGlobal(r.topRight()).y() - verticalOffset()
            );
    return p;
}

// ----------------------------
// GenericProposalWidgetPrivate
// ----------------------------
class GenericProposalWidgetPrivate : public QObject
{
    Q_OBJECT

public:
    GenericProposalWidgetPrivate(QWidget *completionWidget);

    const QWidget *m_underlyingWidget;
    GenericProposalListView *m_completionListView;
    IGenericProposalModel *m_model;
    QRect m_displayRect;
    bool m_isSynchronized;
    bool m_explicitlySelected;
    AssistReason m_reason;
246
    AssistKind m_kind;
247
    bool m_justInvoked;
Leandro Melo's avatar
Leandro Melo committed
248 249 250
    QPointer<GenericProposalInfoFrame> m_infoFrame;
    QTimer m_infoTimer;
    CodeAssistant *m_assistant;
251
    bool m_autoWidth;
Leandro Melo's avatar
Leandro Melo committed
252 253 254 255 256 257 258 259 260 261 262 263

public slots:
    void handleActivation(const QModelIndex &modelIndex);
    void maybeShowInfoTip();
};

GenericProposalWidgetPrivate::GenericProposalWidgetPrivate(QWidget *completionWidget)
    : m_underlyingWidget(0)
    , m_completionListView(new GenericProposalListView(completionWidget))
    , m_model(0)
    , m_isSynchronized(true)
    , m_explicitlySelected(false)
264
    , m_justInvoked(false)
Leandro Melo's avatar
Leandro Melo committed
265
    , m_assistant(0)
266
    , m_autoWidth(true)
Leandro Melo's avatar
Leandro Melo committed
267 268 269 270
{
    connect(m_completionListView, SIGNAL(activated(QModelIndex)),
            this, SLOT(handleActivation(QModelIndex)));

271
    m_infoTimer.setInterval(Constants::COMPLETION_ASSIST_TOOLTIP_DELAY);
Leandro Melo's avatar
Leandro Melo committed
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
    m_infoTimer.setSingleShot(true);
    connect(&m_infoTimer, SIGNAL(timeout()), SLOT(maybeShowInfoTip()));
}

void GenericProposalWidgetPrivate::handleActivation(const QModelIndex &modelIndex)
{
    static_cast<GenericProposalWidget *>
            (m_completionListView->parent())->notifyActivation(modelIndex.row());
}

void GenericProposalWidgetPrivate::maybeShowInfoTip()
{
    const QModelIndex &current = m_completionListView->currentIndex();
    if (!current.isValid())
        return;

    const QString &infoTip = current.data(Qt::WhatsThisRole).toString();
    if (infoTip.isEmpty()) {
        delete m_infoFrame.data();
        m_infoTimer.setInterval(200);
        return;
    }

    if (m_infoFrame.isNull())
        m_infoFrame = new GenericProposalInfoFrame(m_completionListView);

    m_infoFrame->move(m_completionListView->infoFramePos());
    m_infoFrame->setText(infoTip);
    m_infoFrame->adjustSize();
    m_infoFrame->show();
    m_infoFrame->raise();

    m_infoTimer.setInterval(0);
}

// ------------------------
// GenericProposalWidget
// ------------------------
GenericProposalWidget::GenericProposalWidget()
hjk's avatar
hjk committed
311
    : d(new GenericProposalWidgetPrivate(this))
Leandro Melo's avatar
Leandro Melo committed
312
{
313 314 315 316 317 318 319 320 321
    if (HostOsInfo::isMacHost()) {
        if (d->m_completionListView->horizontalScrollBar())
            d->m_completionListView->horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
        if (d->m_completionListView->verticalScrollBar())
            d->m_completionListView->verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
    } else {
        // This improves the look with QGTKStyle.
        setFrameStyle(d->m_completionListView->frameStyle());
    }
hjk's avatar
hjk committed
322 323 324 325 326 327 328
    d->m_completionListView->setFrameStyle(QFrame::NoFrame);
    d->m_completionListView->setAttribute(Qt::WA_MacShowFocusRect, false);
    d->m_completionListView->setUniformItemSizes(true);
    d->m_completionListView->setSelectionBehavior(QAbstractItemView::SelectItems);
    d->m_completionListView->setSelectionMode(QAbstractItemView::SingleSelection);
    d->m_completionListView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d->m_completionListView->setMinimumSize(1, 1);
329 330
    connect(d->m_completionListView->verticalScrollBar(), SIGNAL(valueChanged(int)),
            this, SLOT(updatePositionAndSize()));
331 332 333 334
    connect(d->m_completionListView->verticalScrollBar(), SIGNAL(sliderPressed()),
            this, SLOT(turnOffAutoWidth()));
    connect(d->m_completionListView->verticalScrollBar(), SIGNAL(sliderReleased()),
            this, SLOT(turnOnAutoWidth()));
Leandro Melo's avatar
Leandro Melo committed
335 336 337

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setMargin(0);
hjk's avatar
hjk committed
338
    layout->addWidget(d->m_completionListView);
Leandro Melo's avatar
Leandro Melo committed
339

hjk's avatar
hjk committed
340
    d->m_completionListView->installEventFilter(this);
Leandro Melo's avatar
Leandro Melo committed
341 342 343 344 345 346 347

    setObjectName(QLatin1String("m_popupFrame"));
    setMinimumSize(1, 1);
}

GenericProposalWidget::~GenericProposalWidget()
{
hjk's avatar
hjk committed
348 349
    delete d->m_model;
    delete d;
Leandro Melo's avatar
Leandro Melo committed
350 351 352 353
}

void GenericProposalWidget::setAssistant(CodeAssistant *assistant)
{
hjk's avatar
hjk committed
354
    d->m_assistant = assistant;
Leandro Melo's avatar
Leandro Melo committed
355 356 357 358
}

void GenericProposalWidget::setReason(AssistReason reason)
{
hjk's avatar
hjk committed
359 360 361
    d->m_reason = reason;
    if (d->m_reason == ExplicitlyInvoked)
        d->m_justInvoked = true;
Leandro Melo's avatar
Leandro Melo committed
362 363
}

364 365
void GenericProposalWidget::setKind(AssistKind kind)
{
hjk's avatar
hjk committed
366
    d->m_kind = kind;
367 368
}

Leandro Melo's avatar
Leandro Melo committed
369 370 371
void GenericProposalWidget::setUnderlyingWidget(const QWidget *underlyingWidget)
{
    setFont(underlyingWidget->font());
hjk's avatar
hjk committed
372
    d->m_underlyingWidget = underlyingWidget;
Leandro Melo's avatar
Leandro Melo committed
373 374 375 376
}

void GenericProposalWidget::setModel(IAssistProposalModel *model)
{
hjk's avatar
hjk committed
377 378 379
    delete d->m_model;
    d->m_model = static_cast<IGenericProposalModel *>(model);
    d->m_completionListView->setModel(new ModelAdapter(d->m_model, d->m_completionListView));
Leandro Melo's avatar
Leandro Melo committed
380

hjk's avatar
hjk committed
381
    connect(d->m_completionListView->selectionModel(),
Leandro Melo's avatar
Leandro Melo committed
382
            SIGNAL(currentChanged(QModelIndex,QModelIndex)),
hjk's avatar
hjk committed
383
            &d->m_infoTimer,
Leandro Melo's avatar
Leandro Melo committed
384 385 386 387 388
            SLOT(start()));
}

void GenericProposalWidget::setDisplayRect(const QRect &rect)
{
hjk's avatar
hjk committed
389
    d->m_displayRect = rect;
Leandro Melo's avatar
Leandro Melo committed
390 391 392 393
}

void GenericProposalWidget::setIsSynchronized(bool isSync)
{
hjk's avatar
hjk committed
394
    d->m_isSynchronized = isSync;
Leandro Melo's avatar
Leandro Melo committed
395 396 397 398 399
}

void GenericProposalWidget::showProposal(const QString &prefix)
{
    ensurePolished();
hjk's avatar
hjk committed
400
    d->m_model->removeDuplicates();
Leandro Melo's avatar
Leandro Melo committed
401 402 403
    if (!updateAndCheck(prefix))
        return;
    show();
hjk's avatar
hjk committed
404
    d->m_completionListView->setFocus();
Leandro Melo's avatar
Leandro Melo committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
}

void GenericProposalWidget::updateProposal(const QString &prefix)
{
    if (!isVisible())
        return;
    updateAndCheck(prefix);
}

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

void GenericProposalWidget::notifyActivation(int index)
{
    abort();
hjk's avatar
hjk committed
422
    emit proposalItemActivated(d->m_model->proposalItem(index));
Leandro Melo's avatar
Leandro Melo committed
423 424 425 426 427 428 429 430 431 432 433 434 435
}

void GenericProposalWidget::abort()
{
    if (isVisible())
        close();
    deleteLater();
}

bool GenericProposalWidget::updateAndCheck(const QString &prefix)
{
    // Keep track in the case there has been an explicit selection.
    int preferredItemId = -1;
hjk's avatar
hjk committed
436
    if (d->m_explicitlySelected)
Leandro Melo's avatar
Leandro Melo committed
437
        preferredItemId =
hjk's avatar
hjk committed
438
                d->m_model->persistentId(d->m_completionListView->currentIndex().row());
Leandro Melo's avatar
Leandro Melo committed
439 440

    // Filter, sort, etc.
hjk's avatar
hjk committed
441
    d->m_model->reset();
Leandro Melo's avatar
Leandro Melo committed
442
    if (!prefix.isEmpty())
hjk's avatar
hjk committed
443 444 445 446
        d->m_model->filter(prefix);
    if (d->m_model->size() == 0
            || (!d->m_model->keepPerfectMatch(d->m_reason)
                && isPerfectMatch(prefix, d->m_model))) {
Leandro Melo's avatar
Leandro Melo committed
447 448 449
        abort();
        return false;
    }
450
    if (d->m_model->isSortable(prefix))
451
        d->m_model->sort(prefix);
hjk's avatar
hjk committed
452
    d->m_completionListView->reset();
Leandro Melo's avatar
Leandro Melo committed
453 454 455

    // Try to find the previosly explicit selection (if any). If we can find the item set it
    // as the current. Otherwise (it might have been filtered out) select the first row.
hjk's avatar
hjk committed
456
    if (d->m_explicitlySelected) {
Leandro Melo's avatar
Leandro Melo committed
457
        Q_ASSERT(preferredItemId != -1);
hjk's avatar
hjk committed
458 459 460
        for (int i = 0; i < d->m_model->size(); ++i) {
            if (d->m_model->persistentId(i) == preferredItemId) {
                d->m_completionListView->selectRow(i);
Leandro Melo's avatar
Leandro Melo committed
461 462 463 464
                break;
            }
        }
    }
hjk's avatar
hjk committed
465 466 467 468
    if (!d->m_completionListView->currentIndex().isValid()) {
        d->m_completionListView->selectFirstRow();
        if (d->m_explicitlySelected)
            d->m_explicitlySelected = false;
Leandro Melo's avatar
Leandro Melo committed
469 470 471
    }

    if (TextEditorSettings::instance()->completionSettings().m_partiallyComplete
hjk's avatar
hjk committed
472 473 474 475 476
            && d->m_kind == Completion
            && d->m_justInvoked
            && d->m_isSynchronized) {
        if (d->m_model->size() == 1) {
            IAssistProposalItem *item = d->m_model->proposalItem(0);
Leandro Melo's avatar
Leandro Melo committed
477 478 479 480 481 482
            if (item->implicitlyApplies()) {
                abort();
                emit proposalItemActivated(item);
                return false;
            }
        }
hjk's avatar
hjk committed
483 484
        if (d->m_model->supportsPrefixExpansion()) {
            const QString &proposalPrefix = d->m_model->proposalPrefix();
Leandro Melo's avatar
Leandro Melo committed
485 486 487 488 489
            if (proposalPrefix.length() > prefix.length())
                emit prefixExpanded(proposalPrefix);
        }
    }

hjk's avatar
hjk committed
490 491
    if (d->m_justInvoked)
        d->m_justInvoked = false;
492

Leandro Melo's avatar
Leandro Melo committed
493 494 495 496 497 498
    updatePositionAndSize();
    return true;
}

void GenericProposalWidget::updatePositionAndSize()
{
499 500 501
    if (!d->m_autoWidth)
        return;

hjk's avatar
hjk committed
502
    const QSize &shint = d->m_completionListView->calculateSize();
Leandro Melo's avatar
Leandro Melo committed
503 504 505 506 507 508
    const int fw = frameWidth();
    const int width = shint.width() + fw * 2 + 30;
    const int height = shint.height() + fw * 2;

    // Determine the position, keeping the popup on the screen
    const QDesktopWidget *desktop = QApplication::desktop();
509 510 511
    const QRect screen = HostOsInfo::isMacHost()
            ? desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget))
            : desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget));
Leandro Melo's avatar
Leandro Melo committed
512

hjk's avatar
hjk committed
513
    QPoint pos = d->m_displayRect.bottomLeft();
Leandro Melo's avatar
Leandro Melo committed
514 515
    pos.rx() -= 16 + fw;    // Space for the icons
    if (pos.y() + height > screen.bottom())
hjk's avatar
hjk committed
516
        pos.setY(d->m_displayRect.top() - height);
Leandro Melo's avatar
Leandro Melo committed
517 518 519 520 521
    if (pos.x() + width > screen.right())
        pos.setX(screen.right() - width);
    setGeometry(pos.x(), pos.y(), width, height);
}

522 523 524 525 526 527 528 529 530 531 532
void GenericProposalWidget::turnOffAutoWidth()
{
    d->m_autoWidth = false;
}

void GenericProposalWidget::turnOnAutoWidth()
{
    d->m_autoWidth = true;
    updatePositionAndSize();
}

533 534 535 536 537 538 539 540 541
static bool useCarbonWorkaround()
{
#if (QT_VERSION < 0x050000) && defined(Q_OS_DARWIN) && ! defined(QT_MAC_USE_COCOA)
    return true;
#else
    return false;
#endif
}

Leandro Melo's avatar
Leandro Melo committed
542 543 544 545
bool GenericProposalWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::FocusOut) {
        abort();
546 547 548 549 550 551 552 553 554
        if (useCarbonWorkaround()) {
            QFocusEvent *fe = static_cast<QFocusEvent *>(e);
            if (fe->reason() == Qt::OtherFocusReason) {
                // Qt/carbon workaround
                // focus out is received before the key press event.
                if (d->m_completionListView->currentIndex().isValid())
                    emit proposalItemActivated(d->m_model->proposalItem(
                                                   d->m_completionListView->currentIndex().row()));
            }
Leandro Melo's avatar
Leandro Melo committed
555
        }
hjk's avatar
hjk committed
556 557
        if (d->m_infoFrame)
            d->m_infoFrame->close();
Leandro Melo's avatar
Leandro Melo committed
558 559 560 561 562 563
        return true;
    } else if (e->type() == QEvent::ShortcutOverride) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        switch (ke->key()) {
        case Qt::Key_N:
        case Qt::Key_P:
564
            if (ke->modifiers() == Qt::KeyboardModifiers(HostOsInfo::controlModifier())) {
Leandro Melo's avatar
Leandro Melo committed
565 566 567 568 569 570 571 572 573
                e->accept();
                return true;
            }
        }
    } else if (e->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        switch (ke->key()) {
        case Qt::Key_Escape:
            abort();
574
            e->accept();
Leandro Melo's avatar
Leandro Melo committed
575 576 577 578 579
            return true;

        case Qt::Key_N:
        case Qt::Key_P:
            // select next/previous completion
hjk's avatar
hjk committed
580
            d->m_explicitlySelected = true;
581
            if (ke->modifiers() == Qt::KeyboardModifiers(HostOsInfo::controlModifier())) {
Leandro Melo's avatar
Leandro Melo committed
582
                int change = (ke->key() == Qt::Key_N) ? 1 : -1;
hjk's avatar
hjk committed
583 584
                int nrows = d->m_model->size();
                int row = d->m_completionListView->currentIndex().row();
Leandro Melo's avatar
Leandro Melo committed
585 586
                int newRow = (row + change + nrows) % nrows;
                if (newRow == row + change || !ke->isAutoRepeat())
hjk's avatar
hjk committed
587
                    d->m_completionListView->selectRow(newRow);
Leandro Melo's avatar
Leandro Melo committed
588 589 590 591 592 593
                return true;
            }
            break;

        case Qt::Key_Tab:
        case Qt::Key_Return:
594 595 596 597 598 599
            if (!useCarbonWorkaround()) {
                abort();
                if (d->m_completionListView->currentIndex().isValid())
                    emit proposalItemActivated(d->m_model->proposalItem(
                                                   d->m_completionListView->currentIndex().row()));
            }
Leandro Melo's avatar
Leandro Melo committed
600 601 602
            return true;

        case Qt::Key_Up:
hjk's avatar
hjk committed
603 604 605
            d->m_explicitlySelected = true;
            if (!ke->isAutoRepeat() && d->m_completionListView->isFirstRowSelected()) {
                d->m_completionListView->selectLastRow();
Leandro Melo's avatar
Leandro Melo committed
606 607 608 609 610
                return true;
            }
            return false;

        case Qt::Key_Down:
hjk's avatar
hjk committed
611 612 613
            d->m_explicitlySelected = true;
            if (!ke->isAutoRepeat() && d->m_completionListView->isLastRowSelected()) {
                d->m_completionListView->selectFirstRow();
Leandro Melo's avatar
Leandro Melo committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
                return true;
            }
            return false;

        case Qt::Key_Enter:
        case Qt::Key_PageDown:
        case Qt::Key_PageUp:
            return false;

        case Qt::Key_Right:
        case Qt::Key_Left:
        case Qt::Key_Home:
        case Qt::Key_End:
        case Qt::Key_Backspace:
            // We want these navigation keys to work in the editor.
            break;

        default:
            // Only forward keys that insert text and refine the completion.
            if (ke->text().isEmpty())
                return true;
            break;
        }

        if (ke->text().length() == 1
hjk's avatar
hjk committed
639
                && d->m_completionListView->currentIndex().isValid()
Leandro Melo's avatar
Leandro Melo committed
640 641 642
                && qApp->focusWidget() == o) {
            const QChar &typedChar = ke->text().at(0);
            IAssistProposalItem *item =
hjk's avatar
hjk committed
643
                d->m_model->proposalItem(d->m_completionListView->currentIndex().row());
644
            if (item->prematurelyApplies(typedChar)
hjk's avatar
hjk committed
645
                    && (d->m_reason == ExplicitlyInvoked || item->text().endsWith(typedChar))) {
Leandro Melo's avatar
Leandro Melo committed
646 647 648 649 650 651
                abort();
                emit proposalItemActivated(item);
                return true;
            }
        }

hjk's avatar
hjk committed
652
        QApplication::sendEvent(const_cast<QWidget *>(d->m_underlyingWidget), e);
Leandro Melo's avatar
Leandro Melo committed
653
        if (isVisible())
hjk's avatar
hjk committed
654
            d->m_assistant->notifyChange();
Leandro Melo's avatar
Leandro Melo committed
655 656 657 658 659 660 661 662 663

        return true;
    }
    return false;
}

#include "genericproposalwidget.moc"

} // TextEditor