kcm.cpp 25.4 KB
Newer Older
Marco Martin's avatar
Marco Martin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* This file is part of the KDE Project
   Copyright (c) 2014 Marco Martin <mart@kde.org>
   Copyright (c) 2014 Vishesh Handa <me@vhanda.in>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "kcm.h"
#include "../krdb/krdb.h"
Marco Martin's avatar
Marco Martin committed
22
#include "../cursortheme/xcursor/xcursortheme.h"
Marco Martin's avatar
Marco Martin committed
23
#include "config-kcm.h"
24
#include "config-workspace.h"
Marco Martin's avatar
Marco Martin committed
25
26
27
28
29
#include <klauncher_iface.h>

#include <KAboutData>
#include <KSharedConfig>
#include <KGlobalSettings>
Marco Martin's avatar
Marco Martin committed
30
#include <KIconLoader>
31
32
#include <KAutostart>
#include <KRun>
33
#include <KService>
Marco Martin's avatar
Marco Martin committed
34

35
#include <QDebug>
36
37
#include <QQuickItem>
#include <QQuickWindow>
38
39
#include <QStandardPaths>
#include <QProcess>
Marco Martin's avatar
Marco Martin committed
40
41
42
43
#include <QStandardItemModel>
#include <QX11Info>

#include <KLocalizedString>
44
#include <KPackage/PackageLoader>
Marco Martin's avatar
Marco Martin committed
45
46
47
48
49
50
51
52

#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>

#ifdef HAVE_XFIXES
#  include <X11/extensions/Xfixes.h>
#endif

53
54
KCMLookandFeel::KCMLookandFeel(QObject* parent, const QVariantList& args)
    : KQuickAddons::ConfigModule(parent, args)
55
    , m_config(QStringLiteral("kdeglobals"))
Marco Martin's avatar
Marco Martin committed
56
57
58
59
60
61
    , m_configGroup(m_config.group("KDE"))
    , m_applyColors(true)
    , m_applyWidgetStyle(true)
    , m_applyIcons(true)
    , m_applyPlasmaTheme(true)
    , m_applyCursors(true)
62
    , m_applyWindowSwitcher(true)
63
    , m_applyDesktopSwitcher(true)
64
    , m_resetDefaultLayout(false)
65
    , m_applyWindowDecoration(true)
Marco Martin's avatar
Marco Martin committed
66
67
{
    qmlRegisterType<QStandardItemModel>();
Marco Martin's avatar
Marco Martin committed
68
    qmlRegisterType<KCMLookandFeel>();
69
    KAboutData* about = new KAboutData(QStringLiteral("kcm_lookandfeel"), i18n("Global Theme"),
70
71
                                       QStringLiteral("0.1"), QString(), KAboutLicense::LGPL);
    about->addAuthor(i18n("Marco Martin"), QString(), QStringLiteral("mart@kde.org"));
Marco Martin's avatar
Marco Martin committed
72
    setAboutData(about);
73
    setButtons(Apply | Default);
Marco Martin's avatar
Marco Martin committed
74
75
76
77

    m_model = new QStandardItemModel(this);
    QHash<int, QByteArray> roles = m_model->roleNames();
    roles[PluginNameRole] = "pluginName";
78
    roles[DescriptionRole] = "description";
79
    roles[ScreenshotRole] = "screenshot";
80
    roles[FullScreenPreviewRole] = "fullScreenPreview";
Marco Martin's avatar
Marco Martin committed
81
82
83
84
85
86
87
88
89
90
    roles[HasSplashRole] = "hasSplash";
    roles[HasLockScreenRole] = "hasLockScreen";
    roles[HasRunCommandRole] = "hasRunCommand";
    roles[HasLogoutRole] = "hasLogout";

    roles[HasColorsRole] = "hasColors";
    roles[HasWidgetStyleRole] = "hasWidgetStyle";
    roles[HasIconsRole] = "hasIcons";
    roles[HasPlasmaThemeRole] = "hasPlasmaTheme";
    roles[HasCursorsRole] = "hasCursors";
91
    roles[HasWindowSwitcherRole] = "hasWindowSwitcher";
92
    roles[HasDesktopSwitcherRole] = "hasDesktopSwitcher";
Marco Martin's avatar
Marco Martin committed
93
    m_model->setItemRoleNames(roles);
94
    loadModel();
Marco Martin's avatar
Marco Martin committed
95
96
}

