snippetssettingspage.cpp 18.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** 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.
**
**************************************************************************/

#include "snippetssettingspage.h"
#include "snippetsmanager.h"
#include "snippeteditor.h"
#include "isnippeteditordecorator.h"
#include "snippet.h"
#include "snippetscollection.h"
#include "snippetssettings.h"
#include "reuse.h"
#include "ui_snippetssettingspage.h"

#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>

#include <QtCore/QSharedPointer>
#include <QtCore/QModelIndex>
#include <QtCore/QAbstractTableModel>
#include <QtCore/QList>
#include <QtCore/QSettings>
#include <QtCore/QTextStream>
#include <QtGui/QMessageBox>

namespace TextEditor {
namespace Internal {

// SnippetsTableModel
class SnippetsTableModel : public QAbstractTableModel
{
    Q_OBJECT
public:
    SnippetsTableModel(QObject *parent);
    virtual ~SnippetsTableModel() {}

    virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
    virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
    virtual Qt::ItemFlags flags(const QModelIndex &modelIndex) const;
    virtual QVariant data(const QModelIndex &modelIndex, int role = Qt::DisplayRole) const;
    virtual bool setData(const QModelIndex &modelIndex, const QVariant &value,
                         int role = Qt::EditRole);
    virtual QVariant headerData(int section, Qt::Orientation orientation,
                                int role = Qt::DisplayRole) const;

    void load(Snippet::Group group);

    QModelIndex createSnippet();
    QModelIndex insertSnippet(const Snippet &snippet);
    void removeSnippet(const QModelIndex &modelIndex);
    const Snippet &snippetAt(const QModelIndex &modelIndex) const;
    void setSnippetContent(const QModelIndex &modelIndex, const QString &content);
Leandro Melo's avatar
Leandro Melo committed
78 79 80
    void revertBuitInSnippet(const QModelIndex &modelIndex);
    void restoreRemovedBuiltInSnippets();
    void resetSnippets();
81 82

private:
Leandro Melo's avatar
Leandro Melo committed
83
    void replaceSnippet(const Snippet &snippet, const QModelIndex &modelIndex);
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    static bool isValidTrigger(const QString &s);

    Snippet::Group m_activeGroup;
    QSharedPointer<SnippetsCollection> m_collection;
};

SnippetsTableModel::SnippetsTableModel(QObject *parent) :
    QAbstractTableModel(parent),
    m_activeGroup(Snippet::Cpp),
    m_collection(SnippetsManager::instance()->snippetsCollection())
{}

int SnippetsTableModel::rowCount(const QModelIndex &) const
{
    if (m_collection.isNull())
        return 0;
    return m_collection->totalActiveSnippets(m_activeGroup);
}

int SnippetsTableModel::columnCount(const QModelIndex &) const
{
    if (m_collection.isNull())
        return 0;
    return 2;
}

Qt::ItemFlags SnippetsTableModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags itemFlags = QAbstractTableModel::flags(index);
    if (index.isValid())
        itemFlags |= Qt::ItemIsEditable;
    return itemFlags;
}

QVariant SnippetsTableModel::data(const QModelIndex &modelIndex, int role) const
{
    if (!modelIndex.isValid())
        return QVariant();

    if (role == Qt::DisplayRole || role == Qt::EditRole) {
        const Snippet &snippet = m_collection->snippet(modelIndex.row(), m_activeGroup);
        if (modelIndex.column() == 0)
            return snippet.trigger();
        else
            return snippet.complement();
    } else {
        return QVariant();
    }
}

bool SnippetsTableModel::setData(const QModelIndex &modelIndex, const QVariant &value, int role)
{
    if (modelIndex.isValid() && role == Qt::EditRole) {
Leandro Melo's avatar
Leandro Melo committed
137
        Snippet snippet(m_collection->snippet(modelIndex.row(), m_activeGroup));
138 139 140 141 142 143 144 145 146 147 148 149 150
        if (modelIndex.column() == 0) {
            const QString &s = value.toString();
            if (!isValidTrigger(s)) {
                QMessageBox::critical(0, tr("Error"), tr("Not a valid trigger."));
                if (snippet.trigger().isEmpty())
                    removeSnippet(modelIndex);
                return false;
            }
            snippet.setTrigger(s);
        } else {
            snippet.setComplement(value.toString());
        }

Leandro Melo's avatar
Leandro Melo committed
151
        replaceSnippet(snippet, modelIndex);
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
        return true;
    }
    return false;
}

QVariant SnippetsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole || orientation != Qt::Horizontal)
        return QVariant();

    if (section == 0)
        return tr("Trigger");
    else
        return tr("Complement");
}

