aboutsummaryrefslogtreecommitdiff
path: root/src/corelib/theme/mtheme.cpp
blob: 5bf58005a2155135ebd1864c3ddac6eba54d2895 (plain)
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
385
386
387
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
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
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
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
624
625
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
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
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it 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.
**
****************************************************************************/

#include "mtheme.h"
#include "mtheme_p.h"

#include "mlibrary.h"
M_LIBRARY

#ifdef Q_WS_X11
#include <QX11Info>
#endif
#include <QPixmap>
#include <MDebug>
#include <QCoreApplication>
#include <QFileInfo>
#include <QSettings>
#include <QDir>
#include <QSharedMemory>

#include "private/mwidgetcontroller_p.h"

#ifdef HAVE_GCONF
#include "mgconfitem.h"
#endif

#include "mclassfactory.h"
#include "mstyle.h"
#include "mremotethemedaemon.h"
#include "mlocalthemedaemon.h"
#include "mstylesheet.h"
#include "mwidgetcontroller.h"
#include "mwidgetview.h"
#include "mscenemanager.h"
#include "mscene.h"
#include "mscalableimage.h"

#include "private/mstylesheet_p.h"
#include "private/mwidgetcontroller_p.h"

#include "mapplication.h"
#include "mapplicationwindow.h"
#include "mcomponentdata.h"
#include "mcomponentdata_p.h"

#include "mgraphicssystemhelper.h"

// Must be last as it conflicts with some Qt defined types
#ifdef Q_WS_X11
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#endif

#ifdef HAVE_MEEGOGRAPHICSSYSTEM
#include <sys/mman.h>
#endif

MTheme *gTheme = 0;

QHash<QString, MLibrary *>* MThemePrivate::libraries = NULL;
MThemePrivate::RegisteredStyleContainers MThemePrivate::styleContainers;

namespace
{
    // "default_pixmap_MyPixmap_47_47"
    static QString defaultPixmapCacheId(const QString &name, int width, int height)
    {
        return QString::fromLatin1("default_pixmap_") + name
                + QChar::fromLatin1('_') + QString::number(width)
                + QChar::fromLatin1('_') + QString::number(height);
    }

    // "scalable_image_myscalable_5_5_5_5
    static QString scalableImageCacheId(const QString &name, int left, int top, int right, int bottom)
    {
        return QString::fromLatin1("scalable_image_") + name
                + QChar::fromLatin1('_') + QString::number(left)
                + QChar::fromLatin1('_') + QString::number(top)
                + QChar::fromLatin1('_') + QString::number(right)
                + QChar::fromLatin1('_') + QString::number(bottom);
    }
} // anonymous namespace

MThemePrivate::LeakedStyles MThemePrivate::leakedStyles;

void mMessageHandler(QtMsgType type, const char *msg);

MThemePrivate::LeakedStyles::~LeakedStyles()
{
    // as LeakedStyles is a static class the method handler could not be valid
    // anymore at this point. work around this problem by creating a new one
    qInstallMsgHandler(mMessageHandler);

    QHash<MStyle*, QString>::iterator end = styles.end();
    for (QHash<MStyle*, QString>::iterator iterator = styles.begin();
            iterator != end;
            ++iterator) {
        MStyle *leak = iterator.key();
        QString id = iterator.value();

        mWarning("mtheme.cpp") << "Style:" << id << "not released!" << "refcount:" << leak->references();
    }
}

void MThemePrivate::addLeakedStyle(MStyle *style, const QString &id)
{
    leakedStyles.insert(style, id);
}

void MThemePrivate::removeLeakedStyle(MStyle *style)
{
    leakedStyles.remove(style);
}

MTheme::MTheme(const QString &applicationName, const QString &, ThemeService themeService) :
    d_ptr(new MThemePrivate(applicationName, themeService))
{
    if (gTheme || (MComponentData::instance() && MComponentData::instance()->d_ptr->theme))
        qFatal("There cannot be multiple instances of MTheme, use MTheme::instance() instead of constructing a new one");

    Q_D(MTheme);

    d->q_ptr = this;

    connect(d->themeDaemon, SIGNAL(themeChanged(QStringList, QStringList)),
            SLOT(themeChangedSlot(QStringList, QStringList)));

    connect(d->themeDaemon, SIGNAL(pixmapCreatedOrChanged(QString, QSize, MPixmapHandle)),
            SLOT(pixmapCreatedOrChangedSlot(QString, QSize, MPixmapHandle)));

    connect(d->themeDaemon, SIGNAL(themeChangeCompleted()), SIGNAL(themeChangeCompleted()));

#ifdef HAVE_GCONF
    connect(&d->locale, SIGNAL(valueChanged()), SLOT(localeChangedSlot()));
#endif

    gTheme = this;
}

