quicktoolbar.cpp 16.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Kai Koehne's avatar
Kai Koehne committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Kai Koehne's avatar
Kai Koehne committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Kai Koehne's avatar
Kai Koehne 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.
Kai Koehne's avatar
Kai Koehne 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
Kai Koehne's avatar
Kai Koehne committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
Kai Koehne's avatar
Kai Koehne committed
29

30
#include "quicktoolbar.h"
31
#include "quicktoolbarsettingspage.h"
32 33

#include <utils/changeset.h>
34 35
#include <qmleditorwidgets/contextpanewidget.h>
#include <qmleditorwidgets/customcolordialog.h>
36 37 38 39 40
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljspropertyreader.h>
#include <qmljs/qmljsrewriter.h>
#include <qmljs/qmljsindenter.h>
41
#include <qmljs/qmljscontext.h>
42 43
#include <qmljs/qmljsbind.h>
#include <qmljs/qmljsscopebuilder.h>
44
#include <qmljs/qmljsevaluate.h>
45
#include <qmljs/qmljsutils.h>
46 47 48
#include <texteditor/basetexteditor.h>
#include <texteditor/tabsettings.h>
#include <coreplugin/icore.h>
49

50
#include <QDebug>
51 52 53 54 55 56 57

using namespace QmlJS;
using namespace AST;
using namespace QmlEditorWidgets;

