File: chat-window-style-manager.cpp

package info (click to toggle)
ktp-text-ui 0.8.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,680 kB
  • ctags: 1,142
  • sloc: cpp: 9,451; sh: 15; makefile: 9
file content (384 lines) | stat: -rw-r--r-- 13,241 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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
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
274
275
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
   kopetechat-window-style-manager.cpp - Manager all chat window styles

   Copyright (c) 2005      by Michaƫl Larouche     <larouche@kde.org>

   Kopete    (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>

   *************************************************************************
   *                                                                       *
   * This program is free software; you can redistribute it and/or modify  *
   * it under the terms of the GNU General Public License as published by  *
   * the Free Software Foundation; either version 2 of the License, or     *
   * (at your option) any later version.                                   *
   *                                                                       *
   *************************************************************************
*/

#include "chat-window-style-manager.h"
#include "chat-style-plist-file-reader.h"
#include "chat-window-style.h"

// Qt includes
#include <QtCore/QStack>
#include <QtCore/QFileInfo>

// KDE includes
#include <KStandardDirs>
#include <KDirLister>
#include <KDebug>
#include <KUrl>
#include <KGlobal>
#include <KArchive>
#include <KZip>
#include <KTar>
#include <KMimeType>
#include <KIO/NetAccess>
#include <KSharedConfig>
#include <KConfigGroup>


class ChatWindowStyleManager::Private
{
public:
    Private(ChatWindowStyleManager *parent)
            : q(parent), styleDirLister(0) {}

    ~Private() {
        if (styleDirLister) {
            styleDirLister->deleteLater();
        }

        qDeleteAll(stylePool);
    }

    ChatWindowStyleManager *q;
    KDirLister *styleDirLister;
    QMap <QString, QString > availableStyles;

    // key = style id, value = ChatWindowStyle instance
    QHash<QString, ChatWindowStyle*> stylePool;

    QStack<KUrl> styleDirs;
};

ChatWindowStyleManager *ChatWindowStyleManager::self()
{
    static ChatWindowStyleManager s;
    return &s;
}

ChatWindowStyleManager::ChatWindowStyleManager(QObject *parent)
        : QObject(parent), d(new Private(this))
{
    kDebug() ;
}

ChatWindowStyleManager::~ChatWindowStyleManager()
{
    kDebug() ;
    delete d;
}

void ChatWindowStyleManager::loadStyles()
{
    // Make sure there exists a directory where chat styles can be installed to and it will be watched for changes
    KStandardDirs::locateLocal("data", QLatin1String("ktelepathy/styles/"));

    QStringList chatStyles = KGlobal::dirs()->findDirs("data", QLatin1String("ktelepathy/styles"));

    Q_FOREACH(const QString &styleDir, chatStyles) {
        kDebug() << styleDir;
        d->styleDirs.push(KUrl(styleDir));
    }

    d->styleDirLister = new KDirLister(this);
    d->styleDirLister->setDirOnlyMode(true);

    connect(d->styleDirLister, SIGNAL(newItems(KFileItemList)),
            this, SLOT(slotNewStyles(KFileItemList)));
    connect(d->styleDirLister, SIGNAL(completed()), this, SLOT(slotDirectoryFinished()));

    if (!d->styleDirs.isEmpty()) {
        d->styleDirLister->openUrl(d->styleDirs.pop(), KDirLister::Keep);
    }
}

QMap<QString, QString> ChatWindowStyleManager::getAvailableStyles() const
{
    return d->availableStyles;
}

int ChatWindowStyleManager::installStyle(const QString &styleBundlePath)
{
    QString localStyleDir;
    KStandardDirs::locateLocal("data", QLatin1String("ktelepathy/styles/"));
    QStringList chatStyles = KGlobal::dirs()->findDirs("data", QLatin1String("ktelepathy/styles"));
    // findDirs returns preferred paths first, let's check if one of them is writable
    Q_FOREACH(const QString& styleDir, chatStyles) {
        kDebug() << styleDir;
        if (QFileInfo(styleDir).isWritable()) {
            localStyleDir = styleDir;
            break;
        }
    }
    if (localStyleDir.isEmpty()) { // none of dirs is writable
        kDebug()<< "not writable";
        return StyleNoDirectoryValid;
    }

    KArchiveEntry *currentEntry = 0L;
    KArchiveDirectory *currentDir = 0L;
    KArchive *archive = 0L;

    QString currentBundleMimeType = KMimeType::findByPath(styleBundlePath, 0, false)->name();
    if (currentBundleMimeType == QLatin1String("application/zip")) {
        archive = new KZip(styleBundlePath);
    } else if (currentBundleMimeType == QLatin1String("application/x-compressed-tar") ||
               currentBundleMimeType == QLatin1String("application/x-bzip-compressed-tar") ||
               currentBundleMimeType == QLatin1String("application/x-gzip") ||
               currentBundleMimeType == QLatin1String("application/x-bzip")) {
        archive = new KTar(styleBundlePath);
    } else if (currentBundleMimeType == QLatin1String("application/octet-stream")) {
        archive = new KZip(styleBundlePath);
        if (!archive->open(QIODevice::ReadOnly)) {
            delete archive;
            kDebug() << "!zip";
            archive = new KTar(styleBundlePath);
            if (!archive->open(QIODevice::ReadOnly)) {
                delete archive;
                kDebug() << "!tar" << styleBundlePath;
                return StyleCannotOpen;
            }
        }
    } else {
        kDebug() << "unsupported file type" << currentBundleMimeType;
        kDebug() << styleBundlePath;
        return StyleUnknow;
    }

    if (archive == 0 ||  !archive->open(QIODevice::ReadOnly)) {
        delete archive;
        kDebug() << "cannot open theme file";
        return StyleCannotOpen;
    }

    const KArchiveDirectory *rootDir = archive->directory();

    // Ok where we go to check if the archive is valid.
    // Each time we found a correspondance to a theme bundle, we add a point to validResult.
    // A valid style bundle must have:
    // -a Contents, Contents/Resources, Co/Res/Incoming, Co/Res/Outgoing dirs
    // main.css, Footer.html, Header.html, Status.html files in Contents/Resources.
    // So for a style bundle to be valid, it must have a result greather than 2, because we test for 2 required entry.
    int validResult = 0;
    const QStringList entries = rootDir->entries();
    // Will be reused later.
    QStringList::ConstIterator entriesIt;
    for (entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt) {
        currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
    kDebug() << "Current entry name: " << currentEntry->name();
        if (currentEntry->isDirectory()) {
            currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);
            if (currentDir) {
                if (currentDir->entry(QLatin1String("Contents"))) {
                   kDebug() << "Contents found";
                   validResult += 1;
                }
                if (currentDir->entry(QLatin1String("Contents/Resources"))) {
                    kDebug() << "Contents/Resources found";
                    validResult += 1;
                }
            }
        }
    }
    kDebug() << "Valid result: " << QString::number(validResult);
    // The archive is a valid style bundle.
    if (validResult >= 2) {
        bool installOk = false;
        for (entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt) {
            currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
            if (currentEntry && currentEntry->isDirectory()) {
                // Ignore this MacOS X "garbage" directory in zip.
                if (currentEntry->name() == QLatin1String("__MACOSX")) {
                    continue;
                } else {
                    currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);
                    if (currentDir) {
                        currentDir->copyTo(localStyleDir + currentDir->name());
                        installOk = true;
                    }
                }
            }
        }

        archive->close();
        delete archive;

        if (installOk) {
            return StyleInstallOk;
        } else {
            return StyleUnknow;
        }
    } else {
        archive->close();
        delete archive;

        kDebug() << "style not valid";
        return StyleNotValid;
    }

    if (archive) {
        archive->close();
        delete archive;
    }

    return StyleUnknow;
}

