abstractmobileapp.cpp 18.1 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** 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.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30 31 32 33 34 35 36 37 38 39 40 41 42 43
**
**************************************************************************/

#include "abstractmobileapp.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>

#ifndef CREATORLESSTEST
#include <coreplugin/icore.h>
#endif // CREATORLESSTEST

44 45
#include <utils/fileutils.h>

46 47 48 49
namespace Qt4ProjectManager {

AbstractGeneratedFileInfo::AbstractGeneratedFileInfo()
    : fileType(ExtendedFile)
50
    , currentVersion(-1)
51 52 53 54 55 56 57 58 59 60 61
    , version(-1)
    , dataChecksum(0)
    , statedChecksum(0)
{
}

const QString AbstractMobileApp::CFileComment(QLatin1String("//"));
const QString AbstractMobileApp::ProFileComment(QLatin1String("#"));
const QString AbstractMobileApp::DeploymentPriFileName(QLatin1String("deployment.pri"));
const QString AbstractMobileApp::FileChecksum(QLatin1String("checksum"));
const QString AbstractMobileApp::FileStubVersion(QLatin1String("version"));
62
const int AbstractMobileApp::StubVersion = 5;
63 64

AbstractMobileApp::AbstractMobileApp()
65 66
    : m_orientation(ScreenOrientationAuto)
    , m_networkEnabled(true)
67 68 69 70 71 72 73 74 75 76 77 78 79
{
}

AbstractMobileApp::~AbstractMobileApp() { }

QString AbstractMobileApp::symbianUidForPath(const QString &path)
{
    quint32 hash = 5381;
    for (int i = 0; i < path.size(); ++i) {
        const char c = path.at(i).toAscii();
        hash ^= c + ((c - i) << i % 20) + ((c + i) << (i + 5) % 20) + ((c - 2 * i) << (i + 10) % 20) + ((c + 2 * i) << (i + 15) % 20);
    }
    return QString::fromLatin1("0xE")
80
            + QString::fromLatin1("%1").arg(hash, 7, 16, QLatin1Char('0')).right(7).toUpper();
81 82
}

83
void AbstractMobileApp::setOrientation(ScreenOrientation orientation)
84 85 86 87
{
    m_orientation = orientation;
}

88
AbstractMobileApp::ScreenOrientation AbstractMobileApp::orientation() const
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
{
    return m_orientation;
}

void AbstractMobileApp::setProjectName(const QString &name)
{
    m_projectName = name;
}

QString AbstractMobileApp::projectName() const
{
    return m_projectName;
}

void AbstractMobileApp::setProjectPath(const QString &path)
{
    m_projectPath.setFile(path);
}

void AbstractMobileApp::setSymbianSvgIcon(const QString &icon)
{
    m_symbianSvgIcon = icon;
}

QString AbstractMobileApp::symbianSvgIcon() const
{
    return path(SymbianSvgIconOrigin);
}

118
void AbstractMobileApp::setMaemoPngIcon64(const QString &icon)
119
{
120
    m_maemoPngIcon64 = icon;
121 122
}

123
QString AbstractMobileApp::maemoPngIcon64() const
124
{
125 126 127 128 129 130 131 132 133 134 135
    return path(MaemoPngIconOrigin64);
}

void AbstractMobileApp::setMaemoPngIcon80(const QString &icon)
{
    m_maemoPngIcon80 = icon;
}

QString AbstractMobileApp::maemoPngIcon80() const
{
    return path(MaemoPngIconOrigin80);
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
}

void AbstractMobileApp::setSymbianTargetUid(const QString &uid)
{
    m_symbianTargetUid = uid;
}

QString AbstractMobileApp::symbianTargetUid() const
{
    return !m_symbianTargetUid.isEmpty() ? m_symbianTargetUid
        : symbianUidForPath(path(AppPro));
}

void AbstractMobileApp::setNetworkEnabled(bool enabled)
{
    m_networkEnabled = enabled;
}

bool AbstractMobileApp::networkEnabled() const
{
    return m_networkEnabled;
}

QString AbstractMobileApp::path(int fileType) const
{
    const QString originsRootApp = originsRoot();
    const QString originsRootShared = templatesRoot() + QLatin1String("shared/");
    const QString mainCppFileName = QLatin1String("main.cpp");
    const QString symbianIconFileName = QLatin1String("symbianicon.svg");
165 166
    QString cleanProjectName = m_projectName;
    cleanProjectName.replace(QLatin1Char('-'), QString());
167 168 169
    switch (fileType) {
        case MainCpp:               return outputPathBase() + mainCppFileName;
        case MainCppOrigin:         return originsRootApp + mainCppFileName;
170
        case AppPro:                return outputPathBase() + cleanProjectName + QLatin1String(".pro");
171 172
        case AppProOrigin:          return originsRootApp + QLatin1String("app.pro");
        case AppProPath:            return outputPathBase();
173 174
        case DesktopFremantle:      return outputPathBase() + cleanProjectName + QLatin1String(".desktop");
        case DesktopHarmattan:      return outputPathBase() + cleanProjectName + QLatin1String("_harmattan.desktop");
175 176 177
        case DesktopOrigin:         return originsRootShared + QLatin1String("app.desktop");
        case DeploymentPri:         return outputPathBase() + DeploymentPriFileName;
        case DeploymentPriOrigin:   return originsRootShared + DeploymentPriFileName;
178
        case SymbianSvgIcon:        return outputPathBase() + cleanProjectName + QLatin1String(".svg");
179 180
        case SymbianSvgIconOrigin:  return !m_symbianSvgIcon.isEmpty() ? m_symbianSvgIcon
                                        : originsRootShared + symbianIconFileName;
181 182 183 184 185 186
        case MaemoPngIcon64:        return outputPathBase() + cleanProjectName +  QLatin1String("64.png");
        case MaemoPngIconOrigin64:  return !m_maemoPngIcon64.isEmpty() ? m_maemoPngIcon64
                                        : originsRootShared + QLatin1String("maemoicon64.png");
        case MaemoPngIcon80:        return outputPathBase() + cleanProjectName +  QLatin1String("80.png");
        case MaemoPngIconOrigin80:  return !m_maemoPngIcon80.isEmpty() ? m_maemoPngIcon80
                                        : originsRootShared + QLatin1String("maemoicon80.png");
187 188 189 190 191
        default:                    return pathExtended(fileType);
    }
    return QString();
}

192 193 194 195 196 197 198 199 200
bool AbstractMobileApp::readTemplate(int fileType, QByteArray *data, QString *errorMessage) const
{
    Utils::FileReader reader;
    if (!reader.fetch(path(fileType), errorMessage))
        return false;
    *data = reader.data();
    return true;
}

201
QByteArray AbstractMobileApp::generateDesktopFile(QString *errorMessage, int fileType) const
202
{
203 204
    QByteArray desktopFileContent;
    if (!readTemplate(DesktopOrigin, &desktopFileContent, errorMessage))
205
        return QByteArray();
206 207 208 209 210 211 212
    if (fileType == AbstractGeneratedFileInfo::DesktopFileFremantle) {
        desktopFileContent.replace("Icon=thisApp",
            "Icon=" + projectName().toUtf8() + "64");
    } else if (fileType == AbstractGeneratedFileInfo::DesktopFileHarmattan) {
        desktopFileContent.replace("Icon=thisApp",
            "Icon=/usr/share/icons/hicolor/80x80/apps/" + projectName().toUtf8() + "80.png");
    }
213 214 215 216 217
    return desktopFileContent.replace("thisApp", projectName().toUtf8());
}

QByteArray AbstractMobileApp::generateMainCpp(QString *errorMessage) const
{
218 219
    QByteArray mainCppInput;
    if (!readTemplate(MainCppOrigin, &mainCppInput, errorMessage))
220
        return QByteArray();
221
    QTextStream in(&mainCppInput);
222 223 224 225 226 227 228 229 230 231

    QByteArray mainCppContent;
    QTextStream out(&mainCppContent, QIODevice::WriteOnly);

    QString line;
    while (!(line = in.readLine()).isNull()) {
        bool adaptLine = true;
        if (line.contains(QLatin1String("// ORIENTATION"))) {
            const char *orientationString;
            switch (orientation()) {
232 233
            case ScreenOrientationLockLandscape:
                orientationString = "ScreenOrientationLockLandscape";
234
                break;
235 236
            case ScreenOrientationLockPortrait:
                orientationString = "ScreenOrientationLockPortrait";
237
                break;
238 239
            case ScreenOrientationAuto:
                orientationString = "ScreenOrientationAuto";
240
                break;
Feetu Nyrhinen's avatar
Feetu Nyrhinen committed
241 242 243
            case ScreenOrientationImplicit:
            default:
                continue; // omit line
244 245 246
            }
            insertParameter(line, mainWindowClassName() + QLatin1String("::")
                + QLatin1String(orientationString));
247 248
        } else if (line.contains(QLatin1String("// DELETE_LINE"))) {
            continue; // omit this line in the output
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        } else {
            adaptLine = adaptCurrentMainCppTemplateLine(line);
        }
        if (adaptLine) {
            const int commentIndex = line.indexOf(QLatin1String(" //"));
            if (commentIndex != -1)
                line.truncate(commentIndex);
            out << line << endl;
        }
    }

    return mainCppContent;
}

QByteArray AbstractMobileApp::generateProFile(QString *errorMessage) const
{
    const QChar comment = QLatin1Char('#');
266 267
    QByteArray proFileInput;
    if (!readTemplate(AppProOrigin, &proFileInput, errorMessage))
268
        return QByteArray();
269
    QTextStream in(&proFileInput);
270 271 272 273 274

    QByteArray proFileContent;
    QTextStream out(&proFileContent, QIODevice::WriteOnly);

    QString valueOnNextLine;
275
    bool commentOutNextLine = false;
276 277 278 279 280 281
    QString line;
    while (!(line = in.readLine()).isNull()) {
        if (line.contains(QLatin1String("# TARGETUID3"))) {
            valueOnNextLine = symbianTargetUid();
        } else if (line.contains(QLatin1String("# NETWORKACCESS"))
            && !networkEnabled()) {
282
            commentOutNextLine = true;
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        } else if (line.contains(QLatin1String("# DEPLOYMENTFOLDERS"))) {
            // Eat lines
            QString nextLine;
            while (!(nextLine = in.readLine()).isNull()
                && !nextLine.contains(QLatin1String("# DEPLOYMENTFOLDERS_END")))
            { }
            if (nextLine.isNull())
                continue;

            int foldersCount = 0;
            QStringList folders;
            foreach (const DeploymentFolder &folder, deploymentFolders()) {
                foldersCount++;
                const QString folderName =
                    QString::fromLatin1("folder_%1").arg(foldersCount, 2, 10, QLatin1Char('0'));
                out << folderName << ".source = " << folder.first << endl;
                if (!folder.second.isEmpty())
                    out << folderName << ".target = " << folder.second << endl;
                folders.append(folderName);
            }
            if (foldersCount > 0)
                out << "DEPLOYMENTFOLDERS = " << folders.join(QLatin1String(" ")) << endl;
305 306
        } else if (line.contains(QLatin1String("# REMOVE_NEXT_LINE"))) {
            in.readLine(); // eats the following line
307
        } else {
308
            handleCurrentProFileTemplateLine(line, in, out, commentOutNextLine);
309 310 311 312 313 314 315 316 317 318 319 320 321 322
        }

        // Remove all marker comments
        if (line.trimmed().startsWith(comment)
            && line.trimmed().endsWith(comment))
            continue;

        if (!valueOnNextLine.isEmpty()) {
            out << line.left(line.indexOf(QLatin1Char('=')) + 2)
                << QDir::fromNativeSeparators(valueOnNextLine) << endl;
            valueOnNextLine.clear();
            continue;
        }

323
        if (commentOutNextLine) {
324
            out << comment << line << endl;
325
            commentOutNextLine = false;
326 327 328 329 330 331 332 333 334 335
            continue;
        }
        out << line << endl;
    };

    proFileContent.replace("../shared/" + DeploymentPriFileName.toAscii(),
        DeploymentPriFileName.toAscii());
    return proFileContent;
}

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
QList<AbstractGeneratedFileInfo> AbstractMobileApp::fileUpdates(const QString &mainProFile) const
{
    QList<AbstractGeneratedFileInfo> result;
    foreach (const AbstractGeneratedFileInfo &file, updateableFiles(mainProFile)) {
        AbstractGeneratedFileInfo newFile = file;
        QFile readFile(newFile.fileInfo.absoluteFilePath());
        if (!readFile.open(QIODevice::ReadOnly))
           continue;
        const QString firstLine = readFile.readLine();
        const QStringList elements = firstLine.split(QLatin1Char(' '));
        if (elements.count() != 5 || elements.at(1) != FileChecksum
                || elements.at(3) != FileStubVersion)
            continue;
        const QString versionString = elements.at(4);
        newFile.version = versionString.startsWith(QLatin1String("0x"))
            ? versionString.toInt(0, 16) : 0;
        newFile.statedChecksum = elements.at(2).toUShort(0, 16);
        QByteArray data = readFile.readAll();
        data.replace('\x0D', "");
        data.replace('\x0A', "");
        newFile.dataChecksum = qChecksum(data.constData(), data.length());
        if (newFile.dataChecksum != newFile.statedChecksum
                || newFile.version < newFile.currentVersion)
            result.append(newFile);
    }
    return result;
}


bool AbstractMobileApp::updateFiles(const QList<AbstractGeneratedFileInfo> &list, QString &error) const
{
    error.clear();
    foreach (const AbstractGeneratedFileInfo &info, list) {
        const QByteArray data = generateFile(info.fileType, &error);
        if (!error.isEmpty())
            return false;
372 373 374
        Utils::FileSaver saver(QDir::cleanPath(info.fileInfo.absoluteFilePath()));
        saver.write(data);
        if (!saver.finalize(&error))
375 376 377 378 379
            return false;
    }
    return true;
}

380
#ifndef CREATORLESSTEST
381 382
// The definition of QtQuickApp::templatesRoot() for
// CREATORLESSTEST is in tests/manual/appwizards/helpers.cpp
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
QString AbstractMobileApp::templatesRoot()
{
    return Core::ICore::instance()->resourcePath()
        + QLatin1String("/templates/");
}

Core::GeneratedFile AbstractMobileApp::file(const QByteArray &data,
    const QString &targetFile)
{
    Core::GeneratedFile generatedFile(targetFile);
    generatedFile.setBinary(true);
    generatedFile.setBinaryContents(data);
    return generatedFile;
}

Core::GeneratedFiles AbstractMobileApp::generateFiles(QString *errorMessage) const
{
    Core::GeneratedFiles files;
    files << file(generateFile(AbstractGeneratedFileInfo::AppProFile, errorMessage), path(AppPro));
    files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute);
    files << file(generateFile(AbstractGeneratedFileInfo::MainCppFile, errorMessage), path(MainCpp));
    files << file(generateFile(AbstractGeneratedFileInfo::SymbianSvgIconFile, errorMessage), path(SymbianSvgIcon));
405 406
    files << file(generateFile(AbstractGeneratedFileInfo::MaemoPngIconFile64, errorMessage), path(MaemoPngIcon64));
    files << file(generateFile(AbstractGeneratedFileInfo::MaemoPngIconFile80, errorMessage), path(MaemoPngIcon80));
407 408
    files << file(generateFile(AbstractGeneratedFileInfo::DesktopFileFremantle, errorMessage), path(DesktopFremantle));
    files << file(generateFile(AbstractGeneratedFileInfo::DesktopFileHarmattan, errorMessage), path(DesktopHarmattan));
409 410 411 412 413 414 415 416 417 418 419 420
    return files;
}
#endif // CREATORLESSTEST