Marco Martin's avatar
Marco Martin committed
97
98
99
100
KCMLookandFeel::~KCMLookandFeel()
{
}

101
void KCMLookandFeel::reloadModel()
Marco Martin's avatar
Marco Martin committed
102
{
103
    loadModel();
Marco Martin's avatar
Marco Martin committed
104
}
Marco Martin's avatar
Marco Martin committed
105

106
QStandardItemModel *KCMLookandFeel::lookAndFeelModel() const
Marco Martin's avatar
Marco Martin committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
{
    return m_model;
}

QString KCMLookandFeel::selectedPlugin() const
{
    return m_selectedPlugin;
}

void KCMLookandFeel::setSelectedPlugin(const QString &plugin)
{
    if (m_selectedPlugin == plugin) {
        return;
    }

122
    const bool firstTime = m_selectedPlugin.isNull();
Marco Martin's avatar
Marco Martin committed
123
124
    m_selectedPlugin = plugin;
    emit selectedPluginChanged();
125
    emit selectedPluginIndexChanged();
126
127
128
129

    if (!firstTime) {
        setNeedsSave(true);
    }
Marco Martin's avatar
Marco Martin committed
130
131
}

132
133
134
135
136
137
138
139
140
141
int KCMLookandFeel::selectedPluginIndex() const
{
    for (int i = 0; i < m_model->rowCount(); ++i) {
        if (m_model->data(m_model->index(i, 0), PluginNameRole).toString() == m_selectedPlugin) {
            return i;
        }
    }
    return -1;
}

142
QList<KPackage::Package> KCMLookandFeel::availablePackages(const QStringList &components)
143
{
144
    QList<KPackage::Package> packages;
145
    QStringList paths;
146
    const QStringList dataPaths = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation);
147

148
    paths.reserve(dataPaths.count());
149
    for (const QString &path : dataPaths) {
150
        QDir dir(path + QStringLiteral("/plasma/look-and-feel"));
151
152
153
154
        paths << dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
    }

    for (const QString &path : paths) {
155
        KPackage::Package pkg = KPackage::PackageLoader::self()->loadPackage(QStringLiteral("Plasma/LookAndFeel"));
156
        pkg.setPath(path);
157
        pkg.setFallbackPackage(KPackage::Package());
158
        if (components.isEmpty()) {
159
            packages << pkg;
160
161
162
163
164
165
166
        } else {
            for (const auto &component : components) {
                if (!pkg.filePath(component.toUtf8()).isEmpty()) {
                    packages << pkg;
                    break;
                }
            }
167
168
169
170
171
172
        }
    }

    return packages;
}