namespace QmlJSEditor {

58
static inline const ObjectValue * getPropertyChangesTarget(Node *node, const ScopeChain &scopeChain)
59
{
60
    UiObjectInitializer *initializer = initializerOfObject(node);
61 62 63 64
    if (initializer) {
        for (UiObjectMemberList *members = initializer->members; members; members = members->next) {
            if (UiScriptBinding *scriptBinding = cast<UiScriptBinding *>(members->member)) {
                if (scriptBinding->qualifiedId
65
                        && scriptBinding->qualifiedId->name == QLatin1String("target")
66
                        && ! scriptBinding->qualifiedId->next) {
Christian Kamm's avatar
Christian Kamm committed
67
                    Evaluate evaluator(&scopeChain);
68
                    const Value *targetValue = evaluator(scriptBinding->statement);
69
                    if (const ObjectValue *targetObject = value_cast<ObjectValue>(targetValue))
70
                        return targetObject;
71
                    else
72
                        return 0;
73 74 75 76
                }
            }
        }
    }
Thomas Hartmann's avatar
Thomas Hartmann committed
77
    return 0;
78 79
}

80 81 82 83
QuickToolBar::QuickToolBar(QObject *parent)
    : ::QmlJS::IContextPane(parent)
    , m_editor(0)
    , m_blockWriting(false)
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
{
    m_node = 0;
    contextWidget();

    m_propertyOrder
               << QLatin1String("id")
               << QLatin1String("name")
               << QLatin1String("target")
               << QLatin1String("property")
               << QLatin1String("x")
               << QLatin1String("y")
               << QLatin1String("width")
               << QLatin1String("height")
               << QLatin1String("position")
               << QLatin1String("color")
               << QLatin1String("radius")
               << QLatin1String("text")
               << QLatin1String("font.family")
               << QLatin1String("font.bold")
               << QLatin1String("font.italic")
               << QLatin1String("font.underline")
               << QLatin1String("font.strikeout")
               << QString::null
               << QLatin1String("states")
               << QLatin1String("transitions")
               ;
}

QuickToolBar::~QuickToolBar()
{
    //if the pane was never activated the widget is not in a widget tree
    if (!m_widget.isNull())
        delete m_widget.data();
117
        m_widget = 0;
118 119
}

120
void QuickToolBar::apply(TextEditor::BaseTextEditor *editor, Document::Ptr document, const ScopeChain *scopeChain, AST::Node *node, bool update, bool force)
121 122 123 124 125 126
{
    if (!QuickToolBarSettings::get().enableContextPane && !force && !update) {
        contextWidget()->hide();
        return;
    }

127
    if (document.isNull())
128 129 130 131 132 133 134
        return;

    if (update && editor != m_editor)
        return; //do not update for different editor

    m_blockWriting = true;

135
    const ObjectValue *scopeObject = document->bind()->findQmlObject(node);
136

137 138
    bool isPropertyChanges = false;

Christian Kamm's avatar
Christian Kamm committed
139
    if (scopeChain && scopeObject) {
140
        m_prototypes.clear();
141 142
        foreach (const ObjectValue *object,
                 PrototypeIterator(scopeObject, scopeChain->context()).all()) {
143
            m_prototypes.append(object->className());
144
        }
145

146
        if (m_prototypes.contains(QLatin1String("PropertyChanges"))) {
147
            isPropertyChanges = true;
148
            const ObjectValue *targetObject = getPropertyChangesTarget(node, *scopeChain);
149
            m_prototypes.clear();
150
            if (targetObject) {
151 152
                foreach (const ObjectValue *object,
                         PrototypeIterator(targetObject, scopeChain->context()).all()) {
153 154
                    m_prototypes.append(object->className());
                }
155
            }
156 157 158
        }
    }

159
    setEnabled(document->isParsedCorrectly());
160 161 162 163 164 165 166 167 168
    m_editor = editor;
    contextWidget()->setParent(editor->widget()->parentWidget());
    contextWidget()->colorDialog()->setParent(editor->widget()->parentWidget());

    if (cast<UiObjectDefinition*>(node) || cast<UiObjectBinding*>(node)) {
        UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(node);
        UiObjectBinding *objectBinding = cast<UiObjectBinding*>(node);

        QString name;
Thomas Hartmann's avatar
Thomas Hartmann committed
169 170 171
        quint32 offset = 0;
        quint32 end = 0;
        UiObjectInitializer *initializer = 0;
172
        if (objectDefinition) {
173
            name = objectDefinition->qualifiedTypeNameId->name.toString();
174 175 176 177
            initializer = objectDefinition->initializer;
            offset = objectDefinition->firstSourceLocation().offset;
            end = objectDefinition->lastSourceLocation().end();
        } else if (objectBinding) {
178
            name = objectBinding->qualifiedTypeNameId->name.toString();
179 180 181 182 183
            initializer = objectBinding->initializer;
            offset = objectBinding->firstSourceLocation().offset;
            end = objectBinding->lastSourceLocation().end();
        }

Christian Kamm's avatar
Christian Kamm committed
184
        if (!scopeChain) {
185 186 187 188 189 190
            if (name != m_oldType)
                m_prototypes.clear();
        }

        m_oldType = name;

191 192
        m_prototypes.append(name);

193 194 195 196 197 198 199 200 201
        int line1;
        int column1;
        int line2;
        int column2;
        m_editor->convertPosition(offset, &line1, &column1); //get line
        m_editor->convertPosition(end, &line2, &column2); //get line

        QRegion reg;
        if (line1 > -1 && line2 > -1)
202
            reg = m_editor->editorWidget()->translatedLineRegion(line1 - 1, line2);
203 204 205 206 207

        QRect rect;
        rect.setHeight(widget()->height() + 10);
        rect.setWidth(reg.boundingRect().width() - reg.boundingRect().left());
        rect.moveTo(reg.boundingRect().topLeft());
208
        reg = reg.intersected(rect);
209

210
        if (contextWidget()->acceptsType(m_prototypes)) {
211
            m_node = 0;
212
            PropertyReader propertyReader(document, initializer);
213
            QTextCursor tc(editor->editorWidget()->document());
Orgad Shaneh's avatar
Orgad Shaneh committed
214
            tc.setPosition(offset);
215
            QPoint p1 = editor->editorWidget()->mapToParent(editor->editorWidget()->viewport()->mapToParent(editor->editorWidget()->cursorRect(tc).topLeft()) - QPoint(0, contextWidget()->height() + 10));
216
            tc.setPosition(end);
217
            QPoint p2 = editor->editorWidget()->mapToParent(editor->editorWidget()->viewport()->mapToParent(editor->editorWidget()->cursorRect(tc).bottomLeft()) + QPoint(0, 10));
218 219 220
            QPoint offset = QPoint(10, 0);
            if (reg.boundingRect().width() < 400)
                offset = QPoint(400 - reg.boundingRect().width() + 10 ,0);
221
            QPoint p3 = editor->editorWidget()->mapToParent(editor->editorWidget()->viewport()->mapToParent(reg.boundingRect().topRight()) + offset);
222
            p2.setX(p1.x());
223 224 225
            contextWidget()->setIsPropertyChanges(isPropertyChanges);
            if (!update)
                contextWidget()->setType(m_prototypes);
226 227 228 229 230
            if (!update)
                contextWidget()->activate(p3 , p1, p2, QuickToolBarSettings::get().pinContextPane);
            else
                contextWidget()->rePosition(p3 , p1, p2, QuickToolBarSettings::get().pinContextPane);
            contextWidget()->setOptions(QuickToolBarSettings::get().enableContextPane, QuickToolBarSettings::get().pinContextPane);
231
            contextWidget()->setPath(document->path());
Orgad Shaneh's avatar
Orgad Shaneh committed
232
            contextWidget()->setProperties(&propertyReader);
233
            m_doc = document;
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
            m_node = node;
        } else {
            contextWidget()->setParent(0);
            contextWidget()->hide();
            contextWidget()->colorDialog()->hide();
        }
    } else {
        contextWidget()->setParent(0);
        contextWidget()->hide();
        contextWidget()->colorDialog()->hide();
    }

    m_blockWriting = false;

}

250
bool QuickToolBar::isAvailable(TextEditor::BaseTextEditor *, Document::Ptr document, AST::Node *node)
251
{
252
    if (document.isNull())
253 254 255 256 257
        return false;

    if (!node)
        return false;

258
    QString name;
259

260 261
    UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(node);
    UiObjectBinding *objectBinding = cast<UiObjectBinding*>(node);
262
    if (objectDefinition)
263
        name = objectDefinition->qualifiedTypeNameId->name.toString();
264

265
    else if (objectBinding)
266
        name = objectBinding->qualifiedTypeNameId->name.toString();
267

268 269
    QStringList prototypes;
    prototypes.append(name);
270

271 272 273 274 275 276 277 278 279
    if (prototypes.contains(QLatin1String("Rectangle")) ||
            prototypes.contains(QLatin1String("Image")) ||
            prototypes.contains(QLatin1String("BorderImage")) ||
            prototypes.contains(QLatin1String("TextEdit")) ||
            prototypes.contains(QLatin1String("TextInput")) ||
            prototypes.contains(QLatin1String("PropertyAnimation")) ||
            prototypes.contains(QLatin1String("NumberAnimation")) ||
            prototypes.contains(QLatin1String("Text")) ||
            prototypes.contains(QLatin1String("PropertyChanges")))
280
        return true;
281

282
    return false;
283 284 285 286 287 288 289
}

void QuickToolBar::setProperty(const QString &propertyName, const QVariant &value)
{

    QString stringValue = value.toString();
    if (value.type() == QVariant::Color)
290
        stringValue = QLatin1Char('\"') + value.toString() + QLatin1Char('\"');
291 292 293 294 295

    if (cast<UiObjectDefinition*>(m_node) || cast<UiObjectBinding*>(m_node)) {
        UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(m_node);
        UiObjectBinding *objectBinding = cast<UiObjectBinding*>(m_node);

296
        UiObjectInitializer *initializer = 0;
297 298 299 300 301 302 303 304 305 306 307 308 309
        if (objectDefinition)
            initializer = objectDefinition->initializer;
        else if (objectBinding)
            initializer = objectBinding->initializer;

        Utils::ChangeSet changeSet;
        Rewriter rewriter(m_doc->source(), &changeSet, m_propertyOrder);

        int line = -1;
        int endLine;

        Rewriter::BindingType bindingType = Rewriter::ScriptBinding;

310
        if (stringValue.contains(QLatin1Char('{')) && stringValue.contains(QLatin1Char('}')))
311 312 313
            bindingType = Rewriter::ObjectBinding;

        PropertyReader propertyReader(m_doc, initializer);
314
        if (propertyReader.hasProperty(propertyName))
315
            rewriter.changeBinding(initializer, propertyName, stringValue, bindingType);
316
        else
317 318 319 320 321 322
            rewriter.addBinding(initializer, propertyName, stringValue, bindingType);

        int column;

        int changeSetPos = changeSet.operationList().last().pos1;
        int changeSetLength = changeSet.operationList().last().text.length();
323
        QTextCursor tc = m_editor->editorWidget()->textCursor();
324 325 326 327 328 329 330
        tc.beginEditBlock();
        changeSet.apply(&tc);

        m_editor->convertPosition(changeSetPos, &line, &column); //get line
        m_editor->convertPosition(changeSetPos + changeSetLength, &endLine, &column); //get line

        if (line > 0) {
331
            TextEditor::TabSettings ts = m_editor->baseTextDocument()->tabSettings();
332 333 334 335 336
            QmlJSIndenter indenter;
            indenter.setTabSize(ts.m_tabSize);
            indenter.setIndentSize(ts.m_indentSize);

            for (int i=line;i<=endLine;i++) {
337 338
                QTextBlock start = m_editor->baseTextDocument()->document()->findBlockByNumber(i);
                QTextBlock end = m_editor->baseTextDocument()->document()->findBlockByNumber(i);
339 340

                if (end.isValid()) {
341 342 343
                    const int indent = indenter.indentForBottomLine(m_editor->baseTextDocument()
                                                                    ->document()->begin(),
                                                                    end.next(), QChar::Null);
344 345 346 347 348 349 350 351 352 353 354 355 356 357
                    ts.indentLine(start, indent);
                }
            }
        }
        tc.endEditBlock();
    }
}

void QuickToolBar::removeProperty(const QString &propertyName)
{
    if (cast<UiObjectDefinition*>(m_node) || cast<UiObjectBinding*>(m_node)) {
        UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(m_node);
        UiObjectBinding *objectBinding = cast<UiObjectBinding*>(m_node);

358
        UiObjectInitializer *initializer = 0;
359 360 361 362 363 364 365 366 367 368
        if (objectDefinition)
            initializer = objectDefinition->initializer;
        else if (objectBinding)
            initializer = objectBinding->initializer;

        PropertyReader propertyReader(m_doc, initializer);
        if (propertyReader.hasProperty(propertyName)) {
            Utils::ChangeSet changeSet;
            Rewriter rewriter(m_doc->source(), &changeSet, m_propertyOrder);
            rewriter.removeBindingByName(initializer, propertyName);
369
            QTextCursor tc(m_editor->editorWidget()->document());
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
            changeSet.apply(&tc);
        }
    }
}

void QuickToolBar::setEnabled(bool b)
{
    if (m_widget)
        contextWidget()->currentWidget()->setEnabled(b);
    if (!b)
        widget()->hide();
}


QWidget* QuickToolBar::widget()
{
    return contextWidget();
}


void QuickToolBar::onPropertyChanged(const QString &name, const QVariant &value)
{
    if (m_blockWriting)
        return;
    if (!m_doc)
        return;

    setProperty(name, value);
    m_doc.clear(); //the document is outdated
}

void QuickToolBar::onPropertyRemovedAndChange(const QString &remove, const QString &change, const QVariant &value, bool removeFirst)
{
    if (m_blockWriting)
        return;

    if (!m_doc)
        return;

409
    QTextCursor tc(m_editor->editorWidget()->document());
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
    tc.beginEditBlock();

    if (removeFirst) {
        removeProperty(remove);
        setProperty(change, value);
    } else {
        setProperty(change, value);
        removeProperty(remove);
    }


    tc.endEditBlock();

    m_doc.clear(); //the document is outdated

}

void QuickToolBar::onPinnedChanged(bool b)
{
    QuickToolBarSettings settings = QuickToolBarSettings::get();
    settings.pinContextPane = b;
    settings.set();
}

void QuickToolBar::onEnabledChanged(bool b)
{
    QuickToolBarSettings settings = QuickToolBarSettings::get();
    settings.pinContextPane = b;
    settings.enableContextPane = b;
    settings.set();
}

ContextPaneWidget* QuickToolBar::contextWidget()
{
    if (m_widget.isNull()) { //lazily recreate widget
        m_widget = new ContextPaneWidget;
        connect(m_widget.data(), SIGNAL(propertyChanged(QString,QVariant)), this, SLOT(onPropertyChanged(QString,QVariant)));
        connect(m_widget.data(), SIGNAL(removeProperty(QString)), this, SLOT(onPropertyRemoved(QString)));
Robert Loehning's avatar
Robert Loehning committed
448
        connect(m_widget.data(), SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)), this, SLOT(onPropertyRemovedAndChange(QString,QString,QVariant,bool)));
449 450
        connect(m_widget.data(), SIGNAL(enabledChanged(bool)), this, SLOT(onEnabledChanged(bool)));
        connect(m_widget.data(), SIGNAL(pinnedChanged(bool)), this, SLOT(onPinnedChanged(bool)));
451
        connect(m_widget.data(), SIGNAL(closed()), this, SIGNAL(closed()));
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    }
    return m_widget.data();
}

void QuickToolBar::onPropertyRemoved(const QString &propertyName)
{
    if (m_blockWriting)
        return;

    if (!m_doc)
        return;

    removeProperty(propertyName);
    m_doc.clear(); //the document is outdated
}

} //QmlDesigner