qt4maemotarget.cpp 38.1 KB
Newer Older
1
2
3
4
5
6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
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
**
Tobias Hunger's avatar
Tobias Hunger 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
Tobias Hunger's avatar
Tobias Hunger 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.
**
Tobias Hunger's avatar
Tobias Hunger committed
28
29
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
30
31
32
**
**************************************************************************/

33
#include "qt4maemotarget.h"
34

35
36
#include "maemoglobal.h"
#include "maemopackagecreationstep.h"
37
#include "maemorunconfiguration.h"
38
#include "maemotoolchain.h"
39
40
#include "qt4maemodeployconfiguration.h"

Tobias Hunger's avatar
Tobias Hunger committed
41
#include <coreplugin/filemanager.h>
42
43
44
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
45
#include <projectexplorer/abi.h>
46
#include <projectexplorer/customexecutablerunconfiguration.h>
47
48
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectnodes.h>
49
#include <projectexplorer/toolchain.h>
50
#include <qt4projectmanager/qt4project.h>
51
#include <utils/fileutils.h>
52

53
#include <utils/filesystemwatcher.h>
54
#include <utils/fileutils.h>
55

56
#include <QtGui/QApplication>
57
#include <QtGui/QMainWindow>
58
#include <QtCore/QBuffer>
Christian Kandeler's avatar
Christian Kandeler committed
59
#include <QtCore/QRegExp>
60
61
62
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
Christian Kandeler's avatar
Christian Kandeler committed
63
64
#include <QtCore/QProcess>
#include <QtCore/QStringList>
65
#include <QtGui/QIcon>
66
#include <QtGui/QMessageBox>
67

Friedemann Kleint's avatar
Friedemann Kleint committed
68
69
#include <cctype>

70
71
72
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

73
namespace {
Christian Kandeler's avatar
Christian Kandeler committed
74
const QByteArray NameFieldName("Package");
75
76
const QByteArray IconFieldName("XB-Maemo-Icon-26");
const QByteArray ShortDescriptionFieldName("Description");
Christian Kandeler's avatar
Christian Kandeler committed
77
const QByteArray PackageFieldName("Package");
78
const QLatin1String PackagingDirName("qtc_packaging");
79
80
81
const QByteArray NameTag("Name");
const QByteArray SummaryTag("Summary");
const QByteArray VersionTag("Version");
Christian Kandeler's avatar
Christian Kandeler committed
82
const QByteArray ReleaseTag("Release");
83
84
85
86
87

bool adaptTagValue(QByteArray &document, const QByteArray &fieldName,
    const QByteArray &newFieldValue, bool caseSensitive)
{
    QByteArray adaptedLine = fieldName + ": " + newFieldValue;
Friedemann Kleint's avatar
Friedemann Kleint committed
88
    const QByteArray completeTag = fieldName + ':';
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    const int lineOffset = caseSensitive ? document.indexOf(completeTag)
        : document.toLower().indexOf(completeTag.toLower());
    if (lineOffset == -1) {
        document.append(adaptedLine).append('\n');
        return true;
    }

    int newlineOffset = document.indexOf('\n', lineOffset);
    bool updated = false;
    if (newlineOffset == -1) {
        newlineOffset = document.length();
        adaptedLine += '\n';
        updated = true;
    }
    const int replaceCount = newlineOffset - lineOffset;
    if (!updated && document.mid(lineOffset, replaceCount) != adaptedLine)
        updated = true;
    if (updated)
        document.replace(lineOffset, replaceCount, adaptedLine);
    return updated;
}


112
113
114
} // anonymous namespace


115
AbstractQt4MaemoTarget::AbstractQt4MaemoTarget(Qt4Project *parent, const QString &id) :
116
    Qt4BaseTarget(parent, id),
117
    m_filesWatcher(new Utils::FileSystemWatcher(this)),
118
    m_buildConfigurationFactory(new Qt4BuildConfigurationFactory(this)),
119
    m_isInitialized(false)
120
{
121
    m_filesWatcher->setObjectName(QLatin1String("Qt4MaemoTarget"));
122
    setIcon(QIcon(":/projectexplorer/images/MaemoDevice.png"));
123
    connect(parent, SIGNAL(addedTarget(ProjectExplorer::Target*)),
124
125
126
        this, SLOT(handleTargetAdded(ProjectExplorer::Target*)));
    connect(parent, SIGNAL(fromMapFinished()),
        this, SLOT(handleFromMapFinished()));
127
128
}

129
AbstractQt4MaemoTarget::~AbstractQt4MaemoTarget()
130
131
132
{ }

AbstractQt4MaemoTarget::DebugArchitecture AbstractQt4MaemoTarget::debugArchitecture() const
133
{
134
135
136
137
138
139
140
141
142
    // TODO: This functionality should be inside the debugger.
    const ProjectExplorer::Abi &abi
        = activeBuildConfiguration()->toolChain()->targetAbi();
    DebugArchitecture arch(abi.toString());

    // TODO: This might do the wrong thing for x64.
    arch.gnuTarget = QLatin1String(abi.architecture() == ProjectExplorer::Abi::ArmArchitecture
        ? "arm-none-linux-gnueabi": "i386-unknown-linux-gnu");
    return arch;
143
}
144