173
void KCMLookandFeel::loadModel()
Marco Martin's avatar
Marco Martin committed
174
175
176
{
    m_model->clear();

177
178
    const QList<KPackage::Package> pkgs = availablePackages({"defaults", "layouts"});
    for (const KPackage::Package &pkg : pkgs) {
Marco Martin's avatar
Marco Martin committed
179
180
181
        if (!pkg.metadata().isValid()) {
            continue;
        }
Marco Martin's avatar
Marco Martin committed
182
        QStandardItem* row = new QStandardItem(pkg.metadata().name());
183
184
        row->setData(pkg.metadata().pluginId(), PluginNameRole);
        row->setData(pkg.metadata().description(), DescriptionRole);
185
        row->setData(pkg.filePath("preview"), ScreenshotRole);
186
        row->setData(pkg.filePath("fullscreenpreview"), FullScreenPreviewRole);
Marco Martin's avatar
Marco Martin committed
187
188
189
190
191
192
193
194
195
196

        //What the package provides
        row->setData(!pkg.filePath("splashmainscript").isEmpty(), HasSplashRole);
        row->setData(!pkg.filePath("lockscreenmainscript").isEmpty(), HasLockScreenRole);
        row->setData(!pkg.filePath("runcommandmainscript").isEmpty(), HasRunCommandRole);
        row->setData(!pkg.filePath("logoutmainscript").isEmpty(), HasLogoutRole);

        if (!pkg.filePath("defaults").isEmpty()) {
            KSharedConfigPtr conf = KSharedConfig::openConfig(pkg.filePath("defaults"));
            KConfigGroup cg(conf, "kdeglobals");
197
            cg = KConfigGroup(&cg, "General");
Marco Martin's avatar
Marco Martin committed
198
199
200
201
            bool hasColors = !cg.readEntry("ColorScheme", QString()).isEmpty();
            if (!hasColors) {
                hasColors = !pkg.filePath("colors").isEmpty();
            }
202
            row->setData(hasColors, HasColorsRole);
203
            cg = KConfigGroup(&cg, "KDE");
Marco Martin's avatar
Marco Martin committed
204
205
206
207
208
209
210
211
212
213
214
215
            row->setData(!cg.readEntry("widgetStyle", QString()).isEmpty(), HasWidgetStyleRole);
            cg = KConfigGroup(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "Icons");
            row->setData(!cg.readEntry("Theme", QString()).isEmpty(), HasIconsRole);

            cg = KConfigGroup(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "Theme");
            row->setData(!cg.readEntry("name", QString()).isEmpty(), HasPlasmaThemeRole);

            cg = KConfigGroup(conf, "kcminputrc");
            cg = KConfigGroup(&cg, "Mouse");
            row->setData(!cg.readEntry("cursorTheme", QString()).isEmpty(), HasCursorsRole);
216
217
218
219

            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "WindowSwitcher");
            row->setData(!cg.readEntry("LayoutName", QString()).isEmpty(), HasWindowSwitcherRole);
220
221
222
223

            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "DesktopSwitcher");
            row->setData(!cg.readEntry("LayoutName", QString()).isEmpty(), HasDesktopSwitcherRole);
Marco Martin's avatar
Marco Martin committed
224
225
226
227
        }

        m_model->appendRow(row);
    }
228
    m_model->sort(0 /*column*/);
229
230
231
232
233
    emit selectedPluginIndexChanged();
}

void KCMLookandFeel::load()
{
234
    m_package = KPackage::PackageLoader::self()->loadPackage(QStringLiteral("Plasma/LookAndFeel"));
235
236
237
238
239
240
241
242
243
244
    KConfigGroup cg(KSharedConfig::openConfig(QStringLiteral("kdeglobals")), "KDE");
    const QString packageName = cg.readEntry("LookAndFeelPackage", QString());
    if (!packageName.isEmpty()) {
        m_package.setPath(packageName);
    }

    if (!m_package.metadata().isValid()) {
        return;
    }

245
    setSelectedPlugin(m_package.metadata().pluginId());
246

Anthony Fieroni's avatar
Anthony Fieroni committed
247
    setNeedsSave(false);
Marco Martin's avatar
Marco Martin committed
248
249
250
251
252
}


void KCMLookandFeel::save()
{
253
    KPackage::Package package = KPackage::PackageLoader::self()->loadPackage(QStringLiteral("Plasma/LookAndFeel"));
Marco Martin's avatar
Marco Martin committed
254
255
256
257
258
259
260
261
    package.setPath(m_selectedPlugin);

    if (!package.isValid()) {
        return;
    }

    m_configGroup.writeEntry("LookAndFeelPackage", m_selectedPlugin);

262
    if (m_resetDefaultLayout) {
263
        QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.plasmashell"), QStringLiteral("/PlasmaShell"),
264
265
266
267
268
269
270
271
272
                                                   QStringLiteral("org.kde.PlasmaShell"), QStringLiteral("loadLookAndFeelDefaultLayout"));

        QList<QVariant> args;
        args << m_selectedPlugin;
        message.setArguments(args);

        QDBusConnection::sessionBus().call(message, QDBus::NoBlock);
    }