MTheme::~MTheme()
{
    MStyleSheet::cleanup(false);

    QHash<QString, CachedScalableImage>::iterator i2 = d_ptr->scalableImageIdentifiers.begin();
    QHash<QString, CachedScalableImage>::iterator end2 = d_ptr->scalableImageIdentifiers.end();
    for (; i2 != end2; ++i2) {
        qWarning() << "MTheme - MScalableImage" << i2.key() << "not released!" << "refcount:" << i2.value().refcount;
        releasePixmap(i2.value().image->pixmap());
        delete i2.value().image;
    }

    d_ptr->cleanupGarbage();

    // print identifiers from all pixmaps which were not released
    QHash<QString, CachedPixmap>::iterator i = d_ptr->pixmapIdentifiers.begin();
    QHash<QString, CachedPixmap>::iterator end = d_ptr->pixmapIdentifiers.end();
    for (; i != end; ++i) {
        qWarning() << "MTheme - pixmap" << i.key() << "not released!" << "refcount:" << i.value().refcount;
    }

    // unload all theme libraries
    d_ptr->reloadThemeLibraries(QStringList());

    gTheme = NULL;
    delete d_ptr;
}


bool MTheme::addPixmapDirectory(const QString &directoryName, M::RecursionMode recursive)
{
    QDir dir(directoryName);
    if (!dir.exists())
        return false;

    instance()->d_ptr->themeDaemon->addDirectoryToPixmapSearchList(dir.absolutePath(), recursive);
    return true;
}

void MTheme::clearPixmapDirectories()
{
    instance()->d_ptr->themeDaemon->clearPixmapSearchList();
}

MTheme *MTheme::instance()
{
    if (MComponentData::instance())
        return MComponentData::instance()->d_ptr->theme;

    if (!gTheme) {
        // This allows MTheme to be independent from MApplication.
        // Uses this process' name as the theme identifier by default
        QFileInfo fileInfo(QCoreApplication::instance()->applicationName());
        QString applicationName = fileInfo.fileName();
        gTheme = new MTheme(applicationName);
    }

    return gTheme;
}

const QPixmap *MTheme::pixmap(const QString &id, const QSize &size)
{
    return instance()->d_ptr->pixmap(id, false, size);
}

const QPixmap *MTheme::asyncPixmap(const QString &id, const QSize &size)
{
    return instance()->d_ptr->pixmap(id, true, size);
}

QPixmap *MTheme::pixmapCopy(const QString &id, const QSize &size)
{
    //force daemon to load the pixmap synchronously, then make copy of the
    //pixmap and release it immediately
    const QPixmap *p = instance()->d_ptr->pixmap(id, false, size);
    QPixmap* copy = new QPixmap(p->copy());
    releasePixmap(p);

    return copy;
}

const QPixmap *MThemePrivate::pixmap(const QString &id, bool async, const QSize &size)
{
    if (id.isEmpty()) {
        mWarning("MTheme") << "requested pixmap without id";
        return invalidPixmap();
    }

    // TODO: check if needed
    QSize realSize = size;
    if (realSize.width() < 1)
        realSize.rwidth() = 0;
    if (realSize.height() < 1)
        realSize.rheight() = 0;

    QString identifier = defaultPixmapCacheId(id, realSize.width(), realSize.height());
    const QPixmap *p = fetchPixmapFromCache(identifier);
    // check if we found the pixmap from the cache
    if (p)
        return p;

    QPixmap *result = new QPixmap(async ? realSize : QSize(0, 0));
    pixmapIdentifiers.insert(identifier, CachedPixmap(result, id, realSize));

    if (async) {
        if (showAsyncRequests) {
            result->fill(QColor(0, 255, 0, 255));
        } else {
            result->fill(QColor(0, 0, 0, 0));
        }
        themeDaemon->pixmapHandle(id, realSize);
    } else {
        themeDaemon->pixmapHandleSync(id, realSize);
    }

    return result;
}

