qmljscodecompletion.cpp 33.8 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

Roberto Raggi's avatar
Roberto Raggi committed
30
#include "qmljscodecompletion.h"
31
#include "qmlexpressionundercursor.h"
32
#include "qmljseditor.h"
33
#include "qmljseditorconstants.h"
34

35
#include <qmljs/qmljsmodelmanagerinterface.h>
36 37
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsinterpreter.h>
38
#include <qmljs/qmljslookupcontext.h>
39
#include <qmljs/qmljsscanner.h>
40
#include <qmljs/qmljscompletioncontextfinder.h>
41
#include <qmljs/qmljsscopebuilder.h>
42

43
#include <texteditor/basetexteditor.h>
44
#include <texteditor/completionsettings.h>
45

46
#include <coreplugin/icore.h>
47
#include <coreplugin/editormanager/editormanager.h>
48

49
#include <utils/faketooltip.h>
50
#include <utils/qtcassert.h>
51

52 53
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
54
#include <QtCore/QDir>
55
#include <QtCore/QDebug>
56
#include <QtCore/QDirIterator>
57

58 59 60
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QHBoxLayout>
61
#include <QtGui/QLabel>
62
#include <QtGui/QPainter>
63
#include <QtGui/QStyle>
64
#include <QtGui/QTextBlock>
65
#include <QtGui/QToolButton>
66

67 68
using namespace QmlJSEditor;
using namespace QmlJSEditor::Internal;
69
using namespace QmlJS;
70

71
namespace {
72

73 74
enum CompletionOrder {
    EnumValueOrder = -5,
75 76
    SnippetOrder = -15,
    PropertyOrder = -10,
77 78 79
    SymbolOrder = -20,
    KeywordOrder = -25,
    TypeOrder = -30
80 81
};

82
// Temporary workaround until we have proper icons for QML completion items
83
static QIcon iconForColor(const QColor &color)
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
{
    QPixmap pix(6, 6);

    int pixSize = 20;
    QBrush br(color);

    QPixmap pm(2 * pixSize, 2 * pixSize);
    QPainter pmp(&pm);
    pmp.fillRect(0, 0, pixSize, pixSize, Qt::lightGray);
    pmp.fillRect(pixSize, pixSize, pixSize, pixSize, Qt::lightGray);
    pmp.fillRect(0, pixSize, pixSize, pixSize, Qt::darkGray);
    pmp.fillRect(pixSize, 0, pixSize, pixSize, Qt::darkGray);
    pmp.fillRect(0, 0, 2 * pixSize, 2 * pixSize, color);
    br = QBrush(pm);

    QPainter p(&pix);
    int corr = 1;
    QRect r = pix.rect().adjusted(corr, corr, -corr, -corr);
    p.setBrushOrigin((r.width() % pixSize + pixSize) / 2 + corr, (r.height() % pixSize + pixSize) / 2 + corr);
    p.fillRect(r, br);

    p.fillRect(r.width() / 4 + corr, r.height() / 4 + corr,
               r.width() / 2, r.height() / 2,
               QColor(color.rgb()));
    p.drawRect(pix.rect().adjusted(0, 0, -1, -1));

    return pix;
}

113
static bool checkStartOfIdentifier(const QString &word)
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
{
    if (word.isEmpty())
        return false;

    const QChar ch = word.at(0);

    switch (ch.unicode()) {
    case '_': case '$':
        return true;

    default:
        return ch.isLetter();
    }
}

129
static bool isIdentifierChar(QChar ch)
130 131 132 133 134 135 136 137 138
{
    switch (ch.unicode()) {
    case '_': case '$':
        return true;

    default:
        return ch.isLetterOrNumber();
    }
}
139

140 141 142 143 144
class SearchPropertyDefinitions: protected AST::Visitor
{
    QList<AST::UiPublicMember *> _properties;

public:
145
    QList<AST::UiPublicMember *> operator()(Document::Ptr doc)
146 147
    {
        _properties.clear();
148 149
        if (doc && doc->qmlProgram())
            doc->qmlProgram()->accept(this);
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        return _properties;
    }


protected:
    using AST::Visitor::visit;

