qmljsscriptconsole.cpp 15.6 KB
Newer Older
1 2 3 4 5 6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
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
**
**************************************************************************/

#include "qmljsscriptconsole.h"
#include "interactiveinterpreter.h"
#include "qmladapter.h"
#include "debuggerstringutils.h"

#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>

#include <extensionsystem/pluginmanager.h>
#include <coreplugin/coreconstants.h>
#include <utils/statuslabel.h>

#include <QtGui/QMenu>
#include <QtGui/QTextBlock>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QToolButton>

namespace Debugger {
namespace Internal {

class QmlJSScriptConsolePrivate
{
public:
    QmlJSScriptConsolePrivate()
Aurindam Jana's avatar
Aurindam Jana committed
58
        : prompt(_("> ")),
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
          startOfEditableArea(-1),
          lastKnownPosition(0),
          inferiorStopped(false)
    {
        resetCache();
    }

    void resetCache();
    void appendToHistory(const QString &script);
    bool canEvaluateScript(const QString &script);

    QWeakPointer<QmlAdapter> adapter;

    QString prompt;
    int startOfEditableArea;
    int lastKnownPosition;

    QStringList scriptHistory;
    int scriptHistoryIndex;

    InteractiveInterpreter interpreter;

    bool inferiorStopped;
    QList<QTextEdit::ExtraSelection> selections;
};

void QmlJSScriptConsolePrivate::resetCache()
{
    scriptHistory.clear();
Aurindam Jana's avatar
Aurindam Jana committed
88
    scriptHistory.append(QString());
89 90 91 92 93 94 95 96 97
    scriptHistoryIndex = scriptHistory.count();

    selections.clear();
}

void QmlJSScriptConsolePrivate::appendToHistory(const QString &script)
{
    scriptHistoryIndex = scriptHistory.count();
    scriptHistory.replace(scriptHistoryIndex - 1,script);
Aurindam Jana's avatar
Aurindam Jana committed
98
    scriptHistory.append(QString());
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
    scriptHistoryIndex = scriptHistory.count();
}

bool QmlJSScriptConsolePrivate::canEvaluateScript(const QString &script)
{
    interpreter.clearText();
    interpreter.appendText(script);
    return interpreter.canEvaluate();
}

///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsoleWidget
//
///////////////////////////////////////////////////////////////////////

QmlJSScriptConsoleWidget::QmlJSScriptConsoleWidget(QWidget *parent)
    : QWidget(parent)
{
    QVBoxLayout *vbox = new QVBoxLayout(this);
    vbox->setMargin(0);
    vbox->setSpacing(0);

    QWidget *statusbarContainer = new QWidget;

    QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer);
    hbox->setMargin(0);
    hbox->setSpacing(0);

    //Clear Button
    QToolButton *clearButton = new QToolButton;
    QAction *clearAction = new QAction(tr("Clear Console"), this);
    clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE)));

    clearButton->setDefaultAction(clearAction);

    //Status Label
    m_statusLabel = new Utils::StatusLabel;

    hbox->addWidget(m_statusLabel, 20, Qt::AlignLeft);
    hbox->addWidget(clearButton, 0, Qt::AlignRight);

    m_console = new QmlJSScriptConsole;
    connect(m_console, SIGNAL(evaluateExpression(QString)), this,
            SIGNAL(evaluateExpression(QString)));
    connect(m_console, SIGNAL(updateStatusMessage(const QString &, int)), m_statusLabel,
            SLOT(showStatusMessage(const QString &, int)));
    connect(clearAction, SIGNAL(triggered()), m_console, SLOT(clear()));
    vbox->addWidget(statusbarContainer);
    vbox->addWidget(m_console);

}

void QmlJSScriptConsoleWidget::setQmlAdapter(QmlAdapter *adapter)
{
    m_console->setQmlAdapter(adapter);
}

void QmlJSScriptConsoleWidget::setInferiorStopped(bool inferiorStopped)
{
    m_console->setInferiorStopped(inferiorStopped);
}

void QmlJSScriptConsoleWidget::appendResult(const QString &result)
{
    m_console->appendResult(result);
}

