File indexing completed on 2024-05-05 16:13:54

0001 /*
0002     This file is part of the KDE project
0003     SPDX-FileCopyrightText: 2004 David Faure <faure@kde.org>
0004 
0005     SPDX-License-Identifier: LGPL-2.0-or-later
0006 */
0007 
0008 #include <KIO/EmptyTrashJob>
0009 #include <KLocalizedString>
0010 #include <QCommandLineOption>
0011 #include <QCommandLineParser>
0012 #include <QCoreApplication>
0013 #include <QDataStream>
0014 #include <QDebug>
0015 #include <QUrl>
0016 
0017 int main(int argc, char *argv[])
0018 {
0019     QCoreApplication app(argc, argv);
0020     app.setApplicationName(QStringLiteral("ktrash"));
0021     app.setApplicationVersion(QStringLiteral(PROJECT_VERSION));
0022     app.setOrganizationDomain(QStringLiteral("kde.org"));
0023 
0024     QCommandLineParser parser;
0025     parser.addVersionOption();
0026     parser.addHelpOption();
0027     parser.setApplicationDescription(
0028         i18n("Helper program to handle the KDE trash can\n"
0029              "Note: to move files to the trash, do not use ktrash, but \"kioclient move 'url' trash:/\""));
0030 
0031     parser.addOption(QCommandLineOption(QStringList{QStringLiteral("empty")}, i18n("Empty the contents of the trash")));
0032     parser.addOption(
0033         QCommandLineOption(QStringList{QStringLiteral("restore")}, i18n("Restore a trashed file to its original location"), QStringLiteral("file")));
0034 
0035     parser.process(app);
0036 
0037     if (parser.isSet(QStringLiteral("empty"))) {
0038         // We use a kio job instead of linking to TrashImpl, for a smaller binary
0039         // (and the possibility of a central service at some point)
0040         KIO::Job *job = KIO::emptyTrash();
0041         job->exec();
0042         return 0;
0043     }
0044 
0045     QString restoreArg = parser.value(QStringLiteral("restore"));
0046     if (!restoreArg.isEmpty()) {
0047         if (restoreArg.indexOf(QLatin1String("system:/trash")) == 0) {
0048             restoreArg.replace(0, 13, QStringLiteral("trash:"));
0049         }
0050 
0051         QUrl trashURL(restoreArg);
0052         if (!trashURL.isValid() || trashURL.scheme() != QLatin1String("trash")) {
0053             qCritical() << "Invalid URL for restoring a trashed file, trash:// URL expected:" << trashURL;
0054             return 1;
0055         }
0056 
0057         QByteArray packedArgs;
0058         QDataStream stream(&packedArgs, QIODevice::WriteOnly);
0059         stream << (int)3 << trashURL;
0060         KIO::Job *job = KIO::special(trashURL, packedArgs);
0061         bool ok = job->exec() ? true : false;
0062         if (!ok) {
0063             qCritical() << job->errorString();
0064         }
0065         return 0;
0066     }
0067 
0068     return 0;
0069 }