void SnippetsTableModel::load(Snippet::Group group)
{
    m_activeGroup = group;
    reset();
}

QModelIndex SnippetsTableModel::createSnippet()
{
    Snippet snippet;
    snippet.setGroup(m_activeGroup);
    return insertSnippet(snippet);
}

QModelIndex SnippetsTableModel::insertSnippet(const Snippet &snippet)
{
    const SnippetsCollection::Hint &hint =
        m_collection->computeInsertionHint(snippet, m_activeGroup);
    beginInsertRows(QModelIndex(), hint.index(), hint.index());
    m_collection->insertSnippet(snippet, m_activeGroup, hint);
    endInsertRows();

    return index(hint.index(), 0);
}

void SnippetsTableModel::removeSnippet(const QModelIndex &modelIndex)
{
    beginRemoveRows(QModelIndex(), modelIndex.row(), modelIndex.row());
    m_collection->removeSnippet(modelIndex.row(), m_activeGroup);
    endRemoveRows();
}

const Snippet &SnippetsTableModel::snippetAt(const QModelIndex &modelIndex) const
{
    return m_collection->snippet(modelIndex.row(), m_activeGroup);
}

void SnippetsTableModel::setSnippetContent(const QModelIndex &modelIndex, const QString &content)
{
    m_collection->setSnippetContent(modelIndex.row(), m_activeGroup, content);
}

Leandro Melo's avatar
Leandro Melo committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
void SnippetsTableModel::revertBuitInSnippet(const QModelIndex &modelIndex)
{
    const Snippet &snippet = m_collection->revertedSnippet(modelIndex.row(), m_activeGroup);
    if (snippet.id().isEmpty()) {
        QMessageBox::critical(0, tr("Error"), tr("Error reverting snippet."));
        return;
    }
    replaceSnippet(snippet, modelIndex);
}

void SnippetsTableModel::restoreRemovedBuiltInSnippets()
{
    m_collection->restoreRemovedSnippets(m_activeGroup);
    reset();
}

void SnippetsTableModel::resetSnippets()
{
    m_collection->reset(m_activeGroup);
    reset();
}

void SnippetsTableModel::replaceSnippet(const Snippet &snippet, const QModelIndex &modelIndex)
{
    const int row = modelIndex.row();
    const SnippetsCollection::Hint &hint =
        m_collection->computeReplacementHint(row, snippet, m_activeGroup);
    if (modelIndex.row() == hint.index()) {
        m_collection->replaceSnippet(row, snippet, m_activeGroup, hint);
        emit dataChanged(modelIndex, modelIndex);
    } else {
        if (row < hint.index())
            // Rows will be moved down.
            beginMoveRows(QModelIndex(), row, row, QModelIndex(), hint.index() + 1);
        else
            beginMoveRows(QModelIndex(), row, row, QModelIndex(), hint.index());
        m_collection->replaceSnippet(row, snippet, m_activeGroup, hint);
        endMoveRows();
    }
}

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
bool SnippetsTableModel::isValidTrigger(const QString &s)
{
    if (s.isEmpty())
        return false;
    for (int i = 0; i < s.length(); ++i)
        if (!s.at(i).isLetter())
            return false;
    return true;
}

// SnippetsSettingsPagePrivate
class SnippetsSettingsPagePrivate : public QObject
{
    Q_OBJECT
public:
    SnippetsSettingsPagePrivate(const QString &id);
    ~SnippetsSettingsPagePrivate() { delete m_model; }

    const QString &id() const { return m_id; }
    const QString &displayName() const { return m_displayName; }
    bool isKeyword(const QString &s) const { return m_keywords.contains(s, Qt::CaseInsensitive); }
    void configureUi(QWidget *parent);

