diff --git a/src/appearancegtk2.cpp b/src/appearancegtk2.cpp index 97da9e1..fcda469 100644 --- a/src/appearancegtk2.cpp +++ b/src/appearancegtk2.cpp @@ -1,209 +1,202 @@ /* KDE GTK Configuration Module * * Copyright 2011 José Antonio Sanchez Reynaga * Copyright 2011 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "appearancegtk2.h" #include #include #include #include #include #include #include #include #include bool AppearanceGTK2::loadSettingsPrivate(const QString& path) { QFile configFile(path); if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) return false; const QMap foundSettings = readSettingsTuples(&configFile); for(auto it = foundSettings.constBegin(), itEnd = foundSettings.constEnd(); it!=itEnd; ++it) { if (it.key() == "gtk-theme-name") m_settings["theme"] = *it; - else if (it.key() == "gtk-primary-button-warps-slider") - m_settings["primary_button_warps_slider"] = *it; } return true; } QString AppearanceGTK2::themesGtkrcFile(const QString& themeName) const { QStringList themes=installedThemes(); themes=themes.filter(QRegExp("/"+themeName+"/?$")); if(themes.size()==1) { QDirIterator it(themes.first(), QDirIterator::Subdirectories); while(it.hasNext()) { it.next(); if(it.fileName()=="gtkrc") { // qDebug() << "\tgtkrc file found at : " << it.filePath(); return it.filePath(); } } } return QString(); } bool AppearanceGTK2::saveSettingsPrivate(const QString& gtkrcFile) const { QFile gtkrc{gtkrcFile}; if (gtkrc.open(QIODevice::ReadWrite | QIODevice::Text)) { QString fileContents{gtkrc.readAll()}; modifyGtkrcContents(fileContents); gtkrc.remove(); gtkrc.open(QIODevice::WriteOnly | QIODevice::Text); gtkrc.write(fileContents.toUtf8()); if (QFileInfo(gtkrc).filePath() == defaultConfigFile()) { QProcess::startDetached(QStandardPaths::findExecutable("reload_gtk_apps", {CMAKE_INSTALL_FULL_LIBEXECDIR})); } return true; } else { qWarning() << "There was unable to write the .gtkrc-2.0 file"; return false; } } void AppearanceGTK2::modifyGtkrcContents(QString& fileContents) const { modifyGtkrcProperty("gtk-theme-name", m_settings["theme"], fileContents); removeGtkrcLegacyContents(fileContents); } void AppearanceGTK2::modifyGtkrcProperty(const QString& propertyName, const QString& newValue, QString& fileContents) const { const QRegularExpression regExp{propertyName + "=[^\n]*($|\n)"}; static const QStringList nonStringProperties{ "gtk-toolbar-style", "gtk-menu-images", "gtk-button-images", "gtk-primary-button-warps-slider", }; QString newConfigString; if (nonStringProperties.contains(propertyName)) { newConfigString = propertyName + "=" + newValue + "\n"; } else { newConfigString = propertyName + "=\"" + newValue + "\"\n"; } if (fileContents.contains(regExp)) { fileContents.replace(regExp, newConfigString); } else { fileContents = newConfigString + "\n" + fileContents; } } void AppearanceGTK2::removeGtkrcLegacyContents(QString &fileContents) const { // Remove "include" lines // Example: // include "/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc" static const QRegularExpression includeRegExp(QStringLiteral("include .*\n")); fileContents.remove(includeRegExp); // Remove redundant font config lines // Example: // style "user-font" // { // font_name="Noto Sans Regular" // } // widget_class "*" style "user-font" static const QRegularExpression userFontStyleRegexp(QStringLiteral("style(.|\n)*{(.|\n)*}\nwidget_class.*\"user-font\"")); fileContents.remove(userFontStyleRegexp); } void AppearanceGTK2::reset() { - m_settings = QMap { - {"toolbar_style", "GTK_TOOLBAR_ICONS"}, - {"show_icons_buttons", "0"}, - {"show_icons_menus", "0"}, - {"primary_button_warps_slider", "false"} - }; + m_settings = QMap {}; } QString AppearanceGTK2::defaultConfigFile() const { return QDir::homePath()+"/.gtkrc-2.0"; } QStringList AppearanceGTK2::installedThemes() const { QFileInfoList availableThemes; foreach(const QString& themesDir, QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "themes", QStandardPaths::LocateDirectory)) { QDir root(themesDir); availableThemes += root.entryInfoList(QDir::NoDotAndDotDot|QDir::AllDirs); } //Check if there are themes installed by the user QDir user(QDir::homePath()+"/.themes"); availableThemes += user.entryInfoList(QDir::NoDotAndDotDot|QDir::AllDirs); //we just want actual themes QStringList paths; for(QFileInfoList::const_iterator it=availableThemes.constBegin(); it!=availableThemes.constEnd(); ++it) { bool hasGtkrc = QDir(it->filePath()).exists("gtk-2.0"); //If it doesn't exist, we don't want it on the list if(hasGtkrc) paths += it->filePath(); } return paths; } bool AppearanceGTK2::loadSettings() { reset(); bool b = loadSettingsPrivate("/etc/gtk-2.0/gtkrc"); b |= loadSettingsPrivate(defaultConfigFile()); return b; } bool AppearanceGTK2::saveSettings() const { return saveSettings(defaultConfigFile()); } bool AppearanceGTK2::loadSettings(const QString& gtkrcFile) { reset(); return loadSettingsPrivate(gtkrcFile); } bool AppearanceGTK2::saveSettings(const QString& gtkrcFile) const { return saveSettingsPrivate(gtkrcFile); } diff --git a/src/appearancegtk3.cpp b/src/appearancegtk3.cpp index 7c8589a..038caaf 100644 --- a/src/appearancegtk3.cpp +++ b/src/appearancegtk3.cpp @@ -1,157 +1,155 @@ /* KDE GTK Configuration Module * * Copyright 2011 José Antonio Sanchez Reynaga * Copyright 2011 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "appearancegtk3.h" #include #include #include #include #include #include #undef signals #include #include #define signals Q_SIGNALS QStringList AppearanceGTK3::installedThemes() const { QFileInfoList availableThemes; foreach(const QString& themesDir, QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "themes", QStandardPaths::LocateDirectory)) { QDir root(themesDir); availableThemes += root.entryInfoList(QDir::NoDotAndDotDot|QDir::AllDirs); } //Also show the user-installed themes QDir user(QDir::homePath()+"/.themes"); availableThemes += user.entryInfoList(QDir::NoDotAndDotDot|QDir::AllDirs); //we just want actual themes QStringList themes; // Check that the theme contains a gtk-3.* subdirectory QStringList gtk3SubdirPattern{QStringLiteral("gtk-3.*")}; for(QFileInfoList::const_iterator it=availableThemes.constBegin(); it!=availableThemes.constEnd(); ++it) { QDir themeDir(it->filePath()); if(!themeDir.entryList(gtk3SubdirPattern, QDir::Dirs).isEmpty()) themes += it->filePath(); } return themes; } bool AppearanceGTK3::saveSettings(const KSharedConfig::Ptr& file) const { KConfigGroup group(file, "Settings"); group.writeEntry("gtk-theme-name", m_settings["theme"]); group.writeEntry("gtk-application-prefer-dark-theme", m_settings["application_prefer_dark_theme"]); const bool sync = group.sync(); Q_ASSERT(sync); return true; } bool AppearanceGTK3::loadSettings(const KSharedConfig::Ptr& file) { KConfigGroup group(file, "Settings"); if (!file || !group.isValid()) { qWarning() << "Cannot open the GTK3 config file" << file; return false; } m_settings = QMap { - {"primary_button_warps_slider", "false"}, {"application_prefer_dark_theme", "false"} }; m_settings["theme"] = group.readEntry("gtk-theme-name"); - m_settings["primary_button_warps_slider"] = group.readEntry("gtk-primary-button-warps-slider"); m_settings["application_prefer_dark_theme"] = group.readEntry("gtk-application-prefer-dark-theme"); for(auto it = m_settings.begin(); it != m_settings.end(); ) { if (it.value().isEmpty()) it = m_settings.erase(it); else ++it; } return true; } QString AppearanceGTK3::configFileName() const { return QStringLiteral("gtk-3.0/settings.ini"); } QString AppearanceGTK3::defaultConfigFile() const { QString root = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation); if(root.isEmpty()) root = QFileInfo(QDir::home(), ".config").absoluteFilePath(); return root + '/' + configFileName(); } bool AppearanceGTK3::getApplicationPreferDarkTheme() const { return m_settings["application_prefer_dark_theme"] == "1" || m_settings["application_prefer_dark_theme"] == "true"; } void AppearanceGTK3::setApplicationPreferDarkTheme(const bool& enable) { m_settings["application_prefer_dark_theme"] = enable ? "true" : "false"; } bool AppearanceGTK3::saveSettings(const QString& file) const { auto cfg = KSharedConfig::openConfig(file, KConfig::NoGlobals); return saveSettings(cfg); } bool AppearanceGTK3::loadSettings(const QString& path) { auto cfg = KSharedConfig::openConfig(path, KConfig::NoGlobals); return loadSettings(cfg); } bool AppearanceGTK3::loadSettings() { auto cfg = KSharedConfig::openConfig(configFileName(), KConfig::NoGlobals); return loadSettings(cfg); } bool AppearanceGTK3::saveSettings() const { // FIXME kdebz#387417 // We should maybe use GSettings everywhere in future, but at this moment we // need this to have this configuration available in sandboxed applications which // is only possible through dconf gtk_init(nullptr, nullptr); g_autoptr(GSettings) gsettings = g_settings_new("org.gnome.desktop.interface"); g_settings_set_string(gsettings, "gtk-theme", m_settings["theme"].toUtf8().constData()); g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", getApplicationPreferDarkTheme(), nullptr); auto cfg = KSharedConfig::openConfig(configFileName(), KConfig::NoGlobals); return saveSettings(cfg); } diff --git a/src/gtkconfigkcmodule.cpp b/src/gtkconfigkcmodule.cpp index 124c7c5..de7956f 100644 --- a/src/gtkconfigkcmodule.cpp +++ b/src/gtkconfigkcmodule.cpp @@ -1,388 +1,387 @@ /* KDE GTK Configuration Module * * Copyright 2011 José Antonio Sanchez Reynaga * Copyright 2011 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "gtkconfigkcmodule.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "ui_gui.h" #include "abstractappearance.h" #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(GTKConfigKCModuleFactory, "kde-gtk-config.json", registerPlugin();) GTKConfigKCModule::GTKConfigKCModule(QWidget* parent, const QVariantList& args ) : KCModule(parent) , ui(new Ui::GUI) , installer(0) , uninstaller(0) , m_saveEnabled(true) { Q_UNUSED(args); KAboutData *acercade = new KAboutData("cgc", i18n("GTK Application Style"), PROJECT_VERSION, QString(), KAboutLicense::LGPL_V3, i18n("Copyright 2011 José Antonio Sánchez Reynaga")); acercade->addAuthor(i18n("José Antonio Sánchez Reynaga (antonioJASR)"),i18n("Main Developer"), "joanzare@gmail.com"); acercade->addAuthor(i18n("Aleix Pol i Gonzalez"), i18n("Feature development. Previews, code refactoring."), "aleixpol@blue-systems.com"); acercade->addCredit(i18n("Manuel Tortosa (manutortosa)"), i18n("Ideas, tester, internationalization")); acercade->addCredit(i18n("Adrián Chaves Fernández (Gallaecio)"), i18n("Internationalization")); setAboutData(acercade); setButtons(KCModule::Default | KCModule::Apply); ui->setupUi(this); appareance = new AppearenceGTK; m_tempGtk2Preview = QStandardPaths::writableLocation(QStandardPaths::TempLocation)+ "/gtkrc-2.0"; m_tempGtk3Preview = QStandardPaths::writableLocation(QStandardPaths::TempLocation)+ "/.config/gtk-3.0/settings.ini"; const QIcon previewIcon = QIcon::fromTheme("document-preview"); ui->gtk2Preview->setIcon(previewIcon); ui->gtk3Preview->setIcon(previewIcon); QString gtk2Preview = QStandardPaths::findExecutable("gtk_preview", {CMAKE_INSTALL_FULL_LIBEXECDIR}); QString gtk3Preview = QStandardPaths::findExecutable("gtk3_preview", {CMAKE_INSTALL_FULL_LIBEXECDIR}); m_p2 = new KProcess(this); m_p2->setEnv("GTK2_RC_FILES", m_tempGtk2Preview, true); if(!gtk2Preview.isEmpty()) { *m_p2 << gtk2Preview; connect(m_p2, SIGNAL(finished(int)), this, SLOT(untogglePreview())); } m_p3 = new KProcess(this); m_p3->setEnv("XDG_CONFIG_HOME", QStandardPaths::writableLocation(QStandardPaths::TempLocation)+"/.config"); if(!gtk3Preview.isEmpty()) { *m_p3 << gtk3Preview; connect(m_p3, SIGNAL(finished(int)), this, SLOT(untogglePreview())); } ui->gtk2Preview->setVisible(!gtk2Preview.isEmpty()); ui->gtk3Preview->setVisible(!gtk3Preview.isEmpty()); //UI changes connect(ui->cb_theme, SIGNAL(currentIndexChanged(int)), this, SLOT(appChanged())); connect(ui->cb_theme_gtk3, SIGNAL(currentIndexChanged(int)), this, SLOT(appChanged())); connect(ui->checkBox_theme_gtk3_prefer_dark, &QAbstractButton::clicked, this, >KConfigKCModule::appChanged); - connect(ui->buttonGroup_primary_button_warps_slider, SIGNAL(buttonToggled(QAbstractButton*, bool)), this, SLOT(appChanged())); //preview updates connect(ui->gtk2Preview, &QAbstractButton::clicked, this, >KConfigKCModule::runGtk2IfNecessary); connect(ui->gtk3Preview, &QAbstractButton::clicked, this, >KConfigKCModule::runGtk3IfNecessary); QMenu* m = new QMenu(this); m->addAction(QIcon::fromTheme("get-hot-new-stuff"), i18n("Download GTK2 themes..."), this, >KConfigKCModule::showThemeGHNS); m->addAction(QIcon::fromTheme("get-hot-new-stuff"), i18n("Download GTK3 themes..."), this, >KConfigKCModule::installThemeGTK3GHNS); m->addAction(QIcon::fromTheme("archive-insert"), i18n("Install a local theme..."), this, >KConfigKCModule::showDialogForInstall); m->addAction(QIcon::fromTheme("archive-remove"), i18n("Uninstall a local theme..."), this, >KConfigKCModule::showDialogForUninstall); ui->newThemes->setMenu(m); ui->newThemes->setIcon(QIcon::fromTheme("get-hot-new-stuff")); } GTKConfigKCModule::~GTKConfigKCModule() { m_p2->kill(); m_p3->kill(); QFile::remove(m_tempGtk2Preview); QFile::remove(m_tempGtk3Preview); delete appareance; m_p2->waitForFinished(); m_p3->waitForFinished(); delete ui; } void GTKConfigKCModule::syncUI() { appareance->setThemeGtk3(ui->cb_theme_gtk3->currentText()); appareance->setTheme(ui->cb_theme->currentText()); appareance->setApplicationPreferDarkTheme(ui->checkBox_theme_gtk3_prefer_dark->isChecked()); } void GTKConfigKCModule::showThemeGHNS() { KNS3::DownloadDialog d("cgctheme.knsrc", this); if(d.exec()) { refreshLists(); } } void GTKConfigKCModule::installThemeGTK3GHNS() { KNS3::DownloadDialog d("cgcgtk3.knsrc", this); if(d.exec()) { refreshLists(); } } void GTKConfigKCModule::refreshLists() { refreshThemesUi(true); } void GTKConfigKCModule::appChanged() { if (m_loading) return; savePreviewConfig(); emit changed(true); } void GTKConfigKCModule::savePreviewConfig() { if(!m_saveEnabled || !(ui->gtk2Preview->isChecked() || ui->gtk3Preview->isChecked())) return; // qDebug() << "saving UI..."; syncUI(); if(ui->gtk3Preview->isChecked()) { //we don't want to recursively loop between savePreviewConfig and runIfNecessary m_saveEnabled = false; m_p3->kill(); appareance->gtk3Appearance()->saveSettings(m_tempGtk3Preview); //need to make sure runIfNecessary() to know that it's not running m_p3->waitForFinished(); m_p3->start(); ui->gtk3Preview->setChecked(true); m_saveEnabled = true; } else if(ui->gtk2Preview->isChecked()) { appareance->gtk2Appearance()->saveSettings(m_tempGtk2Preview); } } void GTKConfigKCModule::runGtk2IfNecessary(bool checked) { KProcess* p = m_p2; KProcess* np = m_p3; if(checked) { np->kill(); np->waitForFinished(); savePreviewConfig(); if(p->state() == QProcess::NotRunning) p->start(); } else { p->kill(); p->waitForFinished(); } } void GTKConfigKCModule::runGtk3IfNecessary(bool checked) { KProcess* p = m_p3; KProcess* np = m_p2; if(checked) { np->kill(); np->waitForFinished(); savePreviewConfig(); if(p->state() == QProcess::NotRunning) p->start(); } else { p->kill(); p->waitForFinished(); } } void GTKConfigKCModule::save() { /* qDebug() << "******************************************* INSTALLATION :\n" << "theme : " << appareance->getTheme() << "\n" << "themeGTK3 : " << appareance->getThemeGtk3() << "\n" << "********************************************************"; */ syncUI(); if(!appareance->saveFileConfig()) KMessageBox::error(this, i18n("Failed to save configuration.")); } void setComboItem(QComboBox* combo, const QStringList& texts) { foreach(const QString& text, texts) { int pos = combo->findText(text); if(pos>=0) { combo->setCurrentIndex(pos); return; } } } void GTKConfigKCModule::defaults() { refreshThemesUi(false); // qDebug() << "loading defaults..."; m_saveEnabled = false; setComboItem(ui->cb_theme, QStringList("oxygen-gtk") << "Clearlooks"); setComboItem(ui->cb_theme_gtk3, QStringList("oxygen-gtk") << "Adwaita"); m_saveEnabled = true; appChanged(); } void GTKConfigKCModule::load() { m_saveEnabled = false; bool someCorrect = appareance->loadFileConfig(); m_loading = true; if(someCorrect) { refreshLists(); } else { defaults(); } m_loading = false; m_saveEnabled = true; } class MyStringListModel : public QAbstractListModel { public: MyStringListModel(const QStringList &texts, QObject* parent) : QAbstractListModel(parent), m_texts(texts) { } QVariant data(const QModelIndex & index, int role) const override { if (role != Qt::DisplayRole || !index.isValid() || index.row()>=m_texts.count()) return {}; return m_texts[index.row()]; } int rowCount(const QModelIndex & parent) const override { return parent.isValid() ? 0 : m_texts.count(); } void setStrings(const QSet &list) { const auto current = m_texts.toSet(); const auto oldRows = QSet(current).subtract(list); const auto newRows = QSet(list).subtract(current); if (!newRows.isEmpty()) { beginInsertRows({}, m_texts.count(), m_texts.count() + newRows.count()); m_texts += newRows.toList(); endInsertRows(); } int from = -1; for(const auto &row: oldRows) { for(; from(combo->model()); if (!model) { combo->setModel(new MyStringListModel(texts, combo)); } else { model->setStrings(texts.toSet()); } const int idx = combo->findText(temp); combo->setCurrentIndex(qMax(0, idx)); } void GTKConfigKCModule::refreshThemesUi(bool useConfig) { //theme gtk2 bool wasenabled = m_saveEnabled; m_saveEnabled = false; refreshComboSameCurrentValue(ui->cb_theme, useConfig ? appareance->getTheme() : ui->cb_theme->currentText(), appareance->gtk2Appearance()->installedThemesNames()); //theme gtk3 refreshComboSameCurrentValue(ui->cb_theme_gtk3, useConfig ? appareance->getThemeGtk3() : ui->cb_theme_gtk3->currentText(), appareance->gtk3Appearance()->installedThemesNames()); // dark theme for gtk3 ui->checkBox_theme_gtk3_prefer_dark->setChecked(appareance->getApplicationPreferDarkTheme()); m_saveEnabled = wasenabled; emit changed(true); } void GTKConfigKCModule::showDialogForInstall() { if(!installer) { installer = new DialogInstaller(this); connect(installer, &DialogInstaller::themeInstalled, this, >KConfigKCModule::refreshLists); } installer->exec(); refreshThemesUi(); } void GTKConfigKCModule::showDialogForUninstall() { if(!uninstaller) { uninstaller = new DialogUninstaller(this, appareance); connect(uninstaller, &DialogUninstaller::themeUninstalled, this, >KConfigKCModule::refreshLists); } uninstaller->refreshListsForUninstall(); uninstaller->exec(); refreshThemesUi(); } void GTKConfigKCModule::untogglePreview() { if(sender()==m_p2) ui->gtk2Preview->setChecked(false); else ui->gtk3Preview->setChecked(false); } #include "gtkconfigkcmodule.moc"