const MScalableImage *MTheme::scalableImage(const QString &id, int left, int right, int top, int bottom)
{
    // check if we already have this scalable image in the cache
    QString scalableidentifier = scalableImageCacheId(id, left, top, right, bottom);
    QHash<QString, CachedScalableImage>::iterator i = instance()->d_ptr->scalableImageIdentifiers.find(scalableidentifier);
    if (i != instance()->d_ptr->scalableImageIdentifiers.end()) {
        //image found, increase refcount and return it
        i.value().refcount.ref();
        return i.value().image;
    }

    //first try to fetch the used pixmap from the cache
    QString pixmapidentifier = defaultPixmapCacheId(id, 0, 0);
    const QPixmap *p = instance()->d_ptr->fetchPixmapFromCache(pixmapidentifier);
    if (!p) {
        QPixmap *result = new QPixmap();

        instance()->d_ptr->pixmapIdentifiers.insert(pixmapidentifier, CachedPixmap(result, id, QSize(0, 0)));
        instance()->d_ptr->themeDaemon->pixmapHandleSync(id, QSize(0, 0));

        p = result;
    }

    //create the actual scalable image and cache it
    MScalableImage *image = new MScalableImage(p, left, right, top, bottom, id);
    instance()->d_ptr->scalableImageIdentifiers.insert(scalableidentifier, CachedScalableImage(image));

    return image;
}

void MTheme::releaseScalableImage(const MScalableImage *image)
{
    // find the image from cache and decrease refcount + release if refcount = 0
    // TODO: this could be optimized
    QHash<QString, CachedScalableImage>::iterator i = instance()->d_ptr->scalableImageIdentifiers.begin();
    QHash<QString, CachedScalableImage>::iterator end = instance()->d_ptr->scalableImageIdentifiers.end();
    for (; i != end; ++i) {
        // is this the image which we should release?
        if (i.value().image == image) {
            if (!i.value().refcount.deref()) {
                releasePixmap(i.value().image->pixmap());
                delete i.value().image;
                instance()->d_ptr->scalableImageIdentifiers.erase(i);
            }
            break;
        }
    }
}

void MTheme::releasePixmap(const QPixmap *pixmap)
{
    // NULL pixmap, do nothing
    if (!pixmap)
        return;

    // invalidPixmap, no need to release it
    if (pixmap == instance()->d_ptr->invalidPixmap()) {
        return;
    }

    if (instance()->d_ptr->releasePixmap(pixmap))
        return;

    // check if we didn't find the pixmap from our cache
    Q_ASSERT_X(false, "MTheme::releasePixmap", "Pixmap not found from the cache!");
}

QHash<QString, CachedPixmap>::iterator MThemePrivate::findCachedPixmap(const QPixmap *pixmap)
{
    // TODO: this could be optimized
    QHash<QString, CachedPixmap>::iterator i = pixmapIdentifiers.begin();
    QHash<QString, CachedPixmap>::iterator end = pixmapIdentifiers.end();
    for (; i != end; ++i) {       // is this the pixmap which we should release?
        if (i.value().pixmap == pixmap) {
            return i;
        }
    }
    return end;
}

bool MThemePrivate::releasePixmapNow(const QPixmap *pixmap)
{
    return releasePixmapNow(findCachedPixmap(pixmap));
}

bool MThemePrivate::releasePixmapNow(QHash<QString, CachedPixmap>::iterator i)
{
    if (i != pixmapIdentifiers.end()) {
        if (!i.value().refcount || !i.value().refcount.deref()) {
            themeDaemon->releasePixmap(i.value().imageId, i.value().size);
            if (i->addr) {
#ifdef HAVE_MEEGOGRAPHICSSYSTEM
                munmap(i->addr, i->numBytes);
#endif
            }
            delete i.value().pixmap;
            if (releasedPixmaps.contains(i.value().pixmap))
                releasedPixmaps.remove(releasedPixmaps.indexOf(i.value().pixmap));
            pixmapIdentifiers.erase(i);
        }
        return true;
    }
    return false;
}

bool MThemePrivate::releasePixmap(const QPixmap *pixmap)
{
    QHash<QString, CachedPixmap>::iterator i = findCachedPixmap(pixmap);

    if (i != pixmapIdentifiers.end()) {
        if (!i.value().refcount.deref()) {
            releasedPixmaps.append(pixmap);
        }
        return true;
    }
    return false;
}