    void apply();
    void finish();

private slots:
    void loadSnippetGroup(int index);
    void markSnippetsCollection();
    void addSnippet();
    void removeSnippet();
Leandro Melo's avatar
Leandro Melo committed
281 282 283
    void revertBuiltInSnippet();
    void restoreRemovedBuiltInSnippets();
    void resetAllSnippets();
284 285
    void selectSnippet(const QModelIndex &parent, int row);
    void selectMovedSnippet(const QModelIndex &, int, int, const QModelIndex &, int row);
Leandro Melo's avatar
Leandro Melo committed
286 287
    void setSnippetContent();
    void updateCurrentSnippetDependent(const QModelIndex &modelIndex = QModelIndex());
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

private:
    SnippetEditor *currentEditor() const;
    SnippetEditor *editorAt(int i) const;

    static void decorateEditor(SnippetEditor *editor, Snippet::Group group);

    void loadSettings();
    bool settingsChanged() const;
    void writeSettings();

    const QString m_id;
    const QString m_displayName;
    const QString m_settingsPrefix;
    SnippetsTableModel *m_model;
    bool m_snippetsCollectionChanged;
    QString m_keywords;
    SnippetsSettings m_settings;
    Ui::SnippetsSettingsPage m_ui;
};

SnippetsSettingsPagePrivate::SnippetsSettingsPagePrivate(const QString &id) :
    m_id(id),
    m_displayName(tr("Snippets")),
    m_settingsPrefix(QLatin1String("Text")),
    m_model(new SnippetsTableModel(0)),
    m_snippetsCollectionChanged(false)
{}

SnippetEditor *SnippetsSettingsPagePrivate::currentEditor() const
{
    return editorAt(m_ui.snippetsEditorStack->currentIndex());
}

SnippetEditor *SnippetsSettingsPagePrivate::editorAt(int i) const
{
    return static_cast<SnippetEditor *>(m_ui.snippetsEditorStack->widget(i));
}

void SnippetsSettingsPagePrivate::configureUi(QWidget *w)
{
    m_ui.setupUi(w);

    m_ui.groupCombo->insertItem(Snippet::Cpp, fromSnippetGroup(Snippet::Cpp));
    m_ui.groupCombo->insertItem(Snippet::Qml, fromSnippetGroup(Snippet::Qml));
    m_ui.groupCombo->insertItem(Snippet::PlainText, fromSnippetGroup(Snippet::PlainText));

    m_ui.snippetsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_ui.snippetsTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_ui.snippetsTable->horizontalHeader()->setStretchLastSection(true);
    m_ui.snippetsTable->horizontalHeader()->setHighlightSections(false);
    m_ui.snippetsTable->verticalHeader()->setVisible(false);
    m_ui.snippetsTable->verticalHeader()->setDefaultSectionSize(20);
    m_ui.snippetsTable->setModel(m_model);

    m_ui.snippetsEditorStack->insertWidget(Snippet::Cpp, new SnippetEditor(w));
    m_ui.snippetsEditorStack->insertWidget(Snippet::Qml, new SnippetEditor(w));
    m_ui.snippetsEditorStack->insertWidget(Snippet::PlainText, new SnippetEditor(w));
    decorateEditor(editorAt(Snippet::Cpp), Snippet::Cpp);
    decorateEditor(editorAt(Snippet::Qml), Snippet::Qml);
    decorateEditor(editorAt(Snippet::PlainText), Snippet::PlainText);

Leandro Melo's avatar
Leandro Melo committed
350 351
    m_ui.revertButton->setEnabled(false);

352 353 354 355 356 357
    QTextStream(&m_keywords) << m_displayName;

    loadSettings();
    loadSnippetGroup(m_ui.groupCombo->currentIndex());

    connect(editorAt(Snippet::Cpp), SIGNAL(snippetContentChanged()),
Leandro Melo's avatar
Leandro Melo committed
358
            this, SLOT(setSnippetContent()));
359
    connect(editorAt(Snippet::Qml), SIGNAL(snippetContentChanged()),
Leandro Melo's avatar
Leandro Melo committed
360
            this, SLOT(setSnippetContent()));
361
    connect(editorAt(Snippet::PlainText), SIGNAL(snippetContentChanged()),
Leandro Melo's avatar
Leandro Melo committed
362
            this, SLOT(setSnippetContent()));
363 364 365 366 367 368 369 370 371 372 373 374 375

    connect(m_model, SIGNAL(rowsInserted(QModelIndex, int, int)),
            this, SLOT(selectSnippet(QModelIndex,int)));
    connect(m_model, SIGNAL(rowsInserted(QModelIndex, int, int)),
            this, SLOT(markSnippetsCollection()));
    connect(m_model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
            this, SLOT(markSnippetsCollection()));
    connect(m_model, SIGNAL(rowsMoved(QModelIndex, int, int, QModelIndex, int)),
            this, SLOT(selectMovedSnippet(QModelIndex,int,int,QModelIndex,int)));
    connect(m_model, SIGNAL(rowsMoved(QModelIndex, int, int, QModelIndex, int)),
            this, SLOT(markSnippetsCollection()));
    connect(m_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(markSnippetsCollection()));
Leandro Melo's avatar
Leandro Melo committed
376 377
    connect(m_model, SIGNAL(modelReset()), this, SLOT(updateCurrentSnippetDependent()));
    connect(m_model, SIGNAL(modelReset()), this, SLOT(markSnippetsCollection()));
378 379 380 381

    connect(m_ui.groupCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(loadSnippetGroup(int)));
    connect(m_ui.addButton, SIGNAL(clicked()), this, SLOT(addSnippet()));
    connect(m_ui.removeButton, SIGNAL(clicked()), this, SLOT(removeSnippet()));
Leandro Melo's avatar
Leandro Melo committed
382 383 384 385
    connect(m_ui.resetAllButton, SIGNAL(clicked()), this, SLOT(resetAllSnippets()));
    connect(m_ui.restoreRemovedButton, SIGNAL(clicked()),
            this, SLOT(restoreRemovedBuiltInSnippets()));
    connect(m_ui.revertButton, SIGNAL(clicked()), this, SLOT(revertBuiltInSnippet()));
386
    connect(m_ui.snippetsTable->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
Leandro Melo's avatar
Leandro Melo committed
387
            this, SLOT(updateCurrentSnippetDependent(QModelIndex)));
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
}