Marco Martin's avatar
Marco Martin committed
273
274
275
276
277
278
279
280
281
282
    if (!package.filePath("defaults").isEmpty()) {
        KSharedConfigPtr conf = KSharedConfig::openConfig(package.filePath("defaults"));
        KConfigGroup cg(conf, "kdeglobals");
        cg = KConfigGroup(&cg, "KDE");
        if (m_applyWidgetStyle) {
            setWidgetStyle(cg.readEntry("widgetStyle", QString()));
        }

        if (m_applyColors) {
            QString colorsFile = package.filePath("colors");
Marco Martin's avatar
Marco Martin committed
283
284
            KConfigGroup cg(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "General");
Marco Martin's avatar
Marco Martin committed
285
            QString colorScheme = cg.readEntry("ColorScheme", QString());
Marco Martin's avatar
Marco Martin committed
286

Marco Martin's avatar
Marco Martin committed
287
288
289
290
291
292
293
            if (!colorsFile.isEmpty()) {
                if (!colorScheme.isEmpty()) {
                    setColors(colorScheme, colorsFile);
                } else {
                    setColors(package.metadata().name(), colorsFile);
                }
            } else if (!colorScheme.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
294
                colorScheme.remove(QLatin1Char('\'')); // So Foo's does not become FooS
295
                QRegExp fixer(QStringLiteral("[\\W,.-]+(.?)"));
Marco Martin's avatar
Marco Martin committed
296
                int offset;
Marco Martin's avatar
Marco Martin committed
297
                while ((offset = fixer.indexIn(colorScheme)) >= 0) {
Marco Martin's avatar
Marco Martin committed
298
                    colorScheme.replace(offset, fixer.matchedLength(), fixer.cap(1).toUpper());
Marco Martin's avatar
Marco Martin committed
299
                }
Marco Martin's avatar
Marco Martin committed
300
                colorScheme.replace(0, 1, colorScheme.at(0).toUpper());
301
302
303
304
305
306
307
308
309
310
311

                //NOTE: why this loop trough all the scheme files?
                //the scheme theme name is an heuristic, there is no plugin metadata whatsoever.
                //is based on the file name stripped from weird characters or the
                //eventual id- prefix store.kde.org puts, so we can just find a
                //theme that ends as the specified name
                bool schemeFound = false;
                const QStringList schemeDirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("color-schemes"), QStandardPaths::LocateDirectory);
                for (const QString &dir : schemeDirs) {
                    const QStringList fileNames = QDir(dir).entryList(QStringList()<<QStringLiteral("*.colors"));
                    for (const QString &file : fileNames) {
312
313
                        if (file.endsWith(colorScheme + QStringLiteral(".colors"))) {
                            setColors(colorScheme, dir + QLatin1Char('/') + file);
314
315
316
317
318
319
320
321
                            schemeFound = true;
                            break;
                        }
                    }
                    if (schemeFound) {
                        break;
                    }
                }
Marco Martin's avatar
Marco Martin committed
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
            }
        }

        if (m_applyIcons) {
            cg = KConfigGroup(conf, "kdeglobals");
            cg = KConfigGroup(&cg, "Icons");
            setIcons(cg.readEntry("Theme", QString()));
        }

        if (m_applyPlasmaTheme) {
            cg = KConfigGroup(conf, "plasmarc");
            cg = KConfigGroup(&cg, "Theme");
            setPlasmaTheme(cg.readEntry("name", QString()));
        }

        if (m_applyCursors) {
            cg = KConfigGroup(conf, "kcminputrc");
            cg = KConfigGroup(&cg, "Mouse");
            setCursorTheme(cg.readEntry("cursorTheme", QString()));
        }
342
343
344
345
346
347

        if (m_applyWindowSwitcher) {
            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "WindowSwitcher");
            setWindowSwitcher(cg.readEntry("LayoutName", QString()));
        }
348
349
350
351
352
353

        if (m_applyDesktopSwitcher) {
            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "DesktopSwitcher");
            setDesktopSwitcher(cg.readEntry("LayoutName", QString()));
        }