bool ChatWindowStyleManager::removeStyle(const QString &styleId)
{
    Q_UNUSED(styleId)
//    kDebug() << styleId;
//    // Find for the current style in avaiableStyles map.
//    int foundStyleIdx = d->availableStyles.indexOf(styleId);

//    if (foundStyleIdx != -1) {
//        d->availableStyles.removeAt(foundStyleIdx);

//        // Remove and delete style from pool if needed.
//        if (d->stylePool.contains(styleId)) {
//            ChatWindowStyle *deletedStyle = d->stylePool[styleId];
//            d->stylePool.remove(styleId);
//            delete deletedStyle;
//        }

//        QStringList styleDirs = KGlobal::dirs()->findDirs("appdata", QString("styles/%1").arg(styleId));
//        if (styleDirs.isEmpty()) {
//            kDebug() << "Failed to find style" << styleId;
//            return false;
//        }

//        // attempt to delete all dirs with this style
//        int numDeleted = 0;
//        Q_FOREACH(const QString& stylePath, styleDirs) {
//            KUrl urlStyle(stylePath);
//            // Do the actual deletion of the directory style.
//            if (KIO::NetAccess::del(urlStyle, 0))
//                numDeleted++;
//        }
//        return numDeleted == styleDirs.count();
//    } else {
//        return false;
//    }
    return false;
}