void SnippetsSettingsPagePrivate::decorateEditor(SnippetEditor *editor, Snippet::Group group)
{
    const QList<ISnippetEditorDecorator *> &decorators =
        ExtensionSystem::PluginManager::instance()->getObjects<ISnippetEditorDecorator>();
    foreach (ISnippetEditorDecorator *decorator, decorators)
        if (decorator->supports(group))
            decorator->apply(editor);
}

void SnippetsSettingsPagePrivate::apply()
{
    if (settingsChanged())
        writeSettings();

404 405 406 407
    if (m_snippetsCollectionChanged) {
        SnippetsManager::instance()->snippetsCollection()->synchronize();
        m_snippetsCollectionChanged = false;
    }
408 409 410 411 412
}

void SnippetsSettingsPagePrivate::finish()
{
    if (m_snippetsCollectionChanged) {
413
        SnippetsManager::instance()->snippetsCollection()->reload();
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 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        m_snippetsCollectionChanged = false;
    }
}

void SnippetsSettingsPagePrivate::loadSettings()
{
    if (QSettings *s = Core::ICore::instance()->settings()) {
        m_settings.fromSettings(m_settingsPrefix, s);
        m_ui.groupCombo->setCurrentIndex(toSnippetGroup(m_settings.lastUsedSnippetGroup()));
    }
}

void SnippetsSettingsPagePrivate::writeSettings()
{
    if (QSettings *s = Core::ICore::instance()->settings()) {
        m_settings.setLastUsedSnippetGroup(m_ui.groupCombo->currentText());
        m_settings.toSettings(m_settingsPrefix, s);
    }
}

bool SnippetsSettingsPagePrivate::settingsChanged() const
{
    if (m_settings.lastUsedSnippetGroup() != m_ui.groupCombo->currentText())
        return true;
    return false;
}

void SnippetsSettingsPagePrivate::loadSnippetGroup(int index)
{
    m_ui.snippetsEditorStack->setCurrentIndex(index);
    currentEditor()->clear();
    m_model->load(Snippet::Group(index));
}

void SnippetsSettingsPagePrivate::markSnippetsCollection()
{
    if (!m_snippetsCollectionChanged)
        m_snippetsCollectionChanged = true;
}

void SnippetsSettingsPagePrivate::addSnippet()
{
    const QModelIndex &modelIndex = m_model->createSnippet();
    selectSnippet(QModelIndex(), modelIndex.row());
    m_ui.snippetsTable->edit(modelIndex);
}