354
355
356
357

        if (m_applyWindowDecoration) {
            cg = KConfigGroup(conf, "kwinrc");
            cg = KConfigGroup(&cg, "org.kde.kdecoration2");
358
#ifdef HAVE_BREEZE_DECO
359
360
361
362
363
364
365
366
367
368
369
370
371
            setWindowDecoration(cg.readEntry("library", QStringLiteral(BREEZE_KDECORATION_PLUGIN_ID)), cg.readEntry("theme", QString()));
#else
            setWindowDecoration(cg.readEntry("library", QStringLiteral("org.kde.kwin.aurorae")), cg.readEntry("theme", QString()));
#endif
        }

        // Reload KWin if something changed, but only once.
        if (m_applyWindowSwitcher || m_applyDesktopSwitcher || m_applyWindowDecoration) {
            QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KWin"),
                                                    QStringLiteral("org.kde.KWin"),
                                                    QStringLiteral("reloadConfig"));
            QDBusConnection::sessionBus().send(message);
        }
372
373
374
375
376
377
378
379
380

        //autostart
        if (m_resetDefaultLayout) {
            //remove all the old package to autostart
            {
                KSharedConfigPtr oldConf = KSharedConfig::openConfig(m_package.filePath("defaults"));
                cg = KConfigGroup(oldConf, QStringLiteral("Autostart"));
                const QStringList autostartServices = cg.readEntry("Services", QStringList());

381
382
383
384
385
386
387
388
                if (qEnvironmentVariableIsSet("KDE_FULL_SESSION")) {
                    for (const QString &serviceFile : autostartServices) {
                        KService service(serviceFile + QStringLiteral(".desktop"));
                        KAutostart as(serviceFile);
                        as.setAutostarts(false);
                        //FIXME: quite ugly way to stop things, and what about non KDE things?
                        QProcess::startDetached(QStringLiteral("kquitapp5"), {QStringLiteral("--service"), service.property(QStringLiteral("X-DBUS-ServiceName")).toString()});
                    }
389
390
391
392
393
394
395
396
397
398
399
400
                }
            }
            //Set all the stuff in the new lnf to autostart
            {
                cg = KConfigGroup(conf, QStringLiteral("Autostart"));
                const QStringList autostartServices = cg.readEntry("Services", QStringList());

                for (const QString &serviceFile : autostartServices) {
                    KService service(serviceFile + QStringLiteral(".desktop"));
                    KAutostart as(serviceFile);
                    as.setCommand(service.exec());
                    as.setAutostarts(true);
401
402
403
                    if (qEnvironmentVariableIsSet("KDE_FULL_SESSION")) {
                        KRun::runApplication(service, {}, nullptr);
                    }
404
405
406
                }
            }
        }
Marco Martin's avatar
Marco Martin committed
407
408
    }

409
410
411
412
    //TODO: option to enable/disable apply? they don't seem required by UI design
    setSplashScreen(m_selectedPlugin);
    setLockScreen(m_selectedPlugin);

Marco Martin's avatar
Marco Martin committed
413
    m_configGroup.sync();
414
    m_package.setPath(m_selectedPlugin);
Marco Martin's avatar
Marco Martin committed
415
    runRdb(KRdbExportQtColors | KRdbExportGtkTheme | KRdbExportColors | KRdbExportQtSettings | KRdbExportXftSettings);
Marco Martin's avatar
Marco Martin committed
416
417
418
419
}

void KCMLookandFeel::defaults()
{
420
421
422
423
    if (!m_package.metadata().isValid()) {
        return;
    }

424
    setSelectedPlugin(m_package.metadata().pluginId());
Marco Martin's avatar
Marco Martin committed
425
426
427
428
429
430
431
432
433
434
}

void KCMLookandFeel::setWidgetStyle(const QString &style)
{
    if (style.isEmpty()) {
        return;
    }

    m_configGroup.writeEntry("widgetStyle", style);
    m_configGroup.sync();
Marco Martin's avatar
Marco Martin committed
435
    //FIXME: changing style on the fly breaks QQuickWidgets
Marco Martin's avatar
Marco Martin committed
436
    KGlobalSettings::self()->emitChange(KGlobalSettings::StyleChanged);
Marco Martin's avatar
Marco Martin committed
437
438
439
440
}