void MThemePrivate::cleanupGarbage()
{
    for (int i = releasedPixmaps.count(); i > 0; i--) {
        const QPixmap *pixmap = releasedPixmaps[i - 1];
        releasePixmapNow(pixmap);
    }
}

bool MThemePrivate::extractDataForStyleClass(const char *styleClassName,
                                             QList<const MStyleSheet *> &sheets,
                                             QList<QByteArray> &styleMetaObjectHierarchy)
{
    // Go through the inheritance chain and add stylesheets from each assembly
    const QMetaObject *mobj = MClassFactory::instance()->styleMetaObject(styleClassName);
    if (!mobj)
        return false;

    // Exception: For MWidgetStyle we should search in all libraries css'es,
    // otherwise the views styles (including common styles) are not installable
    // on MWidgetController and MStylableWidget.
    if (mobj->className() == MWidgetStyle::staticMetaObject.className()) {
        styleMetaObjectHierarchy.append(mobj->className());
        appendAllLibraryStyleSheets(sheets);
        return true;
    }

    do {
        styleMetaObjectHierarchy.append(mobj->className());

        M::AssemblyType assemblyType = MClassFactory::instance()->styleAssemblyType(mobj->className());
        if (assemblyType == M::Application) {
            mobj = mobj->superClass();
            continue;
        }
        QString assemblyName = MClassFactory::instance()->styleAssemblyName(mobj->className());

        // find proper library
        if (!MThemePrivate::appendLibraryStyleSheet(sheets, assemblyName)) {
            mWarning("MTheme") << "Cannot find library. You must register your library to theming using M_LIBRARY macro." << '(' << assemblyName << ')';
        }
        mobj = mobj->superClass();
    } while (mobj->className() != QObject::staticMetaObject.className());

    return true;
}

QList<const MStyleSheet *> MThemePrivate::extractSheetsForClassHierarchy(const QList<const MStyleSheet *> &sheets,
                                                                         const QList<QByteArray> &parentHierarchy)
{
    QList<const MStyleSheet *> parentSheets;

    foreach (const QByteArray &className, parentHierarchy) {
        M::AssemblyType assemblyType = MClassFactory::instance()->widgetAssemblyType(className);
        if (assemblyType == M::Application || assemblyType == M::AssemblyNone)
            continue;

        QString assemblyName = MClassFactory::instance()->widgetAssemblyName(className);
        MLibrary *library = libraries->value(assemblyName, NULL);
        if (library && library->stylesheet()) {
            if (!sheets.contains(library->stylesheet()) && !parentSheets.contains(library->stylesheet())) {
                parentSheets.insert(0, library->stylesheet());
            }
        }
    }

    return parentSheets;
}

void MThemePrivate::appendAllLibraryStyleSheets(QList<const MStyleSheet *> &sheets)
{
    foreach(QString assemblyName, libraries->keys())
        MThemePrivate::appendLibraryStyleSheet(sheets, assemblyName);
}

bool MThemePrivate::appendLibraryStyleSheet(QList<const MStyleSheet *> &sheets, const QString &assemblyName)
{
    MLibrary *library = libraries->value(assemblyName, NULL);
    if (library) {
        if (library->stylesheet()) {
            if (!sheets.contains(library->stylesheet()))
                sheets.insert(0, library->stylesheet());
        }
        return true;
    }

    return false;
}

const MStyle *MTheme::style(const char *styleClassName,
                                const QString &objectName)
{
    return MTheme::style(styleClassName, objectName, 0, 0, M::Landscape, NULL);
}