///////////////////////////////////////////////////////////////////////
//
// QmlJSScriptConsole
//
///////////////////////////////////////////////////////////////////////

QmlJSScriptConsole::QmlJSScriptConsole(QWidget *parent)
    : QPlainTextEdit(parent),
      d(new QmlJSScriptConsolePrivate())
{
    connect(this, SIGNAL(cursorPositionChanged()), SLOT(onCursorPositionChanged()));

    setFrameStyle(QFrame::NoFrame);
    setUndoRedoEnabled(false);
    setBackgroundVisible(false);
    const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
    setFont(fs.font());

    displayPrompt();
}

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

void QmlJSScriptConsole::setPrompt(const QString &prompt)
{
    d->prompt = prompt;
}

QString QmlJSScriptConsole::prompt() const
{
    return d->prompt;
}

void QmlJSScriptConsole::setInferiorStopped(bool inferiorStopped)
{
    d->inferiorStopped = inferiorStopped;
    onSelectionChanged();
}

void QmlJSScriptConsole::setQmlAdapter(QmlAdapter *adapter)
{
    d->adapter = adapter;
    clear();
}

void QmlJSScriptConsole::appendResult(const QString &result)
{
    QString currentScript = getCurrentScript();
    d->appendToHistory(currentScript);

    QTextCursor cur = textCursor();
221
    cur.movePosition(QTextCursor::End);
Aurindam Jana's avatar
Aurindam Jana committed
222
    cur.insertText(_("\n"));
223 224
    cur.insertText(result);
    cur.movePosition(QTextCursor::EndOfLine);
Aurindam Jana's avatar
Aurindam Jana committed
225
    cur.insertText(_("\n"));
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
    setTextCursor(cur);
    displayPrompt();

    QTextEdit::ExtraSelection sel;

    QTextCharFormat resultFormat;
    resultFormat.setForeground(QBrush(QColor(Qt::darkGray)));

    QTextCursor c(document()->findBlockByNumber(cur.blockNumber()-1));
    c.movePosition(QTextCursor::StartOfBlock);
    c.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor);

    sel.format = resultFormat;
    sel.cursor = c;

    d->selections.append(sel);

    setExtraSelections(d->selections);
}

void QmlJSScriptConsole::clear()
{
    d->resetCache();

    QPlainTextEdit::clear();
    displayPrompt();
}

void QmlJSScriptConsole::onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
    QDeclarativeDebugExpressionQuery *query = qobject_cast<QDeclarativeDebugExpressionQuery *>(sender());
Aurindam Jana's avatar
Aurindam Jana committed
257

258 259
    if (query && state != QDeclarativeDebugQuery::Error) {
        QString result(query->result().toString());
Aurindam Jana's avatar
Aurindam Jana committed
260 261 262
        if (result == _("<undefined>") && d->inferiorStopped) {
            //don't give up. check if we can still evaluate using javascript engine
            emit evaluateExpression(getCurrentScript());
263
        } else {
Aurindam Jana's avatar
Aurindam Jana committed
264
            appendResult(result);
265
        }
Aurindam Jana's avatar
Aurindam Jana committed
266 267 268
    } else {
        QPlainTextEdit::appendPlainText(QString());
        moveCursor(QTextCursor::EndOfLine);
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
    }
    delete query;
}

void QmlJSScriptConsole::onSelectionChanged()
{
    if (!d->adapter.isNull()) {
        QString status;
        if (!d->inferiorStopped) {
            status.append(tr("Current Selected Object: "));
            status.append(d->adapter.data()->currentSelectedDisplayName());
        }
        emit updateStatusMessage(status, 0);
    }
}