    virtual bool visit(AST::UiPublicMember *member)
    {
        if (member->propertyToken.isValid()) {
            _properties.append(member);
        }

        return true;
    }
};

Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
167
class EnumerateProperties: private Interpreter::MemberProcessor
168 169 170
{
    QSet<const Interpreter::ObjectValue *> _processed;
    QHash<QString, const Interpreter::Value *> _properties;
171
    bool _globalCompletion;
Christian Kamm's avatar
Christian Kamm committed
172
    bool _enumerateGeneratedSlots;
173
    const Interpreter::Context *_context;
174
    const Interpreter::ObjectValue *_currentObject;
175 176

public:
177
    EnumerateProperties(const Interpreter::Context *context)
178
        : _globalCompletion(false),
Christian Kamm's avatar
Christian Kamm committed
179
          _enumerateGeneratedSlots(false),
180 181
          _context(context),
          _currentObject(0)
182 183 184 185 186 187 188 189
    {
    }

    void setGlobalCompletion(bool globalCompletion)
    {
        _globalCompletion = globalCompletion;
    }

Christian Kamm's avatar
Christian Kamm committed
190 191 192 193 194
    void setEnumerateGeneratedSlots(bool enumerate)
    {
        _enumerateGeneratedSlots = enumerate;
    }

195
    QHash<QString, const Interpreter::Value *> operator ()(const Interpreter::Value *value)
196 197 198
    {
        _processed.clear();
        _properties.clear();
199
        _currentObject = Interpreter::value_cast<const Interpreter::ObjectValue *>(value);
200 201 202 203 204 205 206 207 208 209

        enumerateProperties(value);

        return _properties;
    }

    QHash<QString, const Interpreter::Value *> operator ()()
    {
        _processed.clear();
        _properties.clear();
210
        _currentObject = 0;
211

212
        foreach (const Interpreter::ObjectValue *scope, _context->scopeChain().all())
213 214
            enumerateProperties(scope);

215 216 217 218
        return _properties;
    }

private:
219 220
    void insertProperty(const QString &name, const Interpreter::Value *value)
    {
221
        _properties.insert(name, value);
222 223
    }

224
    virtual bool processProperty(const QString &name, const Interpreter::Value *value)
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
225
    {
226
        insertProperty(name, value);
Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
227 228 229
        return true;
    }

230 231 232
    virtual bool processEnumerator(const QString &name, const Interpreter::Value *value)
    {
        if (! _globalCompletion)
233
            insertProperty(name, value);
234 235 236
        return true;
    }

237
    virtual bool processSignal(const QString &, const Interpreter::Value *)
238 239 240 241
    {
        return true;
    }

242
    virtual bool processSlot(const QString &name, const Interpreter::Value *value)
243
    {
244
        insertProperty(name, value);
245 246 247 248
        return true;
    }

    virtual bool processGeneratedSlot(const QString &name, const Interpreter::Value *value)
249
    {
Christian Kamm's avatar
Christian Kamm committed
250
        if (_enumerateGeneratedSlots || (_currentObject && _currentObject->className().endsWith(QLatin1String("Keys")))) {
251
            // ### FIXME: add support for attached properties.
252
            insertProperty(name, value);
253
        }
254 255 256
        return true;
    }

257
    void enumerateProperties(const Interpreter::Value *value)
258 259 260 261
    {
        if (! value)
            return;
        else if (const Interpreter::ObjectValue *object = value->asObjectValue()) {
262
            enumerateProperties(object);
263 264 265
        }
    }

266
    void enumerateProperties(const Interpreter::ObjectValue *object)
267 268 269 270 271
    {
        if (! object || _processed.contains(object))
            return;

        _processed.insert(object);
272
        enumerateProperties(object->prototype(_context));
273

Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
274
        object->processMembers(this);
275 276 277 278 279
    }
};

} // end of anonymous namespace

280 281 282 283 284 285 286
namespace QmlJSEditor {
namespace Internal {

class FunctionArgumentWidget : public QLabel
{
public:
    FunctionArgumentWidget();
287 288 289
    void showFunctionHint(const QString &functionName,
                          const QStringList &signature,
                          int startPosition);
290 291 292 293 294 295 296 297 298

protected:
    bool eventFilter(QObject *obj, QEvent *e);

private:
    void updateArgumentHighlight();
    void updateHintText();