145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
QList<ProjectExplorer::ToolChain *> AbstractQt4MaemoTarget::possibleToolChains(ProjectExplorer::BuildConfiguration *bc) const
{
    QList<ProjectExplorer::ToolChain *> result;

    Qt4BuildConfiguration *qt4Bc = qobject_cast<Qt4BuildConfiguration *>(bc);
    if (!qt4Bc)
        return result;

    QList<ProjectExplorer::ToolChain *> candidates = Qt4BaseTarget::possibleToolChains(bc);
    foreach (ProjectExplorer::ToolChain *i, candidates) {
        MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(i);
        if (!tc)
            continue;
        if (tc->qtVersionId() == qt4Bc->qtVersion()->uniqueId())
            result.append(tc);
    }

    return result;
163
164
}

165

166
Qt4BuildConfigurationFactory *AbstractQt4MaemoTarget::buildConfigurationFactory() const
167
168
169
170
{
    return m_buildConfigurationFactory;
}

171
void AbstractQt4MaemoTarget::createApplicationProFiles()
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
{
    removeUnconfiguredCustomExectutableRunConfigurations();

    QList<Qt4ProFileNode *> profiles = qt4Project()->applicationProFiles();
    QSet<QString> paths;
    foreach (Qt4ProFileNode *pro, profiles)
        paths << pro->path();

    foreach (ProjectExplorer::RunConfiguration *rc, runConfigurations())
        if (MaemoRunConfiguration *qt4rc = qobject_cast<MaemoRunConfiguration *>(rc))
            paths.remove(qt4rc->proFilePath());

    // Only add new runconfigurations if there are none.
    foreach (const QString &path, paths)
        addRunConfiguration(new MaemoRunConfiguration(this, path));

    // Oh still none? Add a custom executable runconfiguration
    if (runConfigurations().isEmpty()) {
        addRunConfiguration(new ProjectExplorer::CustomExecutableRunConfiguration(this));
    }
}
193

dt's avatar
dt committed
194
195
196
197
198
199
200
201
202
203
QList<ProjectExplorer::RunConfiguration *> AbstractQt4MaemoTarget::runConfigurationsForNode(ProjectExplorer::Node *n)
{
    QList<ProjectExplorer::RunConfiguration *> result;
    foreach (ProjectExplorer::RunConfiguration *rc, runConfigurations())
        if (MaemoRunConfiguration *mrc = qobject_cast<MaemoRunConfiguration *>(rc))
            if (mrc->proFilePath() == n->path())
                result << rc;
    return result;
}

204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
bool AbstractQt4MaemoTarget::setProjectVersion(const QString &version,
    QString *error)
{
    bool success = true;
    foreach (Target * const target, project()->targets()) {
        AbstractQt4MaemoTarget * const maemoTarget
            = qobject_cast<AbstractQt4MaemoTarget *>(target);
        if (maemoTarget) {
            if (!maemoTarget->setProjectVersionInternal(version, error))
                success = false;
        }
    }
    return success;
}

Christian Kandeler's avatar
Christian Kandeler committed
219
bool AbstractQt4MaemoTarget::setPackageName(const QString &name)
220
221
222
223
224
225
{
    bool success = true;
    foreach (Target * const target, project()->targets()) {
        AbstractQt4MaemoTarget * const maemoTarget
            = qobject_cast<AbstractQt4MaemoTarget *>(target);
        if (maemoTarget) {
Christian Kandeler's avatar
Christian Kandeler committed
226
            if (!maemoTarget->setPackageNameInternal(name))
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
                success = false;
        }
    }
    return success;
}

bool AbstractQt4MaemoTarget::setShortDescription(const QString &description)
{
    bool success = true;
    foreach (Target * const target, project()->targets()) {
        AbstractQt4MaemoTarget * const maemoTarget
            = qobject_cast<AbstractQt4MaemoTarget *>(target);
        if (maemoTarget) {
            if (!maemoTarget->setShortDescriptionInternal(description))
                success = false;
        }
    }
    return success;
}

QSharedPointer<QFile> AbstractQt4MaemoTarget::openFile(const QString &filePath,
    QIODevice::OpenMode mode, QString *error) const
{
    const QString nativePath = QDir::toNativeSeparators(filePath);
    QSharedPointer<QFile> file(new QFile(filePath));
252
    if (!file->open(mode)) {
253
254
255
256
257
258
259
260
261
        if (error) {
            *error = tr("Cannot open file '%1': %2")
                .arg(nativePath, file->errorString());
        }
        file.clear();
    }
    return file;
}

262
263
264
265
266
void AbstractQt4MaemoTarget::handleFromMapFinished()
{
    handleTargetAdded(this);
}

267
268
269
270
271
void AbstractQt4MaemoTarget::handleTargetAdded(ProjectExplorer::Target *target)
{
    if (target != this)
        return;

272
273
274
275
276
277
278
279
    if (!project()->rootProjectNode()) {
        // Project is not fully setup yet, happens on new project
        // we wait for the fromMapFinished that comes afterwards
        return;
    }

    disconnect(project(), SIGNAL(fromMapFinished()),
        this, SLOT(handleFromMapFinished()));
280
281
282
283
    disconnect(project(), SIGNAL(addedTarget(ProjectExplorer::Target*)),
        this, SLOT(handleTargetAdded(ProjectExplorer::Target*)));
    connect(project(), SIGNAL(aboutToRemoveTarget(ProjectExplorer::Target*)),
        SLOT(handleTargetToBeRemoved(ProjectExplorer::Target*)));
284
    if (createTemplates() == ActionFailed)
285
286
287
        return;
    initPackagingSettingsFromOtherTarget();
    handleTargetAddedSpecial();
288
    m_isInitialized = true;
289
290
291
292
293
294
295
296
}