ChatWindowStyle *ChatWindowStyleManager::getValidStyleFromPool(const QString &styleId)
{
    ChatWindowStyle *style = 0;
    style = getStyleFromPool(styleId);
    if (style) {
        return style;
    }

    kDebug() << "Trying default style";
    // Try default style
    style = getStyleFromPool(QLatin1String("renkoo.AdiumMessageStyle"));
    if (style) {
        return style;
    }

    kDebug() << "Trying first valid style";
    // Try first valid style
    Q_FOREACH(const QString& name, d->availableStyles) {
        style = getStyleFromPool(name);
        if (style) {
            return style;
        }
    }

    kDebug() << "Valid style not found!";
    return 0;
}

ChatWindowStyle *ChatWindowStyleManager::getStyleFromPool(const QString &styleId)
{
    if (d->stylePool.contains(styleId)) {
        kDebug() << styleId << " was on the pool";

        // NOTE: This is a hidden config switch for style developers
        // Check in the config if the cache is disabled.
        // if the cache is disabled, reload the style every time it's getted.
        KConfigGroup config(KGlobal::config(), "KopeteStyleDebug");
        bool disableCache = config.readEntry("disableStyleCache", false);
        if (disableCache) {
            d->stylePool[styleId]->reload();
        }

        return d->stylePool[styleId];
    }

    // Build a chat window style and list its variants, then add it to the pool.
    ChatWindowStyle *style = new ChatWindowStyle(styleId, ChatWindowStyle::StyleBuildNormal);
    if (!style->isValid()) {
        kDebug() << styleId << " is invalid style!";
        delete style;
        return 0;
    }

    d->stylePool.insert(styleId, style);
    kDebug() << styleId << " is just created";

    return style;
}

void ChatWindowStyleManager::slotNewStyles(const KFileItemList &dirList)
{
    Q_FOREACH(const KFileItem &item, dirList) {
        // Ignore data dir(from deprecated XSLT themes)
        if (!item.url().fileName().contains(QLatin1String("data"))) {
            kDebug() << "Listing: " << item.url().fileName();
            // If the style path is already in the pool, that's mean the style was updated on disk
            // Reload the style
            QString styleId = item.url().fileName();
            if (d->stylePool.contains(styleId)) {
                kDebug() << "Updating style: " << styleId;

                d->stylePool[styleId]->reload();

                // Add to available if required.
                if (!d->availableStyles.contains(styleId)) {

                    //FIXME this code is in two places.. this sucks!!!
                    ChatStylePlistFileReader plistReader(item.url().path().append(QLatin1String("/Contents/Info.plist")));
                    QString styleName = plistReader.CFBundleName();
                    if (plistReader.CFBundleName().isEmpty()) {
                        styleName = styleId;
                    }
                    d->availableStyles.insert(styleId, styleName);
                }
            } else {
                ChatStylePlistFileReader plistReader(item.url().path().append(QLatin1String("/Contents/Info.plist")));
                QString styleName = plistReader.CFBundleName();
                if (plistReader.CFBundleName().isEmpty()) {
                    styleName = styleId;
                }
                d->availableStyles.insert(styleId, styleName);
            }
        }
    }
}

void ChatWindowStyleManager::slotDirectoryFinished()
{
    // Start another scanning if the directories stack is not empty
    if (!d->styleDirs.isEmpty()) {
        kDebug() << "Starting another directory.";
        d->styleDirLister->openUrl(d->styleDirs.pop(), KDirLister::Keep);
    } else {
        Q_EMIT loadStylesFinished();
    }
}

#include "chat-window-style-manager.moc"