snippetscollection.cpp 13.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
/**************************************************************************
**
** 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 "snippetscollection.h"
31
#include "reuse.h"
32

33 34 35 36 37 38 39 40 41 42
#include <coreplugin/icore.h>

#include <QtCore/QLatin1String>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QDebug>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QXmlStreamWriter>
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 78
#include <QtAlgorithms>

#include <iterator>
#include <algorithm>

using namespace TextEditor;
using namespace Internal;

namespace {

struct SnippetComp
{
    bool operator()(const Snippet &a, const Snippet &b) const
    {
        const int comp = a.trigger().toLower().localeAwareCompare(b.trigger().toLower());
        if (comp < 0)
            return true;
        else if (comp == 0 &&
                 a.complement().toLower().localeAwareCompare(b.complement().toLower()) < 0)
            return true;
        return false;
    }
};
SnippetComp snippetComp;

struct RemovedSnippetPred
{
    bool operator()(const Snippet &s) const
    {
        return s.isRemoved();
    }
};
RemovedSnippetPred removedSnippetPred;

} // Anonymous

79 80 81 82 83 84 85 86 87
const QLatin1String SnippetsCollection::kSnippet("snippet");
const QLatin1String SnippetsCollection::kSnippets("snippets");
const QLatin1String SnippetsCollection::kTrigger("trigger");
const QLatin1String SnippetsCollection::kId("id");
const QLatin1String SnippetsCollection::kComplement("complement");
const QLatin1String SnippetsCollection::kGroup("group");
const QLatin1String SnippetsCollection::kRemoved("removed");
const QLatin1String SnippetsCollection::kModified("modified");

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
// Hint
SnippetsCollection::Hint::Hint(int index) : m_index(index)
{}

SnippetsCollection::Hint::Hint(int index, QList<Snippet>::iterator it) : m_index(index), m_it(it)
{}

int SnippetsCollection::Hint::index() const
{
    return m_index;
}

// SnippetsCollection
SnippetsCollection::SnippetsCollection() :
    m_snippets(Snippet::GroupSize),
103 104 105 106
    m_activeSnippetsEnd(Snippet::GroupSize),
    m_builtInSnippetsPath(QLatin1String(":/texteditor/snippets/")),
    m_userSnippetsPath(Core::ICore::instance()->userResourcePath() + QLatin1String("/snippets/")),
    m_snippetsFileName(QLatin1String("snippets.xml"))
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 221 222 223
{
    for (Snippet::Group group = Snippet::Cpp; group < Snippet::GroupSize; ++group)
        m_activeSnippetsEnd[group] = m_snippets[group].end();
}

SnippetsCollection::~SnippetsCollection()
{}

void SnippetsCollection::insertSnippet(const Snippet &snippet, Snippet::Group group)
{
    insertSnippet(snippet, group, computeInsertionHint(snippet, group));
}

void SnippetsCollection::insertSnippet(const Snippet &snippet,
                                       Snippet::Group group,
                                       const Hint &hint)
{
    if (snippet.isBuiltIn() && snippet.isRemoved()) {
        m_activeSnippetsEnd[group] = m_snippets[group].insert(m_activeSnippetsEnd[group], snippet);
    } else {
        m_snippets[group].insert(hint.m_it, snippet);
        updateActiveSnippetsEnd(group);
    }
}

SnippetsCollection::Hint SnippetsCollection::computeInsertionHint(const Snippet &snippet,
                                                                  Snippet::Group group)
{
    QList<Snippet> &snippets = m_snippets[group];
    QList<Snippet>::iterator it = qUpperBound(
        snippets.begin(), m_activeSnippetsEnd.at(group), snippet, snippetComp);
    return Hint(static_cast<int>(std::distance(snippets.begin(), it)), it);
}

void SnippetsCollection::replaceSnippet(int index, const Snippet &snippet, Snippet::Group group)
{
    replaceSnippet(index, snippet, group, computeReplacementHint(index, snippet, group));
}

void SnippetsCollection::replaceSnippet(int index,
                                        const Snippet &snippet,
                                        Snippet::Group group,
                                        const Hint &hint)
{
    Snippet replacement(snippet);
    if (replacement.isBuiltIn() && !replacement.isModified())
        replacement.setIsModified(true);

    if (index == hint.index()) {
        m_snippets[group][index] = replacement;
    } else {
        insertSnippet(replacement, group, hint);
        // Consider whether the row moved up towards the beginning or down towards the end.
        if (index < hint.index())
            m_snippets[group].removeAt(index);
        else
            m_snippets[group].removeAt(index + 1);
        updateActiveSnippetsEnd(group);
    }
}

SnippetsCollection::Hint SnippetsCollection::computeReplacementHint(int index,
                                                                    const Snippet &snippet,
                                                                    Snippet::Group group)
{
    QList<Snippet> &snippets = m_snippets[group];
    QList<Snippet>::iterator it = qLowerBound(
        snippets.begin(), m_activeSnippetsEnd.at(group), snippet, snippetComp);
    int hintIndex = static_cast<int>(std::distance(snippets.begin(), it));
    if (index < hintIndex - 1)
        return Hint(hintIndex - 1, it);
    it = qUpperBound(it, m_activeSnippetsEnd.at(group), snippet, snippetComp);
    hintIndex = static_cast<int>(std::distance(snippets.begin(), it));
    if (index > hintIndex)
        return Hint(hintIndex, it);
    // Even if the snipet is at a different index it is still inside a valid range.
    return Hint(index);
}

void SnippetsCollection::removeSnippet(int index, Snippet::Group group)
{
    Snippet snippet(m_snippets.at(group).at(index));
    m_snippets[group].removeAt(index);
    if (snippet.isBuiltIn()) {
        snippet.setIsRemoved(true);
        m_activeSnippetsEnd[group] = m_snippets[group].insert(m_activeSnippetsEnd[group], snippet);
    } else {
        updateActiveSnippetsEnd(group);
    }
}

const Snippet &SnippetsCollection::snippet(int index, Snippet::Group group) const
{
    return m_snippets.at(group).at(index);
}

void SnippetsCollection::setSnippetContent(int index, Snippet::Group group, const QString &content)
{
    Snippet &snippet = m_snippets[group][index];
    snippet.setContent(content);
    if (snippet.isBuiltIn() && !snippet.isModified())
        snippet.setIsModified(true);
}

int SnippetsCollection::totalActiveSnippets(Snippet::Group group) const
{
    return std::distance<QList<Snippet>::const_iterator>(m_snippets.at(group).begin(),
                                                         m_activeSnippetsEnd.at(group));
}

int SnippetsCollection::totalSnippets(Snippet::Group group) const
{
    return m_snippets.at(group).size();
}

void SnippetsCollection::clear()
{
Leandro Melo's avatar
Leandro Melo committed
224 225 226 227 228 229 230 231
    for (Snippet::Group group = Snippet::Cpp; group < Snippet::GroupSize; ++group)
        clear(group);
}

void SnippetsCollection::clear(Snippet::Group group)
{
    m_snippets[group].clear();
    m_activeSnippetsEnd[group] = m_snippets[group].end();
232 233 234 235 236 237 238 239
}

void SnippetsCollection::updateActiveSnippetsEnd(Snippet::Group group)
{
    m_activeSnippetsEnd[group] = std::find_if(m_snippets[group].begin(),
                                              m_snippets[group].end(),
                                              removedSnippetPred);
}
240

Leandro Melo's avatar
Leandro Melo committed
241 242 243 244 245 246 247 248 249 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
void SnippetsCollection::restoreRemovedSnippets(Snippet::Group group)
{
    // The version restored contains the last modifications (if any) by the user.
    // Reverting the snippet can still bring it to the original version.
    QVector<Snippet> toRestore(std::distance(m_activeSnippetsEnd[group], m_snippets[group].end()));
    qCopy(m_activeSnippetsEnd[group], m_snippets[group].end(), toRestore.begin());
    m_snippets[group].erase(m_activeSnippetsEnd[group], m_snippets[group].end());
    foreach (Snippet snippet, toRestore) {
        snippet.setIsRemoved(false);
        insertSnippet(snippet, group);
    }
}

Snippet SnippetsCollection::revertedSnippet(int index, Snippet::Group group) const
{
    const Snippet &candidate = snippet(index, group);
    Q_ASSERT(candidate.isBuiltIn());

    const QList<Snippet> &builtIn =
        readXML(m_builtInSnippetsPath + m_snippetsFileName, candidate.id());
    if (builtIn.size() == 1)
        return builtIn.at(0);
    return Snippet();
}

void SnippetsCollection::reset(Snippet::Group group)
{
    clear(group);

    const QList<Snippet> &builtInSnippets = readXML(m_builtInSnippetsPath + m_snippetsFileName);
    foreach (const Snippet &snippet, builtInSnippets)
        if (group == snippet.group())
            insertSnippet(snippet, snippet.group());
}

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
void SnippetsCollection::reload()
{
    clear();

    QHash<QString, Snippet> activeBuiltInSnippets;
    const QList<Snippet> &builtInSnippets = readXML(m_builtInSnippetsPath + m_snippetsFileName);
    foreach (const Snippet &snippet, builtInSnippets)
        activeBuiltInSnippets.insert(snippet.id(), snippet);

    const QList<Snippet> &userSnippets = readXML(m_userSnippetsPath + m_snippetsFileName);
    foreach (const Snippet &snippet, userSnippets) {
        if (snippet.isBuiltIn())
            // This user snippet overrides the corresponding built-in snippet.
            activeBuiltInSnippets.remove(snippet.id());
        insertSnippet(snippet, snippet.group());
    }

    foreach (const Snippet &snippet, activeBuiltInSnippets)
        insertSnippet(snippet, snippet.group());
}

void SnippetsCollection::synchronize()
{
    if (QFile::exists(m_userSnippetsPath) || QDir().mkpath(m_userSnippetsPath)) {
        QFile file(m_userSnippetsPath + m_snippetsFileName);
        if (file.open(QFile::WriteOnly | QFile::Truncate)) {
            QXmlStreamWriter writer(&file);
            writer.setAutoFormatting(true);
            writer.writeStartDocument();
            writer.writeStartElement(kSnippets);
            for (Snippet::Group group = Snippet::Cpp; group < Snippet::GroupSize; ++group) {
                const int size = totalSnippets(group);
                for (int i = 0; i < size; ++i) {
                    const Snippet &current = snippet(i, group);
Leandro Melo's avatar
Leandro Melo committed
310
                    if (!current.isBuiltIn() || current.isRemoved() || current.isModified())
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
                        writeSnippetXML(current, &writer);
                }
            }
            writer.writeEndElement();
            writer.writeEndDocument();
            file.close();
        }
    }

    reload();
}

void SnippetsCollection::writeSnippetXML(const Snippet &snippet, QXmlStreamWriter *writer)
{
    writer->writeStartElement(kSnippet);
    writer->writeAttribute(kGroup, fromSnippetGroup(snippet.group()));
    writer->writeAttribute(kTrigger, snippet.trigger());
    writer->writeAttribute(kId, snippet.id());
    writer->writeAttribute(kComplement, snippet.complement());
    writer->writeAttribute(kRemoved, fromBool(snippet.isRemoved()));
    writer->writeAttribute(kModified, fromBool(snippet.isModified()));
    writer->writeCharacters(snippet.content());
    writer->writeEndElement();
}

Leandro Melo's avatar
Leandro Melo committed
336
QList<Snippet> SnippetsCollection::readXML(const QString &fileName, const QString &snippetId)
337 338 339 340 341 342 343 344 345 346
{
    QList<Snippet> snippets;
    QFile file(fileName);
    if (file.exists() && file.open(QIODevice::ReadOnly)) {
        QXmlStreamReader xml(&file);
        if (xml.readNextStartElement()) {
            if (xml.name() == kSnippets) {
                while (xml.readNextStartElement()) {
                    if (xml.name() == kSnippet) {
                        const QXmlStreamAttributes &atts = xml.attributes();
Leandro Melo's avatar
Leandro Melo committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
                        const QString &id = atts.value(kId).toString();
                        if (snippetId.isEmpty() || snippetId == id) {
                            Snippet snippet(id);
                            snippet.setTrigger(atts.value(kTrigger).toString());
                            snippet.setComplement(atts.value(kComplement).toString());
                            snippet.setGroup(toSnippetGroup(atts.value(kGroup).toString()));
                            snippet.setIsRemoved(toBool(atts.value(kRemoved).toString()));
                            snippet.setIsModified(toBool(atts.value(kModified).toString()));

                            QString content;
                            while (!xml.atEnd()) {
                                xml.readNext();
                                if (xml.isCharacters()) {
                                    content += xml.text();
                                } else if (xml.isEndElement()) {
                                    snippet.setContent(content);
                                    snippets.append(snippet);
                                    break;
                                }
                            }
367

Leandro Melo's avatar
Leandro Melo committed
368
                            if (!snippetId.isEmpty())
369
                                break;
Leandro Melo's avatar
Leandro Melo committed
370 371
                        } else {
                            xml.skipCurrentElement();
372 373 374 375 376 377 378 379 380 381 382 383 384 385
                        }
                    } else {
                        xml.skipCurrentElement();
                    }
                }
            }
        }
        if (xml.hasError())
            qWarning() << fileName << xml.errorString() << xml.lineNumber() << xml.columnNumber();
        file.close();
    }

    return snippets;
}