void SnippetsSettingsPagePrivate::removeSnippet()
{
    const QModelIndex &modelIndex = m_ui.snippetsTable->selectionModel()->currentIndex();
    if (!modelIndex.isValid()) {
        QMessageBox::critical(0, tr("Error"), tr("No snippet selected."));
        return;
    }
    m_model->removeSnippet(modelIndex);
}

Leandro Melo's avatar
Leandro Melo committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
void SnippetsSettingsPagePrivate::restoreRemovedBuiltInSnippets()
{
    m_model->restoreRemovedBuiltInSnippets();
}

void SnippetsSettingsPagePrivate::revertBuiltInSnippet()
{
    m_model->revertBuitInSnippet(m_ui.snippetsTable->selectionModel()->currentIndex());
}

void SnippetsSettingsPagePrivate::resetAllSnippets()
{
    m_model->resetSnippets();
}

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
void SnippetsSettingsPagePrivate::selectSnippet(const QModelIndex &parent, int row)
{
    QModelIndex topLeft = m_model->index(row, 0, parent);
    QModelIndex bottomRight = m_model->index(row, 1, parent);
    QItemSelection selection(topLeft, bottomRight);
    m_ui.snippetsTable->selectionModel()->select(selection, QItemSelectionModel::SelectCurrent);
    m_ui.snippetsTable->setCurrentIndex(topLeft);
    m_ui.snippetsTable->scrollTo(topLeft);
}

void SnippetsSettingsPagePrivate::selectMovedSnippet(const QModelIndex &,
                                                     int sourceRow,
                                                     int,
                                                     const QModelIndex &destinationParent,
                                                     int destinationRow)
{
    QModelIndex modelIndex;
    if (sourceRow < destinationRow)
        modelIndex = m_model->index(destinationRow - 1, 0, destinationParent);
    else
        modelIndex = m_model->index(destinationRow, 0, destinationParent);
    m_ui.snippetsTable->scrollTo(modelIndex);
Leandro Melo's avatar
Leandro Melo committed
508
    currentEditor()->setPlainText(m_model->snippetAt(modelIndex).content());
509 510
}

Leandro Melo's avatar
Leandro Melo committed
511
void SnippetsSettingsPagePrivate::updateCurrentSnippetDependent(const QModelIndex &modelIndex)
512
{
Leandro Melo's avatar
Leandro Melo committed
513 514 515 516 517 518 519 520
    if (modelIndex.isValid()) {
        const Snippet &snippet = m_model->snippetAt(modelIndex);
        currentEditor()->setPlainText(snippet.content());
        m_ui.revertButton->setEnabled(snippet.isBuiltIn());
    } else {
        currentEditor()->clear();
        m_ui.revertButton->setEnabled(false);
    }
521 522
}

Leandro Melo's avatar
Leandro Melo committed
523
void SnippetsSettingsPagePrivate::setSnippetContent()
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
{
    const QModelIndex &modelIndex = m_ui.snippetsTable->selectionModel()->currentIndex();
    if (modelIndex.isValid()) {
        m_model->setSnippetContent(modelIndex, currentEditor()->toPlainText());
        markSnippetsCollection();
    }
}

// SnippetsSettingsPage
SnippetsSettingsPage::SnippetsSettingsPage(const QString &id, QObject *parent) :
    TextEditorOptionsPage(parent),
    m_d(new SnippetsSettingsPagePrivate(id))
{}

SnippetsSettingsPage::~SnippetsSettingsPage()
{
    delete m_d;
}

QString SnippetsSettingsPage::id() const
{
    return m_d->id();
}

QString SnippetsSettingsPage::displayName() const
{
    return m_d->displayName();
}

bool SnippetsSettingsPage::matches(const QString &s) const
{
    return m_d->isKeyword(s);
}

QWidget *SnippetsSettingsPage::createPage(QWidget *parent)
{
    QWidget *w = new QWidget(parent);
    m_d->configureUi(w);
    return w;
}

void SnippetsSettingsPage::apply()
{
    m_d->apply();
}

void SnippetsSettingsPage::finish()
{
    m_d->finish();
}

} // Internal
} // TextEditor

#include "snippetssettingspage.moc"