diff --git a/CMakeLists.txt b/CMakeLists.txt
index 99aac5d..8410f4d 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,107 +1,109 @@
cmake_minimum_required(VERSION 3.0)
project(KDE-CLI-Tools)
set(PROJECT_VERSION "5.13.80")
set(QT_MIN_VERSION "5.9.0")
set(KF5_MIN_VERSION "5.42.0")
find_package(ECM ${KF5_MIN_VERSION} REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR})
include(KDEInstallDirs)
include(KDECMakeSettings)
include(KDECompilerSettings NO_POLICY_SCOPE)
include(ECMMarkAsTest)
include(ECMMarkNonGuiExecutable)
include(FeatureSummary)
include(CheckIncludeFile)
include(CheckIncludeFiles)
include(CheckSymbolExists)
include(ECMOptionalAddSubdirectory)
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
Widgets
Svg
DBus
)
find_package(Qt5Test ${QT_MIN_VERSION} CONFIG QUIET)
set_package_properties(Qt5Test PROPERTIES
PURPOSE "Required for tests"
TYPE OPTIONAL
)
add_feature_info("Qt5Test" Qt5Test_FOUND "Required for building tests")
if (NOT Qt5Test_FOUND)
set(BUILD_TESTING OFF CACHE BOOL "Build the testing tree.")
endif()
find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS
Config
DocTools
IconThemes
Init
I18n
KCMUtils
KIO
Service
WindowSystem
Activities
OPTIONAL_COMPONENTS
Su
QUIET
)
-
+add_definitions("-DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_TO_ASCII")
+add_definitions(-DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT)
+add_definitions(-DQT_NO_URL_CAST_FROM_STRING)
find_package(LibKWorkspace ${PROJECT_VERSION} REQUIRED)
# Disables automatic conversions from QString (or char *) to QUrl.
add_definitions(-DQT_NO_URL_CAST_FROM_STRING)
find_package(X11)
find_package(XCB COMPONENTS XCB)
if(X11_FOUND AND XCB_XCB_FOUND)
set(HAVE_X11 1)
find_package(Qt5X11Extras ${QT_MIN_VERSION} CONFIG)
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_subdirectory(doc)
add_subdirectory(kcmshell)
add_subdirectory(keditfiletype)
add_subdirectory(kmimetypefinder)
add_subdirectory(ktraderclient)
add_subdirectory(kioclient)
add_subdirectory(ksvgtopng)
if(Qt5X11Extras_FOUND)
add_subdirectory(kstart)
endif()
if(KF5Su_FOUND)
add_subdirectory(kdesu)
endif()
if(UNIX)
add_subdirectory(kdeeject)
add_subdirectory(kbroadcastnotification)
endif()
check_include_files(sys/wait.h HAVE_SYS_WAIT_H)
check_include_file("sys/prctl.h" HAVE_SYS_PRCTL_H)
check_symbol_exists(PR_SET_DUMPABLE "sys/prctl.h" HAVE_PR_SET_DUMPABLE)
check_include_file("sys/procctl.h" HAVE_SYS_PROCCTL_H)
check_symbol_exists(PROC_TRACE_CTL "sys/procctl.h" HAVE_PROC_TRACE_CTL)
if (HAVE_PR_SET_DUMPABLE OR HAVE_PROC_TRACE_CTL)
set(CAN_DISABLE_PTRACE TRUE)
endif()
add_feature_info("prctl-dumpable"
CAN_DISABLE_PTRACE
"Required for disallowing ptrace on kdesu process")
configure_file (config-kde-cli-tools.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-kde-cli-tools.h )
feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
diff --git a/kbroadcastnotification/main.cpp b/kbroadcastnotification/main.cpp
index e250547..a2dad07 100644
--- a/kbroadcastnotification/main.cpp
+++ b/kbroadcastnotification/main.cpp
@@ -1,113 +1,113 @@
/*
* Copyright 2016 Kai Uwe Broulik
*
* 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) 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 14 of version 3 of the license.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
KLocalizedString::setApplicationDomain("kbroadcastnotification");
- KAboutData aboutData("kbroadcastnotification", i18n("Broadcast Notifications"),
- PROJECT_VERSION,
+ KAboutData aboutData(QStringLiteral("kbroadcastnotification"), i18n("Broadcast Notifications"),
+ QLatin1String(PROJECT_VERSION),
i18n("A tool that emits a notification for all users by sending it on the system DBus"),
KAboutLicense::GPL,
i18n("(c) 2016 Kai Uwe Broulik"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
QCommandLineOption applicationNameOption(QStringLiteral("application"), i18n("Name of the application that should be associated with this notification"), QStringLiteral("application"));
parser.addOption(applicationNameOption);
QCommandLineOption summaryOption(QStringLiteral("summary"), i18n("A brief one-line summary of the notification"), QStringLiteral("summary"));
parser.addOption(summaryOption);
QCommandLineOption iconOption(QStringLiteral("icon"), i18n("Icon for the notification"), QStringLiteral("icon"));
parser.addOption(iconOption);
QCommandLineOption uidsOption(QStringLiteral("uids"), i18n("A comma-separated list of user IDs this notification should be sent to. If omitted, the notification will be sent to all users."), QStringLiteral("uids"));
parser.addOption(uidsOption);
QCommandLineOption timeoutOption(QStringLiteral("timeout"), i18n("Timeout for the notification"), QStringLiteral("timeout"));
parser.addOption(timeoutOption);
QCommandLineOption persistentOption(QStringLiteral("persistent"), i18n("Keep the notification in the history until the user closes it"));
parser.addOption(persistentOption);
parser.addPositionalArgument(QStringLiteral("body"), i18n("The actual notification body text"));
parser.process(app);
aboutData.processCommandLine(&parser);
QVariantMap properties;
if (parser.isSet(applicationNameOption)) {
properties.insert(QStringLiteral("appName"), parser.value(applicationNameOption));
}
if (parser.isSet(summaryOption)) {
properties.insert(QStringLiteral("summary"), parser.value(summaryOption));
}
if (parser.isSet(iconOption)) {
properties.insert(QStringLiteral("appIcon"), parser.value(iconOption));
}
if (parser.isSet(uidsOption)) {
const QStringList &uids = parser.value(uidsOption).split(QLatin1Char(','), QString::SkipEmptyParts);
if (!uids.isEmpty()) {
properties.insert(QStringLiteral("uids"), uids);
}
}
if (parser.isSet(timeoutOption)) {
bool ok;
const int timeout = parser.value(timeoutOption).toInt(&ok);
if (ok) {
properties.insert(QStringLiteral("timeout"), timeout);
}
}
if (parser.isSet(persistentOption)) { // takes precedence over timeout if both are set
properties.insert(QStringLiteral("timeout"), 0); // 0 = persistent, -1 = server default
}
const auto &positionalArgs = parser.positionalArguments();
if (positionalArgs.count() == 1) {
properties.insert(QStringLiteral("body"), positionalArgs.first());
}
if (properties.isEmpty()) {
parser.showHelp(1); // never returns
}
QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/org/kde/kbroadcastnotification"),
QStringLiteral("org.kde.BroadcastNotifications"),
QStringLiteral("Notify"));
message.setArguments({properties});
QDBusConnection::systemBus().send(message);
// FIXME can we detect that the message was sent to the bus?
QTimer::singleShot(500, &app, QCoreApplication::quit);
return app.exec();
}
diff --git a/kcmshell/main.cpp b/kcmshell/main.cpp
index de4d301..f73b0a5 100644
--- a/kcmshell/main.cpp
+++ b/kcmshell/main.cpp
@@ -1,330 +1,330 @@
/*
Copyright (c) 1999 Matthias Hoelzer-Kluepfel
Copyright (c) 2000 Matthias Elter
Copyright (c) 2004 Frans Englich
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.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include
#include "main.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
KService::List m_modules;
static bool caseInsensitiveLessThan(const KService::Ptr s1, const KService::Ptr s2)
{
const int compare = QString::compare(s1->desktopEntryName(),
s2->desktopEntryName(),
Qt::CaseInsensitive);
return (compare < 0);
}
static void listModules()
{
// First condition is what systemsettings does, second what kinfocenter does, make sure this is kept in sync
// We need the exist calls because otherwise the trader language aborts if the property doesn't exist and the second part of the or is not evaluated
const KService::List services = KServiceTypeTrader::self()->query( QStringLiteral("KCModule"), QStringLiteral("(exist [X-KDE-System-Settings-Parent-Category] and [X-KDE-System-Settings-Parent-Category] != '') or (exist [X-KDE-ParentApp] and [X-KDE-ParentApp] == 'kinfocenter')") );
for( KService::List::const_iterator it = services.constBegin(); it != services.constEnd(); ++it) {
const KService::Ptr s = (*it);
if (!KAuthorized::authorizeControlModule(s->menuId()))
continue;
m_modules.append(s);
}
- qStableSort(m_modules.begin(), m_modules.end(), caseInsensitiveLessThan);
+ std::stable_sort(m_modules.begin(), m_modules.end(), caseInsensitiveLessThan);
}
static KService::Ptr locateModule(const QString& module)
{
QString path = module;
if (!path.endsWith(QLatin1String(".desktop")))
- path += ".desktop";
+ path += QStringLiteral(".desktop");
KService::Ptr service = KService::serviceByStorageId( path );
if (!service) {
return KService::Ptr();
}
- if (!service->hasServiceType("KCModule")) {
+ if (!service->hasServiceType(QStringLiteral("KCModule"))) {
// Not a KCModule. E.g. "kcmshell5 akonadi" finds services/kresources/kabc/akonadi.desktop, unrelated.
return KService::Ptr();
}
if (service->noDisplay()) {
qDebug() << module << "should not be loaded.";
return KService::Ptr();
}
return service;
}
bool KCMShell::isRunning()
{
const QString owner = QDBusConnection::sessionBus().interface()->serviceOwner(m_serviceName);
if (owner == QDBusConnection::sessionBus().baseService()) {
return false; // We are the one and only.
}
qDebug() << "kcmshell5 with modules '" << m_serviceName << "' is already running.";
- QDBusInterface iface(m_serviceName, "/KCModule/dialog", "org.kde.KCMShellMultiDialog");
- QDBusReply reply = iface.call("activate", KStartupInfo::startupId());
+ QDBusInterface iface(m_serviceName, QStringLiteral("/KCModule/dialog"), QStringLiteral("org.kde.KCMShellMultiDialog"));
+ QDBusReply reply = iface.call(QStringLiteral("activate"), KStartupInfo::startupId());
if (!reply.isValid())
{
qDebug() << "Calling D-Bus function dialog::activate() failed.";
return false; // Error, we have to do it ourselves.
}
return true;
}
KCMShellMultiDialog::KCMShellMultiDialog(KPageDialog::FaceType dialogFace, QWidget *parent)
: KCMultiDialog(parent)
{
setFaceType(dialogFace);
setModal(false);
- QDBusConnection::sessionBus().registerObject("/KCModule/dialog", this, QDBusConnection::ExportScriptableSlots);
+ QDBusConnection::sessionBus().registerObject(QStringLiteral("/KCModule/dialog"), this, QDBusConnection::ExportScriptableSlots);
connect(this, &KCMShellMultiDialog::currentPageChanged,
this, [this](KPageWidgetItem *newPage,KPageWidgetItem *oldPage) {
Q_UNUSED(oldPage);
KCModuleProxy *activeModule = newPage->widget()->findChild();
if (activeModule) {
- KActivities::ResourceInstance::notifyAccessed(QUrl("kcm:" + activeModule->moduleInfo().service()->storageId()),
- "org.kde.systemsettings");
+ KActivities::ResourceInstance::notifyAccessed(QUrl(QStringLiteral("kcm:") + activeModule->moduleInfo().service()->storageId()),
+ QStringLiteral("org.kde.systemsettings"));
}
});
}
void KCMShellMultiDialog::activate(const QByteArray& asn_id)
{
#ifdef HAVE_X11
KStartupInfo::setNewStartupId(this, asn_id);
#endif
}
void KCMShell::setServiceName(const QString &dbusName)
{
m_serviceName = QLatin1String( "org.kde.kcmshell_" ) + dbusName;
QDBusConnection::sessionBus().registerService(m_serviceName);
}
void KCMShell::waitForExit()
{
QDBusServiceWatcher *watcher = new QDBusServiceWatcher(this);
watcher->setConnection(QDBusConnection::sessionBus());
watcher->setWatchMode(QDBusServiceWatcher::WatchForOwnerChange);
watcher->addWatchedService(m_serviceName);
connect(watcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)),
SLOT(appExit(QString,QString,QString)));
exec();
}
void KCMShell::appExit(const QString &appId, const QString &oldName, const QString &newName)
{
Q_UNUSED(appId);
Q_UNUSED(newName);
if (!oldName.isEmpty())
{
qDebug() << "'" << appId << "' closed, quitting.";
qApp->quit();
}
}
extern "C" Q_DECL_EXPORT int kdemain(int _argc, char *_argv[])
{
const bool qpaVariable = qEnvironmentVariableIsSet("QT_QPA_PLATFORM");
KWorkSpace::detectPlatform(_argc, _argv);
KCMShell app(_argc, _argv);
if (!qpaVariable) {
// don't leak the env variable to processes we start
qunsetenv("QT_QPA_PLATFORM");
}
KLocalizedString::setApplicationDomain("kcmshell5");
app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);
- KAboutData aboutData("kcmshell5", i18n("System Settings Module"),
- PROJECT_VERSION,
+ KAboutData aboutData(QStringLiteral("kcmshell5"), i18n("System Settings Module"),
+ QLatin1String(PROJECT_VERSION),
i18n("A tool to start single system settings modules"),
KAboutLicense::GPL,
i18n("(c) 1999-2016, The KDE Developers"));
- aboutData.addAuthor(i18n("Frans Englich"), i18n("Maintainer"), "frans.englich@kde.org");
- aboutData.addAuthor(i18n("Daniel Molkentin"), QString(), "molkentin@kde.org");
- aboutData.addAuthor(i18n("Matthias Hoelzer-Kluepfel"),QString(), "hoelzer@kde.org");
- aboutData.addAuthor(i18n("Matthias Elter"),QString(), "elter@kde.org");
- aboutData.addAuthor(i18n("Matthias Ettrich"),QString(), "ettrich@kde.org");
- aboutData.addAuthor(i18n("Waldo Bastian"),QString(), "bastian@kde.org");
+ aboutData.addAuthor(i18n("Frans Englich"), i18n("Maintainer"), QStringLiteral("frans.englich@kde.org"));
+ aboutData.addAuthor(i18n("Daniel Molkentin"), QString(), QStringLiteral("molkentin@kde.org"));
+ aboutData.addAuthor(i18n("Matthias Hoelzer-Kluepfel"),QString(), QStringLiteral("hoelzer@kde.org"));
+ aboutData.addAuthor(i18n("Matthias Elter"),QString(), QStringLiteral("elter@kde.org"));
+ aboutData.addAuthor(i18n("Matthias Ettrich"),QString(), QStringLiteral("ettrich@kde.org"));
+ aboutData.addAuthor(i18n("Waldo Bastian"),QString(), QStringLiteral("bastian@kde.org"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
parser.addOption(QCommandLineOption(QStringLiteral("list"), i18n("List all possible modules")));
parser.addPositionalArgument(QStringLiteral("module"), i18n("Configuration module to open"));
parser.addOption(QCommandLineOption(QStringLiteral("lang"), i18n("Specify a particular language"), QLatin1String("language")));
parser.addOption(QCommandLineOption(QStringLiteral("silent"), i18n("Do not display main window")));
parser.addOption(QCommandLineOption(QStringLiteral("args"), i18n("Arguments for the module"), QLatin1String("arguments")));
parser.addOption(QCommandLineOption(QStringLiteral("icon"), i18n("Use a specific icon for the window"), QLatin1String("icon")));
parser.addOption(QCommandLineOption(QStringLiteral("caption"), i18n("Use a specific caption for the window"), QLatin1String("caption")));
parser.parse(app.arguments());
aboutData.processCommandLine(&parser);
parser.process(app);
- const QString lang = parser.value("lang");
+ const QString lang = parser.value(QStringLiteral("lang"));
if (!lang.isEmpty()) {
cout << i18n("--lang is deprecated. Please set the LANGUAGE environment variable instead").toLocal8Bit().data() << endl;
}
- if (parser.isSet("list")) {
+ if (parser.isSet(QStringLiteral("list"))) {
cout << i18n("The following modules are available:").toLocal8Bit().data() << endl;
listModules();
int maxLen=0;
for (KService::List::ConstIterator it = m_modules.constBegin(); it != m_modules.constEnd(); ++it) {
int len = (*it)->desktopEntryName().length();
if (len > maxLen)
maxLen = len;
}
for (KService::List::ConstIterator it = m_modules.constBegin(); it != m_modules.constEnd(); ++it) {
- QString entry("%1 - %2");
+ QString entry(QStringLiteral("%1 - %2"));
- entry = entry.arg((*it)->desktopEntryName().leftJustified(maxLen, ' '))
+ entry = entry.arg((*it)->desktopEntryName().leftJustified(maxLen, QLatin1Char(' ')))
.arg(!(*it)->comment().isEmpty() ? (*it)->comment()
: i18n("No description available"));
cout << entry.toLocal8Bit().data() << endl;
}
return 0;
}
if (parser.positionalArguments().count() < 1) {
parser.showHelp();
return -1;
}
QString serviceName;
KService::List modules;
for (int i = 0; i < parser.positionalArguments().count(); i++) {
const QString arg = parser.positionalArguments().at(i);
KService::Ptr service = locateModule(arg);
if (!service) {
- service = locateModule("kcm_" + arg);
+ service = locateModule(QStringLiteral("kcm_") + arg);
}
if (!service) {
- service = locateModule("kcm" + arg);
+ service = locateModule(QStringLiteral("kcm") + arg);
}
if (service) {
modules.append(service);
if (!serviceName.isEmpty()) {
- serviceName += '_';
+ serviceName += QLatin1Char('_');
}
serviceName += arg;
} else {
cerr << i18n("Could not find module '%1'. See kcmshell5 --list for the full list of modules.", arg).toLocal8Bit().constData() << endl;
}
}
/* Check if this particular module combination is already running */
app.setServiceName(serviceName);
if (app.isRunning()) {
app.waitForExit();
return 0;
}
KPageDialog::FaceType ftype = KPageDialog::Plain;
if (modules.count() < 1) {
return -1;
} else if (modules.count() > 1) {
ftype = KPageDialog::List;
}
QStringList moduleArgs;
- const QString x = parser.value("args");
- moduleArgs << x.split(QRegExp(" +"));
+ const QString x = parser.value(QStringLiteral("args"));
+ moduleArgs << x.split(QRegExp(QStringLiteral(" +")));
KCMShellMultiDialog *dlg = new KCMShellMultiDialog(ftype);
dlg->setAttribute(Qt::WA_DeleteOnClose);
- if (parser.isSet("caption")) {
- dlg->setWindowTitle(parser.value("caption"));
+ if (parser.isSet(QStringLiteral("caption"))) {
+ dlg->setWindowTitle(parser.value(QStringLiteral("caption")));
} else if (modules.count() == 1) {
dlg->setWindowTitle(modules.first()->name());
}
for (KService::List::ConstIterator it = modules.constBegin(); it != modules.constEnd(); ++it) {
dlg->addModule(*it, nullptr, moduleArgs);
}
- if (parser.isSet("icon")) {
- dlg->setWindowIcon(QIcon::fromTheme(parser.value("icon")));
- } else if (!parser.isSet("icon") && !modules.isEmpty()) {
+ if (parser.isSet(QStringLiteral("icon"))) {
+ dlg->setWindowIcon(QIcon::fromTheme(parser.value(QStringLiteral("icon"))));
+ } else if (!parser.isSet(QStringLiteral("icon")) && !modules.isEmpty()) {
const QString iconName = KCModuleInfo(modules.first()).icon();
dlg->setWindowIcon( QIcon::fromTheme(iconName) );
}
if (modules.count() == 1 && app.desktopFileName() == QLatin1String("org.kde.kcmshell5")) {
const QString path = QStandardPaths::locate(QStandardPaths::GenericDataLocation,
QStringLiteral("kservices5/%1.desktop").arg(modules.first()->desktopEntryName()));
if (!path.isEmpty()) {
app.setDesktopFileName(path);
}
}
dlg->show();
app.exec();
return 0;
}
// vim: sw=4 et sts=4
diff --git a/kdesu/kdesu.cpp b/kdesu/kdesu.cpp
index f0059aa..f359b3e 100644
--- a/kdesu/kdesu.cpp
+++ b/kdesu/kdesu.cpp
@@ -1,483 +1,483 @@
/* vi: ts=8 sts=4 sw=4
*
* This file is part of the KDE project, module kdesu.
* Copyright (C) 1998 Pietro Iglio
* Copyright (C) 1999,2000 Geert Jansen
*/
#include
#include
#include
#include
#include
#include
#include
#include
#if defined(HAVE_SYS_WAIT_H)
#include
#endif
#if HAVE_SYS_PRCTL_H
#include
#endif
#if HAVE_SYS_PROCCTL_H
#include
#include
#endif
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "sudlg.h"
#define ERR strerror(errno)
static QLoggingCategory category("org.kde.kdesu");
QByteArray command;
const char *Version = PROJECT_VERSION;
// NOTE: if you change the position of the -u switch, be sure to adjust it
// at the beginning of main()
#if 0
// D-BUS has no equivalent
QByteArray dcopNetworkId()
{
QByteArray result;
result.resize(1025);
QFile file(DCOPClient::dcopServerFile());
if (!file.open(QIODevice::ReadOnly))
return "";
int i = file.readLine(result.data(), 1024);
if (i <= 0)
return "";
result.data()[i-1] = '\0'; // strip newline
return result;
}
#endif
static int startApp(QCommandLineParser& p);
int main(int argc, char *argv[])
{
// disable ptrace
#if HAVE_PR_SET_DUMPABLE
prctl(PR_SET_DUMPABLE, 0);
#endif
#if HAVE_PROC_TRACE_CTL
int mode = PROC_TRACE_CTL_DISABLE;
procctl(P_PID, getpid(), PROC_TRACE_CTL, &mode);
#endif
QApplication app(argc, argv);
// FIXME: this can be considered a poor man's solution, as it's not
// directly obvious to a gui user. :)
// anyway, i vote against removing it even when we have a proper gui
// implementation. -- ossi
QByteArray duser = qgetenv("ADMIN_ACCOUNT");
if (duser.isEmpty())
duser = "root";
KLocalizedString::setApplicationDomain("kdesu5");
- KAboutData aboutData("kdesu", i18n("KDE su"),
- Version, i18n("Runs a program with elevated privileges."),
+ KAboutData aboutData(QStringLiteral("kdesu"), i18n("KDE su"),
+ QLatin1String(Version), i18n("Runs a program with elevated privileges."),
KAboutLicense::Artistic,
i18n("Copyright (c) 1998-2000 Geert Jansen, Pietro Iglio"));
aboutData.addAuthor(i18n("Geert Jansen"), i18n("Maintainer"),
- "jansen@kde.org", "http://www.stack.nl/~geertj/");
+ QStringLiteral("jansen@kde.org"), QStringLiteral("http://www.stack.nl/~geertj/"));
aboutData.addAuthor(i18n("Pietro Iglio"), i18n("Original author"),
- "iglio@fub.it");
- app.setWindowIcon(QIcon::fromTheme("dialog-password"));
+ QStringLiteral("iglio@fub.it"));
+ app.setWindowIcon(QIcon::fromTheme(QStringLiteral("dialog-password")));
KAboutData::setApplicationData(aboutData);
// NOTE: if you change the position of the -u switch, be sure to adjust it
// at the beginning of main()
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
- parser.addPositionalArgument("command", i18n("Specifies the command to run as separate arguments"));
- parser.addOption(QCommandLineOption("c", i18n("Specifies the command to run as one string"), "command"));
- parser.addOption(QCommandLineOption("f", i18n("Run command under target uid if is not writable"), "file"));
- parser.addOption(QCommandLineOption("u", i18n("Specifies the target uid"), "user", duser));
- parser.addOption(QCommandLineOption("n", i18n("Do not keep password")));
- parser.addOption(QCommandLineOption("s", i18n("Stop the daemon (forgets all passwords)")));
- parser.addOption(QCommandLineOption("t", i18n("Enable terminal output (no password keeping)")));
- parser.addOption(QCommandLineOption("p", i18n("Set priority value: 0 <= prio <= 100, 0 is lowest"), "prio", "50"));
- parser.addOption(QCommandLineOption("r", i18n("Use realtime scheduling")));
- parser.addOption(QCommandLineOption("noignorebutton", i18n("Do not display ignore button")));
- parser.addOption(QCommandLineOption("i", i18n("Specify icon to use in the password dialog"), "icon name"));
- parser.addOption(QCommandLineOption("d", i18n("Do not show the command to be run in the dialog")));
+ parser.addPositionalArgument(QStringLiteral("command"), i18n("Specifies the command to run as separate arguments"));
+ parser.addOption(QCommandLineOption(QStringLiteral("c"), i18n("Specifies the command to run as one string"), QStringLiteral("command")));
+ parser.addOption(QCommandLineOption(QStringLiteral("f"), i18n("Run command under target uid if is not writable"), QStringLiteral("file")));
+ parser.addOption(QCommandLineOption(QStringLiteral("u"), i18n("Specifies the target uid"), QStringLiteral("user"), QString::fromLatin1(duser)));
+ parser.addOption(QCommandLineOption(QStringLiteral("n"), i18n("Do not keep password")));
+ parser.addOption(QCommandLineOption(QStringLiteral("s"), i18n("Stop the daemon (forgets all passwords)")));
+ parser.addOption(QCommandLineOption(QStringLiteral("t"), i18n("Enable terminal output (no password keeping)")));
+ parser.addOption(QCommandLineOption(QStringLiteral("p"), i18n("Set priority value: 0 <= prio <= 100, 0 is lowest"), QStringLiteral("prio"), QStringLiteral("50")));
+ parser.addOption(QCommandLineOption(QStringLiteral("r"), i18n("Use realtime scheduling")));
+ parser.addOption(QCommandLineOption(QStringLiteral("noignorebutton"), i18n("Do not display ignore button")));
+ parser.addOption(QCommandLineOption(QStringLiteral("i"), i18n("Specify icon to use in the password dialog"), QStringLiteral("icon name")));
+ parser.addOption(QCommandLineOption(QStringLiteral("d"), i18n("Do not show the command to be run in the dialog")));
#ifdef HAVE_X11
/* KDialog originally used --embed for attaching the dialog box. However this is misleading and so we changed to --attach.
* For consistancy, we silently map --embed to --attach */
- parser.addOption(QCommandLineOption("attach", i18nc("Transient means that the kdesu app will be attached to the app specified by the winid so that it is like a dialog box rather than some separate program", "Makes the dialog transient for an X app specified by winid"), "winid"));
- parser.addOption(QCommandLineOption("embed", i18n("Embed into a window"), "winid"));
+ parser.addOption(QCommandLineOption(QStringLiteral("attach"), i18nc("Transient means that the kdesu app will be attached to the app specified by the winid so that it is like a dialog box rather than some separate program", "Makes the dialog transient for an X app specified by winid"), QStringLiteral("winid")));
+ parser.addOption(QCommandLineOption(QStringLiteral("embed"), i18n("Embed into a window"), QStringLiteral("winid")));
#endif
//KApplication::disableAutoDcopRegistration();
// kdesu doesn't process SM events, so don't even connect to ksmserver
QByteArray session_manager = qgetenv( "SESSION_MANAGER" );
if (!session_manager.isEmpty())
unsetenv( "SESSION_MANAGER" );
// but propagate it to the started app
if (!session_manager.isEmpty())
setenv( "SESSION_MANAGER", session_manager.data(), 1 );
{
#ifdef HAVE_X11
KStartupInfoId id;
id.initId();
id.setupStartupEnv(); // make DESKTOP_STARTUP_ID env. var. available again
#endif
}
parser.process(app);
aboutData.processCommandLine(&parser);
int result = startApp(parser);
if (result == 127)
{
KMessageBox::sorry(nullptr, i18n("Cannot execute command '%1'.", QString::fromLocal8Bit(command)));
}
if (result == -2)
{
KMessageBox::sorry(nullptr, i18n("Cannot execute command '%1'. It contains invalid characters.", QString::fromLocal8Bit(command)));
}
return result;
}
static int startApp(QCommandLineParser& p)
{
// Stop daemon and exit?
- if (p.isSet("s"))
+ if (p.isSet(QStringLiteral("s")))
{
KDEsuClient client;
if (client.ping() == -1)
{
qCCritical(category) << "Daemon not running -- nothing to stop\n";
p.showHelp(1);
}
if (client.stopServer() != -1)
{
qCDebug(category) << "Daemon stopped\n";
exit(0);
}
qCCritical(category) << "Could not stop daemon\n";
p.showHelp(1);
}
QString icon;
- if ( p.isSet("i"))
- icon = p.value("i");
+ if ( p.isSet(QStringLiteral("i")))
+ icon = p.value(QStringLiteral("i"));
bool prompt = true;
- if ( p.isSet("d"))
+ if ( p.isSet(QStringLiteral("d")))
prompt = false;
// Get target uid
- QByteArray user = p.value("u").toLocal8Bit();
+ QByteArray user = p.value(QStringLiteral("u")).toLocal8Bit();
QByteArray auth_user = user;
struct passwd *pw = getpwnam(user);
if (pw == nullptr)
{
qCCritical(category) << "User " << user << " does not exist\n";
p.showHelp(1);
}
bool other_uid = (getuid() != pw->pw_uid);
bool change_uid = other_uid;
if (!change_uid) {
char *cur_user = getenv("USER");
if (!cur_user)
cur_user = getenv("LOGNAME");
change_uid = (!cur_user || user != cur_user);
}
// If file is writeable, do not change uid
- QString file = p.value("f");
+ QString file = p.value(QStringLiteral("f"));
if (other_uid && !file.isEmpty())
{
- if (file.startsWith('/'))
+ if (file.startsWith(QLatin1Char('/')))
{
file = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, file);
if (file.isEmpty())
{
qCCritical(category) << "Config file not found: " << file;
p.showHelp(1);
}
}
QFileInfo fi(file);
if (!fi.exists())
{
qCCritical(category) << "File does not exist: " << file;
p.showHelp(1);
}
change_uid = !fi.isWritable();
}
// Get priority/scheduler
- QString tmp = p.value("p");
+ QString tmp = p.value(QStringLiteral("p"));
bool ok;
int priority = tmp.toInt(&ok);
if (!ok || (priority < 0) || (priority > 100))
{
qCCritical(category) << i18n("Illegal priority: %1", tmp);
p.showHelp(1);
}
int scheduler = SuProcess::SchedNormal;
- if (p.isSet("r"))
+ if (p.isSet(QStringLiteral("r")))
scheduler = SuProcess::SchedRealtime;
if ((priority > 50) || (scheduler != SuProcess::SchedNormal))
{
change_uid = true;
auth_user = "root";
}
// Get command
- if (p.isSet("c"))
+ if (p.isSet(QStringLiteral("c")))
{
- command = p.value("c").toLocal8Bit();
+ command = p.value(QStringLiteral("c")).toLocal8Bit();
// Accepting additional arguments here is somewhat weird,
// but one can conceive use cases: have a complex command with
// redirections and additional file names which need to be quoted
// safely.
}
else
{
if( p.positionalArguments().count() == 0 )
{
qCCritical(category) << i18n("No command specified.");
p.showHelp(1);
}
}
foreach(const QString& arg, p.positionalArguments())
{
command += ' ';
command += QFile::encodeName(KShell::quoteArg(arg));
}
// Don't change uid if we're don't need to.
if (!change_uid)
{
int result = system(command);
result = WEXITSTATUS(result);
return result;
}
// Check for daemon and start if necessary
bool just_started = false;
bool have_daemon = true;
KDEsuClient client;
if (!client.isServerSGID())
{
qCWarning(category) << "Daemon not safe (not sgid), not using it.\n";
have_daemon = false;
}
else if (client.ping() == -1)
{
if (client.startServer() == -1)
{
qCWarning(category) << "Could not start daemon, reduced functionality.\n";
have_daemon = false;
}
just_started = true;
}
// Try to exec the command with kdesud.
- bool keep = !p.isSet("n") && have_daemon;
- bool terminal = p.isSet("t");
- bool withIgnoreButton = !p.isSet("noignorebutton");
+ bool keep = !p.isSet(QStringLiteral("n")) && have_daemon;
+ bool terminal = p.isSet(QStringLiteral("t"));
+ bool withIgnoreButton = !p.isSet(QStringLiteral("noignorebutton"));
int winid = -1;
- bool attach = p.isSet("attach");
+ bool attach = p.isSet(QStringLiteral("attach"));
if(attach) {
- winid = p.value("attach").toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
+ winid = p.value(QStringLiteral("attach")).toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
if(!attach)
qCWarning(category) << "Specified winid to attach to is not a valid number";
- } else if(p.isSet("embed")) {
+ } else if(p.isSet(QStringLiteral("embed"))) {
/* KDialog originally used --embed for attaching the dialog box. However this is misleading and so we changed to --attach.
* For consistancy, we silently map --embed to --attach */
attach = true;
- winid = p.value("embed").toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
+ winid = p.value(QStringLiteral("embed")).toInt(&attach, 0); //C style parsing. If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.
if(!attach)
qCWarning(category) << "Specified winid to attach to is not a valid number";
}
QList env;
QByteArray options;
env << ( "DESKTOP_STARTUP_ID=" + KStartupInfo::startupId());
// TODO: Maybe should port this to XDG_*, somehow?
// if (pw->pw_uid)
// {
// // Only propagate KDEHOME for non-root users,
// // root uses KDEROOTHOME
//
// // Translate the KDEHOME of this user to the new user.
// QString kdeHome = KGlobal::dirs()->relativeLocation("home", KGlobal::dirs()->localkdedir());
// if (kdeHome[0] != '/')
// kdeHome.prepend("~/");
// else
// kdeHome.clear(); // Use default
//
// env << ("KDEHOME="+ QFile::encodeName(kdeHome));
// }
KUser u;
env << (QByteArray) ("KDESU_USER=" + u.loginName().toLocal8Bit());
if (keep && !terminal && !just_started)
{
client.setPriority(priority);
client.setScheduler(scheduler);
int result = client.exec(command, user, options, env);
if (result == 0)
{
result = client.exitCode();
return result;
}
}
// Set core dump size to 0 because we will have
// root's password in memory.
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &rlim))
{
qCCritical(category) << "rlimit(): " << ERR;
p.showHelp(1);
}
// Read configuration
KConfigGroup config(KSharedConfig::openConfig(), "Passwords");
int timeout = config.readEntry("Timeout", defTimeout);
// Check if we need a password
SuProcess proc;
proc.setUser(auth_user);
int needpw = proc.checkNeedPassword();
if (needpw < 0)
{
QString err = i18n("Su returned with an error.\n");
KMessageBox::error(nullptr, err);
p.showHelp(1);
}
if (needpw == 0)
{
keep = 0;
qDebug() << "Don't need password!!\n";
}
for (const QChar character : QString::fromLocal8Bit(command)) {
if (!character.isPrint() && character.category() != QChar::Other_Surrogate) {
return -2;
}
}
// Start the dialog
QString password;
if (needpw)
{
#ifdef HAVE_X11
KStartupInfoId id;
id.initId();
KStartupInfoData data;
data.setSilent( KStartupInfoData::Yes );
KStartupInfo::sendChange( id, data );
#endif
KDEsuDialog dlg(user, auth_user, keep && !terminal, icon, withIgnoreButton);
if (prompt)
dlg.addCommentLine(i18n("Command:"), QFile::decodeName(command));
if (defKeep)
dlg.setKeepPassword(true);
if ((priority != 50) || (scheduler != SuProcess::SchedNormal))
{
QString prio;
if (scheduler == SuProcess::SchedRealtime)
prio += i18n("realtime: ");
- prio += QString("%1/100").arg(priority);
+ prio += QStringLiteral("%1/100").arg(priority);
if (prompt)
dlg.addCommentLine(i18n("Priority:"), prio);
}
//Attach dialog
#ifdef HAVE_X11
if(attach)
KWindowSystem::setMainWindow(&dlg, (WId)winid);
#endif
int ret = dlg.exec();
if (ret == KDEsuDialog::Rejected)
{
#ifdef HAVE_X11
KStartupInfo::sendFinish( id );
#endif
p.showHelp(1);
}
if (ret == KDEsuDialog::AsUser)
change_uid = false;
password = dlg.password();
keep = dlg.keepPassword();
#ifdef HAVE_X11
data.setSilent( KStartupInfoData::No );
KStartupInfo::sendChange( id, data );
#endif
}
// Some events may need to be handled (like a button animation)
qApp->processEvents();
// Run command
if (!change_uid)
{
int result = system(command);
result = WEXITSTATUS(result);
return result;
}
else if (keep && have_daemon)
{
client.setPass(password.toLocal8Bit(), timeout);
client.setPriority(priority);
client.setScheduler(scheduler);
int result = client.exec(command, user, options, env);
if (result == 0)
{
result = client.exitCode();
return result;
}
} else
{
SuProcess proc;
proc.setTerminal(terminal);
proc.setErase(true);
proc.setUser(user);
proc.setEnvironment(env);
proc.setPriority(priority);
proc.setScheduler(scheduler);
proc.setCommand(command);
int result = proc.exec(password.toLocal8Bit());
return result;
}
return -1;
}
diff --git a/kdesu/sudlg.cpp b/kdesu/sudlg.cpp
index 6b190c4..fbbf5db 100644
--- a/kdesu/sudlg.cpp
+++ b/kdesu/sudlg.cpp
@@ -1,110 +1,110 @@
/* vi: ts=8 sts=4 sw=4
*
* This file is part of the KDE project, module kdesu.
* Copyright (C) 2000 Geert Jansen
*/
#include "sudlg.h"
#include
#include
#include
#include
KDEsuDialog::KDEsuDialog(QByteArray user, QByteArray authUser, bool enableKeep, const QString& icon, bool withIgnoreButton)
: KPasswordDialog(nullptr, enableKeep ? ShowKeepPassword : NoFlags)
{
if ( !icon.isEmpty() ) {
setPixmap(QIcon::fromTheme(icon).pixmap(style()->pixelMetric(QStyle::PM_LargeIconSize)));
}
if ( withIgnoreButton ) {
buttonBox()->addButton(QDialogButtonBox::Ignore);
}
QString superUserCommand = proc.superUserCommand();
proc.setUser(authUser);
setWindowTitle(i18n("Run as %1", QString::fromLatin1(user)));
QString prompt;
if (proc.useUsersOwnPassword()) {
prompt = i18n("Please enter your password below." );
} else {
if (authUser == "root") {
if(withIgnoreButton)
- prompt = "" + i18n("The action you requested needs root privileges. "
+ prompt = QStringLiteral("") + i18n("The action you requested needs root privileges. "
"Please enter root's password below or click "
- "Ignore to continue with your current privileges.") + "";
+ "Ignore to continue with your current privileges.") + QStringLiteral("");
else
- prompt = "" + i18n("The action you requested needs root privileges. "
- "Please enter root's password below.") + "";
+ prompt = QStringLiteral("") + i18n("The action you requested needs root privileges. "
+ "Please enter root's password below.") + QStringLiteral("");
} else {
if(withIgnoreButton)
- prompt = "" + i18n("The action you requested needs additional privileges. "
+ prompt = QStringLiteral("") + i18n("The action you requested needs additional privileges. "
"Please enter the password for %1 below or click "
"Ignore to continue with your current privileges.", QString::fromLatin1(authUser)) +
- "";
+ QStringLiteral("");
else
- prompt = "" + i18n("The action you requested needs additional privileges. "
+ prompt = QStringLiteral("") + i18n("The action you requested needs additional privileges. "
"Please enter the password for %1 below.", QString::fromLatin1(authUser)) +
- "";
+ QStringLiteral("");
}
}
setPrompt(prompt);
if( withIgnoreButton ) {
connect(buttonBox()->button(QDialogButtonBox::Ignore), SIGNAL(clicked()), SLOT(slotUser1()));
}
}
KDEsuDialog::~KDEsuDialog()
{
}
bool KDEsuDialog::checkPassword()
{
int status = proc.checkInstall(password().toLocal8Bit());
switch (status)
{
case -1:
showErrorMessage(i18n("Conversation with su failed."), UsernameError);
return false;
case 0:
return true;
case SuProcess::SuNotFound:
showErrorMessage(i18n("The program 'su' could not be found.
"
"Ensure your PATH is set correctly."), FatalError);
return false;
case SuProcess::SuNotAllowed:
// This is actually never returned, as kdesu cannot tell the difference.
showErrorMessage(QLatin1String("The impossible happened."), FatalError);
return false;
case SuProcess::SuIncorrectPassword:
showErrorMessage(i18n("Permission denied.
"
"Possibly incorrect password, please try again.
"
"On some systems, you need to be in a special "
"group (often: wheel) to use this program."), PasswordError);
return false;
default:
showErrorMessage(i18n("Internal error: illegal return from "
"SuProcess::checkInstall()"), FatalError);
done(Rejected);
return false;
}
}
void KDEsuDialog::slotUser1()
{
done(AsUser);
}
diff --git a/keditfiletype/filetypedetails.cpp b/keditfiletype/filetypedetails.cpp
index 45edaaa..82fc088 100644
--- a/keditfiletype/filetypedetails.cpp
+++ b/keditfiletype/filetypedetails.cpp
@@ -1,365 +1,365 @@
/* This file is part of the KDE project
Copyright (C) 2000, 2007 David Faure
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License version 2 or at your option version 3 as published by
the Free Software Foundation.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "filetypedetails.h"
// Qt
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// KDE
#include
#include
#include
#include
#include
#include
#include
// Local
#include "kservicelistwidget.h"
#include "typeslistitem.h"
FileTypeDetails::FileTypeDetails( QWidget * parent )
: QWidget( parent ), m_mimeTypeData(nullptr), m_item(nullptr)
{
QVBoxLayout* topLayout = new QVBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
m_mimeTypeLabel = new QLabel(this);
topLayout->addWidget(m_mimeTypeLabel, 0, Qt::AlignCenter);
m_tabWidget = new QTabWidget(this);
topLayout->addWidget(m_tabWidget);
QString wtstr;
// First tab - General
QWidget * firstWidget = new QWidget(m_tabWidget);
QVBoxLayout *firstLayout = new QVBoxLayout(firstWidget);
QHBoxLayout *hBox = new QHBoxLayout();
firstLayout->addLayout(hBox);
iconButton = new KIconButton(firstWidget);
iconButton->setIconType(KIconLoader::Desktop, KIconLoader::MimeType);
connect(iconButton, SIGNAL(iconChanged(QString)), SLOT(updateIcon(QString)));
iconButton->setWhatsThis( i18n("This button displays the icon associated"
" with the selected file type. Click on it to choose a different icon.") );
iconButton->setFixedSize(70, 70);
iconLabel = nullptr;
hBox->addWidget(iconButton);
QGroupBox *gb = new QGroupBox(i18n("Filename Patterns"), firstWidget);
hBox->addWidget(gb);
hBox = new QHBoxLayout(gb);
extensionLB = new QListWidget(gb);
connect(extensionLB, SIGNAL(itemSelectionChanged()), SLOT(enableExtButtons()));
hBox->addWidget(extensionLB);
extensionLB->setFixedHeight(extensionLB->minimumSizeHint().height());
extensionLB->setWhatsThis( i18n("This box contains a list of patterns that can be"
" used to identify files of the selected type. For example, the pattern *.txt is"
" associated with the file type 'text/plain'; all files ending in '.txt' are recognized"
" as plain text files.") );
QVBoxLayout *vbox = new QVBoxLayout();
hBox->addLayout(vbox);
addExtButton = new QPushButton(i18n("Add..."), gb);
- addExtButton->setIcon(QIcon::fromTheme("list-add"));
+ addExtButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
addExtButton->setEnabled(false);
connect(addExtButton, SIGNAL(clicked()),
this, SLOT(addExtension()));
vbox->addWidget(addExtButton);
addExtButton->setWhatsThis( i18n("Add a new pattern for the selected file type.") );
removeExtButton = new QPushButton(i18n("Remove"), gb);
- removeExtButton->setIcon(QIcon::fromTheme("list-remove"));
+ removeExtButton->setIcon(QIcon::fromTheme(QStringLiteral("list-remove")));
removeExtButton->setEnabled(false);
connect(removeExtButton, SIGNAL(clicked()),
this, SLOT(removeExtension()));
vbox->addWidget(removeExtButton);
removeExtButton->setWhatsThis( i18n("Remove the selected filename pattern.") );
vbox->addStretch(1);
gb->setFixedHeight(gb->minimumSizeHint().height());
description = new KLineEdit(firstWidget);
description->setClearButtonShown(true);
connect(description, SIGNAL(textChanged(const QString &)),
SLOT(updateDescription(const QString &)));
QHBoxLayout *descriptionBox = new QHBoxLayout;
descriptionBox->addWidget(new QLabel(i18n("Description:"),firstWidget));
descriptionBox->addWidget(description);
firstLayout->addLayout(descriptionBox);
wtstr = i18n("You can enter a short description for files of the selected"
" file type (e.g. 'HTML Page'). This description will be used by applications"
" like Konqueror to display directory content.");
description->setWhatsThis( wtstr );
serviceListWidget = new KServiceListWidget( KServiceListWidget::SERVICELIST_APPLICATIONS, firstWidget );
connect( serviceListWidget, SIGNAL(changed(bool)), this, SIGNAL(changed(bool)));
firstLayout->addWidget(serviceListWidget,5);
// Second tab - Embedding
QWidget * secondWidget = new QWidget(m_tabWidget);
QVBoxLayout *secondLayout = new QVBoxLayout(secondWidget);
m_autoEmbedBox = new QGroupBox( i18n("Left Click Action in Konqueror"), secondWidget );
secondLayout->addWidget( m_autoEmbedBox );
m_autoEmbedBox->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );
QRadioButton *embViewerRadio = new QRadioButton( i18n("Show file in embedded viewer") );
QRadioButton *sepViewerRadio = new QRadioButton( i18n("Show file in separate viewer") );
- m_rbGroupSettings = new QRadioButton( QString("Use settings for '%1' group") );
+ m_rbGroupSettings = new QRadioButton( QStringLiteral("Use settings for '%1' group") );
m_chkAskSave = new QCheckBox( i18n("Ask whether to save to disk instead (only for Konqueror browser)") );
connect(m_chkAskSave, SIGNAL( toggled(bool) ), SLOT( slotAskSaveToggled(bool) ));
m_autoEmbedGroup = new QButtonGroup(m_autoEmbedBox);
m_autoEmbedGroup->addButton(embViewerRadio, 0);
m_autoEmbedGroup->addButton(sepViewerRadio, 1);
m_autoEmbedGroup->addButton(m_rbGroupSettings, 2);
connect(m_autoEmbedGroup, SIGNAL( buttonClicked(int) ), SLOT( slotAutoEmbedClicked(int) ));
vbox = new QVBoxLayout(m_autoEmbedBox);
vbox->addWidget(embViewerRadio);
vbox->addWidget(sepViewerRadio);
vbox->addWidget(m_rbGroupSettings);
vbox->addWidget(m_chkAskSave);
m_autoEmbedBox->setWhatsThis( i18n("Here you can configure what the Konqueror file manager"
" will do when you click on a file of this type. Konqueror can either display the file in"
" an embedded viewer, or start up a separate application. If set to 'Use settings for G group',"
" the file manager will behave according to the settings of the group G to which this type belongs;"
" for instance, 'image' if the current file type is image/png. Dolphin"
" always shows files in a separate viewer.") );
embedServiceListWidget = new KServiceListWidget( KServiceListWidget::SERVICELIST_SERVICES, secondWidget );
// embedServiceListWidget->setMinimumHeight( serviceListWidget->sizeHint().height() );
connect( embedServiceListWidget, SIGNAL(changed(bool)), this, SIGNAL(changed(bool)));
secondLayout->addWidget(embedServiceListWidget);
m_tabWidget->addTab( firstWidget, i18n("&General") );
m_tabWidget->addTab( secondWidget, i18n("&Embedding") );
}
void FileTypeDetails::updateRemoveButton()
{
removeExtButton->setEnabled(extensionLB->count()>0);
}
void FileTypeDetails::updateIcon(const QString &icon)
{
if (!m_mimeTypeData)
return;
m_mimeTypeData->setUserSpecifiedIcon(icon);
if (m_item)
m_item->setIcon(icon);
emit changed(true);
}
void FileTypeDetails::updateDescription(const QString &desc)
{
if (!m_mimeTypeData)
return;
m_mimeTypeData->setComment(desc);
emit changed(true);
}
void FileTypeDetails::addExtension()
{
if ( !m_mimeTypeData )
return;
bool ok;
QString ext = QInputDialog::getText(this,
i18n( "Add New Extension" ), i18n( "Extension:" ),
- QLineEdit::Normal, "*.", &ok);
+ QLineEdit::Normal, QStringLiteral("*."), &ok);
if (ok) {
extensionLB->addItem(ext);
QStringList patt = m_mimeTypeData->patterns();
patt += ext;
m_mimeTypeData->setPatterns(patt);
updateRemoveButton();
emit changed(true);
}
}
void FileTypeDetails::removeExtension()
{
if (extensionLB->currentRow() == -1)
return;
if ( !m_mimeTypeData )
return;
QStringList patt = m_mimeTypeData->patterns();
patt.removeAll(extensionLB->currentItem()->text());
m_mimeTypeData->setPatterns(patt);
delete extensionLB->takeItem(extensionLB->currentRow());
updateRemoveButton();
emit changed(true);
}
void FileTypeDetails::slotAutoEmbedClicked( int button )
{
if ( !m_mimeTypeData || (button > 2))
return;
m_mimeTypeData->setAutoEmbed( (MimeTypeData::AutoEmbed) button );
updateAskSave();
emit changed(true);
}
void FileTypeDetails::updateAskSave()
{
if ( !m_mimeTypeData )
return;
QMimeDatabase db;
MimeTypeData::AutoEmbed autoEmbed = m_mimeTypeData->autoEmbed();
if (m_mimeTypeData->isMeta() && autoEmbed == MimeTypeData::UseGroupSetting) {
// Resolve by looking at group (we could cache groups somewhere to avoid the re-parsing?)
autoEmbed = MimeTypeData(m_mimeTypeData->majorType()).autoEmbed();
}
const QString mimeType = m_mimeTypeData->name();
QString dontAskAgainName;
if (autoEmbed == MimeTypeData::Yes) // Embedded
- dontAskAgainName = "askEmbedOrSave"+mimeType;
+ dontAskAgainName = QStringLiteral("askEmbedOrSave")+mimeType;
else
- dontAskAgainName = "askSave"+mimeType;
+ dontAskAgainName = QStringLiteral("askSave")+mimeType;
- KSharedConfig::Ptr config = KSharedConfig::openConfig("filetypesrc", KConfig::NoGlobals);
+ KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
// default value
bool ask = config->group("Notification Messages").readEntry(dontAskAgainName, QString()).isEmpty();
// per-mimetype override if there's one
m_mimeTypeData->getAskSave(ask);
bool neverAsk = false;
if (autoEmbed == MimeTypeData::Yes) {
const QMimeType mime = db.mimeTypeForName( mimeType );
if (mime.isValid()) {
// SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC SYNC
// NOTE: Keep this function in sync with
// kparts/src/browseropenorsavequestion.cpp BrowserOpenOrSaveQuestionPrivate::autoEmbedMimeType
// Don't ask for:
// - html (even new tabs would ask, due to about:blank!)
// - dirs obviously (though not common over HTTP :),
// - images (reasoning: no need to save, most of the time, because fast to see)
// e.g. postscript is different, because takes longer to read, so
// it's more likely that the user might want to save it.
// - multipart/* ("server push", see kmultipart)
if (mime.inherits(QStringLiteral("text/html")) ||
mime.inherits(QStringLiteral("application/xml")) ||
mime.inherits(QStringLiteral("inode/directory")) ||
mimeType.startsWith(QLatin1String("image")) ||
mime.inherits(QStringLiteral("multipart/x-mixed-replace")) ||
mime.inherits(QStringLiteral("multipart/replace")))
{
neverAsk = true;
}
}
}
m_chkAskSave->blockSignals(true);
m_chkAskSave->setChecked(ask && !neverAsk);
m_chkAskSave->setEnabled(!neverAsk);
m_chkAskSave->blockSignals(false);
}
void FileTypeDetails::slotAskSaveToggled(bool askSave)
{
if (!m_mimeTypeData)
return;
m_mimeTypeData->setAskSave(askSave);
emit changed(true);
}
void FileTypeDetails::setMimeTypeData( MimeTypeData * mimeTypeData, TypesListItem* item )
{
m_mimeTypeData = mimeTypeData;
m_item = item; // can be 0
Q_ASSERT(mimeTypeData);
m_mimeTypeLabel->setText(i18n("File type %1", mimeTypeData->name()));
if (iconButton) {
iconButton->setIcon(mimeTypeData->icon());
iconButton->setToolTip(mimeTypeData->icon());
}
else
iconLabel->setPixmap(DesktopIcon(mimeTypeData->icon()));
description->setText(mimeTypeData->comment());
m_rbGroupSettings->setText( i18n("Use settings for '%1' group", mimeTypeData->majorType() ) );
extensionLB->clear();
addExtButton->setEnabled(true);
removeExtButton->setEnabled(false);
serviceListWidget->setMimeTypeData( mimeTypeData );
embedServiceListWidget->setMimeTypeData( mimeTypeData );
m_autoEmbedGroup->button(mimeTypeData->autoEmbed())->setChecked(true);
m_rbGroupSettings->setEnabled( mimeTypeData->canUseGroupSetting() );
extensionLB->addItems(mimeTypeData->patterns());
updateAskSave();
}
void FileTypeDetails::enableExtButtons()
{
removeExtButton->setEnabled(true);
}
void FileTypeDetails::refresh()
{
if (!m_mimeTypeData)
return;
// Called when ksycoca has been updated -> refresh data, then widgets
m_mimeTypeData->refresh();
setMimeTypeData(m_mimeTypeData, m_item);
}
diff --git a/keditfiletype/filetypesview.cpp b/keditfiletype/filetypesview.cpp
index bd9e29e..9f9c9f6 100644
--- a/keditfiletype/filetypesview.cpp
+++ b/keditfiletype/filetypesview.cpp
@@ -1,496 +1,495 @@
/* This file is part of the KDE project
Copyright (C) 2000 - 2008 David Faure
Copyright (C) 2008 Urs Wolfer
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 ) version 3 or, at the discretion of KDE e.V. ( which shall
act as a proxy as in section 14 of the GPLv3 ), any later version.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "filetypesview.h"
#include "mimetypewriter.h"
// Qt
#include
#include
#include
#include
#include
#include
#include
#include
#include
// KDE
#include
#include
#include
#include
#include
// Local
#include "newtypedlg.h"
#include "filetypedetails.h"
#include "filegroupdetails.h"
K_PLUGIN_FACTORY(FileTypesViewFactory, registerPlugin();)
-K_EXPORT_PLUGIN(FileTypesViewFactory("filetypes"))
FileTypesView::FileTypesView(QWidget *parent, const QVariantList &)
- : KCModule(/*FileTypesViewFactory::aboutData(),*/ parent)
+ : KCModule(parent)
{
- m_fileTypesConfig = KSharedConfig::openConfig("filetypesrc", KConfig::NoGlobals);
+ m_fileTypesConfig = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
setQuickHelp( i18n("File Associations
"
" This module allows you to choose which applications are associated"
" with a given type of file. File types are also referred to as MIME types"
" (MIME is an acronym which stands for \"Multipurpose Internet Mail"
" Extensions\").
A file association consists of the following:"
"
- Rules for determining the MIME-type of a file, for example"
" the filename pattern *.png, which means 'all files with names that end"
" in .png', is associated with the MIME type \"image/png\";
"
" - A short description of the MIME-type, for example the description"
" of the MIME type \"image/png\" is simply 'PNG image';
"
" - An icon to be used for displaying files of the given MIME-type,"
" so that you can easily identify the type of file in a file"
" manager or file-selection dialog (at least for the types you use often);
"
" - A list of the applications which can be used to open files of the"
" given MIME-type -- if more than one application can be used then the"
" list is ordered by priority.
"
" You may be surprised to find that some MIME types have no associated"
" filename patterns; in these cases, KDE is able to determine the"
" MIME-type by directly examining the contents of the file."));
setButtons(Help | Apply);
QString wtstr;
QHBoxLayout* l = new QHBoxLayout(this);
QVBoxLayout* leftLayout = new QVBoxLayout();
l->addLayout( leftLayout );
patternFilterLE = new KLineEdit(this);
patternFilterLE->setClearButtonShown(true);
patternFilterLE->setTrapReturnKey(true);
patternFilterLE->setPlaceholderText(i18n("Find file type or filename pattern"));
leftLayout->addWidget(patternFilterLE);
connect(patternFilterLE, SIGNAL(textChanged(const QString &)),
this, SLOT(slotFilter(const QString &)));
wtstr = i18n("Enter a part of a filename pattern, and only file types with a "
"matching file pattern will appear in the list. Alternatively, enter "
"a part of a file type name as it appears in the list.");
patternFilterLE->setWhatsThis( wtstr );
typesLV = new TypesListTreeWidget(this);
typesLV->setHeaderLabel(i18n("Known Types"));
leftLayout->addWidget(typesLV);
connect(typesLV, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
this, SLOT(updateDisplay(QTreeWidgetItem *)));
connect(typesLV, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
this, SLOT(slotDoubleClicked(QTreeWidgetItem *)));
typesLV->setWhatsThis( i18n("Here you can see a hierarchical list of"
" the file types which are known on your system. Click on the '+' sign"
" to expand a category, or the '-' sign to collapse it. Select a file type"
" (e.g. text/html for HTML files) to view/edit the information for that"
" file type using the controls on the right.") );
QHBoxLayout* btnsLay = new QHBoxLayout();
leftLayout->addLayout(btnsLay);
btnsLay->addStretch(1);
QPushButton *addTypeB = new QPushButton(i18n("Add..."), this);
- addTypeB->setIcon(QIcon::fromTheme("list-add"));
+ addTypeB->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
connect(addTypeB, SIGNAL(clicked()), SLOT(addType()));
btnsLay->addWidget(addTypeB);
addTypeB->setWhatsThis( i18n("Click here to add a new file type.") );
m_removeTypeB = new QPushButton(i18n("&Remove"), this);
- m_removeTypeB->setIcon(QIcon::fromTheme("list-remove"));
+ m_removeTypeB->setIcon(QIcon::fromTheme(QStringLiteral("list-remove")));
connect(m_removeTypeB, SIGNAL(clicked()), SLOT(removeType()));
btnsLay->addWidget(m_removeTypeB);
m_removeTypeB->setEnabled(false);
m_removeButtonSaysRevert = false;
// For the right panel, prepare a widget stack
m_widgetStack = new QStackedWidget(this);
l->addWidget( m_widgetStack );
// File Type Details
m_details = new FileTypeDetails( m_widgetStack );
connect( m_details, SIGNAL( changed(bool) ),
this, SLOT( setDirty(bool) ) );
connect( m_details, SIGNAL( embedMajor(const QString &, bool &) ),
this, SLOT( slotEmbedMajor(const QString &, bool &)));
m_widgetStack->insertWidget( 1, m_details /*id*/ );
// File Group Details
m_groupDetails = new FileGroupDetails( m_widgetStack );
connect( m_groupDetails, SIGNAL( changed(bool) ),
this, SLOT( setDirty(bool) ) );
m_widgetStack->insertWidget( 2,m_groupDetails /*id*/ );
// Widget shown on startup
m_emptyWidget = new QLabel( i18n("Select a file type by name or by extension"), m_widgetStack);
m_emptyWidget->setAlignment( Qt::AlignCenter );
m_widgetStack->insertWidget( 3,m_emptyWidget );
m_widgetStack->setCurrentWidget( m_emptyWidget );
connect(KSycoca::self(), SIGNAL(databaseChanged(QStringList)), SLOT(slotDatabaseChanged(QStringList)));
}
FileTypesView::~FileTypesView()
{
}
void FileTypesView::setDirty(bool state)
{
emit changed(state);
m_dirty = state;
}
// To order the mimetype list
static bool mimeTypeLessThan(const QMimeType& m1, const QMimeType& m2)
{
return m1.name() < m2.name();
}
// Note that this method loses any newly-added (and not saved yet) mimetypes.
// So this is really only for load().
void FileTypesView::readFileTypes()
{
typesLV->clear();
m_majorMap.clear();
m_itemList.clear();
QMimeDatabase db;
QList mimetypes = db.allMimeTypes();
- qSort(mimetypes.begin(), mimetypes.end(), mimeTypeLessThan);
+ std::sort(mimetypes.begin(), mimetypes.end(), mimeTypeLessThan);
auto it2(mimetypes.constBegin());
for (; it2 != mimetypes.constEnd(); ++it2) {
const QString mimetype = (*it2).name();
- const int index = mimetype.indexOf('/');
+ const int index = mimetype.indexOf(QLatin1Char('/'));
const QString maj = mimetype.left(index);
const QString min = mimetype.right(mimetype.length() - index+1);
TypesListItem* groupItem = m_majorMap.value(maj);
if ( !groupItem ) {
groupItem = new TypesListItem(typesLV, maj);
m_majorMap.insert(maj, groupItem);
}
TypesListItem *item = new TypesListItem(groupItem, (*it2));
m_itemList.append( item );
}
updateDisplay(nullptr);
}
void FileTypesView::slotEmbedMajor(const QString &major, bool &embed)
{
TypesListItem *groupItem = m_majorMap.value(major);
if (!groupItem)
return;
embed = (groupItem->mimeTypeData().autoEmbed() == MimeTypeData::Yes);
}
void FileTypesView::slotFilter(const QString & patternFilter)
{
for (int i = 0; i < typesLV->topLevelItemCount(); ++i) {
typesLV->topLevelItem(i)->setHidden(true);
}
// insert all items and their group that match the filter
Q_FOREACH(TypesListItem* it, m_itemList) {
const MimeTypeData& mimeTypeData = it->mimeTypeData();
if ( patternFilter.isEmpty() || mimeTypeData.matchesFilter(patternFilter) ) {
TypesListItem *group = m_majorMap.value( mimeTypeData.majorType() );
Q_ASSERT(group);
if (group) {
group->setHidden(false);
it->setHidden(false);
}
} else {
it->setHidden(true);
}
}
}
void FileTypesView::addType()
{
const QStringList allGroups = m_majorMap.keys();
NewTypeDialog dialog(allGroups, this);
if (dialog.exec()) {
- const QString newMimeType = dialog.group() + '/' + dialog.text();
+ const QString newMimeType = dialog.group() + QLatin1Char('/') + dialog.text();
QTreeWidgetItemIterator it(typesLV);
TypesListItem *group = m_majorMap.value(dialog.group());
if ( !group ) {
group = new TypesListItem(typesLV, dialog.group());
m_majorMap.insert(dialog.group(), group);
}
// find out if our group has been filtered out -> insert if necessary
QTreeWidgetItem *item = typesLV->topLevelItem(0);
bool insert = true;
while ( item ) {
if ( item == group ) {
insert = false;
break;
}
item = typesLV->itemBelow(item);
}
if ( insert )
typesLV->addTopLevelItem( group );
TypesListItem *tli = new TypesListItem(group, newMimeType);
m_itemList.append( tli );
group->setExpanded(true);
tli->setSelected(true);
setDirty(true);
}
}
void FileTypesView::removeType()
{
TypesListItem *current = static_cast(typesLV->currentItem());
if (!current) {
return;
}
const MimeTypeData& mimeTypeData = current->mimeTypeData();
// Can't delete groups nor essential mimetypes (but the button should be
// disabled already in these cases, so this is just extra safety).
if (mimeTypeData.isMeta() || mimeTypeData.isEssential()) {
return;
}
if (!mimeTypeData.isNew()) {
removedList.append(mimeTypeData.name());
}
if (m_removeButtonSaysRevert) {
// Nothing else to do for now, until saving
updateDisplay(current);
} else {
QTreeWidgetItem *li = typesLV->itemAbove(current);
if (!li)
li = typesLV->itemBelow(current);
if (!li)
li = current->parent();
current->parent()->takeChild(current->parent()->indexOfChild(current));
m_itemList.removeAll(current);
if (li) {
li->setSelected(true);
}
}
setDirty(true);
}
void FileTypesView::slotDoubleClicked(QTreeWidgetItem *item)
{
if ( !item ) return;
item->setExpanded( !item->isExpanded() );
}
void FileTypesView::updateDisplay(QTreeWidgetItem *item)
{
TypesListItem *tlitem = static_cast(item);
updateRemoveButton(tlitem);
if (!item) {
m_widgetStack->setCurrentWidget(m_emptyWidget);
return;
}
const bool wasDirty = m_dirty;
MimeTypeData& mimeTypeData = tlitem->mimeTypeData();
if (mimeTypeData.isMeta()) { // is a group
m_widgetStack->setCurrentWidget(m_groupDetails);
m_groupDetails->setMimeTypeData(&mimeTypeData);
} else {
m_widgetStack->setCurrentWidget(m_details);
m_details->setMimeTypeData(&mimeTypeData);
}
// Updating the display indirectly called change(true)
if (!wasDirty) {
setDirty(false);
}
}
void FileTypesView::updateRemoveButton(TypesListItem* tlitem)
{
bool canRemove = false;
m_removeButtonSaysRevert = false;
if (tlitem) {
const MimeTypeData& mimeTypeData = tlitem->mimeTypeData();
if (!mimeTypeData.isMeta() && !mimeTypeData.isEssential()) {
if (mimeTypeData.isNew()) {
canRemove = true;
} else {
// We can only remove mimetypes that we defined ourselves, not those from freedesktop.org
const QString mimeType = mimeTypeData.name();
qDebug() << mimeType << "hasDefinitionFile:" << MimeTypeWriter::hasDefinitionFile(mimeType);
if (MimeTypeWriter::hasDefinitionFile(mimeType)) {
canRemove = true;
// Is there a global definition for it?
- const QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + mimeType + ".xml" );
+ const QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + mimeType + QStringLiteral(".xml") );
qDebug() << mimeFiles;
if (mimeFiles.count() >= 2 /*a local and a global*/) {
m_removeButtonSaysRevert = true;
qDebug() << removedList;
if (removedList.contains(mimeType)) {
canRemove = false; // already on the "to be reverted" list, user needs to save now
}
}
}
}
}
}
if (m_removeButtonSaysRevert) {
m_removeTypeB->setText(i18n("&Revert"));
m_removeTypeB->setToolTip(i18n("Revert this file type to its initial system-wide definition"));
m_removeTypeB->setWhatsThis(i18n("Click here to revert this file type to its initial system-wide definition, which undoes any changes made to the file type. Note that system-wide file types cannot be deleted. You can however empty their pattern list, to minimize the chances of them being used (but the file type determination from file contents can still end up using them)."));
} else {
m_removeTypeB->setText(i18n("&Remove"));
m_removeTypeB->setToolTip(i18n("Delete this file type definition completely"));
m_removeTypeB->setWhatsThis(i18n("Click here to delete this file type definition completely. This is only possible for user-defined file types. System-wide file types cannot be deleted. You can however empty their pattern list, to minimize the chances of them being used (but the file type determination from file contents can still end up using them)."));
}
m_removeTypeB->setEnabled(canRemove);
}
void FileTypesView::save()
{
bool needUpdateMimeDb = false;
bool needUpdateSycoca = false;
bool didIt = false;
// first, remove those items which we are asked to remove.
Q_FOREACH(const QString& mime, removedList) {
MimeTypeWriter::removeOwnMimeType(mime);
didIt = true;
needUpdateMimeDb = true;
needUpdateSycoca = true; // remove offers for this mimetype
}
removedList.clear();
// now go through all entries and sync those which are dirty.
// don't use typesLV, it may be filtered
QMap::iterator it1 = m_majorMap.begin();
while ( it1 != m_majorMap.end() ) {
TypesListItem *tli = *it1;
if (tli->mimeTypeData().isDirty()) {
qDebug() << "Entry " << tli->name() << " is dirty. Saving.";
if (tli->mimeTypeData().sync())
needUpdateMimeDb = true;
didIt = true;
}
++it1;
}
Q_FOREACH(TypesListItem* tli, m_itemList) {
if (tli->mimeTypeData().isDirty()) {
if (tli->mimeTypeData().isServiceListDirty())
needUpdateSycoca = true;
qDebug() << "Entry " << tli->name() << " is dirty. Saving.";
if (tli->mimeTypeData().sync())
needUpdateMimeDb = true;
didIt = true;
}
}
m_fileTypesConfig->sync();
setDirty(false);
if (needUpdateMimeDb) {
MimeTypeWriter::runUpdateMimeDatabase();
}
if (needUpdateSycoca) {
KBuildSycocaProgressDialog::rebuildKSycoca(this);
}
if (didIt) { // TODO make more specific: only if autoEmbed changed? Well, maybe this is useful for icon and glob changes too...
// Trigger reparseConfiguration of filetypesrc in konqueror
// TODO: the same for dolphin. Or we should probably define a global signal for this.
// Or a KGlobalSettings thing.
QDBusMessage message =
- QDBusMessage::createSignal("/KonqMain", "org.kde.Konqueror.Main", "reparseConfiguration");
+ QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration"));
QDBusConnection::sessionBus().send(message);
}
updateDisplay(typesLV->currentItem());
}
void FileTypesView::load()
{
setEnabled(false);
setCursor( Qt::WaitCursor );
readFileTypes();
unsetCursor();
setDirty(false);
setEnabled(true);
}
void FileTypesView::slotDatabaseChanged(const QStringList& changedResources)
{
qDebug() << changedResources;
- if ( changedResources.contains("xdgdata-mime") // changes in mimetype definitions
- || changedResources.contains("services") ) { // changes in .desktop files
+ if ( changedResources.contains(QStringLiteral("xdgdata-mime")) // changes in mimetype definitions
+ || changedResources.contains(QStringLiteral("services")) ) { // changes in .desktop files
m_details->refresh();
// ksycoca has new KMimeTypes objects for us, make sure to update
// our 'copies' to be in sync with it. Not important for OK, but
// important for Apply (how to differentiate those 2?).
// See BR 35071.
Q_FOREACH(TypesListItem* tli, m_itemList) {
tli->mimeTypeData().refresh();
}
}
}
void FileTypesView::defaults()
{
}
#include "filetypesview.moc"
diff --git a/keditfiletype/keditfiletype.cpp b/keditfiletype/keditfiletype.cpp
index d10ef1d..14ab732 100644
--- a/keditfiletype/keditfiletype.cpp
+++ b/keditfiletype/keditfiletype.cpp
@@ -1,210 +1,210 @@
/* This file is part of the KDE project
Copyright (C) 2000, 2007 David Faure
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License version 2 or at your option version 3 as published by
the Free Software Foundation.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "keditfiletype.h"
#include "mimetypewriter.h"
// Qt
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// KDE
#include
#include
#include
#include
#include
#include
// Local
#include "filetypedetails.h"
#include "typeslistitem.h"
FileTypeDialog::FileTypeDialog( MimeTypeData* mime )
: QDialog( nullptr ),
m_mimeTypeData(mime)
{
init();
}
FileTypeDialog::~FileTypeDialog()
{
delete m_details;
}
void FileTypeDialog::init()
{
m_details = new FileTypeDetails( this );
m_details->setMimeTypeData( m_mimeTypeData );
connect(m_details, SIGNAL(changed(bool)), this, SLOT(clientChanged(bool)));
m_buttonBox = new QDialogButtonBox;
m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel);
connect(m_buttonBox, SIGNAL(accepted()), SLOT(accept()));
connect(m_buttonBox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), SLOT(save()));
connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));
// This code is very similar to kcdialog.cpp
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_details);
layout->addWidget(m_buttonBox);
// TODO setHelp()
setApplyButtonEnabled(false);
connect(KSycoca::self(), SIGNAL(databaseChanged(QStringList)), SLOT(slotDatabaseChanged(QStringList)));
}
void FileTypeDialog::setApplyButtonEnabled(bool enabled)
{
m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(enabled);
}
void FileTypeDialog::save()
{
if (m_mimeTypeData->isDirty()) {
const bool servicesDirty = m_mimeTypeData->isServiceListDirty();
if (m_mimeTypeData->sync())
MimeTypeWriter::runUpdateMimeDatabase();
if (servicesDirty)
KBuildSycocaProgressDialog::rebuildKSycoca(this);
// Trigger reparseConfiguration of filetypesrc in konqueror
QDBusMessage message =
- QDBusMessage::createSignal("/KonqMain", "org.kde.Konqueror.Main", "reparseConfiguration");
+ QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration"));
QDBusConnection::sessionBus().send(message);
}
}
void FileTypeDialog::accept()
{
save();
QDialog::accept();
}
void FileTypeDialog::clientChanged(bool state)
{
m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(state);
m_buttonBox->button(QDialogButtonBox::Apply)->setEnabled(state);
}
void FileTypeDialog::slotDatabaseChanged(const QStringList& changedResources)
{
qDebug() << changedResources;
- if ( changedResources.contains("xdgdata-mime") // changes in mimetype definitions
- || changedResources.contains("services") ) { // changes in .desktop files
+ if ( changedResources.contains(QStringLiteral("xdgdata-mime")) // changes in mimetype definitions
+ || changedResources.contains(QStringLiteral("services")) ) { // changes in .desktop files
m_details->refresh();
}
}
int main(int argc, char ** argv)
{
QApplication app(argc, argv);
app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);
- QApplication::setWindowIcon(QIcon::fromTheme("preferences-desktop-filetype-association"));
+ QApplication::setWindowIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-filetype-association")));
- KAboutData aboutData( "keditfiletype", i18n("File Type Editor"), PROJECT_VERSION,
+ KAboutData aboutData( QStringLiteral("keditfiletype"), i18n("File Type Editor"), QLatin1String(PROJECT_VERSION),
i18n("KDE file type editor - simplified version for editing a single file type"),
KAboutLicense::GPL,
i18n("(c) 2000, KDE developers") );
- aboutData.addAuthor(i18n("Preston Brown"), QString(), "pbrown@kde.org");
- aboutData.addAuthor(i18n("David Faure"), QString(), "faure@kde.org");
+ aboutData.addAuthor(i18n("Preston Brown"), QString(), QStringLiteral("pbrown@kde.org"));
+ aboutData.addAuthor(i18n("David Faure"), QString(), QStringLiteral("faure@kde.org"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
- parser.addOption(QCommandLineOption(QStringList() << "parent", i18n("Makes the dialog transient for the window specified by winid"), "winid"));
- parser.addPositionalArgument("mimetype", i18n("File type to edit (e.g. text/html)"));
+ parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("parent"), i18n("Makes the dialog transient for the window specified by winid"), QStringLiteral("winid")));
+ parser.addPositionalArgument(QStringLiteral("mimetype"), i18n("File type to edit (e.g. text/html)"));
parser.process(app);
aboutData.processCommandLine(&parser);
if (parser.positionalArguments().count() == 0)
parser.showHelp();
QMimeDatabase db;
QString arg = parser.positionalArguments().first();
MimeTypeData* mimeTypeData = nullptr;
- const bool createType = arg.startsWith('*');
+ const bool createType = arg.startsWith(QLatin1Char('*'));
if ( createType ) {
- QString mimeString = "application/x-kdeuser%1";
+ QString mimeString = QStringLiteral("application/x-kdeuser%1");
QString mimeTypeName;
int inc = 0;
bool ok = false;
do {
++inc;
mimeTypeName = mimeString.arg(inc);
ok = !db.mimeTypeForName(mimeTypeName).isValid();
} while (!ok);
QStringList patterns;
if ( arg.length() > 2 )
patterns << arg.toLower() << arg.toUpper();
QString comment;
if ( arg.startsWith( QLatin1String("*.") ) && arg.length() >= 3 ) {
const QString type = arg.mid( 3 ).prepend( arg[2].toUpper() );
comment = i18n( "%1 File", type );
}
mimeTypeData = new MimeTypeData(mimeTypeName, true); // new mimetype
mimeTypeData->setComment(comment);
mimeTypeData->setPatterns(patterns);
}
else {
const QString mimeTypeName = arg;
QMimeType mime = db.mimeTypeForName(mimeTypeName);
if (!mime.isValid()) {
qCritical() << "Mimetype" << mimeTypeName << "not found" ;
return 1;
}
mimeTypeData = new MimeTypeData(mime);
}
FileTypeDialog dlg( mimeTypeData );
- if( parser.isSet( "parent" )) {
+ if( parser.isSet( QStringLiteral("parent") )) {
bool ok;
- long id = parser.value("parent").toLong(&ok);
+ long id = parser.value(QStringLiteral("parent")).toLong(&ok);
if (ok)
KWindowSystem::setMainWindow( &dlg, (WId)id );
}
if ( !createType )
dlg.setWindowTitle( i18n("Edit File Type %1", mimeTypeData->name()) );
else {
dlg.setWindowTitle( i18n("Create New File Type %1", mimeTypeData->name()) );
dlg.setApplyButtonEnabled(true);
}
dlg.show(); // non-modal
return app.exec();
}
diff --git a/keditfiletype/kservicelistwidget.cpp b/keditfiletype/kservicelistwidget.cpp
index 7600d9a..226140c 100644
--- a/keditfiletype/kservicelistwidget.cpp
+++ b/keditfiletype/kservicelistwidget.cpp
@@ -1,415 +1,415 @@
/* This file is part of the KDE project
Copyright (C) 2003 Waldo Bastian
Copyright (C) 2003 David Faure
Copyright (C) 2002 Daniel Molkentin
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License version 2 as published by the Free Software Foundation.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "kservicelistwidget.h"
// Qt
#include
#include
#include
#include
#include
// KDE
#include
#include
#include
#include
// Local
#include "kserviceselectdlg.h"
#include "mimetypedata.h"
KServiceListItem::KServiceListItem( const KService::Ptr& pService, int kind )
: QListWidgetItem(), storageId(pService->storageId()), desktopPath(pService->entryPath())
{
if ( kind == KServiceListWidget::SERVICELIST_APPLICATIONS )
setText( pService->name() );
else
setText( i18n( "%1 (%2)", pService->name(), pService->desktopEntryName() ) );
if (!pService->isApplication())
localPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/kservices5/") + desktopPath;
else
localPath = pService->locateLocal();
}
KServiceListWidget::KServiceListWidget(int kind, QWidget *parent)
: QGroupBox( kind == SERVICELIST_APPLICATIONS ? i18n("Application Preference Order")
: i18n("Services Preference Order"), parent ),
m_kind( kind ), m_mimeTypeData( nullptr )
{
QHBoxLayout *lay= new QHBoxLayout(this);
servicesLB = new QListWidget(this);
connect(servicesLB, SIGNAL(itemSelectionChanged()), SLOT(enableMoveButtons()));
lay->addWidget(servicesLB);
connect( servicesLB, SIGNAL( itemDoubleClicked(QListWidgetItem*)), this, SLOT( editService()));
QString wtstr =
(kind == SERVICELIST_APPLICATIONS ?
i18n("This is a list of applications associated with files of the selected"
" file type. This list is shown in Konqueror's context menus when you select"
" \"Open With...\". If more than one application is associated with this file type,"
" then the list is ordered by priority with the uppermost item taking precedence"
" over the others.") :
i18n("This is a list of services associated with files of the selected"
" file type. This list is shown in Konqueror's context menus when you select"
" a \"Preview with...\" option. If more than one service is associated with this file type,"
" then the list is ordered by priority with the uppermost item taking precedence"
" over the others."));
setWhatsThis( wtstr );
servicesLB->setWhatsThis( wtstr );
QVBoxLayout *btnsLay= new QVBoxLayout();
lay->addLayout(btnsLay);
servUpButton = new QPushButton(i18n("Move &Up"), this);
- servUpButton->setIcon(QIcon::fromTheme("arrow-up"));
+ servUpButton->setIcon(QIcon::fromTheme(QStringLiteral("arrow-up")));
servUpButton->setEnabled(false);
connect(servUpButton, SIGNAL(clicked()), SLOT(promoteService()));
btnsLay->addWidget(servUpButton);
servUpButton->setWhatsThis( kind == SERVICELIST_APPLICATIONS ?
i18n("Assigns a higher priority to the selected\n"
"application, moving it up in the list. Note: This\n"
"only affects the selected application if the file type is\n"
"associated with more than one application.") :
i18n("Assigns a higher priority to the selected\n"
"service, moving it up in the list."));
servDownButton = new QPushButton(i18n("Move &Down"), this);
- servDownButton->setIcon(QIcon::fromTheme("arrow-down"));
+ servDownButton->setIcon(QIcon::fromTheme(QStringLiteral("arrow-down")));
servDownButton->setEnabled(false);
connect(servDownButton, SIGNAL(clicked()), SLOT(demoteService()));
btnsLay->addWidget(servDownButton);
servDownButton->setWhatsThis( kind == SERVICELIST_APPLICATIONS ?
i18n("Assigns a lower priority to the selected\n"
"application, moving it down in the list. Note: This \n"
"only affects the selected application if the file type is\n"
"associated with more than one application."):
i18n("Assigns a lower priority to the selected\n"
"service, moving it down in the list."));
servNewButton = new QPushButton(i18n("Add..."), this);
- servNewButton->setIcon(QIcon::fromTheme("list-add"));
+ servNewButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
servNewButton->setEnabled(false);
connect(servNewButton, SIGNAL(clicked()), SLOT(addService()));
btnsLay->addWidget(servNewButton);
servNewButton->setWhatsThis( i18n( "Add a new application for this file type." ) );
servEditButton = new QPushButton(i18n("Edit..."), this);
- servEditButton->setIcon(QIcon::fromTheme("edit-rename"));
+ servEditButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename")));
servEditButton->setEnabled(false);
connect(servEditButton, SIGNAL(clicked()), SLOT(editService()));
btnsLay->addWidget(servEditButton);
servEditButton->setWhatsThis( i18n( "Edit command line of the selected application." ) );
servRemoveButton = new QPushButton(i18n("Remove"), this);
- servRemoveButton->setIcon(QIcon::fromTheme("list-remove"));
+ servRemoveButton->setIcon(QIcon::fromTheme(QStringLiteral("list-remove")));
servRemoveButton->setEnabled(false);
connect(servRemoveButton, SIGNAL(clicked()), SLOT(removeService()));
btnsLay->addWidget(servRemoveButton);
servRemoveButton->setWhatsThis( i18n( "Remove the selected application from the list." ) );
btnsLay->addStretch(1);
}
void KServiceListWidget::setMimeTypeData( MimeTypeData * mimeTypeData )
{
m_mimeTypeData = mimeTypeData;
if ( servNewButton )
servNewButton->setEnabled(true);
// will need a selection
servUpButton->setEnabled(false);
servDownButton->setEnabled(false);
servicesLB->clear();
servicesLB->setEnabled(false);
if (m_mimeTypeData) {
const QStringList services = ( m_kind == SERVICELIST_APPLICATIONS )
? m_mimeTypeData->appServices()
: m_mimeTypeData->embedServices();
if (services.isEmpty()) {
if (m_kind == SERVICELIST_APPLICATIONS)
servicesLB->addItem(i18nc("No applications associated with this file type", "None"));
else
servicesLB->addItem(i18nc("No components associated with this file type", "None"));
} else {
Q_FOREACH(const QString& service, services) {
KService::Ptr pService = KService::serviceByStorageId(service);
if (pService)
servicesLB->addItem( new KServiceListItem(pService, m_kind) );
}
servicesLB->setEnabled(true);
}
}
if (servRemoveButton)
servRemoveButton->setEnabled(servicesLB->currentRow() > -1);
if (servEditButton)
servEditButton->setEnabled(servicesLB->currentRow() > -1);
}
void KServiceListWidget::promoteService()
{
if (!servicesLB->isEnabled()) {
return;
}
int selIndex = servicesLB->currentRow();
if (selIndex == 0) {
return;
}
QListWidgetItem *selItem = servicesLB->item(selIndex);
servicesLB->takeItem(selIndex);
servicesLB->insertItem(selIndex-1,selItem);
servicesLB->setCurrentRow(selIndex - 1);
updatePreferredServices();
emit changed(true);
}
void KServiceListWidget::demoteService()
{
if (!servicesLB->isEnabled()) {
return;
}
int selIndex = servicesLB->currentRow();
if (selIndex == servicesLB->count() - 1) {
return;
}
QListWidgetItem *selItem = servicesLB->item(selIndex);
servicesLB->takeItem(selIndex);
servicesLB->insertItem(selIndex + 1, selItem);
servicesLB->setCurrentRow(selIndex + 1);
updatePreferredServices();
emit changed(true);
}
void KServiceListWidget::addService()
{
if (!m_mimeTypeData)
return;
KService::Ptr service;
if ( m_kind == SERVICELIST_APPLICATIONS )
{
KOpenWithDialog dlg(m_mimeTypeData->name(), QString(), this);
dlg.setSaveNewApplications(true);
if (dlg.exec() != QDialog::Accepted)
return;
service = dlg.service();
Q_ASSERT(service);
if (!service)
return; // Don't crash if KOpenWith wasn't able to create service.
}
else
{
KServiceSelectDlg dlg(m_mimeTypeData->name(), QString(), this);
if (dlg.exec() != QDialog::Accepted)
return;
service = dlg.service();
Q_ASSERT(service);
if (!service)
return;
}
// Did the list simply show "None"?
const bool hadDummyEntry = ( m_kind == SERVICELIST_APPLICATIONS )
? m_mimeTypeData->appServices().isEmpty()
: m_mimeTypeData->embedServices().isEmpty();
if (hadDummyEntry) {
delete servicesLB->takeItem(0); // Remove the "None" item.
servicesLB->setEnabled(true);
} else {
// check if it is a duplicate entry
for (int index = 0; index < servicesLB->count(); index++) {
if (static_cast( servicesLB->item(index) )->desktopPath
== service->entryPath()) {
// ##### shouldn't we make the existing entry the default one?
return;
}
}
}
servicesLB->insertItem(0, new KServiceListItem(service, m_kind));
servicesLB->setCurrentItem(nullptr);
updatePreferredServices();
emit changed(true);
}
void KServiceListWidget::editService()
{
if (!m_mimeTypeData)
return;
const int selected = servicesLB->currentRow();
if (selected < 0)
return;
// Only edit applications, not services as
// they don't have any parameters
if (m_kind != SERVICELIST_APPLICATIONS)
return;
// Just like popping up an add dialog except that we
// pass the current command line as a default
KServiceListItem *selItem = (KServiceListItem*)servicesLB->item(selected);
const QString desktopPath = selItem->desktopPath;
KService::Ptr service = KService::serviceByDesktopPath(desktopPath);
if (!service)
return;
QString path = service->entryPath();
{
// If the path to the desktop file is relative, try to get the full
// path from QStandardPaths.
QString fullPath = QStandardPaths::locate(QStandardPaths::ApplicationsLocation, path);
if (!fullPath.isEmpty()) {
path = fullPath;
}
}
- KFileItem item(QUrl::fromLocalFile(path), "application/x-desktop", KFileItem::Unknown);
+ KFileItem item(QUrl::fromLocalFile(path), QStringLiteral("application/x-desktop"), KFileItem::Unknown);
KPropertiesDialog dlg(item, this);
if (dlg.exec() != QDialog::Accepted)
return;
// Note that at this point, ksycoca has been updated,
// and setMimeTypeData has been called again, so all the items have been recreated.
// Reload service
service = KService::serviceByDesktopPath(desktopPath);
if (!service)
return;
// Remove the old one...
delete servicesLB->takeItem(selected);
// ...check that it's not a duplicate entry...
bool addIt = true;
for (int index = 0; index < servicesLB->count(); index++) {
if (static_cast(servicesLB->item(index))->desktopPath
== service->entryPath()) {
addIt = false;
break;
}
}
// ...and add it in the same place as the old one:
if (addIt) {
servicesLB->insertItem(selected, new KServiceListItem(service, m_kind));
servicesLB->setCurrentRow(selected);
}
updatePreferredServices();
emit changed(true);
}
void KServiceListWidget::removeService()
{
if (!m_mimeTypeData) return;
int selected = servicesLB->currentRow();
if ( selected >= 0 ) {
delete servicesLB->takeItem( selected );
updatePreferredServices();
emit changed(true);
}
// Update buttons and service list again (e.g. to re-add "None")
setMimeTypeData(m_mimeTypeData);
}
void KServiceListWidget::updatePreferredServices()
{
if (!m_mimeTypeData)
return;
QStringList sl;
unsigned int count = servicesLB->count();
for (unsigned int i = 0; i < count; i++) {
KServiceListItem *sli = (KServiceListItem *) servicesLB->item(i);
sl.append( sli->storageId );
}
sl.removeDuplicates();
if ( m_kind == SERVICELIST_APPLICATIONS )
m_mimeTypeData->setAppServices(sl);
else
m_mimeTypeData->setEmbedServices(sl);
}
void KServiceListWidget::enableMoveButtons()
{
int idx = servicesLB->currentRow();
if (servicesLB->model()->rowCount() <= 1)
{
servUpButton->setEnabled(false);
servDownButton->setEnabled(false);
}
else if ( idx == (servicesLB->model()->rowCount() - 1) )
{
servUpButton->setEnabled(true);
servDownButton->setEnabled(false);
}
else if (idx == 0)
{
servUpButton->setEnabled(false);
servDownButton->setEnabled(true);
}
else
{
servUpButton->setEnabled(true);
servDownButton->setEnabled(true);
}
if ( servRemoveButton )
servRemoveButton->setEnabled(true);
if ( servEditButton )
servEditButton->setEnabled( m_kind == SERVICELIST_APPLICATIONS );
}
diff --git a/keditfiletype/kserviceselectdlg.cpp b/keditfiletype/kserviceselectdlg.cpp
index 47b3d6b..f00f85c 100644
--- a/keditfiletype/kserviceselectdlg.cpp
+++ b/keditfiletype/kserviceselectdlg.cpp
@@ -1,72 +1,72 @@
/* This file is part of the KDE project
Copyright (C) 2000 David Faure
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.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
#include "kserviceselectdlg.h"
#include "kservicelistwidget.h"
#include
#include
#include
#include
KServiceSelectDlg::KServiceSelectDlg( const QString& /*serviceType*/, const QString& /*value*/, QWidget *parent )
: QDialog( parent )
{
setObjectName( QLatin1String( "serviceSelectDlg" ) );
setModal( true );
setWindowTitle( i18n( "Add Service" ) );
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget( new QLabel( i18n( "Select service:" ) ) );
m_listbox=new QListWidget();
m_buttonBox = new QDialogButtonBox;
m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
// Can't make a KTrader query since we don't have a servicetype to give,
// we want all services that are not applications.......
// So we have to do it the slow way
// ### Why can't we query for KParts/ReadOnlyPart as the servicetype? Should work fine!
const KService::List allServices = KService::allServices();
KService::List::const_iterator it(allServices.constBegin());
for ( ; it != allServices.constEnd() ; ++it )
- if ( (*it)->hasServiceType( "KParts/ReadOnlyPart" ) )
+ if ( (*it)->hasServiceType( QStringLiteral("KParts/ReadOnlyPart") ) )
{
m_listbox->addItem( new KServiceListItem( (*it), KServiceListWidget::SERVICELIST_SERVICES ) );
}
m_listbox->model()->sort(0);
m_listbox->setMinimumHeight(350);
m_listbox->setMinimumWidth(400);
layout->addWidget( m_listbox );
layout->addWidget( m_buttonBox );
connect(m_listbox,SIGNAL(itemDoubleClicked(QListWidgetItem*)),SLOT(accept()));
connect(m_buttonBox, SIGNAL(accepted()), SLOT(accept()));
connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));
}
KServiceSelectDlg::~KServiceSelectDlg()
{
}
KService::Ptr KServiceSelectDlg::service()
{
int selIndex = m_listbox->currentRow();
KServiceListItem *selItem = static_cast(m_listbox->item(selIndex));
return KService::serviceByDesktopPath( selItem->desktopPath );
}
diff --git a/keditfiletype/mimetypedata.cpp b/keditfiletype/mimetypedata.cpp
index e024f94..476f0ca 100644
--- a/keditfiletype/mimetypedata.cpp
+++ b/keditfiletype/mimetypedata.cpp
@@ -1,557 +1,557 @@
/* This file is part of the KDE project
Copyright (C) 2003 Waldo Bastian
Copyright (C) 2003, 2007 David Faure
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License version 2 or at your option version 3 as published by
the Free Software Foundation.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "mimetypedata.h"
#include
#include "mimetypewriter.h"
#include
#include
#include
#include
#include
#include
#include
#include
MimeTypeData::MimeTypeData(const QString& major)
: m_askSave(AskSaveDefault),
m_bNewItem(false),
m_bFullInit(true),
m_isGroup(true),
m_appServicesModified(false),
m_embedServicesModified(false),
m_userSpecifiedIconModified(false),
m_major(major)
{
m_autoEmbed = readAutoEmbed();
}
MimeTypeData::MimeTypeData(const QMimeType& mime)
: m_mimetype(mime),
m_askSave(AskSaveDefault), // TODO: the code for initializing this is missing. FileTypeDetails initializes the checkbox instead...
m_bNewItem(false),
m_bFullInit(false),
m_isGroup(false),
m_appServicesModified(false),
m_embedServicesModified(false),
m_userSpecifiedIconModified(false)
{
const QString mimeName = m_mimetype.name();
- const int index = mimeName.indexOf('/');
+ const int index = mimeName.indexOf(QLatin1Char('/'));
if (index != -1) {
m_major = mimeName.left(index);
m_minor = mimeName.mid(index+1);
} else {
m_major = mimeName;
}
initFromQMimeType();
}
MimeTypeData::MimeTypeData(const QString& mimeName, bool)
: m_askSave(AskSaveDefault),
m_bNewItem(true),
m_bFullInit(false),
m_isGroup(false),
m_appServicesModified(false),
m_embedServicesModified(false),
m_userSpecifiedIconModified(false)
{
- const int index = mimeName.indexOf('/');
+ const int index = mimeName.indexOf(QLatin1Char('/'));
if (index != -1) {
m_major = mimeName.left(index);
m_minor = mimeName.mid(index+1);
} else {
m_major = mimeName;
}
m_autoEmbed = UseGroupSetting;
// all the rest is empty by default
}
void MimeTypeData::initFromQMimeType()
{
m_comment = m_mimetype.comment();
setPatterns(m_mimetype.globPatterns());
m_autoEmbed = readAutoEmbed();
// Parse XML file to find out if the user specified a custom icon name
QString file = name().toLower() + QLatin1String(".xml");
- QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "mime/" + file);
+ QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("mime/") + file);
if (mimeFiles.isEmpty()) {
// This is for shared-mime-info < 1.3 that did not lowecase mime names
file = name() + QLatin1String(".xml");
- mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "mime/" + file);
+ mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("mime/") + file);
if (mimeFiles.isEmpty()) {
qWarning() << "No file found for" << file << ", even though the file appeared in a directory listing.";
qWarning() << "Either it was just removed, or the directory doesn't have executable permission...";
- qWarning() << QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "mime", QStandardPaths::LocateDirectory);
+ qWarning() << QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("mime"), QStandardPaths::LocateDirectory);
return;
}
}
QListIterator mimeFilesIter(mimeFiles);
mimeFilesIter.toBack();
while (mimeFilesIter.hasPrevious()) { // global first, then local.
const QString fullPath = mimeFilesIter.previous();
QFile qfile(fullPath);
if (!qfile.open(QFile::ReadOnly))
continue;
QXmlStreamReader xml(&qfile);
if (xml.readNextStartElement()) {
- if (xml.name() != "mime-type") {
+ if (xml.name() != QLatin1String("mime-type")) {
continue;
}
const QString mimeName = xml.attributes().value(QLatin1String("type")).toString();
if (mimeName.isEmpty())
continue;
if (QString::compare(mimeName, name(), Qt::CaseInsensitive) != 0) {
qWarning() << "Got name" << mimeName << "in file" << file << "expected" << name();
}
while (xml.readNextStartElement()) {
const QStringRef tag = xml.name();
- if (tag == "icon") {
+ if (tag == QLatin1String("icon")) {
m_userSpecifiedIcon = xml.attributes().value(QLatin1String("name")).toString();
}
xml.skipCurrentElement();
}
}
}
}
MimeTypeData::AutoEmbed MimeTypeData::readAutoEmbed() const
{
- const KSharedConfig::Ptr config = KSharedConfig::openConfig("filetypesrc", KConfig::NoGlobals);
- const QString key = QString("embed-") + name();
+ const KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
+ const QString key = QStringLiteral("embed-") + name();
const KConfigGroup group(config, "EmbedSettings");
if (m_isGroup) {
// embedding is false by default except for image/*, multipart/* and inode/* (hardcoded in konq)
- const bool defaultValue = (m_major == "image" || m_major == "multipart" || m_major == "inode");
+ const bool defaultValue = (m_major == QLatin1String("image") || m_major == QLatin1String("multipart") || m_major == QLatin1String("inode"));
return group.readEntry(key, defaultValue) ? Yes : No;
} else {
if (group.hasKey(key))
return group.readEntry(key, false) ? Yes : No;
// TODO if ( !mimetype.property( "X-KDE-LocalProtocol" ).toString().isEmpty() )
// TODO return MimeTypeData::Yes; // embed by default for zip, tar etc.
return MimeTypeData::UseGroupSetting;
}
}
void MimeTypeData::writeAutoEmbed()
{
- KSharedConfig::Ptr config = KSharedConfig::openConfig("filetypesrc", KConfig::NoGlobals);
+ KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
if (!config->isConfigWritable(true))
return;
- const QString key = QString("embed-") + name();
+ const QString key = QStringLiteral("embed-") + name();
KConfigGroup group(config, "EmbedSettings");
if (m_isGroup) {
group.writeEntry(key, m_autoEmbed == Yes);
} else {
if (m_autoEmbed == UseGroupSetting)
group.deleteEntry(key);
else
group.writeEntry(key, m_autoEmbed == Yes);
}
}
bool MimeTypeData::isEssential() const
{
// Keep in sync with KMimeType::checkEssentialMimeTypes
const QString n = name();
- if ( n == "application/octet-stream" )
+ if ( n == QLatin1String("application/octet-stream") )
return true;
- if ( n == "inode/directory" )
+ if ( n == QLatin1String("inode/directory") )
return true;
- if ( n == "inode/blockdevice" )
+ if ( n == QLatin1String("inode/blockdevice") )
return true;
- if ( n == "inode/chardevice" )
+ if ( n == QLatin1String("inode/chardevice") )
return true;
- if ( n == "inode/socket" )
+ if ( n == QLatin1String("inode/socket") )
return true;
- if ( n == "inode/fifo" )
+ if ( n == QLatin1String("inode/fifo") )
return true;
- if ( n == "application/x-shellscript" )
+ if ( n == QLatin1String("application/x-shellscript") )
return true;
- if ( n == "application/x-executable" )
+ if ( n == QLatin1String("application/x-executable") )
return true;
- if ( n == "application/x-desktop" )
+ if ( n == QLatin1String("application/x-desktop") )
return true;
return false;
}
void MimeTypeData::setUserSpecifiedIcon(const QString& icon)
{
if (icon == m_userSpecifiedIcon) {
return;
}
m_userSpecifiedIcon = icon;
m_userSpecifiedIconModified = true;
}
QStringList MimeTypeData::getAppOffers() const
{
QStringList services;
const KService::List offerList =
- KMimeTypeTrader::self()->query(name(), "Application");
+ KMimeTypeTrader::self()->query(name(), QStringLiteral("Application"));
KService::List::const_iterator it(offerList.begin());
for (; it != offerList.constEnd(); ++it) {
if ((*it)->allowAsDefault())
services.append((*it)->storageId());
}
return services;
}
QStringList MimeTypeData::getPartOffers() const
{
QStringList services;
const KService::List partOfferList =
- KMimeTypeTrader::self()->query(name(), "KParts/ReadOnlyPart");
+ KMimeTypeTrader::self()->query(name(), QStringLiteral("KParts/ReadOnlyPart"));
for ( KService::List::const_iterator it = partOfferList.begin(); it != partOfferList.constEnd(); ++it)
services.append((*it)->storageId());
return services;
}
void MimeTypeData::getMyServiceOffers() const
{
m_appServices = getAppOffers();
m_embedServices = getPartOffers();
m_bFullInit = true;
}
QStringList MimeTypeData::appServices() const
{
if (!m_bFullInit) {
getMyServiceOffers();
}
return m_appServices;
}
QStringList MimeTypeData::embedServices() const
{
if (!m_bFullInit) {
getMyServiceOffers();
}
return m_embedServices;
}
bool MimeTypeData::isMimeTypeDirty() const
{
Q_ASSERT(!m_isGroup);
if (m_bNewItem)
return true;
if (!m_mimetype.isValid()) {
qWarning() << "MimeTypeData for" << name() << "says 'not new' but is without a mimetype? Should not happen.";
return true;
}
if (m_mimetype.comment() != m_comment) {
qDebug() << "Mimetype Comment Dirty: old=" << m_mimetype.comment() << "m_comment=" << m_comment;
return true;
}
if (m_userSpecifiedIconModified) {
qDebug() << "m_userSpecifiedIcon has changed. Now set to" << m_userSpecifiedIcon;
return true;
}
QStringList storedPatterns = m_mimetype.globPatterns();
storedPatterns.sort(); // see ctor
if ( storedPatterns != m_patterns) {
qDebug() << "Mimetype Patterns Dirty: old=" << storedPatterns
<< "m_patterns=" << m_patterns;
return true;
}
if (readAutoEmbed() != m_autoEmbed)
return true;
return false;
}
bool MimeTypeData::isServiceListDirty() const
{
return !m_isGroup && (m_appServicesModified || m_embedServicesModified);
}
bool MimeTypeData::isDirty() const
{
if ( m_bNewItem ) {
qDebug() << "New item, need to save it";
return true;
}
if ( !m_isGroup ) {
if (isServiceListDirty())
return true;
if (isMimeTypeDirty())
return true;
}
else // is a group
{
if (readAutoEmbed() != m_autoEmbed)
return true;
}
if (m_askSave != AskSaveDefault)
return true;
// nothing seems to have changed, it's not dirty.
return false;
}
bool MimeTypeData::sync()
{
if (m_isGroup) {
writeAutoEmbed();
return false;
}
if (m_askSave != AskSaveDefault) {
- KSharedConfig::Ptr config = KSharedConfig::openConfig("filetypesrc", KConfig::NoGlobals);
+ KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
if (!config->isConfigWritable(true))
return false;
KConfigGroup cg = config->group("Notification Messages");
if (m_askSave == AskSaveYes) {
// Ask
- cg.deleteEntry("askSave"+name());
- cg.deleteEntry("askEmbedOrSave"+name());
+ cg.deleteEntry(QStringLiteral("askSave")+name());
+ cg.deleteEntry(QStringLiteral("askEmbedOrSave")+name());
} else {
// Do not ask, open
- cg.writeEntry("askSave"+name(), "no" );
- cg.writeEntry("askEmbedOrSave"+name(), "no" );
+ cg.writeEntry(QStringLiteral("askSave")+name(), QStringLiteral("no") );
+ cg.writeEntry(QStringLiteral("askEmbedOrSave")+name(), QStringLiteral("no") );
}
}
writeAutoEmbed();
bool needUpdateMimeDb = false;
if (isMimeTypeDirty()) {
MimeTypeWriter mimeTypeWriter(name());
mimeTypeWriter.setComment(m_comment);
if (!m_userSpecifiedIcon.isEmpty()) {
mimeTypeWriter.setIconName(m_userSpecifiedIcon);
}
mimeTypeWriter.setPatterns(m_patterns);
if (!mimeTypeWriter.write())
return false;
m_userSpecifiedIconModified = false;
needUpdateMimeDb = true;
}
syncServices();
return needUpdateMimeDb;
}
static const char s_DefaultApplications[] = "Default Applications";
static const char s_AddedAssociations[] = "Added Associations";
static const char s_RemovedAssociations[] = "Removed Associations";
void MimeTypeData::syncServices()
{
if (!m_bFullInit)
return;
- KSharedConfig::Ptr profile = KSharedConfig::openConfig("mimeapps.list", KConfig::NoGlobals, QStandardPaths::GenericConfigLocation);
+ KSharedConfig::Ptr profile = KSharedConfig::openConfig(QStringLiteral("mimeapps.list"), KConfig::NoGlobals, QStandardPaths::GenericConfigLocation);
if (!profile->isConfigWritable(true)) // warn user if mimeapps.list is root-owned (#155126/#94504)
return;
const QStringList oldAppServices = getAppOffers();
if (oldAppServices != m_appServices) {
// Save the default application according to mime-apps-spec 1.0
KConfigGroup defaultApp(profile, s_DefaultApplications);
saveDefaultApplication(defaultApp, m_appServices);
// Save preferred services
KConfigGroup addedApps(profile, s_AddedAssociations);
saveServices(addedApps, m_appServices);
KConfigGroup removedApps(profile, s_RemovedAssociations);
saveRemovedServices(removedApps, m_appServices, oldAppServices);
}
const QStringList oldPartServices = getPartOffers();
if (oldPartServices != m_embedServices) {
// Handle removed services
KConfigGroup addedParts(profile, "Added KDE Service Associations");
saveServices(addedParts, m_embedServices);
KConfigGroup removedParts(profile, "Removed KDE Service Associations");
saveRemovedServices(removedParts, m_embedServices, oldPartServices);
}
// Clean out any kde-mimeapps.list which would take precedence any cancel our changes.
const QString desktops = QString::fromLocal8Bit(qgetenv("XDG_CURRENT_DESKTOP"));
- foreach (const QString &desktop, desktops.split(":", QString::SkipEmptyParts)) {
+ foreach (const QString &desktop, desktops.split(QLatin1Char(':'), QString::SkipEmptyParts)) {
const QString file = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)
+ QLatin1Char('/') + desktop.toLower() + QLatin1String("-mimeapps.list");
if (QFileInfo::exists(file)) {
qDebug() << "Cleaning up" << file;
KConfig conf(file, KConfig::NoGlobals);
KConfigGroup(&conf, s_DefaultApplications).deleteEntry(name());
KConfigGroup(&conf, s_AddedAssociations).deleteEntry(name());
KConfigGroup(&conf, s_RemovedAssociations).deleteEntry(name());
}
}
m_appServicesModified = false;
m_embedServicesModified = false;
}
static QStringList collectStorageIds(const QStringList& services)
{
QStringList serviceList;
QStringList::const_iterator it(services.begin());
for (int i = services.count(); it != services.end(); ++it, i--) {
KService::Ptr pService = KService::serviceByStorageId(*it);
if (!pService) {
qWarning() << "service with storage id" << *it << "not found";
continue; // Where did that one go?
}
serviceList.append(pService->storageId());
}
return serviceList;
}
void MimeTypeData::saveRemovedServices(KConfigGroup & config, const QStringList& services, const QStringList& oldServices)
{
QStringList removedServiceList = config.readXdgListEntry(name());
Q_FOREACH(const QString& service, services) {
// If removedServiceList.contains(service), then it was previously removed but has been added back
removedServiceList.removeAll(service);
}
Q_FOREACH(const QString& oldService, oldServices) {
if (!services.contains(oldService)) {
// The service was in m_appServices (or m_embedServices) but has been removed
removedServiceList.append(oldService);
}
}
if (removedServiceList.isEmpty())
config.deleteEntry(name());
else
config.writeXdgListEntry(name(), removedServiceList);
}
void MimeTypeData::saveServices(KConfigGroup & config, const QStringList& services)
{
if (services.isEmpty())
config.deleteEntry(name());
else
config.writeXdgListEntry(name(), collectStorageIds(services));
}
void MimeTypeData::saveDefaultApplication(KConfigGroup & config, const QStringList& services)
{
if (services.isEmpty())
config.deleteEntry(name());
else
config.writeXdgListEntry(name(), QStringList(collectStorageIds(services).first()));
}
void MimeTypeData::refresh()
{
if (m_isGroup)
return;
QMimeDatabase db;
m_mimetype = db.mimeTypeForName( name() );
if (m_mimetype.isValid()) {
if (m_bNewItem) {
qDebug() << "OK, created" << name();
m_bNewItem = false; // if this was a new mimetype, we just created it
}
if (!isMimeTypeDirty()) {
// Update from the xml, in case something was changed from out of this kcm
// (e.g. using KOpenWithDialog, or keditfiletype + kcmshell filetypes)
initFromQMimeType();
}
if (!m_appServicesModified && !m_embedServicesModified) {
m_bFullInit = false; // refresh services too
}
}
}
void MimeTypeData::getAskSave(bool &_askSave)
{
if (m_askSave == AskSaveYes)
_askSave = true;
if (m_askSave == AskSaveNo)
_askSave = false;
}
void MimeTypeData::setAskSave(bool _askSave)
{
m_askSave = _askSave ? AskSaveYes : AskSaveNo;
}
bool MimeTypeData::canUseGroupSetting() const
{
// "Use group settings" isn't available for zip, tar etc.; those have a builtin default...
if (!m_mimetype.isValid()) // e.g. new mimetype
return true;
const bool hasLocalProtocolRedirect = !KProtocolManager::protocolForArchiveMimetype(name()).isEmpty();
return !hasLocalProtocolRedirect;
}
void MimeTypeData::setPatterns(const QStringList &p)
{
m_patterns = p;
// Sort them, since update-mime-database doesn't respect order (order of globs file != order of xml),
// and this code says things like if (m_mimetype.patterns() == m_patterns).
// We could also sort in KMimeType::setPatterns but this would just slow down the
// normal use case (anything else than this KCM) for no good reason.
m_patterns.sort();
}
bool MimeTypeData::matchesFilter(const QString& filter) const
{
if (name().contains(filter, Qt::CaseInsensitive))
return true;
if (m_comment.contains(filter, Qt::CaseInsensitive))
return true;
if (!m_patterns.filter(filter, Qt::CaseInsensitive).isEmpty())
return true;
return false;
}
void MimeTypeData::setAppServices(const QStringList &dsl)
{
m_appServices = dsl;
m_appServicesModified = true;
}
void MimeTypeData::setEmbedServices(const QStringList &dsl)
{
m_embedServices = dsl;
m_embedServicesModified = true;
}
QString MimeTypeData::icon() const
{
if (!m_userSpecifiedIcon.isEmpty())
return m_userSpecifiedIcon;
if (m_mimetype.isValid())
return m_mimetype.iconName();
return QString();
}
diff --git a/keditfiletype/mimetypedata.h b/keditfiletype/mimetypedata.h
index 04728af..11ad9c1 100644
--- a/keditfiletype/mimetypedata.h
+++ b/keditfiletype/mimetypedata.h
@@ -1,139 +1,139 @@
/* This file is part of the KDE project
Copyright (C) 2003 Waldo Bastian
Copyright (C) 2003, 2007 David Faure
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License version 2 or at your option version 3 as published by
the Free Software Foundation.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef MIMETYPEDATA_H
#define MIMETYPEDATA_H
#include
#include
class KConfigGroup;
/**
* This is a non-gui (data) class, that represents a mimetype.
* It is a QMimeType plus the changes we made to it.
*/
class MimeTypeData
{
public:
// Constructor used for groups
MimeTypeData(const QString& major);
// Real constructor, used for an existing mimetype.
MimeTypeData(const QMimeType& mime);
// Real constructor, used for a new mimetype.
MimeTypeData(const QString& mimeName, bool /*unused, just to distinguish from the other QString ctor*/);
- QString name() const { return m_isGroup ? m_major : m_major + '/' + m_minor; }
+ QString name() const { return m_isGroup ? m_major : m_major + QLatin1Char('/') + m_minor; }
QString majorType() const { return m_major; }
QString minorType() const { return m_minor; }
void setMinor(const QString& m) { m_minor = m; }
QString comment() const { return m_comment; }
void setComment(const QString& c) { m_comment = c; }
/**
* Returns true if "this" is a group
*/
bool isMeta() const { return m_isGroup; }
/**
* Returns true if the type is essential, i.e. can't be deleted
* (see KMimeType::checkEssentialMimeTypes)
*/
bool isEssential() const;
QString icon() const;
void setUserSpecifiedIcon(const QString& icon);
QStringList patterns() const { return m_patterns; }
void setPatterns(const QStringList &p);
QStringList appServices() const;
void setAppServices(const QStringList &dsl);
QStringList embedServices() const;
void setEmbedServices(const QStringList &dsl);
enum AutoEmbed { Yes = 0, No = 1, UseGroupSetting = 2 };
AutoEmbed autoEmbed() const { return m_autoEmbed; }
void setAutoEmbed( AutoEmbed a ) { m_autoEmbed = a; }
const QMimeType& mimeType() const { return m_mimetype; }
bool canUseGroupSetting() const;
void getAskSave(bool &);
void setAskSave(bool);
/**
* Returns true if the mimetype data has any unsaved changes.
*/
bool isDirty() const;
/**
* Returns true if the mimetype data has any unsaved changes in the service list.
*/
bool isServiceListDirty() const;
/**
* Save changes to disk.
* Does not check isDirty(), so the common idiom is if (data.isDirty()) { needUpdate = data.sync(); }
* Returns true if update-mime-database needs to be run afterwards
*/
bool sync();
/**
* Update m_mimetype from the xml when Apply is pressed
*/
void refresh();
/**
* Return true if this is a new mimetype, i.e. one that is not yet on disk
*/
bool isNew() const { return m_bNewItem; }
/**
* Helper method for the filtering in the listview
*/
bool matchesFilter(const QString& filter) const;
private:
void initFromQMimeType();
AutoEmbed readAutoEmbed() const;
void writeAutoEmbed();
bool isMimeTypeDirty() const; // whether the mimetype definition file needs saving
QStringList getAppOffers() const;
QStringList getPartOffers() const;
void getMyServiceOffers() const;
void syncServices();
void saveServices(KConfigGroup & config, const QStringList& services);
void saveDefaultApplication(KConfigGroup & config, const QStringList& services);
void saveRemovedServices(KConfigGroup & config, const QStringList& services, const QStringList& oldServices);
QMimeType m_mimetype;
enum AskSave { AskSaveYes = 0, AskSaveNo = 1, AskSaveDefault = 2 };
AskSave m_askSave:3;
AutoEmbed m_autoEmbed:3;
bool m_bNewItem:1;
mutable bool m_bFullInit:1; // lazy init of m_appServices and m_embedServices
bool m_isGroup:1;
bool m_appServicesModified:1;
bool m_embedServicesModified:1;
bool m_userSpecifiedIconModified:1;
QString m_major, m_minor, m_comment, m_userSpecifiedIcon;
QStringList m_patterns;
mutable QStringList m_appServices;
mutable QStringList m_embedServices;
};
#endif /* MIMETYPEDATA_H */
diff --git a/keditfiletype/mimetypewriter.cpp b/keditfiletype/mimetypewriter.cpp
index 22259c4..b94c069 100644
--- a/keditfiletype/mimetypewriter.cpp
+++ b/keditfiletype/mimetypewriter.cpp
@@ -1,178 +1,178 @@
/* This file is part of the KDE project
Copyright (C) 2007, 2008 David Faure
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 ) version 3 or, at the discretion of KDE e.V. ( which shall
act as a proxy as in section 14 of the GPLv3 ), any later version.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "mimetypewriter.h"
#include
#include
#include
#include
#include
#include
#include
#include
class MimeTypeWriterPrivate
{
public:
QString localFilePath() const;
QString m_mimeType;
QString m_comment;
QString m_iconName;
QStringList m_patterns;
QString m_marker;
};
MimeTypeWriter::MimeTypeWriter(const QString& mimeType)
: d(new MimeTypeWriterPrivate)
{
d->m_mimeType = mimeType;
Q_ASSERT(!mimeType.isEmpty());
}
MimeTypeWriter::~MimeTypeWriter()
{
delete d;
}
void MimeTypeWriter::setComment(const QString& comment)
{
d->m_comment = comment;
}
void MimeTypeWriter::setPatterns(const QStringList& patterns)
{
d->m_patterns = patterns;
}
void MimeTypeWriter::setIconName(const QString& iconName)
{
d->m_iconName = iconName;
}
void MimeTypeWriter::setMarker(const QString& marker)
{
d->m_marker = marker;
}
bool MimeTypeWriter::write()
{
const QString packageFileName = d->localFilePath();
qDebug() << "writing" << packageFileName;
QFile packageFile(packageFileName);
if (!packageFile.open(QIODevice::WriteOnly)) {
qCritical() << "Couldn't open" << packageFileName << "for writing";
return false;
}
QXmlStreamWriter writer(&packageFile);
writer.setAutoFormatting(true);
writer.writeStartDocument();
if (!d->m_marker.isEmpty()) {
writer.writeComment(d->m_marker);
}
- const QString nsUri = "http://www.freedesktop.org/standards/shared-mime-info";
+ const QString nsUri = QStringLiteral("http://www.freedesktop.org/standards/shared-mime-info");
writer.writeDefaultNamespace(nsUri);
- writer.writeStartElement("mime-info");
- writer.writeStartElement(nsUri, "mime-type");
- writer.writeAttribute("type", d->m_mimeType);
+ writer.writeStartElement(QStringLiteral("mime-info"));
+ writer.writeStartElement(nsUri, QStringLiteral("mime-type"));
+ writer.writeAttribute(QStringLiteral("type"), d->m_mimeType);
if (!d->m_comment.isEmpty()) {
- writer.writeStartElement(nsUri, "comment");
+ writer.writeStartElement(nsUri, QStringLiteral("comment"));
writer.writeCharacters(d->m_comment);
writer.writeEndElement(); // comment
}
if (!d->m_iconName.isEmpty()) {
// User-specified icon name
- writer.writeStartElement(nsUri, "icon");
- writer.writeAttribute("name", d->m_iconName);
+ writer.writeStartElement(nsUri, QStringLiteral("icon"));
+ writer.writeAttribute(QStringLiteral("name"), d->m_iconName);
writer.writeEndElement(); // icon
}
// Allow this local definition to override the global definition
- writer.writeStartElement(nsUri, "glob-deleteall");
+ writer.writeStartElement(nsUri, QStringLiteral("glob-deleteall"));
writer.writeEndElement(); // glob-deleteall
foreach(const QString& pattern, d->m_patterns) {
- writer.writeStartElement(nsUri, "glob");
- writer.writeAttribute("pattern", pattern);
+ writer.writeStartElement(nsUri, QStringLiteral("glob"));
+ writer.writeAttribute(QStringLiteral("pattern"), pattern);
writer.writeEndElement(); // glob
}
writer.writeEndElement(); // mime-info
writer.writeEndElement(); // mime-type
writer.writeEndDocument();
return true;
}
void MimeTypeWriter::runUpdateMimeDatabase()
{
const QString localPackageDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/");
Q_ASSERT(!localPackageDir.isEmpty());
KProcess proc;
- proc << "update-mime-database";
+ proc << QStringLiteral("update-mime-database");
proc << localPackageDir;
const int exitCode = proc.execute();
if (exitCode) {
qWarning() << proc.program() << "exited with error code" << exitCode;
}
}
QString MimeTypeWriterPrivate::localFilePath() const
{
// XDG shared mime: we must write into a /share/mime/packages/ file...
// To simplify our job, let's use one "input" file per mimetype, in the user's dir.
// (this writes into $HOME/.local/share/mime by default)
//
// We could also use Override.xml, says the spec, but then we'd need to merge with other mimetypes,
// and in ~/.local we don't really expect other packages to be installed anyway...
QString baseName = m_mimeType;
- baseName.replace('/', '-');
- QString packagesDirName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/") + "packages/";
+ baseName.replace(QLatin1Char('/'), QLatin1Char('-'));
+ QString packagesDirName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/") + QStringLiteral("packages/");
// create the directory, the saving will fail if it doesn't exist (bug#356237)
QDir(packagesDirName).mkpath(QStringLiteral("."));
- return packagesDirName + baseName + ".xml" ;
+ return packagesDirName + baseName + QStringLiteral(".xml");
}
static QString existingDefinitionFile(const QString& mimeType)
{
QString baseName = mimeType;
- baseName.replace('/', '-');
- return QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + "packages/" + baseName + ".xml" );
+ baseName.replace(QLatin1Char('/'), QLatin1Char('-'));
+ return QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + QStringLiteral("packages/") + baseName + QStringLiteral(".xml") );
}
bool MimeTypeWriter::hasDefinitionFile(const QString& mimeType)
{
return !existingDefinitionFile(mimeType).isEmpty();
}
void MimeTypeWriter::removeOwnMimeType(const QString& mimeType)
{
const QString file = existingDefinitionFile(mimeType);
Q_ASSERT(!file.isEmpty());
QFile::remove(file);
// We must also remove the generated XML file, update-mime-database doesn't do that, for unknown media types
- QString xmlFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + mimeType + ".xml" );
+ QString xmlFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + mimeType + QStringLiteral(".xml") );
QFile::remove(xmlFile);
}
/// WARNING: this code is duplicated between apps/nsplugins and runtime/filetypes
diff --git a/keditfiletype/newtypedlg.cpp b/keditfiletype/newtypedlg.cpp
index 78c2fdd..4471b87 100644
--- a/keditfiletype/newtypedlg.cpp
+++ b/keditfiletype/newtypedlg.cpp
@@ -1,90 +1,90 @@
/* This file is part of the KDE project
Copyright 2000 Kurt Granroth
2008 David Faure
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License version 2 or at your option version 3 as published by
the Free Software Foundation.
This program 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
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
// Own
#include "newtypedlg.h"
// Qt
#include
#include
#include
#include
#include
#include
#include
// KDE
#include
#include
NewTypeDialog::NewTypeDialog(const QStringList &groups, QWidget *parent)
: QDialog( parent )
{
setModal( true );
setWindowTitle( i18n( "Create New File Type" ) );
QVBoxLayout *mainLayout = new QVBoxLayout(this);
QFormLayout *formLayout = new QFormLayout;
QLabel *l = new QLabel(i18n("Group:"));
m_groupCombo = new QComboBox;
m_groupCombo->setEditable(true);
m_groupCombo->addItems(groups);
- m_groupCombo->setCurrentIndex(m_groupCombo->findText("application")); // certainly a better default than "all"
+ m_groupCombo->setCurrentIndex(m_groupCombo->findText(QStringLiteral("application"))); // certainly a better default than "all"
formLayout->addRow(l, m_groupCombo);
m_groupCombo->setWhatsThis( i18n("Select the category under which"
" the new file type should be added.") );
// Line 1: mimetype name
l = new QLabel(i18n("Type name:"));
m_typeEd = new KLineEdit;
formLayout->addRow(l, m_typeEd);
m_typeEd->setWhatsThis(i18n("Type the name of the file type. For instance, if you selected 'image' as category and you type 'custom' here, the file type 'image/custom' will be created."));
m_typeEd->setFocus();
m_buttonBox = new QDialogButtonBox;
m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
mainLayout->addLayout(formLayout);
mainLayout->addWidget(m_buttonBox);
connect(m_buttonBox, SIGNAL(accepted()), SLOT(accept()));
connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));
// Set a minimum width so that caption is not half-hidden
setMinimumWidth(300);
}
QString NewTypeDialog::group() const
{
return m_groupCombo->currentText();
}
QString NewTypeDialog::text() const
{
return m_typeEd->text();
}
diff --git a/keditfiletype/tests/filetypestest.cpp b/keditfiletype/tests/filetypestest.cpp
index d712eba..b2a9311 100644
--- a/keditfiletype/tests/filetypestest.cpp
+++ b/keditfiletype/tests/filetypestest.cpp
@@ -1,430 +1,430 @@
/* This file is part of the KDE project
Copyright 2007 David Faure
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 ) version 3 or, at the discretion of KDE e.V. ( which shall
act as a proxy as in section 14 of the GPLv3 ), any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Boston, MA 02110-1301, USA.
*/
#include
#include
#include
#include
// Qt
#include
#include
#include
#include
#include
#include
#include
#include
class FileTypesTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase()
{
extern KSERVICE_EXPORT bool kservice_require_kded;
kservice_require_kded = false;
QLoggingCategory::setFilterRules(QStringLiteral("kf5.kcoreaddons.kdirwatch.debug=true"));
QStandardPaths::setTestModeEnabled(true);
m_mimeTypeCreatedSuccessfully = false;
QStringList appsDirs = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
//qDebug() << appsDirs;
- m_localApps = appsDirs.first() + '/';
+ m_localApps = appsDirs.first() + QLatin1Char('/');
m_localConfig = QDir(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation));
QVERIFY(QDir().mkpath(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/mime/packages")));
- QFile::remove(m_localConfig.filePath("mimeapps.list"));
+ QFile::remove(m_localConfig.filePath(QStringLiteral("mimeapps.list")));
// Create fake applications for some tests below.
bool mustUpdateKSycoca = false;
- fakeApplication = "fakeapplication.desktop";
+ fakeApplication = QStringLiteral("fakeapplication.desktop");
if (createDesktopFile(m_localApps + fakeApplication))
mustUpdateKSycoca = true;
- fakeApplication2 = "fakeapplication2.desktop";
+ fakeApplication2 = QStringLiteral("fakeapplication2.desktop");
if (createDesktopFile(m_localApps + fakeApplication2))
mustUpdateKSycoca = true;
// Cleanup after testMimeTypePatterns if it failed mid-way
- const QString packageFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/") + "packages/text-plain.xml" ;
+ const QString packageFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/") + QStringLiteral("packages/text-plain.xml") ;
if (!packageFileName.isEmpty()) {
QFile::remove(packageFileName);
MimeTypeWriter::runUpdateMimeDatabase();
mustUpdateKSycoca = true;
}
- QFile::remove(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QLatin1Char('/') + "filetypesrc");
+ QFile::remove(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QLatin1Char('/') + QStringLiteral("filetypesrc"));
if ( mustUpdateKSycoca ) {
// Update ksycoca in ~/.kde-unit-test after creating the above
runKBuildSycoca();
}
KService::Ptr fakeApplicationService = KService::serviceByStorageId(fakeApplication);
QVERIFY(fakeApplicationService);
}
void testMimeTypeGroupAutoEmbed()
{
- MimeTypeData data("text");
- QCOMPARE(data.majorType(), QString("text"));
- QCOMPARE(data.name(), QString("text"));
+ MimeTypeData data(QStringLiteral("text"));
+ QCOMPARE(data.majorType(), QStringLiteral("text"));
+ QCOMPARE(data.name(), QStringLiteral("text"));
QVERIFY(data.isMeta());
QCOMPARE(data.autoEmbed(), MimeTypeData::No); // text doesn't autoembed by default
QVERIFY(!data.isDirty());
data.setAutoEmbed(MimeTypeData::Yes);
QCOMPARE(data.autoEmbed(), MimeTypeData::Yes);
QVERIFY(data.isDirty());
QVERIFY(!data.sync()); // save to disk. Should succeed, but return false (no need to run update-mime-database)
QVERIFY(!data.isDirty());
// Check what's on disk by creating another MimeTypeData instance
- MimeTypeData data2("text");
+ MimeTypeData data2(QStringLiteral("text"));
QCOMPARE(data2.autoEmbed(), MimeTypeData::Yes);
QVERIFY(!data2.isDirty());
data2.setAutoEmbed(MimeTypeData::No); // revert to default, for next time
QVERIFY(data2.isDirty());
QVERIFY(!data2.sync());
QVERIFY(!data2.isDirty());
// TODO test askSave after cleaning up the code
}
void testMimeTypeAutoEmbed()
{
QMimeDatabase db;
- MimeTypeData data(db.mimeTypeForName("text/plain"));
- QCOMPARE(data.majorType(), QString("text"));
- QCOMPARE(data.minorType(), QString("plain"));
- QCOMPARE(data.name(), QString("text/plain"));
+ MimeTypeData data(db.mimeTypeForName(QStringLiteral("text/plain")));
+ QCOMPARE(data.majorType(), QStringLiteral("text"));
+ QCOMPARE(data.minorType(), QStringLiteral("plain"));
+ QCOMPARE(data.name(), QStringLiteral("text/plain"));
QVERIFY(!data.isMeta());
QCOMPARE(data.autoEmbed(), MimeTypeData::UseGroupSetting);
QVERIFY(!data.isDirty());
data.setAutoEmbed(MimeTypeData::Yes);
QCOMPARE(data.autoEmbed(), MimeTypeData::Yes);
QVERIFY(data.isDirty());
QVERIFY(!data.sync()); // save to disk. Should succeed, but return false (no need to run update-mime-database)
QVERIFY(!data.isDirty());
// Check what's on disk by creating another MimeTypeData instance
- MimeTypeData data2(db.mimeTypeForName("text/plain"));
+ MimeTypeData data2(db.mimeTypeForName(QStringLiteral("text/plain")));
QCOMPARE(data2.autoEmbed(), MimeTypeData::Yes);
QVERIFY(!data2.isDirty());
data2.setAutoEmbed(MimeTypeData::UseGroupSetting); // revert to default, for next time
QVERIFY(data2.isDirty());
QVERIFY(!data2.sync());
QVERIFY(!data2.isDirty());
}
void testMimeTypePatterns()
{
// Given the text/plain mimetype
QMimeDatabase db;
- MimeTypeData data(db.mimeTypeForName("text/plain"));
- QCOMPARE(data.name(), QString("text/plain"));
- QCOMPARE(data.majorType(), QString("text"));
- QCOMPARE(data.minorType(), QString("plain"));
+ MimeTypeData data(db.mimeTypeForName(QStringLiteral("text/plain")));
+ QCOMPARE(data.name(), QStringLiteral("text/plain"));
+ QCOMPARE(data.majorType(), QStringLiteral("text"));
+ QCOMPARE(data.minorType(), QStringLiteral("plain"));
QVERIFY(!data.isMeta());
QStringList patterns = data.patterns();
- QVERIFY(patterns.contains("*.txt"));
- QVERIFY(!patterns.contains("*.toto"));
+ QVERIFY(patterns.contains(QStringLiteral("*.txt")));
+ QVERIFY(!patterns.contains(QStringLiteral("*.toto")));
// When the user changes the patterns
const QStringList origPatterns = patterns;
- patterns.removeAll("*.txt");
- patterns.append("*.toto"); // yes, a french guy wrote this, as you can see
+ patterns.removeAll(QStringLiteral("*.txt"));
+ patterns.append(QStringLiteral("*.toto")); // yes, a french guy wrote this, as you can see
patterns.sort(); // for future comparisons
QVERIFY(!data.isDirty());
data.setPatterns(patterns);
QVERIFY(data.isDirty());
bool needUpdateMimeDb = data.sync();
QVERIFY(needUpdateMimeDb);
MimeTypeWriter::runUpdateMimeDatabase();
// Then the GUI and the QMimeDatabase API should show the new patterns
QCOMPARE(data.patterns(), patterns);
data.refresh(); // reload from the xml
QCOMPARE(data.patterns(), patterns);
// Check what's in QMimeDatabase
- QStringList newPatterns = db.mimeTypeForName("text/plain").globPatterns();
+ QStringList newPatterns = db.mimeTypeForName(QStringLiteral("text/plain")).globPatterns();
newPatterns.sort();
QCOMPARE(newPatterns, patterns);
QVERIFY(!data.isDirty());
// And then removing the custom file by hand should revert to the initial state
- const QString packageFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/") + "packages/text-plain.xml" ;
+ const QString packageFileName = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/") + QStringLiteral("packages/text-plain.xml") ;
QVERIFY(!packageFileName.isEmpty());
QFile::remove(packageFileName);
MimeTypeWriter::runUpdateMimeDatabase();
// Check what's in QMimeDatabase
- newPatterns = db.mimeTypeForName("text/plain").globPatterns();
+ newPatterns = db.mimeTypeForName(QStringLiteral("text/plain")).globPatterns();
newPatterns.sort();
QCOMPARE(newPatterns, origPatterns);
}
void testAddService()
{
QMimeDatabase db;
- const char* mimeTypeName = "application/rtf"; // use inherited mimetype to test #321706
+ QString mimeTypeName = QStringLiteral("application/rtf"); // use inherited mimetype to test #321706
MimeTypeData data(db.mimeTypeForName(mimeTypeName));
QStringList appServices = data.appServices();
//qDebug() << appServices;
QVERIFY(!appServices.isEmpty());
const QString oldPreferredApp = appServices.first();
QVERIFY(!appServices.contains(fakeApplication)); // already there? hmm can't really test then
QVERIFY(!data.isDirty());
appServices.prepend(fakeApplication);
data.setAppServices(appServices);
QVERIFY(data.isDirty());
QVERIFY(!data.sync()); // success, but no need to run update-mime-database
runKBuildSycoca();
QVERIFY(!data.isDirty());
// Check what's in ksycoca
checkMimeTypeServices(mimeTypeName, appServices);
// Check what's in mimeapps.list
checkAddedAssociationsContains(mimeTypeName, fakeApplication);
// Test reordering apps, i.e. move fakeApplication under oldPreferredApp
appServices.removeFirst();
appServices.insert(1, fakeApplication);
data.setAppServices(appServices);
QVERIFY(!data.sync()); // success, but no need to run update-mime-database
runKBuildSycoca();
QVERIFY(!data.isDirty());
// Check what's in ksycoca
checkMimeTypeServices(mimeTypeName, appServices);
// Check what's in mimeapps.list
checkAddedAssociationsContains(mimeTypeName, fakeApplication);
// Now test removing (in the same test, since it's inter-dependent)
QVERIFY(appServices.removeAll(fakeApplication) > 0);
data.setAppServices(appServices);
QVERIFY(data.isDirty());
QVERIFY(!data.sync()); // success, but no need to run update-mime-database
runKBuildSycoca();
// Check what's in ksycoca
checkMimeTypeServices(mimeTypeName, appServices);
// Check what's in mimeapps.list
checkRemovedAssociationsContains(mimeTypeName, fakeApplication);
}
void testRemoveTwice()
{
QMimeDatabase db;
// Remove fakeApplication from image/png
- const char* mimeTypeName = "image/png";
+ QString mimeTypeName = QStringLiteral("image/png");
MimeTypeData data(db.mimeTypeForName(mimeTypeName));
QStringList appServices = data.appServices();
qDebug() << "initial list for" << mimeTypeName << appServices;
QVERIFY(appServices.removeAll(fakeApplication) > 0);
data.setAppServices(appServices);
QVERIFY(!data.sync()); // success, but no need to run update-mime-database
runKBuildSycoca();
// Check what's in ksycoca
checkMimeTypeServices(mimeTypeName, appServices);
// Check what's in mimeapps.list
checkRemovedAssociationsContains(mimeTypeName, fakeApplication);
// Remove fakeApplication2 from image/png; must keep the previous entry in "Removed Associations"
qDebug() << "Removing fakeApplication2";
QVERIFY(appServices.removeAll(fakeApplication2) > 0);
data.setAppServices(appServices);
QVERIFY(!data.sync()); // success, but no need to run update-mime-database
runKBuildSycoca();
// Check what's in ksycoca
checkMimeTypeServices(mimeTypeName, appServices);
// Check what's in mimeapps.list
checkRemovedAssociationsContains(mimeTypeName, fakeApplication);
// Check what's in mimeapps.list
checkRemovedAssociationsContains(mimeTypeName, fakeApplication2);
// And now re-add fakeApplication2...
qDebug() << "Re-adding fakeApplication2";
appServices.prepend(fakeApplication2);
data.setAppServices(appServices);
QVERIFY(!data.sync()); // success, but no need to run update-mime-database
runKBuildSycoca();
// Check what's in ksycoca
checkMimeTypeServices(mimeTypeName, appServices);
// Check what's in mimeapps.list
checkRemovedAssociationsContains(mimeTypeName, fakeApplication);
checkRemovedAssociationsDoesNotContain(mimeTypeName, fakeApplication2);
}
void testCreateMimeType()
{
QMimeDatabase db;
- const QString mimeTypeName = "fake/unit-test-fake-mimetype";
+ const QString mimeTypeName = QStringLiteral("fake/unit-test-fake-mimetype");
// Clean up after previous runs if necessary
if (MimeTypeWriter::hasDefinitionFile(mimeTypeName))
MimeTypeWriter::removeOwnMimeType(mimeTypeName);
MimeTypeData data(mimeTypeName, true);
- data.setComment("Fake MimeType");
- QStringList patterns = QStringList() << "*.pkg.tar.gz";
+ data.setComment(QStringLiteral("Fake MimeType"));
+ QStringList patterns = QStringList() << QStringLiteral("*.pkg.tar.gz");
data.setPatterns(patterns);
QVERIFY(data.isDirty());
QVERIFY(data.sync());
MimeTypeWriter::runUpdateMimeDatabase();
//runKBuildSycoca();
// QMimeDatabase doesn't even try to update the cache if less than
// 5000 ms have passed
QTest::qSleep(5000);
QMimeType mime = db.mimeTypeForName(mimeTypeName);
QVERIFY(mime.isValid());
- QCOMPARE(mime.comment(), QString("Fake MimeType"));
+ QCOMPARE(mime.comment(), QStringLiteral("Fake MimeType"));
QCOMPARE(mime.globPatterns(), patterns); // must sort them if more than one
// Testcase for the shaman.xml bug
- QCOMPARE(db.mimeTypeForFile("/whatever/foo.pkg.tar.gz").name(), QString("fake/unit-test-fake-mimetype"));
+ QCOMPARE(db.mimeTypeForFile(QStringLiteral("/whatever/foo.pkg.tar.gz")).name(), QStringLiteral("fake/unit-test-fake-mimetype"));
m_mimeTypeCreatedSuccessfully = true;
}
void testDeleteMimeType()
{
QMimeDatabase db;
if (!m_mimeTypeCreatedSuccessfully)
QSKIP("This test relies on testCreateMimeType");
- const QString mimeTypeName = "fake/unit-test-fake-mimetype";
+ const QString mimeTypeName = QStringLiteral("fake/unit-test-fake-mimetype");
QVERIFY(MimeTypeWriter::hasDefinitionFile(mimeTypeName));
MimeTypeWriter::removeOwnMimeType(mimeTypeName);
MimeTypeWriter::runUpdateMimeDatabase();
//runKBuildSycoca();
QMimeType mime = db.mimeTypeForName(mimeTypeName);
QVERIFY(mime.isValid());
}
void testModifyMimeTypeComment() // of a system mimetype. And check that it's re-read correctly.
{
QMimeDatabase db;
- const char* mimeTypeName = "image/png";
+ QString mimeTypeName = QStringLiteral("image/png");
MimeTypeData data(db.mimeTypeForName(mimeTypeName));
QCOMPARE(data.comment(), QString::fromLatin1("PNG image"));
- const char* fakeComment = "PNG image [testing]";
+ QString fakeComment = QStringLiteral("PNG image [testing]");
data.setComment(fakeComment);
QVERIFY(data.isDirty());
QVERIFY(data.sync());
MimeTypeWriter::runUpdateMimeDatabase();
//runKBuildSycoca();
QMimeType mime = db.mimeTypeForName(mimeTypeName);
QVERIFY(mime.isValid());
- QCOMPARE(mime.comment(), QString::fromLatin1(fakeComment));
+ QCOMPARE(mime.comment(), fakeComment);
// Cleanup
QVERIFY(MimeTypeWriter::hasDefinitionFile(mimeTypeName));
MimeTypeWriter::removeOwnMimeType(mimeTypeName);
}
void cleanupTestCase()
{
// If we remove it, then every run of the unit test has to run kbuildsycoca... slow.
//QFile::remove(QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation) + QLatin1Char('/') + "fakeapplication.desktop");
}
private: // helper methods
void checkAddedAssociationsContains(const QString& mimeTypeName, const QString& application)
{
- const KConfig config(m_localConfig.filePath("mimeapps.list"), KConfig::NoGlobals);
+ const KConfig config(m_localConfig.filePath(QStringLiteral("mimeapps.list")), KConfig::NoGlobals);
const KConfigGroup group(&config, "Added Associations");
const QStringList addedEntries = group.readXdgListEntry(mimeTypeName);
if (!addedEntries.contains(application)) {
qWarning() << addedEntries << "does not contain" << application;
QVERIFY(addedEntries.contains(application));
}
}
void checkRemovedAssociationsContains(const QString& mimeTypeName, const QString& application)
{
- const KConfig config(m_localConfig.filePath("mimeapps.list"), KConfig::NoGlobals);
+ const KConfig config(m_localConfig.filePath(QStringLiteral("mimeapps.list")), KConfig::NoGlobals);
const KConfigGroup group(&config, "Removed Associations");
const QStringList removedEntries = group.readXdgListEntry(mimeTypeName);
if (!removedEntries.contains(application)) {
qWarning() << removedEntries << "does not contain" << application;
QVERIFY(removedEntries.contains(application));
}
}
void checkRemovedAssociationsDoesNotContain(const QString& mimeTypeName, const QString& application)
{
- const KConfig config(m_localConfig.filePath("mimeapps.list"), KConfig::NoGlobals);
+ const KConfig config(m_localConfig.filePath(QStringLiteral("mimeapps.list")), KConfig::NoGlobals);
const KConfigGroup group(&config, "Removed Associations");
const QStringList removedEntries = group.readXdgListEntry(mimeTypeName);
if (removedEntries.contains(application)) {
qWarning() << removedEntries << "contains" << application;
QVERIFY(!removedEntries.contains(application));
}
}
void runKBuildSycoca()
{
// Wait for notifyDatabaseChanged DBus signal
// (The real KCM code simply does the refresh in a slot, asynchronously)
QProcess proc;
//proc.setProcessChannelMode(QProcess::ForwardedChannels);
- const QString kbuildsycoca = QStandardPaths::findExecutable(KBUILDSYCOCA_EXENAME);
+ const QString kbuildsycoca = QStandardPaths::findExecutable(QLatin1String(KBUILDSYCOCA_EXENAME));
QVERIFY(!kbuildsycoca.isEmpty());
QStringList args;
- args << "--testmode";
+ args << QStringLiteral("--testmode");
proc.start(kbuildsycoca, args);
QSignalSpy spy(KSycoca::self(), SIGNAL(databaseChanged(QStringList)));
proc.waitForFinished();
qDebug() << "waiting for signal";
QVERIFY(spy.wait(10000));
qDebug() << "got signal";
}
bool createDesktopFile(const QString& path)
{
if (!QFile::exists(path)) {
KDesktopFile file(path);
KConfigGroup group = file.desktopGroup();
group.writeEntry("Name", "FakeApplication");
group.writeEntry("Type", "Application");
group.writeEntry("Exec", "ls");
group.writeEntry("MimeType", "image/png");
return true;
}
return false;
}
void checkMimeTypeServices(const QString& mimeTypeName, const QStringList& expectedServices)
{
QMimeDatabase db;
MimeTypeData data2(db.mimeTypeForName(mimeTypeName));
if (data2.appServices() != expectedServices)
qDebug() << "got" << data2.appServices() << "expected" << expectedServices;
QCOMPARE(data2.appServices(), expectedServices);
}
QString fakeApplication; // storage id of the fake application
QString fakeApplication2; // storage id of the fake application2
QString m_localApps;
QDir m_localConfig;
bool m_mimeTypeCreatedSuccessfully;
};
QTEST_MAIN(FileTypesTest)
#include "filetypestest.moc"
diff --git a/kioclient/kioclient.cpp b/kioclient/kioclient.cpp
index 737572c..ee89561 100644
--- a/kioclient/kioclient.cpp
+++ b/kioclient/kioclient.cpp
@@ -1,418 +1,418 @@
/* This file is part of the KDE project
Copyright (C) 1999-2006 David Faure
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 "kioclient.h"
#include
#include
#include
#include
#ifndef KIOCORE_ONLY
#include
#include
#include
#include
#include
#endif
#include
#include
#include
#include
#include
#include
#include
bool ClientApp::m_ok = true;
static bool s_interactive = true;
static KIO::JobFlags s_jobFlags = KIO::DefaultFlags;
static QUrl makeURL(const QString &urlArg)
{
return QUrl::fromUserInput(urlArg, QDir::currentPath());
}
static QList makeUrls(const QStringList& urlArgs)
{
QList ret;
foreach(const QString& url, urlArgs) {
ret += makeURL(url);
}
return ret;
}
#ifdef KIOCLIENT_AS_KIOCLIENT5
static void usage()
{
puts(i18n("\nSyntax:\n").toLocal8Bit());
puts(i18n(" kioclient openProperties 'url'\n"
" # Opens a properties menu\n\n").toLocal8Bit());
puts(i18n(" kioclient exec 'url' ['mimetype']\n"
" # Tries to open the document pointed to by 'url', in the application\n"
" # associated with it in KDE. You may omit 'mimetype'.\n"
" # In this case the mimetype is determined\n"
" # automatically. Of course URL may be the URL of a\n"
" # document, or it may be a *.desktop file.\n"
" # 'url' can be an executable, too.\n").toLocal8Bit());
puts(i18n(" kioclient move 'src' 'dest'\n"
" # Moves the URL 'src' to 'dest'.\n"
" # 'src' may be a list of URLs.\n").toLocal8Bit());
puts(i18n(" # 'dest' may be \"trash:/\" to move the files\n"
" # to the trash.\n").toLocal8Bit());
puts(i18n(" # the short version kioclient mv\n"
" # is also available.\n\n").toLocal8Bit());
puts(i18n(" kioclient download ['src']\n"
" # Copies the URL 'src' to a user-specified location'.\n"
" # 'src' may be a list of URLs, if not present then\n"
" # a URL will be requested.\n\n").toLocal8Bit());
puts(i18n(" kioclient copy 'src' 'dest'\n"
" # Copies the URL 'src' to 'dest'.\n"
" # 'src' may be a list of URLs.\n").toLocal8Bit());
puts(i18n(" # the short version kioclient cp\n"
" # is also available.\n\n").toLocal8Bit());
puts(i18n(" kioclient cat 'url'\n"
" # Writes out the contents of 'url' to stdout\n\n").toLocal8Bit());
puts(i18n(" kioclient ls 'url'\n"
" # Lists the contents of the directory 'url' to stdout\n\n").toLocal8Bit());
puts(i18n(" kioclient remove 'url'\n"
" # Removes the URL\n"
" # 'url' may be a list of URLs.\n").toLocal8Bit());
puts(i18n(" # the short version kioclient rm\n"
" # is also available.\n\n").toLocal8Bit());
puts(i18n("*** Examples:\n").toLocal8Bit());
puts(i18n(" kioclient exec file:/home/weis/data/test.html\n"
" // Opens the file with default binding\n\n").toLocal8Bit());
puts(i18n(" kioclient exec ftp://localhost/\n"
" // Opens new window with URL\n\n").toLocal8Bit());
puts(i18n(" kioclient exec file:/root/Desktop/emacs.desktop\n"
" // Starts emacs\n\n").toLocal8Bit());
puts(i18n(" kioclient exec .\n"
" // Opens the current directory. Very convenient.\n\n").toLocal8Bit());
}
#endif
int main( int argc, char **argv )
{
#ifdef KIOCORE_ONLY
QCoreApplication app(argc, argv);
#else
QApplication app(argc, argv);
#endif
KLocalizedString::setApplicationDomain("kioclient5");
- QString appName = "kioclient";
+ QString appName = QStringLiteral("kioclient");
QString programName = i18n("KIO Client");
QString description = i18n("Command-line tool for network-transparent operations");
- QString version = PROJECT_VERSION;
+ QString version = QLatin1String(PROJECT_VERSION);
KAboutData data(appName, programName, version, description, KAboutLicense::LGPL_V2);
KAboutData::setApplicationData(data);
QCommandLineParser parser;
data.setupCommandLine(&parser);
- parser.addOption(QCommandLineOption("noninteractive", i18n("Non-interactive use: no message boxes. If you don't want a "
+ parser.addOption(QCommandLineOption(QStringLiteral("noninteractive"), i18n("Non-interactive use: no message boxes. If you don't want a "
"graphical connection, use --platform offscreen")));
#if !defined(KIOCLIENT_AS_KDEOPEN)
- parser.addOption(QCommandLineOption("overwrite", i18n("Overwrite destination if it exists (for copy and move)")));
+ parser.addOption(QCommandLineOption(QStringLiteral("overwrite"), i18n("Overwrite destination if it exists (for copy and move)")));
#endif
#if defined(KIOCLIENT_AS_KDEOPEN)
- parser.addPositionalArgument("url", i18n("file or URL"), i18n("urls..."));
+ parser.addPositionalArgument(QStringLiteral("url"), i18n("file or URL"), i18n("urls..."));
#elif defined(KIOCLIENT_AS_KDECP5)
- parser.addPositionalArgument("src", i18n("Source URL or URLs"), i18n("urls..."));
- parser.addPositionalArgument("dest", i18n("Destination URL"), i18n("url"));
+ parser.addPositionalArgument(QStringLiteral("src"), i18n("Source URL or URLs"), i18n("urls..."));
+ parser.addPositionalArgument(QStringLiteral("dest"), i18n("Destination URL"), i18n("url"));
#elif defined(KIOCLIENT_AS_KDEMV5)
- parser.addPositionalArgument("src", i18n("Source URL or URLs"), i18n("urls..."));
- parser.addPositionalArgument("dest", i18n("Destination URL"), i18n("url"));
+ parser.addPositionalArgument(QStringLiteral("src"), i18n("Source URL or URLs"), i18n("urls..."));
+ parser.addPositionalArgument(QStringLiteral("dest"), i18n("Destination URL"), i18n("url"));
#elif defined(KIOCLIENT_AS_KIOCLIENT5)
- parser.addOption(QCommandLineOption("commands", i18n("Show available commands")));
- parser.addPositionalArgument("command", i18n("Command (see --commands)"), i18n("command"));
- parser.addPositionalArgument("URLs", i18n("Arguments for command"), i18n("urls..."));
+ parser.addOption(QCommandLineOption(QStringLiteral("commands"), i18n("Show available commands")));
+ parser.addPositionalArgument(QStringLiteral("command"), i18n("Command (see --commands)"), i18n("command"));
+ parser.addPositionalArgument(QStringLiteral("URLs"), i18n("Arguments for command"), i18n("urls..."));
#endif
// KCmdLineArgs::addTempFileOption();
parser.process(app);
data.processCommandLine(&parser);
#ifdef KIOCLIENT_AS_KIOCLIENT5
- if ( argc == 1 || parser.isSet("commands") )
+ if ( argc == 1 || parser.isSet(QStringLiteral("commands")) )
{
puts(parser.helpText().toLocal8Bit());
puts("\n\n");
usage();
return 0;
}
#endif
ClientApp client;
return client.doIt(parser) ? 0 /*no error*/ : 1 /*error*/;
}
static bool krun_has_error = false;
void ClientApp::delayedQuit()
{
#ifndef KIOCORE_ONLY
// don't access the KRun instance later, it will be deleted after calling slots
if( static_cast< const KRun* >( sender())->hasError())
krun_has_error = true;
#endif
}
static void checkArgumentCount(int count, int min, int max)
{
if (count < min)
{
fputs( i18nc("@info:shell", "%1: Syntax error, not enough arguments\n", qAppName()).toLocal8Bit(), stderr );
::exit(1);
}
if (max && (count > max))
{
fputs( i18nc("@info:shell", "%1: Syntax error, too many arguments\n", qAppName()).toLocal8Bit(), stderr );
::exit(1);
}
}
#ifndef KIOCORE_ONLY
bool ClientApp::kde_open(const QUrl& url, const QString& mimeType, bool allowExec)
{
if ( mimeType.isEmpty() ) {
KRun * run = new KRun( url, nullptr );
run->setRunExecutables(allowExec);
QObject::connect( run, SIGNAL( finished() ), this, SLOT( delayedQuit() ));
QObject::connect( run, SIGNAL( error() ), this, SLOT( delayedQuit() ));
qApp->exec();
return !krun_has_error;
} else {
return KRun::runUrl(url, mimeType, nullptr, KRun::RunFlags(KRun::RunExecutables));
}
}
#endif
bool ClientApp::doCopy( const QStringList& urls )
{
QList srcLst(makeUrls(urls));
QUrl dest = srcLst.takeLast();
KIO::Job * job = KIO::copy( srcLst, dest, s_jobFlags );
if ( !s_interactive )
job->setUiDelegate( nullptr );
connect( job, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
qApp->exec();
return m_ok;
}
void ClientApp::slotEntries(KIO::Job*, const KIO::UDSEntryList& list)
{
KIO::UDSEntryList::ConstIterator it=list.begin();
for (; it != list.end(); ++it) {
// For each file...
QString name = (*it).stringValue( KIO::UDSEntry::UDS_NAME );
std::cout << qPrintable(name) << std::endl;
}
}
bool ClientApp::doList( const QStringList& urls )
{
QUrl dir = makeURL(urls.first());
KIO::Job * job = KIO::listDir(dir, KIO::HideProgressInfo);
if ( !s_interactive )
job->setUiDelegate(nullptr);
connect(job, SIGNAL(entries(KIO::Job*,KIO::UDSEntryList)),
SLOT(slotEntries(KIO::Job*,KIO::UDSEntryList)));
connect(job, SIGNAL(result(KJob *)), this, SLOT(slotResult(KJob *)));
qApp->exec();
return m_ok;
}
bool ClientApp::doMove( const QStringList& urls )
{
QList srcLst(makeUrls(urls));
QUrl dest = srcLst.takeLast();
KIO::Job * job = KIO::move( srcLst, dest, s_jobFlags );
if ( !s_interactive )
job->setUiDelegate( nullptr );
connect( job, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
qApp->exec();
return m_ok;
}
bool ClientApp::doRemove( const QStringList& urls )
{
KIO::Job * job = KIO::del( makeUrls(urls), s_jobFlags );
if ( !s_interactive )
job->setUiDelegate( nullptr );
connect( job, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
qApp->exec();
return m_ok;
}
bool ClientApp::doIt(const QCommandLineParser& parser)
{
const int argc = parser.positionalArguments().count();
checkArgumentCount(argc, 1, 0);
- if ( !parser.isSet( "noninteractive" ) ) {
+ if ( !parser.isSet( QStringLiteral("noninteractive") ) ) {
s_interactive = false;
s_jobFlags = KIO::HideProgressInfo;
}
#if !defined(KIOCLIENT_AS_KDEOPEN)
- if (parser.isSet("overwrite")) {
+ if (parser.isSet(QStringLiteral("overwrite"))) {
s_jobFlags |= KIO::Overwrite;
}
#endif
#ifdef KIOCLIENT_AS_KDEOPEN
- return kde_open(makeURL(parser.positionalArguments().at(0)), QByteArray(), false);
+ return kde_open(makeURL(parser.positionalArguments().at(0)), QString(), false);
#elif defined(KIOCLIENT_AS_KDECP5)
checkArgumentCount(argc, 2, 0);
return doCopy(parser.positionalArguments());
#elif defined(KIOCLIENT_AS_KDEMV5)
checkArgumentCount(argc, 2, 0);
return doMove(parser.positionalArguments());
#else
// Normal kioclient mode
QString command = parser.positionalArguments().first();
#ifndef KIOCORE_ONLY
- if ( command == "openProperties" )
+ if ( command == QLatin1String("openProperties") )
{
checkArgumentCount(argc, 2, 2); // openProperties
QUrl url = makeURL(parser.positionalArguments().last());
KPropertiesDialog * p = new KPropertiesDialog(url, nullptr /*no parent*/ );
QObject::connect( p, SIGNAL( destroyed() ), qApp, SLOT( quit() ));
QObject::connect( p, SIGNAL( canceled() ), this, SLOT( slotDialogCanceled() ));
p->show();
qApp->exec();
return m_ok;
}
else
#endif
- if ( command == "cat" )
+ if ( command == QLatin1String("cat") )
{
checkArgumentCount(argc, 2, 2); // cat
QUrl url = makeURL(parser.positionalArguments().last());
KIO::TransferJob* job = KIO::get(url, KIO::NoReload, s_jobFlags);
if ( !s_interactive )
job->setUiDelegate( nullptr );
connect(job, SIGNAL(data(KIO::Job*,QByteArray) ), this, SLOT(slotPrintData(KIO::Job*,QByteArray)));
connect(job, SIGNAL( result( KJob * ) ), this, SLOT( slotResult( KJob * ) ) );
qApp->exec();
return m_ok;
}
#ifndef KIOCORE_ONLY
- else if ( command == "exec" )
+ else if ( command ==QLatin1String( "exec") )
{
checkArgumentCount(argc, 2, 3);
return kde_open( makeURL(parser.positionalArguments()[1]),
argc == 3 ? parser.positionalArguments().last() : QString(),
true );
}
#endif
- else if ( command == "download" )
+ else if ( command == QLatin1String("download") )
{
checkArgumentCount(argc, 0, 0);
QStringList args = parser.positionalArguments();
args.removeFirst();
QList srcLst = makeUrls(args);
if (srcLst.isEmpty())
return m_ok;
QUrl dsturl = QFileDialog::getSaveFileUrl(nullptr, i18n("Destination where to download the files"), (!srcLst.isEmpty()) ? QUrl() : srcLst.first() );
if (dsturl.isEmpty()) // canceled
return m_ok; // AK - really okay?
KIO::Job * job = KIO::copy( srcLst, dsturl, s_jobFlags );
if ( !s_interactive )
job->setUiDelegate( nullptr );
connect( job, SIGNAL( result( KJob * ) ), qApp, SLOT( slotResult( KJob * ) ) );
qApp->exec();
return m_ok;
}
- else if ( command == "copy" || command == "cp" )
+ else if ( command == QLatin1String("copy") || command == QLatin1String("cp") )
{
checkArgumentCount(argc, 3, 0); // cp
QStringList args = parser.positionalArguments();
args.removeFirst();
return doCopy(args);
}
- else if ( command == "move" || command == "mv" )
+ else if ( command == QLatin1String("move") || command == QLatin1String("mv") )
{
checkArgumentCount(argc, 3, 0); // mv
QStringList args = parser.positionalArguments();
args.removeFirst();
return doMove(args);
}
- else if ( command == "list" || command == "ls" )
+ else if ( command == QLatin1String("list") || command == QLatin1String("ls") )
{
checkArgumentCount(argc, 2, 2); // ls
QStringList args = parser.positionalArguments();
args.removeFirst();
return doList(args);
}
- else if ( command == "remove" || command == "rm" )
+ else if ( command == QLatin1String("remove") || command == QLatin1String("rm") )
{
checkArgumentCount(argc, 2, 0); // rm
QStringList args = parser.positionalArguments();
args.removeFirst();
return doRemove(args);
}
else
{
fputs( i18nc("@info:shell", "%1: Syntax error, unknown command '%2'\n", qAppName(), command).toLocal8Bit().data(), stderr );
return false;
}
Q_UNREACHABLE();
#endif
}
void ClientApp::slotResult( KJob * job )
{
if (job->error()) {
#ifndef KIOCORE_ONLY
if (s_interactive) {
static_cast(job)->uiDelegate()->showErrorMessage();
} else
#endif
{
qWarning() << job->errorString();
}
}
m_ok = !job->error();
qApp->quit();
}
void ClientApp::slotDialogCanceled()
{
m_ok = false;
qApp->quit();
}
void ClientApp::slotPrintData(KIO::Job*, const QByteArray &data)
{
if (!data.isEmpty())
std::cout.write(data.constData(), data.size());
}
ClientApp::ClientApp()
: QObject()
{
}
diff --git a/kmimetypefinder/kmimetypefinder.cpp b/kmimetypefinder/kmimetypefinder.cpp
index bf7960e..95879ff 100644
--- a/kmimetypefinder/kmimetypefinder.cpp
+++ b/kmimetypefinder/kmimetypefinder.cpp
@@ -1,77 +1,77 @@
/*
* Copyright (C) 2002 David Faure
* Copyright (C) 2008 Pino Toscano
*
* 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
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
KLocalizedString::setApplicationDomain("kmimetypefinder5");
KAboutData aboutData( QLatin1String("kmimetypefinder"), i18n("MIME Type Finder"), QLatin1String(PROJECT_VERSION ));
aboutData.setShortDescription(i18n("Gives the MIME type for a given file"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("c") << QLatin1String("content"), i18n("Use only the file content for determining the MIME type.")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("f") << QLatin1String("filename-only"), i18n("Whether use the file name only for determining the MIME type. Not used if -c is specified.")));
parser.addPositionalArgument(QLatin1String("filename"), i18n("The filename to test. '-' to read from stdin."));
parser.process(app);
aboutData.processCommandLine(&parser);
if( parser.positionalArguments().count() < 1 ) {
printf( "No filename specified\n" );
return 1;
}
const QString fileName = parser.positionalArguments().at( 0 );
QMimeDatabase db;
QMimeType mime;
if (fileName == QLatin1String("-")) {
QFile qstdin;
qstdin.open(stdin, QIODevice::ReadOnly);
const QByteArray data = qstdin.readAll();
mime = db.mimeTypeForData(data);
- } else if (parser.isSet("c")) {
+ } else if (parser.isSet(QStringLiteral("c"))) {
mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent);
- } else if (parser.isSet("f")) {
+ } else if (parser.isSet(QStringLiteral("f"))) {
mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchExtension);
} else {
mime = db.mimeTypeForFile(fileName);
}
if ( !mime.isDefault() ) {
printf("%s\n", mime.name().toLatin1().constData());
} else {
return 1; // error
}
return 0;
}
diff --git a/kstart/kstart.cpp b/kstart/kstart.cpp
index 0db0134..fce5c73 100644
--- a/kstart/kstart.cpp
+++ b/kstart/kstart.cpp
@@ -1,441 +1,441 @@
/*
* kstart.C. Part of the KDE project.
*
* Copyright (C) 1997-2000 Matthias Ettrich
*
* First port to NETWM by David Faure
* Send to system tray by Richard Moore
* 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) 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 14 of version 3 of the license.
* This program 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 General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include
#include "kstart.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
// some globals
static KProcess* proc = nullptr;
static QString exe;
static QString url;
static QString windowtitle;
static QString windowclass;
static int desktop = 0;
static bool activate = false;
static bool iconify = false;
static bool fullscreen = false;
static NET::States state = {};
static NET::States mask = {};
static NET::WindowType windowtype = NET::Unknown;
KStart::KStart()
:QObject()
{
NETRootInfo i( QX11Info::connection(), NET::Supported );
bool useRule = i.isSupported( NET::WM2KDETemporaryRules );
if( useRule )
sendRule();
else {
// connect to window add to get the NEW windows
connect(KWindowSystem::self(), SIGNAL(windowAdded(WId)), SLOT(windowAdded(WId)));
}
// propagate the app startup notification info to the started app
// We are not using KApplication, so the env remained set
KStartupInfoId id = KStartupInfo::currentStartupIdEnv();
//finally execute the comand
if (proc) {
if( int pid = proc->startDetached() ) {
KStartupInfoData data;
data.addPid( pid );
data.setName( exe );
- data.setBin( exe.mid( exe.lastIndexOf( '/' ) + 1 ));
+ data.setBin( exe.mid( exe.lastIndexOf( QLatin1Char('/') ) + 1 ));
KStartupInfo::sendChange( id, data );
}
else
KStartupInfo::sendFinish( id ); // failed to start
} else {
QString error;
QString dbusService;
int pid;
if (KToolInvocation::startServiceByDesktopPath(exe, url, &error, &dbusService, &pid) == 0) {
printf("%s\n", qPrintable(dbusService));
} else {
qCritical() << error;
}
}
QTimer::singleShot( useRule ? 0 : 120 * 1000, qApp, SLOT( quit()));
}
void KStart::sendRule() {
KXMessages msg;
QString message;
if( !windowtitle.isEmpty() )
- message += "title=" + windowtitle + "\ntitlematch=3\n"; // 3 = regexp match
+ message += QStringLiteral("title=") + windowtitle + QStringLiteral("\ntitlematch=3\n"); // 3 = regexp match
if( !windowclass.isEmpty() )
- message += "wmclass=" + windowclass + "\nwmclassmatch=1\n" // 1 = exact match
- + "wmclasscomplete="
+ message += QStringLiteral("wmclass=") + windowclass + QStringLiteral("\nwmclassmatch=1\n") // 1 = exact match
+ + QStringLiteral("wmclasscomplete=")
// if windowclass contains a space (i.e. 2 words, use whole WM_CLASS)
- + ( windowclass.contains( ' ' ) ? "true" : "false" ) + '\n';
+ + ( windowclass.contains( QLatin1Char(' ') ) ? QStringLiteral("true") : QStringLiteral("false") ) + QLatin1Char('\n');
if( (!windowtitle.isEmpty()) || (!windowclass.isEmpty()) ) {
// always ignore these window types
- message += "types=" + QString().setNum( -1U &
- ~( NET::TopMenuMask | NET::ToolbarMask | NET::DesktopMask | NET::SplashMask | NET::MenuMask )) + '\n';
+ message += QStringLiteral("types=") + QString().setNum( -1U &
+ ~( NET::TopMenuMask | NET::ToolbarMask | NET::DesktopMask | NET::SplashMask | NET::MenuMask )) + QLatin1Char('\n');
} else {
// accept only "normal" windows
- message += "types=" + QString().setNum( NET::NormalMask | NET::DialogMask ) + '\n';
+ message += QStringLiteral("types=") + QString().setNum( NET::NormalMask | NET::DialogMask ) + QLatin1Char('\n');
}
if ( ( desktop > 0 && desktop <= KWindowSystem::numberOfDesktops() )
|| desktop == NETWinInfo::OnAllDesktops ) {
- message += "desktop=" + QString().setNum( desktop ) + "\ndesktoprule=3\n";
+ message += QStringLiteral("desktop=") + QString().setNum( desktop ) + QStringLiteral("\ndesktoprule=3\n");
}
if (activate)
- message += "fsplevel=0\nfsplevelrule=2\n";
+ message += QStringLiteral("fsplevel=0\nfsplevelrule=2\n");
if (iconify)
- message += "minimize=true\nminimizerule=3\n";
+ message += QStringLiteral("minimize=true\nminimizerule=3\n");
if ( windowtype != NET::Unknown ) {
- message += "type=" + QString().setNum( windowtype ) + "\ntyperule=2";
+ message += QStringLiteral("type=") + QString().setNum( windowtype ) + QStringLiteral("\ntyperule=2");
}
if ( state ) {
if( state & NET::KeepAbove )
- message += "above=true\naboverule=3\n";
+ message += QStringLiteral("above=true\naboverule=3\n");
if( state & NET::KeepBelow )
- message += "below=true\nbelowrule=3\n";
+ message += QStringLiteral("below=true\nbelowrule=3\n");
if( state & NET::SkipTaskbar )
- message += "skiptaskbar=true\nskiptaskbarrule=3\n";
+ message += QStringLiteral("skiptaskbar=true\nskiptaskbarrule=3\n");
if( state & NET::SkipPager )
- message += "skippager=true\nskippagerrule=3\n";
+ message += QStringLiteral("skippager=true\nskippagerrule=3\n");
if( state & NET::MaxVert )
- message += "maximizevert=true\nmaximizevertrule=3\n";
+ message += QStringLiteral("maximizevert=true\nmaximizevertrule=3\n");
if( state & NET::MaxHoriz )
- message += "maximizehoriz=true\nmaximizehorizrule=3\n";
+ message += QStringLiteral("maximizehoriz=true\nmaximizehorizrule=3\n");
if( state & NET::FullScreen )
- message += "fullscreen=true\nfullscreenrule=3\n";
+ message += QStringLiteral("fullscreen=true\nfullscreenrule=3\n");
}
msg.broadcastMessage( "_KDE_NET_WM_TEMPORARY_RULES", message, -1 );
qApp->flush();
}
const NET::WindowTypes SUPPORTED_WINDOW_TYPES_MASK = NET::NormalMask | NET::DesktopMask | NET::DockMask
| NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask
| NET::UtilityMask | NET::SplashMask;
void KStart::windowAdded(WId w){
KWindowInfo info( w, NET::WMWindowType | NET::WMName );
// always ignore these window types
if( info.windowType( SUPPORTED_WINDOW_TYPES_MASK ) == NET::TopMenu
|| info.windowType( SUPPORTED_WINDOW_TYPES_MASK ) == NET::Toolbar
|| info.windowType( SUPPORTED_WINDOW_TYPES_MASK ) == NET::Desktop )
return;
if ( !windowtitle.isEmpty() ) {
QString title = info.name().toLower();
QRegExp r( windowtitle.toLower());
if ( !r.exactMatch(title) )
return; // no match
}
if ( !windowclass.isEmpty() ) {
#ifdef __GNUC__
#warning "Porting required"
#endif
#if 0
XClassHint hint;
if( !XGetClassHint( QX11Info::display(), w, &hint ))
return;
Q3CString cls = windowclass.contains( ' ' )
? Q3CString( hint.res_name ) + ' ' + hint.res_class : Q3CString( hint.res_class );
cls = cls.toLower();
XFree( hint.res_name );
XFree( hint.res_class );
if( cls != windowclass )
return;
#endif
}
if( windowtitle.isEmpty() && windowclass.isEmpty() ) {
// accept only "normal" windows
if( info.windowType( SUPPORTED_WINDOW_TYPES_MASK ) != NET::Unknown
&& info.windowType( SUPPORTED_WINDOW_TYPES_MASK ) != NET::Normal
&& info.windowType( SUPPORTED_WINDOW_TYPES_MASK ) != NET::Dialog )
return;
}
applyStyle( w );
QApplication::exit();
}
//extern Atom qt_wm_state; // defined in qapplication_x11.cpp
static bool wstate_withdrawn( WId winid )
{
Q_UNUSED(winid);
#ifdef __GNUC__
#warning "Porting required."
#endif
//Porting info: The Qt4 equivalent for qt_wm_state is qt_x11Data->atoms[QX11Data::WM_STATE]
//which can be accessed via the macro ATOM(WM_STATE). Unfortunately, neither of these seem
//to be exported out of the Qt environment. This value may have to be acquired from somewhere else.
/*
Atom type;
int format;
unsigned long length, after;
unsigned char *data;
int r = XGetWindowProperty( QX11Info::display(), winid, qt_wm_state, 0, 2,
false, AnyPropertyType, &type, &format,
&length, &after, &data );
bool withdrawn = true;
if ( r == Success && data && format == 32 ) {
quint32 *wstate = (quint32*)data;
withdrawn = (*wstate == WithdrawnState );
XFree( (char *)data );
}
return withdrawn;
*/
return true;
}
void KStart::applyStyle(WId w ) {
if ( state || iconify || windowtype != NET::Unknown || desktop >= 1 ) {
XWithdrawWindow(QX11Info::display(), w, QX11Info::appScreen());
QApplication::flush();
while ( !wstate_withdrawn(w) )
;
}
NETWinInfo info(QX11Info::connection(), w, QX11Info::appRootWindow(), NET::WMState, NET::Properties2());
if ( ( desktop > 0 && desktop <= KWindowSystem::numberOfDesktops() )
|| desktop == NETWinInfo::OnAllDesktops )
info.setDesktop( desktop );
if (iconify) {
XWMHints * hints = XGetWMHints(QX11Info::display(), w );
if (hints ) {
hints->flags |= StateHint;
hints->initial_state = IconicState;
XSetWMHints( QX11Info::display(), w, hints );
XFree(hints);
}
}
if ( windowtype != NET::Unknown ) {
info.setWindowType( windowtype );
}
if ( state )
info.setState( state, mask );
if ( fullscreen ) {
QRect r = QApplication::desktop()->screenGeometry();
XMoveResizeWindow( QX11Info::display(), w, r.x(), r.y(), r.width(), r.height() );
}
XSync(QX11Info::display(), False);
XMapWindow(QX11Info::display(), w );
XSync(QX11Info::display(), False);
if (activate)
KWindowSystem::forceActiveWindow( w );
QApplication::flush();
}
int main( int argc, char *argv[] )
{
QApplication app(argc, argv);
KLocalizedString::setApplicationDomain( "kstart5" );
- KAboutData aboutData(QStringLiteral("kstart"), i18n("KStart"), PROJECT_VERSION,
+ KAboutData aboutData(QStringLiteral("kstart"), i18n("KStart"), QString::fromLatin1(PROJECT_VERSION),
i18n(""
"Utility to launch applications with special window properties \n"
"such as iconified, maximized, a certain virtual desktop, a special decoration\n"
"and so on." ),
KAboutLicense::GPL,
i18n("(C) 1997-2000 Matthias Ettrich (ettrich@kde.org)"));
- aboutData.addAuthor( i18n("Matthias Ettrich"), QString(), "ettrich@kde.org" );
- aboutData.addAuthor( i18n("David Faure"), QString(), "faure@kde.org" );
- aboutData.addAuthor( i18n("Richard J. Moore"), QString(), "rich@kde.org" );
+ aboutData.addAuthor( i18n("Matthias Ettrich"), QString(), QStringLiteral("ettrich@kde.org") );
+ aboutData.addAuthor( i18n("David Faure"), QString(), QStringLiteral("faure@kde.org") );
+ aboutData.addAuthor( i18n("Richard J. Moore"), QString(), QStringLiteral("rich@kde.org") );
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("!+command"), i18n("Command to execute")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("service"), i18n("Alternative to : desktop file to start. D-Bus service will be printed to stdout"), QLatin1String("desktopfile")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("url"), i18n("Optional URL to pass , when using --service"), QLatin1String("url")));
// "!" means: all options after command are treated as arguments to the command
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("window"), i18n("A regular expression matching the window title"), QLatin1String("regexp")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("windowclass"),
i18n("A string matching the window class (WM_CLASS property)\n"
"The window class can be found out by running\n"
"'xprop | grep WM_CLASS' and clicking on a window\n"
"(use either both parts separated by a space or only the right part).\n"
"NOTE: If you specify neither window title nor window class,\n"
"then the very first window to appear will be taken;\n"
"omitting both options is NOT recommended."), QLatin1String("class")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("desktop"), i18n("Desktop on which to make the window appear"), QLatin1String("number")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("currentdesktop"), i18n("Make the window appear on the desktop that was active\nwhen starting the application")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("alldesktops"), i18n("Make the window appear on all desktops")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("iconify"), i18n("Iconify the window")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("maximize"), i18n("Maximize the window")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("maximize-vertically"), i18n("Maximize the window vertically")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("maximize-horizontally"), i18n("Maximize the window horizontally")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("fullscreen"), i18n("Show window fullscreen")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("type"), i18n("The window type: Normal, Desktop, Dock, Toolbar, \nMenu, Dialog, TopMenu or Override"), QLatin1String("type")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("activate"),
i18n("Jump to the window even if it is started on a \n"
"different virtual desktop")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("ontop") << QLatin1String("keepabove"), i18n("Try to keep the window above other windows")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("onbottom") << QLatin1String("keepbelow"), i18n("Try to keep the window below other windows")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("skiptaskbar"), i18n("The window does not get an entry in the taskbar")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("skippager"), i18n("The window does not get an entry on the pager")));
parser.process(app);
aboutData.processCommandLine(&parser);
- if (parser.isSet("service")) {
- exe = parser.value("service");
- url = parser.value("url");
+ if (parser.isSet(QStringLiteral("service"))) {
+ exe = parser.value(QStringLiteral("service"));
+ url = parser.value(QStringLiteral("url"));
} else {
if ( parser.positionalArguments().count() == 0 )
qCritical() << i18n("No command specified");
exe = parser.positionalArguments().at(0);
proc = new KProcess;
for(int i=0; i < parser.positionalArguments().count(); i++)
(*proc) << parser.positionalArguments().at(i);
}
- desktop = parser.value( "desktop" ).toInt();
- if ( parser.isSet ( "alldesktops") )
+ desktop = parser.value( QStringLiteral("desktop") ).toInt();
+ if ( parser.isSet ( QStringLiteral("alldesktops")) )
desktop = NETWinInfo::OnAllDesktops;
- if ( parser.isSet ( "currentdesktop") )
+ if ( parser.isSet ( QStringLiteral("currentdesktop")) )
desktop = KWindowSystem::currentDesktop();
- windowtitle = parser.value( "window" );
- windowclass = parser.value( "windowclass" );
+ windowtitle = parser.value( QStringLiteral("window" ));
+ windowclass = parser.value( QStringLiteral("windowclass" ));
if( !windowclass.isEmpty() )
windowclass = windowclass.toLower();
if( windowtitle.isEmpty() && windowclass.isEmpty())
qWarning() << "Omitting both --window and --windowclass arguments is not recommended" ;
- QString s = parser.value( "type" );
+ QString s = parser.value( QStringLiteral("type") );
if ( !s.isEmpty() ) {
s = s.toLower();
- if ( s == "desktop" )
+ if ( s == QLatin1String("desktop") )
windowtype = NET::Desktop;
- else if ( s == "dock" )
+ else if ( s == QLatin1String("dock") )
windowtype = NET::Dock;
- else if ( s == "toolbar" )
+ else if ( s == QLatin1String("toolbar") )
windowtype = NET::Toolbar;
- else if ( s == "menu" )
+ else if ( s == QLatin1String("menu") )
windowtype = NET::Menu;
- else if ( s == "dialog" )
+ else if ( s == QLatin1String("dialog") )
windowtype = NET::Dialog;
- else if ( s == "override" )
+ else if ( s == QLatin1String("override") )
windowtype = NET::Override;
- else if ( s == "topmenu" )
+ else if ( s == QLatin1String("topmenu") )
windowtype = NET::TopMenu;
else
windowtype = NET::Normal;
}
- if ( parser.isSet( "keepabove" ) ) {
+ if ( parser.isSet( QStringLiteral("keepabove") ) ) {
state |= NET::KeepAbove;
mask |= NET::KeepAbove;
- } else if ( parser.isSet( "keepbelow" ) ) {
+ } else if ( parser.isSet( QStringLiteral("keepbelow") ) ) {
state |= NET::KeepBelow;
mask |= NET::KeepBelow;
}
- if ( parser.isSet( "skiptaskbar" ) ) {
+ if ( parser.isSet( QStringLiteral("skiptaskbar") ) ) {
state |= NET::SkipTaskbar;
mask |= NET::SkipTaskbar;
}
- if ( parser.isSet( "skippager" ) ) {
+ if ( parser.isSet( QStringLiteral("skippager") ) ) {
state |= NET::SkipPager;
mask |= NET::SkipPager;
}
- activate = parser.isSet("activate");
+ activate = parser.isSet(QStringLiteral("activate"));
- if ( parser.isSet("maximize") ) {
+ if ( parser.isSet(QStringLiteral("maximize")) ) {
state |= NET::Max;
mask |= NET::Max;
}
- if ( parser.isSet("maximize-vertically") ) {
+ if ( parser.isSet(QStringLiteral("maximize-vertically")) ) {
state |= NET::MaxVert;
mask |= NET::MaxVert;
}
- if ( parser.isSet("maximize-horizontally") ) {
+ if ( parser.isSet(QStringLiteral("maximize-horizontally")) ) {
state |= NET::MaxHoriz;
mask |= NET::MaxHoriz;
}
- iconify = parser.isSet("iconify");
- if ( parser.isSet("fullscreen") ) {
+ iconify = parser.isSet(QStringLiteral("iconify"));
+ if ( parser.isSet(QStringLiteral("fullscreen")) ) {
NETRootInfo i( QX11Info::connection(), NET::Supported );
if( i.isSupported( NET::FullScreen )) {
state |= NET::FullScreen;
mask |= NET::FullScreen;
} else {
windowtype = NET::Override;
fullscreen = true;
}
}
fcntl(XConnectionNumber(QX11Info::display()), F_SETFD, 1);
KStart start;
return app.exec();
}
diff --git a/ksvgtopng/ksvgtopng.cpp b/ksvgtopng/ksvgtopng.cpp
index b5c85ee..5813d4c 100644
--- a/ksvgtopng/ksvgtopng.cpp
+++ b/ksvgtopng/ksvgtopng.cpp
@@ -1,57 +1,57 @@
#include
#include
#include
#include
#include
#include
using std::cout;
using std::endl;
int main(int argc, char **argv)
{
// Initialize Qt application, otherwise for some svg files it can segfault with:
// ASSERT failure in QFontDatabase: "A QApplication object needs to be
// constructed before FontConfig is used."
QApplication app(argc, argv);
if(argc < 5)
{
cout << "Usage : ksvgtopng width height svgfilename outputfilename" << endl;
cout << "Please use full path name for svgfilename" << endl;
return -1;
}
int width = atoi(argv[1]);
int height = atoi(argv[2]);
QImage img(width, height, QImage::Format_ARGB32_Premultiplied);
img.fill(0);
QSvgRenderer renderer(QString::fromLocal8Bit(argv[3]));
if(renderer.isValid())
{
QPainter p(&img);
renderer.render(&p);
/*
// Apply icon sharpening
double factor = 0;
if(width == 16)
factor = 30;
else if(width == 32)
factor = 20;
else if(width == 48)
factor = 10;
else if(width == 64)
factor = 5;
*img = KImageEffect::sharpen(*img, factor); // use QImageBlitz::sharpen()
*/
}
- img.save(argv[4], "PNG");
+ img.save(QString::fromLatin1(argv[4]), "PNG");
return 0;
}
diff --git a/ktraderclient/ktraderclient.cpp b/ktraderclient/ktraderclient.cpp
index b566808..db9d724 100644
--- a/ktraderclient/ktraderclient.cpp
+++ b/ktraderclient/ktraderclient.cpp
@@ -1,123 +1,123 @@
/*
* Copyright (C) 2002, 2003 David Faure
*
* 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
#include
#include
#include
#include
#include
#include
#include
int main( int argc, char **argv )
{
QCoreApplication app(argc, argv);
KLocalizedString::setApplicationDomain("ktraderclient5");
KAboutData aboutData(QLatin1String("ktraderclient"), i18n("KTraderClient"), QLatin1String(PROJECT_VERSION));
- aboutData.addAuthor(i18n("David Faure"), QString(), "faure@kde.org");
+ aboutData.addAuthor(i18n("David Faure"), QString(), QStringLiteral("faure@kde.org"));
aboutData.setShortDescription(i18n("A command-line tool for querying the KDE trader system"));
KAboutData::setApplicationData(aboutData);
QCommandLineParser parser;
aboutData.setupCommandLine(&parser);
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("mimetype"), i18n("A MIME type"), QLatin1String("mimetype")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("servicetype"), i18n("A servicetype, like KParts/ReadOnlyPart or KMyApp/Plugin"), QLatin1String("servicetype")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("constraint"), i18n("A constraint expressed in the trader query language"), QLatin1String("constraint")));
parser.addOption(QCommandLineOption(QStringList() << QLatin1String("short"), i18n("Output only paths to desktop files")));
parser.process(app);
aboutData.processCommandLine(&parser);
- const QString mimetype = parser.value("mimetype");
- QString servicetype = parser.value("servicetype");
- const QString constraint = parser.value("constraint");
- const bool outputProperties = !parser.isSet("short");
+ const QString mimetype = parser.value(QStringLiteral("mimetype"));
+ QString servicetype = parser.value(QStringLiteral("servicetype"));
+ const QString constraint = parser.value(QStringLiteral("constraint"));
+ const bool outputProperties = !parser.isSet(QStringLiteral("short"));
if ( mimetype.isEmpty() && servicetype.isEmpty() )
parser.showHelp();
if ( !mimetype.isEmpty() )
printf( "mimetype is : %s\n", qPrintable( mimetype ) );
if ( !servicetype.isEmpty() )
printf( "servicetype is : %s\n", qPrintable( servicetype ) );
if ( !constraint.isEmpty() )
printf( "constraint is : %s\n", qPrintable( constraint ) );
KService::List offers;
if ( !mimetype.isEmpty() ) {
if ( servicetype.isEmpty() )
- servicetype = "Application";
+ servicetype = QStringLiteral("Application");
offers = KMimeTypeTrader::self()->query( mimetype, servicetype, constraint );
}
else
offers = KServiceTypeTrader::self()->query( servicetype, constraint );
printf("got %d offers.\n", offers.count());
int i = 0;
KService::List::ConstIterator it = offers.constBegin();
const KService::List::ConstIterator end = offers.constEnd();
for (; it != end; ++it, ++i )
{
if (outputProperties) {
printf("---- Offer %d ----\n", i);
QStringList props = (*it)->propertyNames();
QStringList::ConstIterator propIt = props.constBegin();
QStringList::ConstIterator propEnd = props.constEnd();
for (; propIt != propEnd; ++propIt )
{
QVariant prop = (*it)->property( *propIt );
if ( !prop.isValid() )
{
printf("Invalid property %s\n", (*propIt).toLocal8Bit().data());
continue;
}
QString outp = *propIt;
- outp += " : '";
+ outp += QStringLiteral(" : '");
switch ( prop.type() )
{
case QVariant::StringList:
- outp += prop.toStringList().join(" - ");
+ outp += prop.toStringList().join(QStringLiteral(" - "));
break;
case QVariant::Bool:
- outp += prop.toBool() ? "TRUE" : "FALSE";
+ outp += prop.toBool() ? QStringLiteral("TRUE") : QStringLiteral("FALSE");
break;
default:
outp += prop.toString();
break;
}
if ( !outp.isEmpty() )
printf("%s'\n", outp.toLocal8Bit().constData());
}
} else {
printf("%s\n", (*it)->entryPath().toLocal8Bit().constData());
}
}
return 0;
}