    QString m_functionName;
299
    QStringList m_signature;
300 301 302 303 304 305 306 307 308 309
    int m_minimumArgumentCount;
    int m_startpos;
    int m_currentarg;
    int m_current;
    bool m_escapePressed;

    TextEditor::ITextEditor *m_editor;

    QWidget *m_pager;
    QLabel *m_numberLabel;
310
    Utils::FakeToolTip *m_popupFrame;
311 312 313 314 315 316 317 318 319 320 321 322
};


FunctionArgumentWidget::FunctionArgumentWidget():
    m_minimumArgumentCount(0),
    m_startpos(-1),
    m_current(0),
    m_escapePressed(false)
{
    QObject *editorObject = Core::EditorManager::instance()->currentEditor();
    m_editor = qobject_cast<TextEditor::ITextEditor *>(editorObject);

323
    m_popupFrame = new Utils::FakeToolTip(m_editor->widget());
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

    setParent(m_popupFrame);
    setFocusPolicy(Qt::NoFocus);

    m_pager = new QWidget;
    QHBoxLayout *hbox = new QHBoxLayout(m_pager);
    hbox->setMargin(0);
    hbox->setSpacing(0);
    m_numberLabel = new QLabel;
    hbox->addWidget(m_numberLabel);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_pager);
    layout->addWidget(this);
    m_popupFrame->setLayout(layout);

    setTextFormat(Qt::RichText);

    qApp->installEventFilter(this);
}

347
void FunctionArgumentWidget::showFunctionHint(const QString &functionName, const QStringList &signature, int startPosition)
348 349 350 351 352
{
    if (m_startpos == startPosition)
        return;

    m_functionName = functionName;
353 354
    m_signature = signature;
    m_minimumArgumentCount = signature.size();
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    m_startpos = startPosition;
    m_current = 0;
    m_escapePressed = false;

    // update the text
    m_currentarg = -1;
    updateArgumentHighlight();

    m_popupFrame->show();
}

void FunctionArgumentWidget::updateArgumentHighlight()
{
    int curpos = m_editor->position();
    if (curpos < m_startpos) {
        m_popupFrame->close();
        return;
    }

    updateHintText();

    QString str = m_editor->textAt(m_startpos, curpos - m_startpos);
    int argnr = 0;
    int parcount = 0;
Roberto Raggi's avatar
Roberto Raggi committed
379
    Scanner tokenize;
380
    const QList<Token> tokens = tokenize(str);
381
    for (int i = 0; i < tokens.count(); ++i) {
382 383
        const Token &tk = tokens.at(i);
        if (tk.is(Token::LeftParenthesis))
384
            ++parcount;
385
        else if (tk.is(Token::RightParenthesis))
386
            --parcount;
387
        else if (! parcount && tk.is(Token::Colon))
388 389 390 391
            ++argnr;
    }

    if (m_currentarg != argnr) {
392
        // m_currentarg = argnr;
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
        updateHintText();
    }

    if (parcount < 0)
        m_popupFrame->close();
}

bool FunctionArgumentWidget::eventFilter(QObject *obj, QEvent *e)
{
    switch (e->type()) {
    case QEvent::ShortcutOverride:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            m_escapePressed = true;
        }
        break;
    case QEvent::KeyPress:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
            m_escapePressed = true;
        }
        break;
    case QEvent::KeyRelease:
        if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && m_escapePressed) {
            m_popupFrame->close();
            return false;
        }
        updateArgumentHighlight();
        break;
    case QEvent::WindowDeactivate:
    case QEvent::FocusOut:
        if (obj != m_editor->widget())
            break;
        m_popupFrame->close();
        break;
    case QEvent::MouseButtonPress:
    case QEvent::MouseButtonRelease:
    case QEvent::MouseButtonDblClick:
    case QEvent::Wheel: {
            QWidget *widget = qobject_cast<QWidget *>(obj);
            if (! (widget == this || m_popupFrame->isAncestorOf(widget))) {
                m_popupFrame->close();
            }
        }
        break;
    default:
        break;
    }
    return false;
}