const MStyle *MTheme::style(const char *styleClassName,
                            const QString &objectName,
                            const QString &mode,
                            const QString &type,
                            M::Orientation orientation,
                            const MWidgetController *parent)
{
    // The style type should never be "default" - that would probably be a view type
    // that's mistakenly being used as a style type.
    // The caller probably means "" instead.
    Q_ASSERT(type != "default");

    MThemePrivate *d = MTheme::instance()->d_func();

    // list containing all stylesheets from all assemblies from which this style is/inherits + app css
    QList<const MStyleSheet *> sheets;

    QList<QByteArray> styleMetaObjectHierarchy;
    if (!d->extractDataForStyleClass(styleClassName, sheets, styleMetaObjectHierarchy))
         return 0;

    // Get parent data by traversing the MWidgetController pointer we have
    QVector<MStyleSheetPrivate::ParentData> parentsData = MStyleSheetPrivate::extractParentsData(parent);
    for (int i = 0; i < parentsData.size(); i++) {
        MStyleSheetPrivate::ParentData &pd = parentsData[i];
        pd.sheets = d->extractSheetsForClassHierarchy(sheets, pd.hierarchy);
    }

    // add application css
    if (d->application->stylesheet())
        sheets.append(d->application->stylesheet());

    // add custom stylesheet
    if (d->customStylesheet)
        sheets.append(d->customStylesheet);

    QString parentStyleName;
    if (parent) {
        if (!parent->styleName().isNull())
            parentStyleName = parent->styleName();
        else
            parentStyleName = parent->objectName();
    }

    return MStyleSheetPrivate::style(sheets, parentsData, parentStyleName.toAscii(),
                                     styleMetaObjectHierarchy, styleClassName, objectName.toAscii(),
                                     mode.toAscii(), type.toAscii(), orientation);
}

const MStyle *MTheme::style(const char *styleClassName,
                            const QString &objectName,
                            const QString &mode,
                            const QString &type,
                            M::Orientation orientation,
                            const QList<QStringList> &parentClassHierarchies,
                            const QString &parentStyleName)
{
    // The style type should never be "default" - that would probably be a view type
    // that's mistakenly being used as a style type.
    // The caller probably means "" instead.
    Q_ASSERT(type != "default");

    MThemePrivate *d = MTheme::instance()->d_func();

    // list containing all stylesheets from all assemblies from which this style is/inherits + app css
    QList<const MStyleSheet *> sheets;

    QList<QByteArray> styleMetaObjectHierarchy;
    if (!d->extractDataForStyleClass(styleClassName, sheets, styleMetaObjectHierarchy))
         return 0;


    // Get parent data based on the parentClassHierarchies parameter...
    QVector<MStyleSheetPrivate::ParentData> parentsData(parentClassHierarchies.size());
    for (int i = 0; i < parentClassHierarchies.size(); i++) {
        MStyleSheetPrivate::ParentData &pd = parentsData[i];
        QList<QByteArray> parentClassHierarchiesConverted;
        foreach (const QString &str, parentClassHierarchies[i]) {
            parentClassHierarchiesConverted << str.toAscii();
        }
        pd.hierarchy = parentClassHierarchiesConverted;
        pd.sheets = d->extractSheetsForClassHierarchy(sheets, pd.hierarchy);
    }

    // add application css
    if (d->application->stylesheet())
        sheets.append(d->application->stylesheet());

    // add custom stylesheet
    if (d->customStylesheet)
        sheets.append(d->customStylesheet);

    return MStyleSheetPrivate::style(sheets, parentsData, parentStyleName.toAscii(), styleMetaObjectHierarchy, styleClassName, objectName.toAscii(), mode.toAscii(), type.toAscii(), orientation);
}

void MTheme::releaseStyle(const MStyle *style)
{
    if (!style)
        return;

    MStyleSheet::releaseStyle(style);
}

QAbstractAnimation *MTheme::animation(const QString &animationTypeName)
{
    QAbstractAnimation *a = MClassFactory::instance()->createAnimation(animationTypeName);
    if (!a) {
        qWarning() << "Failed to create implementation for: " << animationTypeName;
        return NULL;
    }

    return a;
}

QGraphicsEffect *MTheme::effect(const QString &effectTypeName)
{
    QGraphicsEffect *a = MClassFactory::instance()->createEffect(effectTypeName);
    if (!a) {
        qWarning() << "Failed to create implementation for: " << effectTypeName;
        return NULL;
    }

    return a;
}

MWidgetView *MTheme::view(const MWidgetController *controller)
{
    // Best matching view class name
    QString viewClassName = instance()->d_ptr->determineViewClassForController(controller);

    if (viewClassName.isEmpty()) {
        qWarning() << "Could not find view class for:" << controller->metaObject()->className() << "/" << controller->viewType();
        return NULL;
    }

    MWidgetView *v = MClassFactory::instance()->createView(viewClassName.toStdString().c_str(), controller);
    if (!v) {
        qWarning() << "Failed to create view for:" << controller->metaObject()->className() << "/" << controller->viewType() << ".  Class name found was: " << viewClassName;
        return NULL;
    }

    return v;
}

