bardescriptordocument.cpp 22.1 KB
Newer Older
1 2
/**************************************************************************
**
3
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
4
**
5
** Contact: BlackBerry (qt@blackberry.com)
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
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** 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.
**
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "bardescriptordocument.h"

#include "qnxconstants.h"

36
#include <coreplugin/editormanager/editormanager.h>
37 38
#include <utils/qtcassert.h>

39
#include <QDir>
40 41
#include <QFileInfo>
#include <QMetaEnum>
42
#include <QTextCodec>
43
#include <QSet>
44 45 46 47

using namespace Qnx;
using namespace Qnx::Internal;

48 49
BarDescriptorDocument::BarDescriptorDocument(QObject *parent)
    : Core::TextDocument(parent)
50
{
51
    setId(Constants::QNX_BAR_DESCRIPTOR_EDITOR_ID);
52 53 54 55 56
    // blackberry-nativepackager requires the XML file to be in UTF-8 encoding,
    // force if possible
    if (QTextCodec *defaultUTF8 = QTextCodec::codecForName("UTF-8"))
        setCodec(defaultUTF8);
    else
57
        setCodec(Core::EditorManager::defaultTextCodec());
58 59 60 61 62 63 64 65 66 67 68
}

BarDescriptorDocument::~BarDescriptorDocument()
{
}

bool BarDescriptorDocument::open(QString *errorString, const QString &fileName) {
    QString contents;
    if (read(fileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess)
        return false;

69
    setFilePath(fileName);
70

71
    const bool result = loadContent(contents, false);
72 73 74 75 76 77 78

    if (!result)
        *errorString = tr("%1 does not appear to be a valid application descriptor file").arg(QDir::toNativeSeparators(fileName));

    return result;
}

79
bool BarDescriptorDocument::save(QString *errorString, const QString &fn, bool autoSave)
80 81
{
    QTC_ASSERT(!autoSave, return false);
82
    QTC_ASSERT(fn.isEmpty(), return false);
83

84
    const bool result = write(filePath(), xmlSource(), errorString);
85 86 87
    if (!result)
        return false;

88 89
    m_dirty = false;
    emit Core::IDocument::changed();
90 91 92 93 94
    return true;
}

QString BarDescriptorDocument::defaultPath() const
{
95
    QFileInfo fi(filePath());
96 97 98 99 100
    return fi.absolutePath();
}

QString BarDescriptorDocument::suggestedFileName() const
{
101
    QFileInfo fi(filePath());
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    return fi.fileName();
}

QString BarDescriptorDocument::mimeType() const
{
    return QLatin1String(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE);
}

bool BarDescriptorDocument::shouldAutoSave() const
{
    return false;
}

bool BarDescriptorDocument::isModified() const
{
117
    return m_dirty;
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
}

bool BarDescriptorDocument::isSaveAsAllowed() const
{
    return false;
}

Core::IDocument::ReloadBehavior BarDescriptorDocument::reloadBehavior(Core::IDocument::ChangeTrigger state, Core::IDocument::ChangeType type) const
{
    if (type == TypeRemoved || type == TypePermissions)
        return BehaviorSilent;
    if (type == TypeContents && state == TriggerInternal && !isModified())
        return BehaviorSilent;
    return BehaviorAsk;
}

bool BarDescriptorDocument::reload(QString *errorString, Core::IDocument::ReloadFlag flag, Core::IDocument::ChangeType type)
{
    Q_UNUSED(type);

    if (flag == Core::IDocument::FlagIgnore)
        return true;

141
    return open(errorString, filePath());
142 143 144 145
}

QString BarDescriptorDocument::xmlSource() const
{
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 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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    const int indent = 4;
    return m_barDocument.toString(indent);
}

bool BarDescriptorDocument::loadContent(const QString &xmlCode, bool setDirty, QString *errorMessage, int *errorLine)
{
    if (xmlCode == xmlSource())
        return true;

    bool result = m_barDocument.setContent(xmlCode, errorMessage, errorLine);

    m_dirty = setDirty;

    emitAllChanged();
    emit Core::IDocument::changed();
    return result;
}

QVariant BarDescriptorDocument::value(BarDescriptorDocument::Tag tag) const
{
    const QString tagName = QString::fromLatin1(metaObject()->enumerator(metaObject()->enumeratorOffset()).valueToKey(tag));

    switch (tag) {
    case id:
    case versionNumber:
    case buildId:
    case name:
    case description:
    case author:
    case publisher:
    case authorId:
        return stringValue(tagName);
    case icon:
        return childStringListValue(tagName, QLatin1String("image")).value(0);
    case splashScreens:
        return childStringListValue(tagName, QLatin1String("image"));
    case asset: {
        QVariant var;
        var.setValue(assets());
        return var;
    }
    case aspectRatio:
    case autoOrients:
    case systemChrome:
        return childStringListValue(QLatin1String("initialWindow"), tagName).value(0);
    case transparent:
        return childStringListValue(QLatin1String("initialWindow"), tagName).value(0) == QLatin1String("true");
    case arg:
    case action:
        return stringListValue(tagName);
    case env:
        QVariant var;
        var.setValue(environment());
        return var;
    }

    return QVariant();
}

void BarDescriptorDocument::setValue(BarDescriptorDocument::Tag tag, const QVariant &value)
{
    const QMetaEnum tagEnum = metaObject()->enumerator(metaObject()->enumeratorOffset());
    const QString tagName = QString::fromLatin1(tagEnum.valueToKey(tag));

    switch (tag) {
    case id:
    case versionNumber:
    case buildId:
    case name:
    case description:
    case authorId:
        setStringValue(tagName, value.toString());
        break;
    case icon:
    case splashScreens:
        setChildStringListValue(tagName, QLatin1String("image"), value.toStringList());
        break;
    case asset:
        setAssets(value.value<BarDescriptorAssetList>());
        break;
    case aspectRatio:
    case autoOrients:
    case systemChrome:
        setChildStringListValue(QLatin1String("initialWindow"), tagName, value.toStringList());
        break;
    case transparent:
        setChildStringListValue(QLatin1String("initialWindow"), tagName, QStringList() << (value.toBool() ? QLatin1String("true") : QLatin1String("false")));
        break;
    case arg:
    case action:
        setStringListValue(tagName, value.toStringList());
        break;
    case env:
        setEnvironment(value.value<QList<Utils::EnvironmentItem> >());
        break;
    case author:
    case publisher:
        // Unset <publisher> when setting <author> as only one should be used
        setStringValue(QString::fromLatin1(tagEnum.valueToKey(author)), value.toString());
        setStringValue(QString::fromLatin1(tagEnum.valueToKey(publisher)), QLatin1String(""));
        break;
    }

    m_dirty = true;
    emit changed(tag, value);
    emit Core::IDocument::changed();
}

QString BarDescriptorDocument::stringValue(const QString &tagName) const
{
    QDomNodeList nodes = m_barDocument.elementsByTagName(tagName);
    if (nodes.isEmpty() || nodes.size() > 1)
        return QString();

    QDomNode node = nodes.item(0);
    QDomText textNode = node.firstChild().toText();
    if (textNode.isNull())
        return QString();

    return textNode.data();
}

void BarDescriptorDocument::setStringValue(const QString &tagName, const QString &value)
{
    QDomNodeList nodes = m_barDocument.elementsByTagName(tagName);

    if (nodes.size() > 1)
        return;
274

275 276 277 278 279 280 281 282 283 284
    QDomNode existingNode = nodes.item(0);
    if (existingNode.isNull() && value.isEmpty())
        return;

    if (!existingNode.isNull() && value.isEmpty()) {
        m_barDocument.documentElement().removeChild(existingNode);
    } else if (existingNode.isNull()) {
        QDomElement newNode = m_barDocument.createElement(tagName);
        newNode.appendChild(m_barDocument.createTextNode(value));
        m_barDocument.documentElement().appendChild(newNode);
285
    } else {
286 287 288 289 290 291
        QDomText textNode = existingNode.firstChild().toText();
        if (textNode.isNull())
            return;
        textNode.setData(value);
    }
}
292

293 294 295 296 297
QStringList BarDescriptorDocument::childStringListValue(const QString &tagName, const QString &childTagName) const
{
    QDomNodeList nodes = m_barDocument.elementsByTagName(tagName);
    if (nodes.isEmpty() || nodes.size() > 1)
        return QStringList();
298

299 300 301 302
    QDomNode parentNode = nodes.item(0);
    QDomElement childElm = parentNode.firstChildElement(childTagName);
    if (childElm.isNull())
        return QStringList();
303

304 305 306 307 308
    QStringList result;
    while (!childElm.isNull()) {
        QDomText textNode = childElm.firstChild().toText();
        if (textNode.isNull())
            return QStringList();
309

310
        result.append(textNode.data());
311

312
        childElm = childElm.nextSiblingElement(childTagName);
313
    }
314 315

    return result;
316 317
}

318
void BarDescriptorDocument::setChildStringListValue(const QString &tagName, const QString &childTagName, const QStringList &stringList)
319
{
320
    QDomNodeList nodes = m_barDocument.elementsByTagName(tagName);
321

322 323
    if (nodes.size() > 1)
        return;
324

325
    QDomNode existingNode = nodes.item(0);
326

327 328
    if (existingNode.isNull()) {
        QDomElement newParentNode = m_barDocument.createElement(tagName);
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
        foreach (const QString &value, stringList) {
            QDomElement newChildNode = m_barDocument.createElement(childTagName);
            QDomText newTextNode = m_barDocument.createTextNode(value);
            newChildNode.appendChild(newTextNode);
            newParentNode.appendChild(newChildNode);
        }
        m_barDocument.documentElement().appendChild(newParentNode);
    } else {
        QStringList values = stringList;
        QDomElement childElm = existingNode.firstChildElement(childTagName);
        if (!childElm.isNull()) {
            // Loop through existing elements, remove the existing nodes
            // that no longer are in "values", and remove from "values"
            // the existing nodes that don't need re-creation
            while (!childElm.isNull()) {
                QDomText textNode = childElm.firstChild().toText();
                if (textNode.isNull())
                    continue;

                QDomElement toRemove;
                if (!values.contains(textNode.data()))
                    toRemove = childElm;
                else
                    values.removeAll(textNode.data());

                childElm = childElm.nextSiblingElement(childTagName);

                if (!toRemove.isNull())
                    existingNode.removeChild(toRemove);
            }
360 361
        }

362 363 364 365 366 367 368 369 370 371
        // Add the new elements
        int newElementCount = 0;
        foreach (const QString &value, values) {
            if (value.isEmpty())
                continue;
            QDomElement newChildNode = m_barDocument.createElement(childTagName);
            newChildNode.appendChild(m_barDocument.createTextNode(value));
            existingNode.appendChild(newChildNode);
            ++newElementCount;
        }
372

373 374
        if (newElementCount == 0)
            m_barDocument.documentElement().removeChild(existingNode);
375
    }
376
}
377

378 379 380
QStringList BarDescriptorDocument::stringListValue(const QString &tagName) const
{
    QStringList result;
381

382 383 384 385 386 387 388 389 390 391 392 393
    QDomElement childElm = m_barDocument.documentElement().firstChildElement(tagName);
    while (!childElm.isNull()) {
        QDomText textNode = childElm.firstChild().toText();
        if (textNode.isNull())
            continue;

        result.append(textNode.data());

        childElm = childElm.nextSiblingElement(tagName);
    }

    return result;
394 395
}

396
void BarDescriptorDocument::setStringListValue(const QString &tagName, const QStringList &stringList)
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
    QStringList values = stringList;
    QDomElement childElm = m_barDocument.documentElement().firstChildElement(tagName);
    if (!childElm.isNull()) {
        // Loop through existing elements, remove the existing nodes
        // that no longer are in "values", and remove from "values"
        // the existing nodes that don't need re-creation
        while (!childElm.isNull()) {
            QDomText textNode = childElm.firstChild().toText();
            if (textNode.isNull())
                continue;

            QDomElement toRemove;
            if (!values.contains(textNode.data()))
                toRemove = childElm;
            else
                values.removeAll(textNode.data());

            childElm = childElm.nextSiblingElement(tagName);

            if (!toRemove.isNull())
                m_barDocument.documentElement().removeChild(toRemove);
        }
    }

    // Add the new elements
    foreach (const QString &value, values) {
        if (value.isEmpty())
            continue;
        QDomElement newChildNode = m_barDocument.createElement(tagName);
        newChildNode.appendChild(m_barDocument.createTextNode(value));
        m_barDocument.documentElement().appendChild(newChildNode);
    }
430 431
}

432
BarDescriptorAssetList BarDescriptorDocument::assets() const
433
{
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    BarDescriptorAssetList result;
    QDomNodeList nodes = m_barDocument.elementsByTagName(QLatin1String("asset"));
    if (nodes.isEmpty())
        return result;

    for (int i = 0; i < nodes.size(); ++i) {
        QDomElement assetElm = nodes.item(i).toElement();
        if (assetElm.isNull())
            continue;

        QDomText textNode = assetElm.firstChild().toText();
        if (textNode.isNull())
            continue;

        QString path = assetElm.attribute(QLatin1String("path"));
        QString entry = assetElm.attribute(QLatin1String("entry"));
        QString dest = textNode.data();

        BarDescriptorAsset asset;
        asset.source = path;
        asset.destination = dest;
        asset.entry = entry == QLatin1String("true");
        result.append(asset);
457 458
    }

459
    return result;
460 461
}

462
void BarDescriptorDocument::setAssets(const BarDescriptorAssetList &assets)
463
{
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    QDomNodeList nodes = m_barDocument.elementsByTagName(QLatin1String("asset"));

    BarDescriptorAssetList newAssets = assets;
    QList<QDomNode> toRemove;

    for (int i = 0; i < nodes.size(); ++i) {
        QDomElement assetElm = nodes.at(i).toElement();
        if (assetElm.isNull())
            continue;

        QDomText textNode = assetElm.firstChild().toText();
        if (textNode.isNull())
            continue;

        QString source = assetElm.attribute(QLatin1String("path"));
        bool found = false;
        foreach (const BarDescriptorAsset &asset, newAssets) {
            if (asset.source == source) {
                found = true;
                if (asset.entry) {
                    assetElm.setAttribute(QLatin1String("type"), QLatin1String("Qnx/Elf"));
                    assetElm.setAttribute(QLatin1String("entry"), QLatin1String("true"));
                } else {
                    assetElm.removeAttribute(QLatin1String("type"));
                    assetElm.removeAttribute(QLatin1String("entry"));
                }
                textNode.setData(asset.destination);

                newAssets.removeAll(asset);
                break;
            }
        }

        if (!found)
            toRemove.append(assetElm);
    }

    foreach (const QDomNode &node, toRemove)
        m_barDocument.documentElement().removeChild(node);

    foreach (const BarDescriptorAsset &asset, newAssets) {
        QDomElement assetElm = m_barDocument.createElement(QLatin1String("asset"));
        assetElm.setAttribute(QLatin1String("path"), asset.source);
        if (asset.entry) {
            assetElm.setAttribute(QLatin1String("type"), QLatin1String("Qnx/Elf"));
            assetElm.setAttribute(QLatin1String("entry"), QLatin1String("true"));
510
        }
511 512 513 514 515 516 517 518 519 520 521 522 523 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
        assetElm.appendChild(m_barDocument.createTextNode(asset.destination));
        m_barDocument.documentElement().appendChild(assetElm);
    }
}

QList<Utils::EnvironmentItem> BarDescriptorDocument::environment() const
{
    QList<Utils::EnvironmentItem> result;

    QDomElement envElm = m_barDocument.documentElement().firstChildElement(QLatin1String("env"));
    while (!envElm.isNull()) {
        QString var = envElm.attribute(QLatin1String("var"));
        QString value = envElm.attribute(QLatin1String("value"));

        Utils::EnvironmentItem item(var, value);
        result.append(item);

        envElm = envElm.nextSiblingElement(QLatin1String("env"));
    }
    return result;
}

void BarDescriptorDocument::setEnvironment(const QList<Utils::EnvironmentItem> &environment)
{
    QDomNodeList envNodes = m_barDocument.elementsByTagName(QLatin1String("env"));

    QList<Utils::EnvironmentItem> newEnvironment = environment;
    QList<QDomElement> toRemove;
    for (int i = 0; i < envNodes.size(); ++i) {
        QDomElement elm = envNodes.at(i).toElement();
        if (elm.isNull())
            continue;

        QString var = elm.attribute(QLatin1String("var"));
        bool found = false;
        foreach (const Utils::EnvironmentItem item, newEnvironment) {
            if (item.name == var) {
                found = true;
                elm.setAttribute(QLatin1String("value"), item.value);
                newEnvironment.removeAll(item);
                break;
            }
        }

        if (!found)
            toRemove.append(elm);
    }

    foreach (const QDomNode &node, toRemove)
        m_barDocument.documentElement().removeChild(node);

    foreach (const Utils::EnvironmentItem item, newEnvironment) {
        QDomElement elm = m_barDocument.createElement(QLatin1String("env"));
        elm.setAttribute(QLatin1String("var"), item.name);
        elm.setAttribute(QLatin1String("value"), item.value);
        m_barDocument.documentElement().appendChild(elm);
    }
}

void BarDescriptorDocument::emitAllChanged()
{
    QMetaEnum tags = metaObject()->enumerator(metaObject()->enumeratorOffset());
    for (int i = 0; i < tags.keyCount(); ++i) {
        Tag tag = static_cast<Tag>(tags.value(i));
        emit changed(tag, value(tag));
576 577
    }
}
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623

QString BarDescriptorDocument::bannerComment() const
{
    QDomNode nd = m_barDocument.firstChild();
    QDomProcessingInstruction pi = nd.toProcessingInstruction();
    if (!pi.isNull())
        nd = pi.nextSibling();

    return nd.toComment().data();
}

void BarDescriptorDocument::setBannerComment(const QString &commentText)
{
    QDomNode nd = m_barDocument.firstChild();
    QDomProcessingInstruction pi = nd.toProcessingInstruction();
    if (!pi.isNull())
        nd = pi.nextSibling();

    bool oldDirty = m_dirty;
    QDomComment cnd = nd.toComment();
    if (cnd.isNull()) {
        if (!commentText.isEmpty()) {
            cnd = m_barDocument.createComment(commentText);
            m_barDocument.insertBefore(cnd, nd);
            m_dirty = true;
        }
    } else {
        if (commentText.isEmpty()) {
            m_barDocument.removeChild(cnd);
            m_dirty = true;
        } else {
            if (cnd.data() != commentText) {
                cnd.setData(commentText);
                m_dirty = true;
            }
        }
    }
    if (m_dirty != oldDirty)
        emit Core::IDocument::changed();
}

int BarDescriptorDocument::tagForElement(const QDomElement &element)
{
    QMetaEnum tags = metaObject()->enumerator(metaObject()->enumeratorOffset());
    QDomElement el = element;
    while (!el.isNull()) {
624 625
        const int n = tags.keyToValue(el.tagName().toLatin1().constData());
        if (n > -1)
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
            return n;
        el = el.parentNode().toElement();
    }
    return -1;
}

bool BarDescriptorDocument::expandPlaceHolder_helper(const QDomElement &el,
                                                     const QString &placeholderKey,
                                                     const QString &placeholderText,
                                                     QSet<BarDescriptorDocument::Tag> &changedTags)
{
    // replace attributes
    bool elementChanged = false;
    QDomNamedNodeMap attrs = el.attributes();
    for (int i = 0; i < attrs.count(); ++i) {
        QDomAttr attr = attrs.item(i).toAttr();
        if (!attr.isNull()) {
            QString s = attr.value();
            s.replace(placeholderKey, placeholderText);
            if (s != attr.value()) {
                attr.setValue(s);
                elementChanged = true;
            }
        }
    }

    bool documentChanged = false;
    // replace text
    for (QDomNode nd = el.firstChild(); !nd.isNull(); nd = nd.nextSibling()) {
        QDomText txtnd = nd.toText();
        if (!txtnd.isNull()) {
            QString s = txtnd.data();
            s.replace(placeholderKey, placeholderText);
            if (s != txtnd.data()) {
                txtnd.setData(s);
                elementChanged = true;
            }
        }
        QDomElement child = nd.toElement();
        if (!child.isNull()) {
            bool hit = expandPlaceHolder_helper(child, placeholderKey, placeholderText, changedTags);
            documentChanged = documentChanged || hit;
        }
    }
    if (elementChanged) {
        int n = tagForElement(el);
        if (n >= 0)
            changedTags << static_cast<Tag>(n);
    }
    documentChanged = documentChanged || elementChanged;
    return documentChanged;
}

void BarDescriptorDocument::expandPlaceHolders(const QHash<QString, QString> &placeholdersKeyVals)
{
    QSet<Tag> changedTags;
    QHashIterator<QString, QString> it(placeholdersKeyVals);
    bool docChanged = false;
    while (it.hasNext()) {
        it.next();
        bool expanded = expandPlaceHolder_helper(m_barDocument.documentElement(),
                                                 it.key(), it.value(), changedTags);
        docChanged = docChanged || expanded;
    }
    m_dirty = m_dirty || docChanged;
    foreach (Tag tag, changedTags)
        emit changed(tag, value(tag));
    if (docChanged)
        emit Core::IDocument::changed();
}