void FunctionArgumentWidget::updateHintText()
{
    QString prettyMethod;
    prettyMethod += QString::fromLatin1("function ");
    prettyMethod += m_functionName;
447 448 449 450 451
    prettyMethod += QLatin1Char('(');
    for (int i = 0; i < m_minimumArgumentCount; ++i) {
        if (i != 0)
            prettyMethod += QLatin1String(", ");

Roberto Raggi's avatar
Roberto Raggi committed
452 453 454 455 456
        QString arg = m_signature.at(i);
        if (arg.isEmpty()) {
            arg = QLatin1String("arg");
            arg += QString::number(i + 1);
        }
457

Roberto Raggi's avatar
Roberto Raggi committed
458
        prettyMethod += arg;
459 460
    }
    prettyMethod += QLatin1Char(')');
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

    m_numberLabel->setText(prettyMethod);

    m_popupFrame->setFixedWidth(m_popupFrame->minimumSizeHint().width());

    const QDesktopWidget *desktop = QApplication::desktop();
#ifdef Q_WS_MAC
    const QRect screen = desktop->availableGeometry(desktop->screenNumber(m_editor->widget()));
#else
    const QRect screen = desktop->screenGeometry(desktop->screenNumber(m_editor->widget()));
#endif

    const QSize sz = m_popupFrame->sizeHint();
    QPoint pos = m_editor->cursorRect(m_startpos).topLeft();
    pos.setY(pos.y() - sz.height() - 1);

    if (pos.x() + sz.width() > screen.right())
        pos.setX(screen.right() - sz.width());

    m_popupFrame->move(pos);
}

} } // end of namespace QmlJSEditor::Internal

Roberto Raggi's avatar
Roberto Raggi committed
485
CodeCompletion::CodeCompletion(ModelManagerInterface *modelManager, QObject *parent)
486
    : TextEditor::ICompletionCollector(parent),
487
      m_modelManager(modelManager),
488
      m_editor(0),
489
      m_startPosition(0),
Leandro Melo's avatar
Leandro Melo committed
490
      m_restartCompletion(false),
491
      m_snippetProvider(Constants::QML_SNIPPETS_GROUP_ID, iconForColor(Qt::red), SnippetOrder)
492 493 494
{
    Q_ASSERT(modelManager);
}
495

Roberto Raggi's avatar
Roberto Raggi committed
496
CodeCompletion::~CodeCompletion()
497 498
{ }

Roberto Raggi's avatar
Roberto Raggi committed
499
TextEditor::ITextEditable *CodeCompletion::editor() const
500 501
{ return m_editor; }

Roberto Raggi's avatar
Roberto Raggi committed
502
int CodeCompletion::startPosition() const
503 504
{ return m_startPosition; }

Roberto Raggi's avatar
Roberto Raggi committed
505
bool CodeCompletion::shouldRestartCompletion()
506
{ return m_restartCompletion; }
507

Roberto Raggi's avatar
Roberto Raggi committed
508
bool CodeCompletion::supportsEditor(TextEditor::ITextEditable *editor)
509
{
510
    if (qobject_cast<QmlJSTextEditor *>(editor->widget()))
511 512 513 514 515
        return true;

    return false;
}

Roberto Raggi's avatar
Roberto Raggi committed
516
bool CodeCompletion::triggersCompletion(TextEditor::ITextEditable *editor)
517 518 519 520 521 522 523 524
{
    if (maybeTriggersCompletion(editor)) {
        // check the token under cursor

        if (QmlJSTextEditor *ed = qobject_cast<QmlJSTextEditor *>(editor->widget())) {

            QTextCursor tc = ed->textCursor();
            QTextBlock block = tc.block();
525
            const int column = tc.positionInBlock();
526
            const QChar ch = block.text().at(column - 1);
527 528 529
            const int blockState = qMax(0, block.previous().userState()) & 0xff;
            const QString blockText = block.text();

Roberto Raggi's avatar
Roberto Raggi committed
530
            Scanner scanner;
531 532 533
            const QList<Token> tokens = scanner(blockText, blockState);
            foreach (const Token &tk, tokens) {
                if (column >= tk.begin() && column <= tk.end()) {
534 535
                    if (ch == QLatin1Char('/') && tk.is(Token::String))
                        return true; // path completion inside string literals
536 537
                    if (tk.is(Token::Comment) || tk.is(Token::String))
                        return false;
538
                    break;
539 540
                }
            }
541 542
            if (ch == QLatin1Char('/'))
                return false;
543 544 545 546 547 548 549
        }
        return true;
    }

    return false;
}