const MPalette &MTheme::palette()
{
    return instance()->d_ptr->palette;
}

const MDefaultFonts &MTheme::fonts()
{
    return instance()->d_ptr->fonts;
}

bool MTheme::loadCSS(const QString &filename, InsertMode mode)
{
    if (instance()->d_ptr->loadCSS(filename, mode)) {
        // Re-populate all the styles, custom stylesheet may have overridden something
        for (MThemePrivate::RegisteredStyleContainers::iterator iterator = MThemePrivate::styleContainers.begin(); iterator != MThemePrivate::styleContainers.end(); ++iterator) {
            iterator.value()->reloadStyles();
        }
        // notify all widgets that style needs to be applied
        QSet<MWidgetController *>::iterator end = MWidgetControllerPrivate::allSystemWidgets.end();
        for (QSet<MWidgetController *>::iterator i = MWidgetControllerPrivate::allSystemWidgets.begin();
                i != end; ++i) {
            // get view ask it to apply the new style
            const MWidgetView *view = (*i)->view();
            if (view) {
                const_cast<MWidgetView *>(view)->applyStyle();
            }
        }
        return true;
    }

    return false;
}

bool MThemePrivate::loadCSS(const QString &filename, MTheme::InsertMode mode)
{
    MStyleSheet *newStylesheet = new MStyleSheet(&logicalValues);
    bool result = newStylesheet->load(filename);
    if (result) {
        // loading ok, check what to do.. overwrite or append?
        if ((mode == MTheme::Append) && customStylesheet) {
            // append the loaded style data into the existing stylesheet
            *customStylesheet += *newStylesheet;
            delete newStylesheet;
            newStylesheet = NULL;
        } else {
            // no existing stylesheet or the stylesheet needs to be overwritten
            delete customStylesheet;
            customStylesheet = newStylesheet;
        }

        // Cached entries are not valid any more
        MStyleSheet::cleanup(false);
        return true;
    }

    delete newStylesheet;
    return false;
}

QString MTheme::currentTheme()
{
    MThemePrivate *d = MTheme::instance()->d_func();
    return d->themeDaemon->currentTheme();
}

bool MTheme::hasPendingRequests()
{
    return instance()->d_ptr->themeDaemon->hasPendingRequests();
}

void MTheme::cleanupGarbage()
{
    instance()->d_ptr->cleanupGarbage();
}

void MThemePrivate::reinit(const QString &newApplicationName)
{
    delete application;
    applicationName = newApplicationName;
    application = new MAssembly(applicationName);
    themeDaemon->registerApplicationName(newApplicationName);
    application->themeChanged(themeDaemon->themeInheritanceChain());
}

MThemePrivate::MThemePrivate(const QString &applicationName, MTheme::ThemeService themeService) :
    applicationName(applicationName),
    customStylesheet(NULL),
    invalidPixmapPtr(0),
    application(new MAssembly(applicationName)),
    palette(logicalValues),
    fonts(logicalValues)
#ifdef HAVE_GCONF
    , locale("/meegotouch/i18n/language")
    , showAsyncRequestsItem("/meegotouch/debug/show_async_requests")
#endif
    , showAsyncRequests(false)
{
    switch (themeService) {
    case MTheme::LocalTheme:
        themeDaemon = new MLocalThemeDaemon(applicationName);
        break;

    case MTheme::RemoteTheme:
        themeDaemon = new MRemoteThemeDaemon(applicationName, -1);
        break;

    case MTheme::AnyTheme: {
        MRemoteThemeDaemon *tds = new MRemoteThemeDaemon(applicationName, 0);
        if (tds->connected()) {
            themeDaemon = tds;
        } else {
            delete tds;
            themeDaemon = new MLocalThemeDaemon(applicationName);
        }
    } break;
    }

    // this loads the current theme
    reloadThemeLibraries(themeDaemon->themeLibraryNames());
    refreshLocalThemeConfiguration(themeDaemon->themeInheritanceChain());

#ifdef HAVE_GCONF
    showAsyncRequests = showAsyncRequestsItem.value(false).toBool();
    connect(&showAsyncRequestsItem, SIGNAL(valueChanged()), this, SLOT(updateShowAsyncRequests()));
#endif
}

MThemePrivate::~MThemePrivate()
{
    delete application;
    delete themeDaemon;
    delete invalidPixmapPtr;
    delete customStylesheet;

    // TODO: check if we need to release QPixmaps from pixmapHandles
}