QString AbstractMobileApp::error() const
{
    return m_error;
}

QByteArray AbstractMobileApp::readBlob(const QString &filePath,
    QString *errorMsg) const
{
421 422
    Utils::FileReader reader;
    if (!reader.fetch(filePath, errorMsg))
423
        return QByteArray();
424
    return reader.data();
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
}

QByteArray AbstractMobileApp::generateFile(int fileType,
    QString *errorMessage) const
{
    QByteArray data;
    QString comment = CFileComment;
    bool versionAndChecksum = false;
    switch (fileType) {
        case AbstractGeneratedFileInfo::MainCppFile:
            data = generateMainCpp(errorMessage);
            break;
        case AbstractGeneratedFileInfo::AppProFile:
            data = generateProFile(errorMessage);
            comment = ProFileComment;
            break;
        case AbstractGeneratedFileInfo::SymbianSvgIconFile:
            data = readBlob(path(SymbianSvgIconOrigin), errorMessage);
            break;
444 445 446 447 448
        case AbstractGeneratedFileInfo::MaemoPngIconFile64:
            data = readBlob(path(MaemoPngIconOrigin64), errorMessage);
            break;
        case AbstractGeneratedFileInfo::MaemoPngIconFile80:
            data = readBlob(path(MaemoPngIconOrigin80), errorMessage);
449
            break;
450 451 452
        case AbstractGeneratedFileInfo::DesktopFileFremantle:
        case AbstractGeneratedFileInfo::DesktopFileHarmattan:
            data = generateDesktopFile(errorMessage, fileType);
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
            break;
        case AbstractGeneratedFileInfo::DeploymentPriFile:
            data = readBlob(path(DeploymentPriOrigin), errorMessage);
            comment = ProFileComment;
            versionAndChecksum = true;
            break;
        default:
            data = generateFileExtended(fileType, &versionAndChecksum,
                &comment, errorMessage);
    }
    if (!versionAndChecksum)
        return data;
    QByteArray versioned = data;
    versioned.replace('\x0D', "");
    versioned.replace('\x0A', "");
468
    const QLatin1String hexPrefix("0x");
469
    const quint16 checkSum = qChecksum(versioned.constData(), versioned.length());
470
    const QString checkSumString = hexPrefix + QString::number(checkSum, 16);
471
    const QString versionString
472
        = hexPrefix + QString::number(makeStubVersion(stubVersionMinor()), 16);
473 474
    const QChar sep = QLatin1Char(' ');
    const QString versionLine =
475
            comment + sep + FileChecksum + sep + checkSumString
476 477 478 479 480 481 482 483 484 485 486
            + sep + FileStubVersion + sep + versionString + QLatin1Char('\x0A');
    return versionLine.toAscii() + data;
}

int AbstractMobileApp::makeStubVersion(int minor)
{
    return StubVersion << 16 | minor;
}

QString AbstractMobileApp::outputPathBase() const
{
487 488 489 490
    QString path = m_projectPath.absoluteFilePath();
    if (!path.endsWith(QLatin1Char('/')))
            path.append(QLatin1Char('/'));
    return path + projectName() + QLatin1Char('/');
491 492 493 494 495 496 497 498 499
}

void AbstractMobileApp::insertParameter(QString &line, const QString &parameter)
{
    line.replace(QRegExp(QLatin1String("\\([^()]+\\)")),
        QLatin1Char('(') + parameter + QLatin1Char(')'));
}

} // namespace Qt4ProjectManager