Roberto Raggi's avatar
Roberto Raggi committed
550
bool CodeCompletion::maybeTriggersCompletion(TextEditor::ITextEditable *editor)
551
{
552 553
    const int cursorPosition = editor->position();
    const QChar ch = editor->characterAt(cursorPosition - 1);
554

555
    if (ch == QLatin1Char('(') || ch == QLatin1Char('.') || ch == QLatin1Char('/'))
556
        return true;
557 558
    if (completionSettings().m_completionTrigger != TextEditor::AutomaticCompletion)
        return false;
559 560 561 562

    const QChar characterUnderCursor = editor->characterAt(cursorPosition);

    if (isIdentifierChar(ch) && (characterUnderCursor.isSpace() ||
563 564
                                      characterUnderCursor.isNull() ||
                                      isDelimiter(characterUnderCursor))) {
565 566 567 568 569 570 571 572 573 574 575 576
        int pos = editor->position() - 1;
        for (; pos != -1; --pos) {
            if (! isIdentifierChar(editor->characterAt(pos)))
                break;
        }
        ++pos;

        const QString word = editor->textAt(pos, cursorPosition - pos);
        if (word.length() > 2 && checkStartOfIdentifier(word)) {
            for (int i = 0; i < word.length(); ++i) {
                if (! isIdentifierChar(word.at(i)))
                    return false;
577
            }
578
            return true;
579 580
        }
    }
581 582 583

    return false;
}
584

585
bool CodeCompletion::isDelimiter(QChar ch) const
586 587 588 589 590 591
{
    switch (ch.unicode()) {
    case '{':
    case '}':
    case '[':
    case ']':
592
    case ')':
593
    case '?':
594
    case '!':
595 596 597
    case ':':
    case ';':
    case ',':
598 599 600 601
    case '+':
    case '-':
    case '*':
    case '/':
602 603 604 605 606 607 608
        return true;

    default:
        return false;
    }
}

609 610 611 612 613 614 615 616 617 618
static bool isLiteral(AST::Node *ast)
{
    if (AST::cast<AST::StringLiteral *>(ast))
        return true;
    else if (AST::cast<AST::NumericLiteral *>(ast))
        return true;
    else
        return false;
}

619 620 621 622 623 624 625
bool CodeCompletion::completeUrl(const QString &relativeBasePath, const QString &urlString)
{
    const QUrl url(urlString);
    QString fileName = url.toLocalFile();
    if (fileName.isEmpty())
        return false;

626 627 628 629 630 631
    return completeFileName(relativeBasePath, fileName);
}