QString MThemePrivate::determineViewClassForController(const MWidgetController *controller)
{
    bool exactMatch = false;

    QString controllerClassName = controller->metaObject()->className();
    QString cachedViewClass = controllerViewCache[controllerClassName].value(controller->viewType(), QString::null);
    if (!cachedViewClass.isNull())
        return cachedViewClass;

    // first search from application view configuration
    QString bestMatch = application->viewType(controller, exactMatch);
    if (exactMatch)
        return bestMatch;

    for (const QMetaObject *metaObject = controller->metaObject(); metaObject != &MWidget::staticMetaObject; metaObject = metaObject->superClass()) {

        // check if this widget is declared inside some library
        M::AssemblyType type = MClassFactory::instance()->widgetAssemblyType(metaObject->className());
        if (type == M::Application)
            continue;

        // get name of the library where this widget was declared
        QString assemblyName = MClassFactory::instance()->widgetAssemblyName(metaObject->className());
        if (assemblyName.isEmpty())
            continue;

        // find proper library
        MLibrary *library = libraries->value(assemblyName, NULL);
        Q_ASSERT_X(library, "MTheme", "Failed to find library");

        // try to get view type for the widget
        QString viewClassName = library->viewType(controller, exactMatch);
        if (exactMatch) {
            bestMatch = viewClassName;
            break;
        }

        if (bestMatch.isEmpty()) {
            bestMatch = viewClassName;
        }
    }

    controllerViewCache[controllerClassName].insert(controller->viewType(), bestMatch);

    return bestMatch;
}

const QPixmap *MThemePrivate::fetchPixmapFromCache(const QString &identifier)
{
    QHash<QString, CachedPixmap>::iterator i = pixmapIdentifiers.find(identifier);

    // check if we already have this pixmap in cache
    if (i != pixmapIdentifiers.end()) {
        i.value().refcount.ref();
        if (releasedPixmaps.contains(i.value().pixmap))
            releasedPixmaps.remove(releasedPixmaps.indexOf(i.value().pixmap));
        return i.value().pixmap;
    }

    // if not return null
    return NULL;
}

void MThemePrivate::themeChangedSlot(const QStringList &themeInheritance, const QStringList& libraryNames)
{
    refreshLocalThemeConfiguration(themeInheritance);
    q_ptr->rebuildViewsForWidgets();
    reloadThemeLibraries(libraryNames);
    emit q_ptr->themeIsChanging();
}

void MThemePrivate::refreshLocalThemeConfiguration(const QStringList &themeInheritance)
{
    QString language;

#ifdef HAVE_GCONF
    // determine current language
    language = locale.value("en_GB").toString();
#endif

    // Load logical values from ini file
    logicalValues.load(themeInheritance, language);

    // refresh default fonts & palette
    palette.refresh();
    fonts.refresh();

    // load all css-files from all libraries from all themes.
    foreach(MLibrary * lib, *libraries) {
        lib->themeChanged(themeInheritance);
    }

    // refresh application theme data
    application->themeChanged(themeInheritance);

    // cached data is no more valid
    MStyleSheet::cleanup(false);
}

void MThemePrivate::reloadThemeLibraries(const QStringList& libraryNames)
{
    QString libsuffix;

#ifdef Q_OS_WIN
    // under windows the libraries are suffixed with a "0",
    // e.g. meegotouchviews0.dll, so the 0 here is needed,
    // so that the library can be loaded under windows.
    libsuffix = "0";
#endif

    // store list of libraries that needs to be unloaded
    QSet<QLibrary*> toUnload = openedThemeLibraries;

    // load all new libraries (if the library is already loaded, it will ref the loaded one)
    openedThemeLibraries.clear();
    foreach(const QString& libname, libraryNames) {
        QLibrary* library = new QLibrary(libname + libsuffix);
        if(!library->load()) {
            library->setFileNameAndVersion(libname + libsuffix, M_MAJOR_VERSION);
            library->load();
        }

        if (library->isLoaded()) {
            openedThemeLibraries.insert(library);
        } else {
            mWarning("MTheme") << "Failed to open theme library:" << libname;
            delete library;
        }
    }

    // unload old themelibraries
    foreach(QLibrary* library, toUnload) {
        library->unload();
        delete library;
    }
}