void QmlJSScriptConsole::keyPressEvent(QKeyEvent *e)
{
    bool keyConsumed = false;
    switch (e->key()) {

    case Qt::Key_Return:
    case Qt::Key_Enter:
        if (isEditableArea()) {
            handleReturnKey();
            keyConsumed = true;
        }
        break;

    case Qt::Key_Backspace: {
        QTextCursor cursor = textCursor();
        bool hasSelection = cursor.hasSelection();
        int selectionStart = cursor.selectionStart();
        if ((hasSelection && selectionStart < d->startOfEditableArea)
                || (!hasSelection && selectionStart == d->startOfEditableArea)) {
            keyConsumed = true;
        }
        break;
    }

    case Qt::Key_Delete:
        if (textCursor().selectionStart() < d->startOfEditableArea) {
            keyConsumed = true;
        }
        break;

    case Qt::Key_Tab:
    case Qt::Key_Backtab:
        keyConsumed = true;
        break;

    case Qt::Key_Left:
        if (textCursor().position() == d->startOfEditableArea) {
            keyConsumed = true;
        } else if (e->modifiers() & Qt::ControlModifier && isEditableArea()) {
            handleHomeKey();
            keyConsumed = true;
        }
        break;

    case Qt::Key_Up:
        if (isEditableArea()) {
            handleUpKey();
            keyConsumed = true;
        }
        break;

    case Qt::Key_Down:
        if (isEditableArea()) {
            handleDownKey();
            keyConsumed = true;
        }
        break;

    case Qt::Key_Home:
        if (isEditableArea()) {
            handleHomeKey();
            keyConsumed = true;
        }
        break;

    case Qt::Key_C:
    case Qt::Key_Insert: {
        //Fair to assume that for any selection beyond startOfEditableArea
        //only copy function is allowed.
        QTextCursor cursor = textCursor();
        bool hasSelection = cursor.hasSelection();
        int selectionStart = cursor.selectionStart();
        if (hasSelection && selectionStart < d->startOfEditableArea) {
            if (!(e->modifiers() & Qt::ControlModifier))
                keyConsumed = true;
        }
        break;
    }

    default: {
        QTextCursor cursor = textCursor();
        bool hasSelection = cursor.hasSelection();
        int selectionStart = cursor.selectionStart();
        if (hasSelection && selectionStart < d->startOfEditableArea) {
            keyConsumed = true;
        }
        break;
    }
    }

    if (!keyConsumed)
        QPlainTextEdit::keyPressEvent(e);
}

void QmlJSScriptConsole::contextMenuEvent(QContextMenuEvent *event)
{
    QTextCursor cursor = textCursor();
    Qt::TextInteractionFlags flags = textInteractionFlags();
    bool hasSelection = cursor.hasSelection();
    int selectionStart = cursor.selectionStart();
    bool canBeEdited = true;
    if (hasSelection && selectionStart < d->startOfEditableArea) {
        canBeEdited = false;
    }

    QMenu *menu = new QMenu();
    QAction *a;

    if ((flags & Qt::TextEditable) && canBeEdited) {
        a = menu->addAction(tr("Cut"), this, SLOT(cut()));
        a->setEnabled(cursor.hasSelection());
    }

    a = menu->addAction(tr("Copy"), this, SLOT(copy()));
    a->setEnabled(cursor.hasSelection());

    if ((flags & Qt::TextEditable) && canBeEdited) {
        a = menu->addAction(tr("Paste"), this, SLOT(paste()));
        a->setEnabled(canPaste());
    }

    menu->addSeparator();
    a = menu->addAction(tr("Select All"), this, SLOT(selectAll()));
    a->setEnabled(!document()->isEmpty());

    menu->addSeparator();
    menu->addAction(tr("Clear"), this, SLOT(clear()));

    menu->exec(event->globalPos());

    delete menu;
}

void QmlJSScriptConsole::mouseReleaseEvent(QMouseEvent *e)
{
    QPlainTextEdit::mouseReleaseEvent(e);
    QTextCursor cursor = textCursor();
    if (e->button() == Qt::LeftButton && !cursor.hasSelection() && !isEditableArea()) {
        cursor.setPosition(d->lastKnownPosition);
        setTextCursor(cursor);
    }
}

void QmlJSScriptConsole::onCursorPositionChanged()
{
    if (!isEditableArea()) {
        setTextInteractionFlags(Qt::TextSelectableByMouse);
    } else {
        d->lastKnownPosition = textCursor().position();
        setTextInteractionFlags(Qt::TextEditorInteraction);
    }
}