bool CodeCompletion::completeFileName(const QString &relativeBasePath, const QString &fileName,
                                      const QStringList &patterns)
{
632 633 634 635 636 637 638 639 640 641 642 643
    const QFileInfo fileInfo(fileName);
    QString directoryPrefix;
    if (fileInfo.isRelative()) {
        directoryPrefix = relativeBasePath;
        directoryPrefix += QDir::separator();
        directoryPrefix += fileInfo.path();
    } else {
        directoryPrefix = fileInfo.path();
    }
    if (!QFileInfo(directoryPrefix).exists())
        return false;

644
    QDirIterator dirIterator(directoryPrefix, patterns, QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
645 646 647 648 649 650 651 652 653 654 655 656 657 658
    while (dirIterator.hasNext()) {
        dirIterator.next();
        const QString fileName = dirIterator.fileName();

        TextEditor::CompletionItem item(this);
        item.text += fileName;
        // ### Icon for file completions
        item.icon = iconForColor(Qt::darkBlue);
        m_completions.append(item);
    }

    return !m_completions.isEmpty();
}

659
void CodeCompletion::addCompletions(const QHash<QString, const Interpreter::Value *> &newCompletions,
660
                                    const QIcon &icon, int order)
661 662 663 664 665 666 667 668
{
    QHashIterator<QString, const Interpreter::Value *> it(newCompletions);
    while (it.hasNext()) {
        it.next();

        TextEditor::CompletionItem item(this);
        item.text = it.key();
        item.icon = icon;
669
        item.order = order;
670 671 672 673 674
        m_completions.append(item);
    }
}

void CodeCompletion::addCompletions(const QStringList &newCompletions,
675
                                    const QIcon &icon, int order)
676 677 678 679 680
{
    foreach (const QString &text, newCompletions) {
        TextEditor::CompletionItem item(this);
        item.text = text;
        item.icon = icon;
681
        item.order = order;
682 683 684 685
        m_completions.append(item);
    }
}

686 687
void CodeCompletion::addCompletionsPropertyLhs(
        const QHash<QString, const Interpreter::Value *> &newCompletions,
688
        const QIcon &icon, int order, bool afterOn)
689 690 691 692 693 694 695
{
    QHashIterator<QString, const Interpreter::Value *> it(newCompletions);
    while (it.hasNext()) {
        it.next();

        TextEditor::CompletionItem item(this);
        item.text = it.key();
696 697 698 699

        QLatin1String postfix(": ");
        if (afterOn)
            postfix = QLatin1String(" {");
700 701 702 703
        if (const Interpreter::QmlObjectValue *qmlValue = dynamic_cast<const Interpreter::QmlObjectValue *>(it.value())) {
            // to distinguish "anchors." from "gradient:" we check if the right hand side
            // type is instantiatable or is the prototype of an instantiatable object
            if (qmlValue->hasChildInPackage())
704
                item.text.append(postfix);
705 706 707
            else
                item.text.append(QLatin1Char('.'));
        } else {
708
            item.text.append(postfix);
709 710
        }
        item.icon = icon;
711
        item.order = order;
712 713 714 715
        m_completions.append(item);
    }
}

716 717 718 719 720
static const Interpreter::Value *getPropertyValue(
    const Interpreter::ObjectValue *object,
    const QStringList &propertyNames,
    const Interpreter::Context *context)
{
721
    if (propertyNames.isEmpty() || !object)
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
        return 0;

    const Interpreter::Value *value = object;
    foreach (const QString &name, propertyNames) {
        if (const Interpreter::ObjectValue *objectValue = value->asObjectValue()) {
            value = objectValue->property(name, context);
            if (!value)
                return 0;
        } else {
            return 0;
        }
    }
    return value;
}

Roberto Raggi's avatar
Roberto Raggi committed
737
int CodeCompletion::startCompletion(TextEditor::ITextEditable *editor)
738
{
739 740
    m_restartCompletion = false;

741 742
    m_editor = editor;

743
    QmlJSTextEditor *edit = qobject_cast<QmlJSTextEditor *>(m_editor->widget());
744 745 746
    if (! edit)
        return -1;

747
    m_startPosition = editor->position();
Roberto Raggi's avatar
Roberto Raggi committed
748
    const QString fileName = editor->file()->fileName();
749

Roberto Raggi's avatar
Roberto Raggi committed
750 751
    while (editor->characterAt(m_startPosition - 1).isLetterOrNumber() ||
           editor->characterAt(m_startPosition - 1) == QLatin1Char('_'))
752
        --m_startPosition;
753 754 755

    m_completions.clear();

Roberto Raggi's avatar
Cleanup  
Roberto Raggi committed
756
    const SemanticInfo semanticInfo = edit->semanticInfo();
757

758
    if (! semanticInfo.isValid())
759 760
        return -1;

761
    const Document::Ptr document = semanticInfo.document;
762
    const QFileInfo currentFileInfo(fileName);
763

764 765 766 767
    bool isQmlFile = false;
    if (currentFileInfo.suffix() == QLatin1String("qml"))
        isQmlFile = true;

768
    const QIcon symbolIcon = iconForColor(Qt::darkCyan);
769
    const QIcon keywordIcon = iconForColor(Qt::darkYellow);
770

771
    const QList<AST::Node *> path = semanticInfo.astPath(editor->position());
772
    LookupContext::Ptr lookupContext = semanticInfo.lookupContext(path);
773
    const Interpreter::Context *context = lookupContext->context();
774

Roberto Raggi's avatar
Roberto Raggi committed
775
    // Search for the operator that triggered the completion.
776
    QChar completionOperator;
777
    if (m_startPosition > 0)
778
        completionOperator = editor->characterAt(m_startPosition - 1);
779

780 781 782 783 784 785
    QTextCursor startPositionCursor(edit->document());
    startPositionCursor.setPosition(m_startPosition);
    CompletionContextFinder contextFinder(startPositionCursor);

    const Interpreter::ObjectValue *qmlScopeType = 0;
    if (contextFinder.isInQmlContext())
786
         qmlScopeType = context->lookupType(document.data(), contextFinder.qmlObjectTypeName());
787

788
    if (contextFinder.isInStringLiteral()) {
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        // get the text of the literal up to the cursor position
        QTextCursor tc = edit->textCursor();
        QmlExpressionUnderCursor expressionUnderCursor;
        expressionUnderCursor(tc);
        QString literalText = expressionUnderCursor.text();
        QTC_ASSERT(!literalText.isEmpty() && (
                       literalText.at(0) == QLatin1Char('"')
                       || literalText.at(0) == QLatin1Char('\'')), return -1);
        literalText = literalText.mid(1);

        if (contextFinder.isInImport()) {
            QStringList patterns;
            patterns << QLatin1String("*.qml") << QLatin1String("*.js");
            if (completeFileName(document->path(), literalText, patterns))
                return m_startPosition;
            return -1;
        }
806

807
        const Interpreter::Value *value = getPropertyValue(qmlScopeType, contextFinder.bindingPropertyName(), context);
808 809 810
        if (!value) {
            // do nothing
        } else if (value->asUrlValue()) {
811
            if (completeUrl(document->path(), literalText))
812 813 814 815 816 817 818 819 820 821 822
                return m_startPosition;
        }

        // ### enum completion?

        // completion gets triggered for / in string literals, if we don't
        // return here, this will mean the snippet completion pops up for
        // each / in a string literal that is not triggering file completion
        return -1;
    } else if (completionOperator.isSpace() || completionOperator.isNull() || isDelimiter(completionOperator) ||
               (completionOperator == QLatin1Char('(') && m_startPosition != editor->position())) {
823

Christian Kamm's avatar
Christian Kamm committed
824 825 826 827
        bool doGlobalCompletion = true;
        bool doQmlKeywordCompletion = true;
        bool doJsKeywordCompletion = true;

828 829
        if (contextFinder.isInLhsOfBinding() && qmlScopeType) {
            doGlobalCompletion = false;
Christian Kamm's avatar
Christian Kamm committed
830 831
            doJsKeywordCompletion = false;

832
            EnumerateProperties enumerateProperties(context);
833
            enumerateProperties.setGlobalCompletion(true);
Christian Kamm's avatar
Christian Kamm committed
834
            enumerateProperties.setEnumerateGeneratedSlots(true);
835

836 837 838 839
            // id: is special
            TextEditor::CompletionItem idPropertyCompletion(this);
            idPropertyCompletion.text = QLatin1String("id: ");
            idPropertyCompletion.icon = symbolIcon;
840
            idPropertyCompletion.order = PropertyOrder;
841 842
            m_completions.append(idPropertyCompletion);

843
            addCompletionsPropertyLhs(enumerateProperties(qmlScopeType), symbolIcon, PropertyOrder, contextFinder.isAfterOnInLhsOfBinding());
844 845
            if (const Interpreter::ObjectValue *qmlTypes = context->scopeChain().qmlTypes)
                addCompletions(enumerateProperties(qmlTypes), symbolIcon, TypeOrder);
846

847 848 849
            if (ScopeBuilder::isPropertyChangesObject(context, qmlScopeType)
                    && context->scopeChain().qmlScopeObjects.size() == 2) {
                addCompletions(enumerateProperties(context->scopeChain().qmlScopeObjects.first()), symbolIcon, SymbolOrder);
850
            }
851
        }
852

Christian Kamm's avatar
Christian Kamm committed
853 854 855
        if (contextFinder.isInRhsOfBinding() && qmlScopeType) {
            doQmlKeywordCompletion = false;

856 857 858 859 860 861 862 863 864 865
            // complete enum values for enum properties
            const Interpreter::Value *value = getPropertyValue(qmlScopeType, contextFinder.bindingPropertyName(), context);
            if (const Interpreter::QmlEnumValue *enumValue = dynamic_cast<const Interpreter::QmlEnumValue *>(value)) {
                foreach (const QString &key, enumValue->keys()) {
                    TextEditor::CompletionItem item(this);
                    item.text = key;
                    item.data = QString("\"%1\"").arg(key);
                    item.icon = symbolIcon;
                    item.order = EnumValueOrder;
                    m_completions.append(item);
Christian Kamm's avatar
Christian Kamm committed
866 867 868 869
                }
            }
        }

870 871
        if (doGlobalCompletion) {
            // It's a global completion.
872
            EnumerateProperties enumerateProperties(context);
873
            enumerateProperties.setGlobalCompletion(true);
874
            addCompletions(enumerateProperties(), symbolIcon, SymbolOrder);
Christian Kamm's avatar
Christian Kamm committed
875
        }
876

Christian Kamm's avatar
Christian Kamm committed
877
        if (doJsKeywordCompletion) {
878
            // add js keywords
879
            addCompletions(Scanner::keywords(), keywordIcon, KeywordOrder);
880 881 882
        }

        // add qml extra words
Christian Kamm's avatar
Christian Kamm committed
883
        if (doQmlKeywordCompletion && isQmlFile) {
884
            static QStringList qmlWords;
885
            static QStringList qmlWordsAlsoInJs;
886 887 888

            if (qmlWords.isEmpty()) {
                qmlWords << QLatin1String("property")
889
                        //<< QLatin1String("readonly")
890 891 892
                        << QLatin1String("signal")
                        << QLatin1String("import");
            }
893 894 895
            if (qmlWordsAlsoInJs.isEmpty()) {
                qmlWordsAlsoInJs << QLatin1String("default")
                        << QLatin1String("function");
896
            }
Christian Kamm's avatar
Christian Kamm committed
897

898
            addCompletions(qmlWords, keywordIcon, KeywordOrder);
899
            if (!doJsKeywordCompletion)
900
                addCompletions(qmlWordsAlsoInJs, keywordIcon, KeywordOrder);
901
        }
902 903
    }

904
    else if (completionOperator == QLatin1Char('.') || completionOperator == QLatin1Char('(')) {
Roberto Raggi's avatar
Roberto Raggi committed
905
        // Look at the expression under cursor.
906 907
        QTextCursor tc = edit->textCursor();
        tc.setPosition(m_startPosition - 1);
908

909 910
        QmlExpressionUnderCursor expressionUnderCursor;
        QmlJS::AST::ExpressionNode *expression = expressionUnderCursor(tc);
911

912
        if (expression != 0 && ! isLiteral(expression)) {
Roberto Raggi's avatar
Roberto Raggi committed
913
            // Evaluate the expression under cursor.
914 915
            Interpreter::Engine *interp = lookupContext->engine();
            const Interpreter::Value *value = interp->convertToObject(lookupContext->evaluate(expression));
916 917
            //qDebug() << "type:" << interp.typeId(value);

918
            if (value && completionOperator == QLatin1Char('.')) { // member completion
919
                EnumerateProperties enumerateProperties(context);
920
                if (contextFinder.isInLhsOfBinding() && qmlScopeType && expressionUnderCursor.text().at(0).isLower())
921
                    addCompletionsPropertyLhs(enumerateProperties(value), symbolIcon, PropertyOrder, contextFinder.isAfterOnInLhsOfBinding());
922
                else
923
                    addCompletions(enumerateProperties(value), symbolIcon, SymbolOrder);
924 925
            } else if (value && completionOperator == QLatin1Char('(') && m_startPosition == editor->position()) {
                // function completion
926
                if (const Interpreter::FunctionValue *f = value->asFunctionValue()) {
927 928
                    QString functionName = expressionUnderCursor.text();
                    int indexOfDot = functionName.lastIndexOf(QLatin1Char('.'));
929
                    if (indexOfDot != -1)
930
                        functionName = functionName.mid(indexOfDot + 1);
931

932 933 934 935
                    // Recreate if necessary
                    if (!m_functionArgumentWidget)
                        m_functionArgumentWidget = new QmlJSEditor::Internal::FunctionArgumentWidget;

936 937 938 939 940 941
                    QStringList signature;
                    for (int i = 0; i < f->argumentCount(); ++i)
                        signature.append(f->argumentName(i));

                    m_functionArgumentWidget->showFunctionHint(functionName.trimmed(),
                                                               signature,
942
                                                               m_startPosition);
943 944
                }