void KCMLookandFeel::setColors(const QString &scheme, const QString &colorFile)
{
Marco Martin's avatar
Marco Martin committed
441
    if (scheme.isEmpty() && colorFile.isEmpty()) {
Marco Martin's avatar
Marco Martin committed
442
443
444
        return;
    }

445
    KSharedConfigPtr conf = KSharedConfig::openConfig(colorFile, KSharedConfig::CascadeConfig);
Marco Martin's avatar
Marco Martin committed
446
    foreach (const QString &grp, conf->groupList()) {
447
448
449
        KConfigGroup cg(conf, grp);
        KConfigGroup cg2(&m_config, grp);
        cg.copyTo(&cg2);
450
    }
451

452
453
454
    KConfigGroup configGroup(&m_config, "General");
    configGroup.writeEntry("ColorScheme", scheme);

455
    configGroup.sync();
456
    KGlobalSettings::self()->emitChange(KGlobalSettings::PaletteChanged);
Marco Martin's avatar
Marco Martin committed
457
458
459
460
461
462
463
464
465
466
}

void KCMLookandFeel::setIcons(const QString &theme)
{
    if (theme.isEmpty()) {
        return;
    }

    KConfigGroup cg(&m_config, "Icons");
    cg.writeEntry("Theme", theme);
Marco Martin's avatar
Marco Martin committed
467
468
469
470
471
    cg.sync();

    for (int i=0; i < KIconLoader::LastGroup; i++) {
        KIconLoader::emitChange(KIconLoader::Group(i));
    }
Marco Martin's avatar
Marco Martin committed
472
473
474
475
476
477
478
479
}

void KCMLookandFeel::setPlasmaTheme(const QString &theme)
{
    if (theme.isEmpty()) {
        return;
    }

480
    KConfig config(QStringLiteral("plasmarc"));
Marco Martin's avatar
Marco Martin committed
481
482
483
484
485
486
487
488
489
490
491
492
    KConfigGroup cg(&config, "Theme");
    cg.writeEntry("name", theme);
    cg.sync();
}