void AbstractQt4MaemoTarget::handleTargetToBeRemoved(ProjectExplorer::Target *target)
{
    if (target != this)
        return;
    if (!targetCanBeRemoved())
        return;
297
298
299
300

    Core::ICore * const core = Core::ICore::instance();
    const int answer = QMessageBox::warning(core->mainWindow(),
        tr("Qt Creator"), tr("Do you want to remove the packaging file(s) "
301
302
303
304
           "associated with the target '%1'?").arg(displayName()),
        QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    if (answer == QMessageBox::No)
        return;
305
    const QStringList pkgFilePaths = packagingFilePaths();
306
307
308
309
310
311
312
313
314
    if (!pkgFilePaths.isEmpty()) {
        project()->rootProjectNode()->removeFiles(ProjectExplorer::UnknownFileType,
            pkgFilePaths);
        Core::IVersionControl * const vcs = core->vcsManager()
            ->findVersionControlForDirectory(QFileInfo(pkgFilePaths.first()).dir().path());
        if (vcs && vcs->supportsOperation(Core::IVersionControl::DeleteOperation)) {
            foreach (const QString &filePath, pkgFilePaths)
                vcs->vcsDelete(filePath);
        }
315
    }
316
317
318
319
320
321
322
323
324
325
326
327
    removeTarget();
    QString error;
    const QString packagingPath = project()->projectDirectory()
        + QLatin1Char('/') + PackagingDirName;
    const QStringList otherContents = QDir(packagingPath).entryList(QDir::Dirs
        | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot);
    if (otherContents.isEmpty()) {
        if (!MaemoGlobal::removeRecursively(packagingPath, error))
            qDebug("%s", qPrintable(error));
    }
}

328
AbstractQt4MaemoTarget::ActionStatus AbstractQt4MaemoTarget::createTemplates()
329
330
331
332
333
334
{
    QDir projectDir(project()->projectDirectory());
    if (!projectDir.exists(PackagingDirName)
            && !projectDir.mkdir(PackagingDirName)) {
        raiseError(tr("Error creating Maemo packaging directory '%1'.")
            .arg(PackagingDirName));
335
        return ActionFailed;
336
337
    }

338
339
340
341
342
343
344
345
346
347
348
349
350
    const ActionStatus actionStatus = createSpecialTemplates();
    if (actionStatus == ActionFailed)
        return ActionFailed;
    if (actionStatus == ActionSuccessful) {
        const QStringList &files = packagingFilePaths();
        QMessageBox::StandardButton button
            = QMessageBox::question(Core::ICore::instance()->mainWindow(),
                  tr("Add Packaging Files to Project"),
                  tr("Qt Creator has set up the following files to enable "
                     "packaging:\n   %1\nDo you want to add them to the project?")
                      .arg(files.join(QLatin1String("\n   "))),
                  QMessageBox::Yes | QMessageBox::No);
        if (button == QMessageBox::Yes)
351
            ProjectExplorer::ProjectExplorerPlugin::instance()->addExistingFiles(project()->rootProjectNode(), files);
352
353
    }
    return actionStatus;
354
355
356
357
358
359
360
361
}

bool AbstractQt4MaemoTarget::initPackagingSettingsFromOtherTarget()
{
    bool success = true;
    foreach (const Target * const target, project()->targets()) {
        const AbstractQt4MaemoTarget * const maemoTarget
            = qobject_cast<const AbstractQt4MaemoTarget *>(target);
362
        if (maemoTarget && maemoTarget != this && maemoTarget->m_isInitialized) {
363
364
            if (!setProjectVersionInternal(maemoTarget->projectVersion()))
                success = false;
Christian Kandeler's avatar
Christian Kandeler committed
365
            if (!setPackageNameInternal(maemoTarget->packageName()))
366
367
368
369
370
371
                success = false;
            if (!setShortDescriptionInternal(maemoTarget->shortDescription()))
                success = false;
            break;
        }
    }
372
    return initAdditionalPackagingSettingsFromOtherTarget();
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
}

void AbstractQt4MaemoTarget::raiseError(const QString &reason)
{
    QMessageBox::critical(0, tr("Error creating Maemo templates"), reason);
}

AbstractDebBasedQt4MaemoTarget::AbstractDebBasedQt4MaemoTarget(Qt4Project *parent,
    const QString &id) : AbstractQt4MaemoTarget(parent, id)
{
}

AbstractDebBasedQt4MaemoTarget::~AbstractDebBasedQt4MaemoTarget() {}

QString AbstractDebBasedQt4MaemoTarget::projectVersion(QString *error) const
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
{
    QSharedPointer<QFile> changeLog = openFile(changeLogFilePath(),
        QIODevice::ReadOnly, error);
    if (!changeLog)
        return QString();
    const QByteArray &firstLine = changeLog->readLine();
    const int openParenPos = firstLine.indexOf('(');
    if (openParenPos == -1) {
        if (error) {
            *error = tr("Debian changelog file '%1' has unexpected format.")
                .arg(QDir::toNativeSeparators(changeLog->fileName()));
        }
        return QString();
    }
    const int closeParenPos = firstLine.indexOf(')', openParenPos);
    if (closeParenPos == -1) {
        if (error) {
            *error = tr("Debian changelog file '%1' has unexpected format.")
                .arg(QDir::toNativeSeparators(changeLog->fileName()));
        }
        return QString();
    }
    return QString::fromUtf8(firstLine.mid(openParenPos + 1,
        closeParenPos - openParenPos - 1).data());
}

414
bool AbstractDebBasedQt4MaemoTarget::setProjectVersionInternal(const QString &version,
415
    QString *error)
416
417
{
    const QString filePath = changeLogFilePath();
418
419
    Utils::FileReader reader;
    if (!reader.fetch(filePath, error))
420
        return false;
421
    QString content = QString::fromUtf8(reader.data());
422
423
    content.replace(QRegExp(QLatin1String("\\([a-zA-Z0-9_\\.]+\\)")),
        QLatin1Char('(') + version + QLatin1Char(')'));
Tobias Hunger's avatar
Tobias Hunger committed
424
    Core::FileChangeBlocker update(filePath);
425
426
427
    Utils::FileSaver saver(filePath);
    saver.write(content.toUtf8());
    return saver.finalize(error);
428
429
}

430
QIcon AbstractDebBasedQt4MaemoTarget::packageManagerIcon(QString *error) const
431
432
433
434
435
436
437
438
439
440
441
442
443
{
    const QByteArray &base64Icon = controlFileFieldValue(IconFieldName, true);
    if (base64Icon.isEmpty())
        return QIcon();
    QPixmap pixmap;
    if (!pixmap.loadFromData(QByteArray::fromBase64(base64Icon))) {
        if (error)
            *error = tr("Invalid icon data in Debian control file.");
        return QIcon();
    }
    return QIcon(pixmap);
}

444
bool AbstractDebBasedQt4MaemoTarget::setPackageManagerIconInternal(const QString &iconFilePath,
445
    QString *error)
446
447
{
    const QString filePath = controlFilePath();
448
449
    Utils::FileReader reader;
    if (!reader.fetch(filePath, error))
450
451
452
        return false;
    const QPixmap pixmap(iconFilePath);
    if (pixmap.isNull()) {
453
454
        if (error)
            *error = tr("Could not read image file '%1'.").arg(iconFilePath);
455
456
457
458
459
460
461
462
        return false;
    }

    QByteArray iconAsBase64;
    QBuffer buffer(&iconAsBase64);
    buffer.open(QIODevice::WriteOnly);
    if (!pixmap.scaled(48, 48).save(&buffer,
        QFileInfo(iconFilePath).suffix().toAscii())) {
463
464
        if (error)
            *error = tr("Could not export image file '%1'.").arg(iconFilePath);
465
466
467
468
        return false;
    }
    buffer.close();
    iconAsBase64 = iconAsBase64.toBase64();
469
    QByteArray contents = reader.data();
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    const QByteArray iconFieldNameWithColon = IconFieldName + ':';
    const int iconFieldPos = contents.startsWith(iconFieldNameWithColon)
        ? 0 : contents.indexOf('\n' + iconFieldNameWithColon);
    if (iconFieldPos == -1) {
        if (!contents.endsWith('\n'))
            contents += '\n';
        contents.append(iconFieldNameWithColon).append(' ').append(iconAsBase64)
            .append('\n');
    } else {
        const int oldIconStartPos = (iconFieldPos != 0) + iconFieldPos
            + iconFieldNameWithColon.length();
        int nextEolPos = contents.indexOf('\n', oldIconStartPos);
        while (nextEolPos != -1 && nextEolPos != contents.length() - 1
            && contents.at(nextEolPos + 1) != '\n'
            && (contents.at(nextEolPos + 1) == '#'
                || std::isspace(contents.at(nextEolPos + 1))))
            nextEolPos = contents.indexOf('\n', nextEolPos + 1);
        if (nextEolPos == -1)
            nextEolPos = contents.length();
        contents.replace(oldIconStartPos, nextEolPos - oldIconStartPos,
            ' ' + iconAsBase64);
    }
Tobias Hunger's avatar
Tobias Hunger committed
492
    Core::FileChangeBlocker update(filePath);
493
494
495
    Utils::FileSaver saver(filePath);
    saver.write(contents);
    return saver.finalize(error);
496
497
}

Christian Kandeler's avatar
Christian Kandeler committed
498
QString AbstractDebBasedQt4MaemoTarget::packageName() const
499
500
501
502
{
    return QString::fromUtf8(controlFileFieldValue(NameFieldName, false));
}

Christian Kandeler's avatar
Christian Kandeler committed
503
504
bool AbstractDebBasedQt4MaemoTarget::setPackageNameInternal(const QString &packageName)
{
505
506
    const QString oldPackageName = this->packageName();

Christian Kandeler's avatar
Christian Kandeler committed
507
508
509
510
    if (!setControlFieldValue(NameFieldName, packageName.toUtf8()))
        return false;
    if (!setControlFieldValue("Source", packageName.toUtf8()))
        return false;
511

512
513
    Utils::FileReader reader;
    if (!reader.fetch(changeLogFilePath()))
Christian Kandeler's avatar
Christian Kandeler committed
514
        return false;
515
    QString changelogContents = QString::fromUtf8(reader.data());
Christian Kandeler's avatar
Christian Kandeler committed
516
    QRegExp pattern(QLatin1String("[^\\s]+( \\(\\d\\.\\d\\.\\d\\))"));
517
    changelogContents.replace(pattern, packageName + QLatin1String("\\1"));
518
519
520
    Utils::FileSaver saver(changeLogFilePath());
    saver.write(changelogContents.toUtf8());
    if (!saver.finalize())
521
522
        return false;

523
    if (!reader.fetch(rulesFilePath()))
524
        return false;
525
    QByteArray rulesContents = reader.data();
526
527
528
    const QString oldString = QLatin1String("debian/") + oldPackageName;
    const QString newString = QLatin1String("debian/") + packageName;
    rulesContents.replace(oldString.toUtf8(), newString.toUtf8());
529
    Utils::FileSaver rulesSaver(rulesFilePath());
530
531
    rulesSaver.write(rulesContents);
    return rulesSaver.finalize();
Christian Kandeler's avatar
Christian Kandeler committed
532
533
534
535
}

QString AbstractDebBasedQt4MaemoTarget::packageManagerName() const
{
536
    return QString::fromUtf8(controlFileFieldValue(packageManagerNameFieldName(), false));
Christian Kandeler's avatar
Christian Kandeler committed
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
}

bool AbstractDebBasedQt4MaemoTarget::setPackageManagerName(const QString &name,
    QString *error)
{
    bool success = true;
    foreach (Target * const t, project()->targets()) {
        AbstractDebBasedQt4MaemoTarget * const target
            = qobject_cast<AbstractDebBasedQt4MaemoTarget *>(t);
        if (target) {
            if (!target->setPackageManagerNameInternal(name, error))
                success = false;
        }
    }
    return success;
}

bool AbstractDebBasedQt4MaemoTarget::setPackageManagerNameInternal(const QString &name,
    QString *error)
556
{
Christian Kandeler's avatar
Christian Kandeler committed
557
    Q_UNUSED(error);
558
    return setControlFieldValue(packageManagerNameFieldName(), name.toUtf8());
559
560
}

561
QString AbstractDebBasedQt4MaemoTarget::shortDescription() const
562
563
564
565
{
    return QString::fromUtf8(controlFileFieldValue(ShortDescriptionFieldName, false));
}

Christian Kandeler's avatar
Christian Kandeler committed
566
567
568
569
570
571
QString AbstractDebBasedQt4MaemoTarget::packageFileName() const
{
    return QString::fromUtf8(controlFileFieldValue(PackageFieldName, false))
        + QLatin1Char('_') + projectVersion() + QLatin1String("_armel.deb");
}

572
bool AbstractDebBasedQt4MaemoTarget::setShortDescriptionInternal(const QString &description)
573
574
575
576
{
    return setControlFieldValue(ShortDescriptionFieldName, description.toUtf8());
}

577
QString AbstractDebBasedQt4MaemoTarget::debianDirPath() const
578
579
{
    return project()->projectDirectory() + QLatin1Char('/') + PackagingDirName
580
        + QLatin1Char('/') + debianDirName();
581
582
}

583
QStringList AbstractDebBasedQt4MaemoTarget::debianFiles() const
584
585
586
587
588
{
    return QDir(debianDirPath())
        .entryList(QDir::Files, QDir::Name | QDir::IgnoreCase);
}

589
QString AbstractDebBasedQt4MaemoTarget::changeLogFilePath() const
590
591
592
593
{
    return debianDirPath() + QLatin1String("/changelog");
}

594
QString AbstractDebBasedQt4MaemoTarget::controlFilePath() const
595
596
597
598
{
    return debianDirPath() + QLatin1String("/control");
}

599
600
601
602
603
QString AbstractDebBasedQt4MaemoTarget::rulesFilePath() const
{
    return debianDirPath() + QLatin1String("/rules");
}

604
QByteArray AbstractDebBasedQt4MaemoTarget::controlFileFieldValue(const QString &key,
605
606
607
    bool multiLine) const
{
    QByteArray value;
608
609
    Utils::FileReader reader;
    if (!reader.fetch(controlFilePath()))
610
        return value;
611
    const QByteArray &contents = reader.data();
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
    const int keyPos = contents.indexOf(key.toUtf8() + ':');
    if (keyPos == -1)
        return value;
    int valueStartPos = keyPos + key.length() + 1;
    int valueEndPos = contents.indexOf('\n', keyPos);
    if (valueEndPos == -1)
        valueEndPos = contents.count();
    value = contents.mid(valueStartPos, valueEndPos - valueStartPos).trimmed();
    if (multiLine) {
        Q_FOREVER {
            valueStartPos = valueEndPos + 1;
            if (valueStartPos >= contents.count())
                break;
            const char firstChar = contents.at(valueStartPos);
            if (firstChar == '#' || isspace(firstChar)) {
                valueEndPos = contents.indexOf('\n', valueStartPos);
                if (valueEndPos == -1)
                    valueEndPos = contents.count();
                if (firstChar != '#') {
                    value += contents.mid(valueStartPos,
                        valueEndPos - valueStartPos).trimmed();
                }
            } else {
                break;
            }
        }
    }
    return value;
}

642
bool AbstractDebBasedQt4MaemoTarget::setControlFieldValue(const QByteArray &fieldName,
643
644
    const QByteArray &fieldValue)
{
645
646
    Utils::FileReader reader;
    if (!reader.fetch(controlFilePath()))
647
        return false;
648
    QByteArray contents = reader.data();
649
    if (adaptControlFileField(contents, fieldName, fieldValue)) {
Tobias Hunger's avatar
Tobias Hunger committed
650
        Core::FileChangeBlocker update(controlFilePath());
651
        Utils::FileSaver saver(controlFilePath());
652
653
        saver.write(contents);
        return saver.finalize();
654
655
656
657
    }
    return true;
}

658
bool AbstractDebBasedQt4MaemoTarget::adaptControlFileField(QByteArray &document,
659
660
    const QByteArray &fieldName, const QByteArray &newFieldValue)
{
661
    return adaptTagValue(document, fieldName, newFieldValue, true);
662
663
}

664
void AbstractDebBasedQt4MaemoTarget::handleTargetAddedSpecial()
665
{
666
667
668
669
670
671
672
673
    if (controlFileFieldValue(IconFieldName, true).isEmpty()) {
        // Such a file is created by the mobile wizards.
        const QString iconPath = project()->projectDirectory()
            + QLatin1Char('/') + project()->displayName()
            + QLatin1String(".png");
        if (QFileInfo(iconPath).exists())
            setPackageManagerIcon(iconPath);
    }
674
675
676
    m_filesWatcher->addDirectory(debianDirPath(), Utils::FileSystemWatcher::WatchAllChanges);
    m_filesWatcher->addFile(changeLogFilePath(), Utils::FileSystemWatcher::WatchAllChanges);
    m_filesWatcher->addFile(controlFilePath(), Utils::FileSystemWatcher::WatchAllChanges);
677
    connect(m_filesWatcher, SIGNAL(directoryChanged(QString)), this,
678
        SLOT(handleDebianDirContentsChanged()));
679
    connect(m_filesWatcher, SIGNAL(fileChanged(QString)), this,
680
681
682
683
684
685
        SLOT(handleDebianFileChanged(QString)));
    handleDebianDirContentsChanged();
    handleDebianFileChanged(changeLogFilePath());
    handleDebianFileChanged(controlFilePath());
}

686
687
688
689
690
691
bool AbstractDebBasedQt4MaemoTarget::targetCanBeRemoved() const
{
    return QFileInfo(debianDirPath()).exists();
}

void AbstractDebBasedQt4MaemoTarget::removeTarget()
692
693
{
    QString error;
694
    MaemoGlobal::removeRecursively(debianDirPath(), error);
695
696
}

697
698
699
700
701
702
703
704
705
706
707
708
709
void AbstractDebBasedQt4MaemoTarget::handleDebianFileChanged(const QString &filePath)
{
    if (filePath == changeLogFilePath())
        emit changeLogChanged();
    else if (filePath == controlFilePath())
        emit controlChanged();
}

void AbstractDebBasedQt4MaemoTarget::handleDebianDirContentsChanged()
{
    emit debianDirContentsChanged();
}

710
AbstractQt4MaemoTarget::ActionStatus AbstractDebBasedQt4MaemoTarget::createSpecialTemplates()
711
712
{
    if (QFileInfo(debianDirPath()).exists())
713
        return NoActionRequired;
714
715
716
717
    QDir projectDir(project()->projectDirectory());
    QProcess dh_makeProc;
    QString error;
    const Qt4BuildConfiguration * const bc = activeBuildConfiguration();
718
    AbstractMaemoPackageCreationStep::preparePackagingProcess(&dh_makeProc, bc,
719
        projectDir.path() + QLatin1Char('/') + PackagingDirName);
720
721
722
    const QString dhMakeDebianDir = projectDir.path() + QLatin1Char('/')
        + PackagingDirName + QLatin1String("/debian");
    MaemoGlobal::removeRecursively(dhMakeDebianDir, error);
723
724
725
    const QStringList dh_makeArgs = QStringList() << QLatin1String("dh_make")
        << QLatin1String("-s") << QLatin1String("-n") << QLatin1String("-p")
        << (defaultPackageFileName() + QLatin1Char('_')
726
            + AbstractMaemoPackageCreationStep::DefaultVersionNumber);
727
728
    if (!MaemoGlobal::callMad(dh_makeProc, dh_makeArgs, activeBuildConfiguration()->qtVersion(), true)
            || !dh_makeProc.waitForStarted()) {
729
730
        raiseError(tr("Unable to create Debian templates: dh_make failed (%1)")
            .arg(dh_makeProc.errorString()));
731
        return ActionFailed;
732
733
734
735
736
737
738
    }
    dh_makeProc.write("\n"); // Needs user input.
    dh_makeProc.waitForFinished(-1);
    if (dh_makeProc.error() != QProcess::UnknownError
        || dh_makeProc.exitCode() != 0) {
        raiseError(tr("Unable to create debian templates: dh_make failed (%1)")
            .arg(dh_makeProc.errorString()));
739
        return ActionFailed;
740
741
742
743
744
745
    }

    if (!QFile::rename(dhMakeDebianDir, debianDirPath())) {
        raiseError(tr("Unable to move new debian directory to '%1'.")
            .arg(QDir::toNativeSeparators(debianDirPath())));
        MaemoGlobal::removeRecursively(dhMakeDebianDir, error);
746
        return ActionFailed;
747
748
749
750
751
752
753
754
755
756
757
758
759
    }

    QDir debianDir(debianDirPath());
    const QStringList &files = debianDir.entryList(QDir::Files);
    foreach (const QString &fileName, files) {
        if (fileName.endsWith(QLatin1String(".ex"), Qt::CaseInsensitive)
            || fileName.compare(QLatin1String("README.debian"), Qt::CaseInsensitive) == 0
            || fileName.compare(QLatin1String("dirs"), Qt::CaseInsensitive) == 0
            || fileName.compare(QLatin1String("docs"), Qt::CaseInsensitive) == 0) {
            debianDir.remove(fileName);
        }
    }

760
761
    return adaptRulesFile() && adaptControlFile()
        ? ActionSuccessful : ActionFailed;
762
763
}

764
bool AbstractDebBasedQt4MaemoTarget::adaptRulesFile()
765
{
766
767
768
    Utils::FileReader reader;
    if (!reader.fetch(rulesFilePath())) {
        raiseError(reader.errorString());
769
770
        return false;
    }
771
    QByteArray rulesContents = reader.data();
772
    const QByteArray comment("# Uncomment this line for use without Qt Creator");
773
    rulesContents.replace("DESTDIR", "INSTALL_ROOT");
774
775
776
777
    rulesContents.replace("dh_shlibdeps", "# dh_shlibdeps " + comment);
    rulesContents.replace("# Add here commands to configure the package.",
        "# qmake PREFIX=/usr" + comment);
    rulesContents.replace("$(MAKE)\n", "# $(MAKE) " + comment + '\n');
778
779
780
781
782

    // Would be the right solution, but does not work (on Windows),
    // because dpkg-genchanges doesn't know about it (and can't be told).
    // rulesContents.replace("dh_builddeb", "dh_builddeb --destdir=.");

783
784
785
786
    Utils::FileSaver saver(rulesFilePath());
    saver.write(rulesContents);
    if (!saver.finalize()) {
        raiseError(saver.errorString());
787
788
789
790
791
        return false;
    }
    return true;
}

792
bool AbstractDebBasedQt4MaemoTarget::adaptControlFile()
793
{
794
795
796
    Utils::FileReader reader;
    if (!reader.fetch(controlFilePath())) {
        raiseError(reader.errorString());
797
798
        return false;
    }
799
    QByteArray controlContents = reader.data();
800

801
    adaptControlFileField(controlContents, "Section", defaultSection());
802
    adaptControlFileField(controlContents, "Priority", "optional");
803
    adaptControlFileField(controlContents, packageManagerNameFieldName(),
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
        project()->displayName().toUtf8());
    const int buildDependsOffset = controlContents.indexOf("Build-Depends:");
    if (buildDependsOffset == -1) {
        qDebug("Unexpected: no Build-Depends field in debian control file.");
    } else {
        int buildDependsNewlineOffset
            = controlContents.indexOf('\n', buildDependsOffset);
        if (buildDependsNewlineOffset == -1) {
            controlContents += '\n';
            buildDependsNewlineOffset = controlContents.length() - 1;
        }
        controlContents.insert(buildDependsNewlineOffset,
            ", libqt4-dev");
    }

819
    addAdditionalControlFileFields(controlContents);
820
821
822
823
    Utils::FileSaver saver(controlFilePath());
    saver.write(controlContents);
    if (!saver.finalize()) {
        raiseError(saver.errorString());
824
825
826
827
828
        return false;
    }
    return true;
}

829
830
831
832
833
bool AbstractDebBasedQt4MaemoTarget::initAdditionalPackagingSettingsFromOtherTarget()
{
    foreach (const Target * const t, project()->targets()) {
        const AbstractDebBasedQt4MaemoTarget *target
            = qobject_cast<const AbstractDebBasedQt4MaemoTarget *>(t);
834
        if (target && target != this) {
835
836
837
838
839
840
841
            return setControlFieldValue(IconFieldName,
                target->controlFileFieldValue(IconFieldName, true));
        }
    }
    return true;
}

842
843
844
845
846
847
848
849
850
QStringList AbstractDebBasedQt4MaemoTarget::packagingFilePaths() const
{
    QStringList filePaths;
    const QString parentDir = debianDirPath();
    foreach (const QString &fileName, debianFiles())
        filePaths << parentDir + QLatin1Char('/') + fileName;
    return filePaths;
}

Christian Kandeler's avatar
Christian Kandeler committed
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
QString AbstractDebBasedQt4MaemoTarget::defaultPackageFileName() const
{
    QString packageName = project()->displayName().toLower();

    // We also replace dots, because OVI store chokes on them.
    const QRegExp legalLetter(QLatin1String("[a-z0-9+-]"), Qt::CaseSensitive,
        QRegExp::WildcardUnix);

    for (int i = 0; i < packageName.length(); ++i) {
        if (!legalLetter.exactMatch(packageName.mid(i, 1)))
            packageName[i] = QLatin1Char('-');
    }
    return packageName;
}

866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
bool AbstractDebBasedQt4MaemoTarget::setPackageManagerIcon(const QString &iconFilePath,
    QString *error)
{
    bool success = true;
    foreach (Target * const target, project()->targets()) {
        AbstractDebBasedQt4MaemoTarget* const maemoTarget
            = qobject_cast<AbstractDebBasedQt4MaemoTarget*>(target);
        if (maemoTarget) {
            if (!maemoTarget->setPackageManagerIconInternal(iconFilePath, error))
                success = false;
        }
    }
    return success;
}


AbstractRpmBasedQt4MaemoTarget::AbstractRpmBasedQt4MaemoTarget(Qt4Project *parent,
    const QString &id) : AbstractQt4MaemoTarget(parent, id)
{
}

AbstractRpmBasedQt4MaemoTarget::~AbstractRpmBasedQt4MaemoTarget()
{
}

QString AbstractRpmBasedQt4MaemoTarget::specFilePath() const
{
    const QLatin1Char sep('/');
    return project()->projectDirectory() + sep + PackagingDirName + sep
        + specFileName();
}

QString AbstractRpmBasedQt4MaemoTarget::projectVersion(QString *error) const
{
    return QString::fromUtf8(getValueForTag(VersionTag, error));
}

bool AbstractRpmBasedQt4MaemoTarget::setProjectVersionInternal(const QString &version,
    QString *error)
{
    return setValueForTag(VersionTag, version.toUtf8(), error);
}

Christian Kandeler's avatar
Christian Kandeler committed
909
QString AbstractRpmBasedQt4MaemoTarget::packageName() const
910
{
Christian Kandeler's avatar
Christian Kandeler committed
911
    return QString::fromUtf8(getValueForTag(NameTag, 0));
912
913
}

Christian Kandeler's avatar
Christian Kandeler committed
914
bool AbstractRpmBasedQt4MaemoTarget::setPackageNameInternal(const QString &name)
915
916
917
918
919
920
{
    return setValueForTag(NameTag, name.toUtf8(), 0);
}

QString AbstractRpmBasedQt4MaemoTarget::shortDescription() const
{
Christian Kandeler's avatar
Christian Kandeler committed
921
922
923
924
925
926
927
928
929
    return QString::fromUtf8(getValueForTag(SummaryTag, 0));
}

QString AbstractRpmBasedQt4MaemoTarget::packageFileName() const
{
    return packageName() + QLatin1Char('-') + projectVersion() + QLatin1Char('-')
        + QString::fromUtf8(getValueForTag(ReleaseTag, 0)) + QLatin1Char('.')
        + MaemoGlobal::architecture(activeBuildConfiguration()->qtVersion())
        + QLatin1String(".rpm");
930
931
932
933
934
935
936
}

bool AbstractRpmBasedQt4MaemoTarget::setShortDescriptionInternal(const QString &description)
{
    return setValueForTag(SummaryTag, description.toUtf8(), 0);
}

937
AbstractQt4MaemoTarget::ActionStatus AbstractRpmBasedQt4MaemoTarget::createSpecialTemplates()
938
939
{
    if (QFileInfo(specFilePath()).exists())
940
        return NoActionRequired;
941
942
943
944
945
    QByteArray initialContent(
        "Name: %%name%%\n"
        "Summary: <insert short description here>\n"
        "Version: 0.0.1\n"
        "Release: 1\n"
Christian Kandeler's avatar
Christian Kandeler committed
946
        "License: <Enter your application's license here>\n"
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
        "Group: <Set your application's group here>\n"
        "%description\n"
        "<Insert longer, multi-line description\n"
        "here.>\n"
        "\n"
        "%prep\n"
        "%setup -q\n"
        "\n"
        "%build\n"
        "# You can leave this empty for use with Qt Creator."
        "\n"
        "%install\n"
        "rm -rf %{buildroot}\n"
        "make INSTALL_ROOT=%{buildroot} install\n"
        "\n"
        "%clean\n"
        "rm -rf %{buildroot}\n"
        "\n"
        "BuildRequires: \n"
Christian Kandeler's avatar
Christian Kandeler committed
966
967
        "# %define _unpackaged_files_terminate_build 0\n"
        "%files\n"
968
969
        "%defattr(-,root,root,-)"
        "/usr\n"
970
        "/opt\n"
971
        "# Add additional files to be included in the package here.\n"
Christian Kandeler's avatar
Christian Kandeler committed
972
973
        "%pre\n"
        "# Add pre-install scripts here."
974
975
        "%post\n"
        "/sbin/ldconfig # For shared libraries\n"
Christian Kandeler's avatar
Christian Kandeler committed
976
977
978
979
        "%preun\n"
        "# Add pre-uninstall scripts here."
        "%postun\n"
        "# Add post-uninstall scripts here."
980
981
        );
    initialContent.replace("%%name%%", project()->displayName().toUtf8());
982
983
984
    Utils::FileSaver saver(specFilePath());
    saver.write(initialContent);
    return saver.finalize() ? ActionSuccessful : ActionFailed;
985
986
987
988
}

void AbstractRpmBasedQt4MaemoTarget::handleTargetAddedSpecial()
{
989
    m_filesWatcher->addFile(specFilePath(), Utils::FileSystemWatcher::WatchAllChanges);
990
991
992
993
994
995
996
997
998
999
1000
    connect(m_filesWatcher, SIGNAL(fileChanged(QString)), this,
        SIGNAL(specFileChanged()));
}

bool AbstractRpmBasedQt4MaemoTarget::targetCanBeRemoved() const
{
    return QFileInfo(specFilePath()).exists();
}

void AbstractRpmBasedQt4MaemoTarget::removeTarget()
{