void MThemePrivate::registerLibrary(MLibrary *library)
{
    if (!MThemePrivate::libraries)
        MThemePrivate::libraries = new QHash<QString, MLibrary *>();

    MThemePrivate::libraries->insert(library->name(), library);

    // Load theme-specific content of this library (in case the lib was loaded after startup).
    if (gTheme) {
        MThemePrivate *d = MTheme::instance()->d_ptr;
        library->themeChanged(d->themeDaemon->themeInheritanceChain());
    }
}

void MThemePrivate::unregisterLibrary(MLibrary *library)
{
    MThemePrivate::libraries->remove(library->name());

    if (MThemePrivate::libraries->count() == 0) {
        delete MThemePrivate::libraries;
        MThemePrivate::libraries = NULL;
    }
}

void MThemePrivate::pixmapRequestFinished()
{
    Q_Q(MTheme);

    if (!MTheme::hasPendingRequests()) {
        if (MApplication::activeWindow() && MApplication::activeWindow()->viewport()) {
            MApplication::activeWindow()->viewport()->update();
        }
        emit q->pixmapRequestsFinished();
    }
}

QPixmap *MThemePrivate::invalidPixmap()
{
    if (!invalidPixmapPtr) {
        invalidPixmapPtr = new QPixmap(50, 50);
        invalidPixmapPtr->fill(QColor(255, 64, 64, 255));
    }
    return invalidPixmapPtr;
}

void MThemePrivate::pixmapCreatedOrChangedSlot(const QString &imageId, const QSize &size, const MPixmapHandle& pixmapHandle)
{
    QString identifier = defaultPixmapCacheId(imageId, size.width(), size.height());
    QHash<QString, CachedPixmap>::iterator iterator = pixmapIdentifiers.find(identifier);

    if (iterator == pixmapIdentifiers.end()) {
        // the updated pixmap has already been released, but the daemon didn't get the message early enough
        return;
    }

    QPixmap *pixmap = (QPixmap *) iterator.value().pixmap;

    if (!pixmapHandle.isValid()) {
        mWarning("MThemePrivate") << "pixmapChangedSlot - pixmap reload failed (null handle):" << identifier;
        *pixmap = *invalidPixmap();

        pixmapRequestFinished();
        return;
    }

    *pixmap = MGraphicsSystemHelper::pixmapFromHandle(pixmapHandle, &iterator->addr, &iterator->numBytes);

    pixmapRequestFinished();
}


void MTheme::rebuildViewsForWidgets()
{
    Q_D(MTheme);

    // Re-populate all the styles
    // TODO: This could be probably optimized somehow
    for (MThemePrivate::RegisteredStyleContainers::iterator iterator = d->styleContainers.begin(); iterator != d->styleContainers.end(); ++iterator) {
        iterator.value()->reloadStyles();
    }

    // Clear controller -> view cache
    d_ptr->controllerViewCache.clear();

    // go trough all widgets, replace views
    QSet<MWidgetController *>::iterator end = MWidgetControllerPrivate::allSystemWidgets.end();
    for (QSet<MWidgetController *>::iterator i = MWidgetControllerPrivate::allSystemWidgets.begin();
            i != end; ++i) {

        MWidgetController *controller = (*i);

        // figure out the view class name
        QString className = d->determineViewClassForController(controller);

        const MWidgetView *view = controller->view();
        if (view) {
            // check if it's completely new view class for this widget?
            if (className != view->metaObject()->className()) {
                controller->d_func()->deprecateView();
            } else {
                const_cast<MWidgetView *>(view)->applyStyle();
            }
        }
    }
}

void MThemePrivate::registerStyleContainer(MStyleContainer *container)
{
    styleContainers[container] = container;
}

void MThemePrivate::unregisterStyleContainer(MStyleContainer *container)
{
    RegisteredStyleContainers::iterator iterator = styleContainers.find(container);
    if (iterator != styleContainers.end()) {
        styleContainers.erase(iterator);
    }
}

void MThemePrivate::localeChangedSlot()
{
    themeChangedSlot(themeDaemon->themeInheritanceChain(), themeDaemon->themeLibraryNames());
}

#ifdef HAVE_GCONF
void MThemePrivate::updateShowAsyncRequests()
{
    showAsyncRequests = showAsyncRequestsItem.value().toBool();
}
#endif

#include "moc_mtheme.cpp"