void KCMLookandFeel::setCursorTheme(const QString themeName)
{
    //TODO: use pieces of cursor kcm when moved to plasma-desktop
    if (themeName.isEmpty()) {
        return;
    }

493
    KConfig config(QStringLiteral("kcminputrc"));
Marco Martin's avatar
Marco Martin committed
494
495
496
497
498
499
500
501
    KConfigGroup cg(&config, "Mouse");
    cg.writeEntry("cursorTheme", themeName);
    cg.sync();

    // Require the Xcursor version that shipped with X11R6.9 or greater, since
    // in previous versions the Xfixes code wasn't enabled due to a bug in the
    // build system (freedesktop bug #975).
#if HAVE_XFIXES && XFIXES_MAJOR >= 2 && XCURSOR_LIB_VERSION >= 10105
502
503
    const int cursorSize = cg.readEntry("cursorSize", 0);

Marco Martin's avatar
Marco Martin committed
504
    QDir themeDir = cursorThemeDir(themeName, 0);
Marco Martin's avatar
debug--    
Marco Martin committed
505

Marco Martin's avatar
Marco Martin committed
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
    if (!themeDir.exists()) {
        return;
    }

    XCursorTheme theme(themeDir);

    if (!CursorTheme::haveXfixes()) {
        return;
    }

    // Set up the proper launch environment for newly started apps
    OrgKdeKLauncherInterface klauncher(QStringLiteral("org.kde.klauncher5"),
                                       QStringLiteral("/KLauncher"),
                                       QDBusConnection::sessionBus());
    klauncher.setLaunchEnv(QStringLiteral("XCURSOR_THEME"), themeName);

    // Update the Xcursor X resources
    runRdb(0);

    // Notify all applications that the cursor theme has changed
    KGlobalSettings::self()->emitChange(KGlobalSettings::CursorChanged);

    // Reload the standard cursors
    QStringList names;

    // Qt cursors
532
533
534
535
536
    names << QStringLiteral("left_ptr")       << QStringLiteral("up_arrow")      << QStringLiteral("cross")      << QStringLiteral("wait")
          << QStringLiteral("left_ptr_watch") << QStringLiteral("ibeam")         << QStringLiteral("size_ver")   << QStringLiteral("size_hor")
          << QStringLiteral("size_bdiag")     << QStringLiteral("size_fdiag")    << QStringLiteral("size_all")   << QStringLiteral("split_v")
          << QStringLiteral("split_h")        << QStringLiteral("pointing_hand") << QStringLiteral("openhand")
          << QStringLiteral("closedhand")     << QStringLiteral("forbidden")     << QStringLiteral("whats_this") << QStringLiteral("copy") << QStringLiteral("move") << QStringLiteral("link");
Marco Martin's avatar
Marco Martin committed
537
538

    // X core cursors
539
540
541
542
543
544
545
546
    names << QStringLiteral("X_cursor")            << QStringLiteral("right_ptr")           << QStringLiteral("hand1")
          << QStringLiteral("hand2")               << QStringLiteral("watch")               << QStringLiteral("xterm")
          << QStringLiteral("crosshair")           << QStringLiteral("left_ptr_watch")      << QStringLiteral("center_ptr")
          << QStringLiteral("sb_h_double_arrow")   << QStringLiteral("sb_v_double_arrow")   << QStringLiteral("fleur")
          << QStringLiteral("top_left_corner")     << QStringLiteral("top_side")            << QStringLiteral("top_right_corner")
          << QStringLiteral("right_side")          << QStringLiteral("bottom_right_corner") << QStringLiteral("bottom_side")
          << QStringLiteral("bottom_left_corner")  << QStringLiteral("left_side")           << QStringLiteral("question_arrow")
          << QStringLiteral("pirate");
Marco Martin's avatar
Marco Martin committed
547
548

    foreach (const QString &name, names) {
549
        XFixesChangeCursorByName(QX11Info::display(), theme.loadCursor(name, cursorSize), QFile::encodeName(name));
Marco Martin's avatar
Marco Martin committed
550
551
552
553
    }

#else
    KMessageBox::information(this,
554
                                 i18n("You have to restart the Plasma session for these changes to take effect."),
Marco Martin's avatar
Marco Martin committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
                                 i18n("Cursor Settings Changed"), "CursorSettingsChanged");
#endif
}

QDir KCMLookandFeel::cursorThemeDir(const QString &theme, const int depth)
{
    // Prevent infinite recursion
    if (depth > 10) {
        return QDir();
    }

    // Search each icon theme directory for 'theme'
    foreach (const QString &baseDir, cursorSearchPaths()) {
        QDir dir(baseDir);
        if (!dir.exists() || !dir.cd(theme)) {
            continue;
        }

        // If there's a cursors subdir, we'll assume this is a cursor theme
574
        if (dir.exists(QStringLiteral("cursors"))) {
Marco Martin's avatar
Marco Martin committed
575
576
577
578
            return dir;
        }

        // If the theme doesn't have an index.theme file, it can't inherit any themes.
579
        if (!dir.exists(QStringLiteral("index.theme"))) {
Marco Martin's avatar
Marco Martin committed
580
581
582
583
            continue;
        }

        // Open the index.theme file, so we can get the list of inherited themes
Laurent Montel's avatar
Laurent Montel committed
584
        KConfig config(dir.path() + QStringLiteral("/index.theme"), KConfig::NoGlobals);
Marco Martin's avatar
Marco Martin committed
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
        KConfigGroup cg(&config, "Icon Theme");

        // Recurse through the list of inherited themes, to check if one of them
        // is a cursor theme.
        QStringList inherits = cg.readEntry("Inherits", QStringList());
        foreach (const QString &inherit, inherits) {
            // Avoid possible DoS
            if (inherit == theme) {
                continue;
            }

            if (cursorThemeDir(inherit, depth + 1).exists()) {
                return dir;
            }
        }
    }

    return QDir();
}