void QmlJSScriptConsole::displayPrompt()
{
    d->startOfEditableArea = textCursor().position() + d->prompt.length();
    QTextCursor cur = textCursor();
    cur.insertText(d->prompt);
    cur.movePosition(QTextCursor::EndOfWord);
    setTextCursor(cur);
}

void QmlJSScriptConsole::handleReturnKey()
{
    QString currentScript = getCurrentScript();
450
    bool scriptEvaluated = false;
451 452 453 454 455

    //Check if string is only white spaces
    if (currentScript.trimmed().isEmpty()) {
        QTextCursor cur = textCursor();
        cur.movePosition(QTextCursor::EndOfLine);
Aurindam Jana's avatar
Aurindam Jana committed
456
        cur.insertText(_("\n"));
457 458
        setTextCursor(cur);
        displayPrompt();
459
        scriptEvaluated = true;
460 461
    }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    if (!scriptEvaluated) {
        //check if it can be evaluated
        if (d->canEvaluateScript(currentScript)) {

            //Select the engine for evaluation based on
            //inferior state
            if (!d->inferiorStopped) {
                if (!d->adapter.isNull()) {
                    QDeclarativeEngineDebug *engineDebug = d->adapter.data()->engineDebugClient();
                    int id = d->adapter.data()->currentSelectedDebugId();
                    if (engineDebug && id != -1) {
                        QDeclarativeDebugExpressionQuery *query =
                                engineDebug->queryExpressionResult(id, currentScript, this);
                        connect(query, SIGNAL(stateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)),
                                this, SLOT(onStateChanged(QmlJsDebugClient::QDeclarativeDebugQuery::State)));
                        scriptEvaluated = true;
                    }
                }
480 481
            }

482 483 484 485
            if (!scriptEvaluated) {
                emit evaluateExpression(currentScript);
                scriptEvaluated = true;
            }
486 487
        }
    }
488 489 490 491 492
    if (!scriptEvaluated) {
        QPlainTextEdit::appendPlainText(QString());
        moveCursor(QTextCursor::EndOfLine);
    }

493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
}

void QmlJSScriptConsole::handleUpKey()
{
    //get the current script and update in script history
    QString currentScript = getCurrentScript();
    d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);

    if (d->scriptHistoryIndex > 1)
        d->scriptHistoryIndex--;

    replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}

void QmlJSScriptConsole::handleDownKey()
{
    //get the current script and update in script history
    QString currentScript = getCurrentScript();
    d->scriptHistory.replace(d->scriptHistoryIndex - 1,currentScript);

    if (d->scriptHistoryIndex < d->scriptHistory.count())
        d->scriptHistoryIndex++;

    replaceCurrentScript(d->scriptHistory.at(d->scriptHistoryIndex - 1));
}

void QmlJSScriptConsole::handleHomeKey()
{
    QTextCursor cursor = textCursor();
    cursor.setPosition(d->startOfEditableArea);
    setTextCursor(cursor);
}

QString QmlJSScriptConsole::getCurrentScript() const
{
    QTextCursor cursor = textCursor();
    cursor.setPosition(d->startOfEditableArea);
530
    while (cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor)) ;
531 532 533 534 535 536 537 538 539 540 541 542 543
    QString script = cursor.selectedText();
    cursor.clearSelection();
    //remove trailing white space
    int end = script.size() - 1;
    while (end > 0 && script[end].isSpace())
        end--;
    return script.left(end + 1);
}

void QmlJSScriptConsole::replaceCurrentScript(const QString &script)
{
    QTextCursor cursor = textCursor();
    cursor.setPosition(d->startOfEditableArea);
544
    while (cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor)) ;
545 546 547 548 549 550 551 552 553 554 555 556
    cursor.deleteChar();
    cursor.insertText(script);
    setTextCursor(cursor);
}

bool QmlJSScriptConsole::isEditableArea() const
{
    return textCursor().position() >= d->startOfEditableArea;
}

} //Internal
} //Debugger