const QStringList KCMLookandFeel::cursorSearchPaths()
{
    if (!m_cursorSearchPaths.isEmpty())
        return m_cursorSearchPaths;

#if XCURSOR_LIB_MAJOR == 1 && XCURSOR_LIB_MINOR < 1
    // These are the default paths Xcursor will scan for cursor themes
    QString path("~/.icons:/usr/share/icons:/usr/share/pixmaps:/usr/X11R6/lib/X11/icons");

    // If XCURSOR_PATH is set, use that instead of the default path
    char *xcursorPath = std::getenv("XCURSOR_PATH");
    if (xcursorPath)
        path = xcursorPath;
#else
    // Get the search path from Xcursor
    QString path = XcursorLibraryPath();
#endif

    // Separate the paths
624
    m_cursorSearchPaths = path.split(QLatin1Char(':'), QString::SkipEmptyParts);
Marco Martin's avatar
Marco Martin committed
625
626
627
628
629
630
631
632
633
634
635
636
637

    // Remove duplicates
    QMutableStringListIterator i(m_cursorSearchPaths);
    while (i.hasNext())
    {
        const QString path = i.next();
        QMutableStringListIterator j(i);
        while (j.hasNext())
            if (j.next() == path)
                j.remove();
    }

    // Expand all occurrences of ~/ to the home dir
638
    m_cursorSearchPaths.replaceInStrings(QRegExp(QStringLiteral("^~\\/")), QDir::home().path() + QLatin1Char('/'));
Marco Martin's avatar
Marco Martin committed
639
640
641
    return m_cursorSearchPaths;
}

642
643
644
645
646
647
void KCMLookandFeel::setSplashScreen(const QString &theme)
{
    if (theme.isEmpty()) {
        return;
    }

648
    KConfig config(QStringLiteral("ksplashrc"));
649
650
651
652
653
654
655
656
657
658
659
660
661
    KConfigGroup cg(&config, "KSplash");
    cg.writeEntry("Theme", theme);
    //TODO: a way to set none as spash in the l&f
    cg.writeEntry("Engine", "KSplashQML");
    cg.sync();
}

void KCMLookandFeel::setLockScreen(const QString &theme)
{
    if (theme.isEmpty()) {
        return;
    }

662
    KConfig config(QStringLiteral("kscreenlockerrc"));
663
664
665
666
667
    KConfigGroup cg(&config, "Greeter");
    cg.writeEntry("Theme", theme);
    cg.sync();
}

668
669
670
671
672
void KCMLookandFeel::setWindowSwitcher(const QString &theme)
{
    if (theme.isEmpty()) {
        return;
    }
673

674
    KConfig config(QStringLiteral("kwinrc"));
675
676
677
678
    KConfigGroup cg(&config, "TabBox");
    cg.writeEntry("LayoutName", theme);
    cg.sync();
}
679

680
681
682
683
684
685
void KCMLookandFeel::setDesktopSwitcher(const QString &theme)
{
    if (theme.isEmpty()) {
        return;
    }

686
    KConfig config(QStringLiteral("kwinrc"));
687
688
689
690
    KConfigGroup cg(&config, "TabBox");
    cg.writeEntry("DesktopLayout", theme);
    cg.writeEntry("DesktopListLayout", theme);
    cg.sync();
691
692
693
694
695
696
697
698
699
700
701
702
703
704
}

void KCMLookandFeel::setWindowDecoration(const QString &library, const QString &theme)
{
    if (library.isEmpty()) {
        return;
    }

    KConfig config(QStringLiteral("kwinrc"));
    KConfigGroup cg(&config, "org.kde.kdecoration2");
    cg.writeEntry("library", library);
    cg.writeEntry("theme", theme);
    
    cg.sync();
705
706
707
708
709
710
711
    // Reload KWin.
    QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KWin"),
                                                      QStringLiteral("org.kde.KWin"),
                                                      QStringLiteral("reloadConfig"));
    QDBusConnection::sessionBus().send(message);
}

712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
void KCMLookandFeel::setResetDefaultLayout(bool reset)
{
    if (m_resetDefaultLayout == reset) {
        return;
    }
    m_resetDefaultLayout = reset;
    emit resetDefaultLayoutChanged();
    if (reset) {
        setNeedsSave(true);
    }
}

bool KCMLookandFeel::resetDefaultLayout() const
{
    return m_resetDefaultLayout;
}