diff --git a/src/core/authinfo.h b/src/core/authinfo.h index b243f500..7379c4e4 100644 --- a/src/core/authinfo.h +++ b/src/core/authinfo.h @@ -1,387 +1,391 @@ /* * This file is part of the KDE libraries * Copyright (C) 2000-2001 Dawit Alemayehu * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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. */ #ifndef KIO_AUTHINFO_H #define KIO_AUTHINFO_H #include "kiocore_export.h" #include #include #include #include #include // Q_DECLARE_METATYPE class QDBusArgument; namespace KIO { class AuthInfoPrivate; /** * @class KIO::AuthInfo authinfo.h * * This class is intended to make it easier to prompt for, cache * and retrieve authorization information. * * When using this class to cache, retrieve or prompt authentication * information, you only need to set the necessary attributes. For * example, to check whether a password is already cached, the only * required information is the URL of the resource and optionally * whether or not a path match should be performed. Similarly, to * prompt for password you only need to optionally set the prompt, * username (if already supplied), comment and commentLabel fields. * * SPECIAL NOTE: If you extend this class to add additional * parameters do not forget to overload the stream insertion and * extraction operators ("<<" and ">>") so that the added data can * be correctly serialized. * * @short A two way messaging class for passing authentication information. * @author Dawit Alemayehu */ class KIOCORE_EXPORT AuthInfo { KIOCORE_EXPORT friend QDataStream &operator<< (QDataStream &s, const AuthInfo &a); KIOCORE_EXPORT friend QDataStream &operator>> (QDataStream &s, AuthInfo &a); KIOCORE_EXPORT friend QDBusArgument &operator<<(QDBusArgument &argument, const AuthInfo &a); KIOCORE_EXPORT friend const QDBusArgument &operator>>(const QDBusArgument &argument, AuthInfo &a); public: /** * Default constructor. */ AuthInfo(); /** * Copy constructor. */ AuthInfo(const AuthInfo &info); /** * Destructor * @since 4.1 */ ~AuthInfo(); /** * Custom assignment operator. */ AuthInfo &operator=(const AuthInfo &info); /** * Use this method to check if the object was modified. * @return true if the object has been modified */ bool isModified() const; /** * Use this method to indicate that this object has been modified. * @param flag true to mark the object as modified, false to clear */ void setModified(bool flag); /** * The URL for which authentication is to be stored. * * This field is required when attempting to cache authorization * and retrieve it. However, it is not needed when prompting * the user for authorization info. * * This setting is @em required except when prompting the * user for password. */ QUrl url; /** * This is @em required for caching. */ QString username; /** * This is @em required for caching. */ QString password; /** * Information to be displayed when prompting * the user for authentication information. * * @note If this field is not set, the authentication * dialog simply displays the preset default prompt. * * This setting is @em optional and empty by default. */ QString prompt; /** * The text to displayed in the title bar of * the password prompting dialog. * * @note If this field is not set, the authentication * dialog simply displays the preset default caption. * * This setting is @em optional and empty by default. */ QString caption; /** * Additional comment to be displayed when prompting * the user for authentication information. * * This field allows you to display a short (no more than * 80 characters) extra description in the password prompt * dialog. For example, this field along with the * commentLabel can be used to describe the server that * requested the authentication: * * \code * Server: Squid Proxy @ foo.com * \endcode * * where "Server:" is the commentLabel and the rest is the * actual comment. Note that it is always better to use * the @p commentLabel field as it will be placed properly * in the dialog rather than to include it within the actual * comment. * * This setting is @em optional and empty by default. */ QString comment; /** * Descriptive label to be displayed in front of the * comment when prompting the user for password. * * This setting is @em optional and only applicable when * the comment field is also set. */ QString commentLabel; /** * A unique identifier that allows caching of multiple * passwords for different resources in the same server. * * Mostly this setting is applicable to the HTTP protocol * whose authentication scheme explicitly defines the use * of such a unique key. However, any protocol that can * generate or supply a unique id can effectively use it * to distinguish passwords. * * This setting is @em optional and not set by default. */ QString realmValue; /** * Field to store any extra authentication information for * protocols that need it. * * This setting is @em optional and mostly applicable for HTTP * protocol. However, any protocol can make use of it to * store extra info. */ QString digestInfo; /** * Flag that, if set, indicates whether a path match should be * performed when requesting for cached authorization. * * A path is deemed to be a match if it is equal to or is a subset * of the cached path. For example, if stored path is "/foo/bar" * and the request's path set to "/foo/bar/acme", then it is a match * whereas it would not if the request's path was set to "/foo". * * This setting is @em optional and false by default. */ bool verifyPath; /** * Flag which if set forces the username field to be read-only. * * This setting is @em optional and false by default. */ bool readOnly; /** * Flag to indicate the persistence of the given password. * * This is a two-way flag, when set before calling openPasswordDialog * it makes the "keep Password" check box visible to the user. * In return the flag will indicate the state of the check box. * By default if the flag is checked the password will be cached * for the entire life of the current KDE session otherwise the * cached password is deleted right after the application using * it has been closed. */ bool keepPassword; /** * Flags for extra fields * @since 4.1 */ enum FieldFlags { ExtraFieldNoFlags = 0, ExtraFieldReadOnly = 1 << 1, ExtraFieldMandatory = 1 << 2 }; /** * Set Extra Field Value. * Currently supported extra-fields: * "domain" (QString), * "anonymous" (bool) * Setting it to an invalid QVariant() will disable the field. * Extra Fields are disabled by default. * @since 4.1 */ void setExtraField(const QString &fieldName, const QVariant &value); /** * Set Extra Field Flags * @since 4.1 */ void setExtraFieldFlags(const QString &fieldName, const FieldFlags flags); /** * Get Extra Field Value * Check QVariant::isValid() to find out if the field exists. * @since 4.1 */ QVariant getExtraField(const QString &fieldName) const; /** * Get Extra Field Flags * @since 4.1 */ AuthInfo::FieldFlags getExtraFieldFlags(const QString &fieldName) const; /** * Register the meta-types for AuthInfo. This is called from * AuthInfo's constructor but needed by daemons on the D-Bus such * as kpasswdserver. * @since 4.3 */ static void registerMetaTypes(); protected: bool modified; private: friend class ::KIO::AuthInfoPrivate; AuthInfoPrivate *const d; }; KIOCORE_EXPORT QDataStream &operator<< (QDataStream &s, const AuthInfo &a); KIOCORE_EXPORT QDataStream &operator>> (QDataStream &s, AuthInfo &a); KIOCORE_EXPORT QDBusArgument &operator<<(QDBusArgument &argument, const AuthInfo &a); KIOCORE_EXPORT const QDBusArgument &operator>>(const QDBusArgument &argument, AuthInfo &a); /** * A Singleton class that provides access to passwords * stored in .netrc files for automatic login purposes. * This is only meant to address backward compatibility * with old automated ftp client style logins... * * @short An interface to the ftp .netrc files * @author Dawit Alemayehu */ class KIOCORE_EXPORT NetRC { public: /** * Specifies the mode to be used when searching for a * matching automatic login info for a given site : * * @li exactOnly search entries with exact host name matches. * @li defaultOnly search entries that are specified as "default". * @li presetOnly search entries that are specified as "preset". * * @see lookup + * @see LookUpMode */ enum LookUpModeFlag { exactOnly = 0x0002, defaultOnly = 0x0004, presetOnly = 0x0008 }; + /** + * Stores a combination of #LookUpModeFlag values. + */ Q_DECLARE_FLAGS(LookUpMode, LookUpModeFlag) /** * Contains auto login information. * @see lookup() */ struct AutoLogin { QString type; QString machine; QString login; QString password; QMap macdef; }; /** * A reference to the instance of the class. * @return the class */ static NetRC *self(); /** * Looks up the @p login information for the given @p url. * * @param url the url whose login information will be checked * @param login the login information will be writte here * @param userealnetrc if true, use $HOME/.netrc file * @param type the type of the login. If null, the @p url's protocol * will be taken * @param mode the LookUpMode flags (ORed) for the query */ bool lookup(const QUrl &url, AutoLogin &login, bool userealnetrc = false, const QString &type = QString(), LookUpMode mode = LookUpMode(exactOnly) | defaultOnly); /** * Reloads the auto login information. */ void reload(); protected: bool parse(const QString &fileName); private: NetRC(); ~NetRC(); NetRC(const NetRC &) = delete; NetRC& operator=(const NetRC &) = delete; private: static NetRC *instance; class NetRCPrivate; NetRCPrivate *const d; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(KIO::NetRC::LookUpMode) Q_DECLARE_METATYPE(KIO::AuthInfo) #endif diff --git a/src/core/global.h b/src/core/global.h index bca8b861..c5c5bac6 100644 --- a/src/core/global.h +++ b/src/core/global.h @@ -1,413 +1,417 @@ /* This file is part of the KDE libraries Copyright (C) 2000-2005 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. */ #ifndef KIO_GLOBAL_H #define KIO_GLOBAL_H #include "kiocore_export.h" #include #include // for QFile::Permissions #include #include "metadata.h" // for source compat #include "jobtracker.h" // for source compat class QUrl; class QTime; #if defined(Q_OS_WIN) && defined(Q_CC_MSVC) // on windows ssize_t is not defined, only SSIZE_T exists #include typedef SSIZE_T ssize_t; #endif /** * @short A namespace for KIO globals * */ namespace KIO { /// 64-bit file offset typedef qlonglong fileoffset_t; /// 64-bit file size typedef qulonglong filesize_t; /** * Converts @p size from bytes to the string representation. * * @param size size in bytes * @return converted size as a string - e.g. 123.4 KiB , 12.0 MiB */ KIOCORE_EXPORT QString convertSize(KIO::filesize_t size); /** * Converts a size to a string representation * Not unlike QString::number(...) * * @param size size in bytes * @return converted size as a string - e.g. 123456789 */ KIOCORE_EXPORT QString number(KIO::filesize_t size); /** * Converts size from kibi-bytes (2^10) to the string representation. * * @param kibSize size in kibi-bytes (2^10) * @return converted size as a string - e.g. 123.4 KiB , 12.0 MiB */ KIOCORE_EXPORT QString convertSizeFromKiB(KIO::filesize_t kibSize); /** * Calculates remaining time in seconds from total size, processed size and speed. * * @param totalSize total size in bytes * @param processedSize processed size in bytes * @param speed speed in bytes per second * @return calculated remaining time in seconds */ KIOCORE_EXPORT unsigned int calculateRemainingSeconds(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed); /** * Convert @p seconds to a string representing number of days, hours, minutes and seconds * * @param seconds number of seconds to convert * @return string representation in a locale depending format */ KIOCORE_EXPORT QString convertSeconds(unsigned int seconds); #if KIOCORE_ENABLE_DEPRECATED_SINCE(3, 4) /** * Calculates remaining time from total size, processed size and speed. * * @param totalSize total size in bytes * @param processedSize processed size in bytes * @param speed speed in bytes per second * @return calculated remaining time * @deprecated Since 3.4, use calculateRemainingSeconds() instead, as QTime is limited to 23:59:59 */ KIOCORE_DEPRECATED_VERSION(3, 4, "Use KIO::calculateRemainingSeconds(KIO::filesize_t, KIO::filesize_t, KIO::filesize_t") KIOCORE_EXPORT QTime calculateRemaining(KIO::filesize_t totalSize, KIO::filesize_t processedSize, KIO::filesize_t speed); #endif /** * Helper for showing information about a set of files and directories * @param items the number of items (= @p files + @p dirs + number of symlinks :) * @param files the number of files * @param dirs the number of dirs * @param size the sum of the size of the @p files * @param showSize whether to show the size in the result * @return the summary string */ KIOCORE_EXPORT QString itemsSummaryString(uint items, uint files, uint dirs, KIO::filesize_t size, bool showSize); /** * Encodes (from the text displayed to the real filename) * This translates '/' into a "unicode fraction slash", QChar(0x2044). * Used by KIO::link, for instance. * @param str the file name to encode * @return the encoded file name */ KIOCORE_EXPORT QString encodeFileName(const QString &str); /** * Decodes (from the filename to the text displayed) * This doesn't do anything anymore, it used to do the opposite of encodeFileName * when encodeFileName was using %2F for '/'. * @param str the file name to decode * @return the decoded file name */ KIOCORE_EXPORT QString decodeFileName(const QString &str); #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 61) /** * Given a directory path and a filename (which usually exists already), * this function returns a suggested name for a file that doesn't exist * in that directory. The existence is only checked for local urls though. * The suggested file name is of the form "foo 1", "foo 2" etc. * @since 5.0 * @deprecated since 5.61, use KFileUtils::suggestName() from KCoreAddons */ KIOCORE_DEPRECATED_VERSION(5, 61, "Use KFileUtils::suggestName(const QUrl &, const QString &) from KCoreAddons") KIOCORE_EXPORT QString suggestName(const QUrl &baseURL, const QString &oldName); #endif /** * Error codes that can be emitted by KIO. */ enum Error { ERR_CANNOT_OPEN_FOR_READING = KJob::UserDefinedError + 1, ERR_CANNOT_OPEN_FOR_WRITING = KJob::UserDefinedError + 2, ERR_CANNOT_LAUNCH_PROCESS = KJob::UserDefinedError + 3, ERR_INTERNAL = KJob::UserDefinedError + 4, ERR_MALFORMED_URL = KJob::UserDefinedError + 5, ERR_UNSUPPORTED_PROTOCOL = KJob::UserDefinedError + 6, ERR_NO_SOURCE_PROTOCOL = KJob::UserDefinedError + 7, ERR_UNSUPPORTED_ACTION = KJob::UserDefinedError + 8, ERR_IS_DIRECTORY = KJob::UserDefinedError + 9, ///< ... where a file was expected ERR_IS_FILE = KJob::UserDefinedError + 10, ///< ... where a directory was expected (e.g. listing) ERR_DOES_NOT_EXIST = KJob::UserDefinedError + 11, ERR_FILE_ALREADY_EXIST = KJob::UserDefinedError + 12, ERR_DIR_ALREADY_EXIST = KJob::UserDefinedError + 13, ERR_UNKNOWN_HOST = KJob::UserDefinedError + 14, ERR_ACCESS_DENIED = KJob::UserDefinedError + 15, ERR_WRITE_ACCESS_DENIED = KJob::UserDefinedError + 16, ERR_CANNOT_ENTER_DIRECTORY = KJob::UserDefinedError + 17, ERR_PROTOCOL_IS_NOT_A_FILESYSTEM = KJob::UserDefinedError + 18, ERR_CYCLIC_LINK = KJob::UserDefinedError + 19, ERR_USER_CANCELED = KJob::KilledJobError, ERR_CYCLIC_COPY = KJob::UserDefinedError + 21, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_CREATE_SOCKET = KJob::UserDefinedError + 22, ///< @deprecated Since 5.0, use ERR_CANNOT_CREATE_SOCKET #endif ERR_CANNOT_CREATE_SOCKET = KJob::UserDefinedError + 22, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_CONNECT = KJob::UserDefinedError + 23, ///< @deprecated Since 5.0, use ERR_CANNOT_CONNECT #endif ERR_CANNOT_CONNECT = KJob::UserDefinedError + 23, ERR_CONNECTION_BROKEN = KJob::UserDefinedError + 24, ERR_NOT_FILTER_PROTOCOL = KJob::UserDefinedError + 25, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_MOUNT = KJob::UserDefinedError + 26, ///< @deprecated Since 5.0, use ERR_CANNOT_MOUNT #endif ERR_CANNOT_MOUNT = KJob::UserDefinedError + 26, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_UNMOUNT = KJob::UserDefinedError + 27, ///< @deprecated Since 5.0, use ERR_CANNOT_UNMOUNT #endif ERR_CANNOT_UNMOUNT = KJob::UserDefinedError + 27, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_READ = KJob::UserDefinedError + 28, ///< @deprecated Since 5.0, use ERR_CANNOT_READ #endif ERR_CANNOT_READ = KJob::UserDefinedError + 28, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_WRITE = KJob::UserDefinedError + 29, ///< @deprecated Since 5.0, use ERR_CANNOT_WRITE #endif ERR_CANNOT_WRITE = KJob::UserDefinedError + 29, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_BIND = KJob::UserDefinedError + 30, ///< @deprecated Since 5.0, use ERR_CANNOT_BIND #endif ERR_CANNOT_BIND = KJob::UserDefinedError + 30, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_LISTEN = KJob::UserDefinedError + 31, ///< @deprecated Since 5.0, use ERR_CANNOT_LISTEN #endif ERR_CANNOT_LISTEN = KJob::UserDefinedError + 31, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_ACCEPT = KJob::UserDefinedError + 32, ///< @deprecated Since 5.0, use ERR_CANNOT_ACCEPT #endif ERR_CANNOT_ACCEPT = KJob::UserDefinedError + 32, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_LOGIN = KJob::UserDefinedError + 33, ///< @deprecated Since 5.0, use ERR_CANNOT_LOGIN #endif ERR_CANNOT_LOGIN = KJob::UserDefinedError + 33, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_STAT = KJob::UserDefinedError + 34, ///< @deprecated Since 5.0, use ERR_CANNOT_STAT #endif ERR_CANNOT_STAT = KJob::UserDefinedError + 34, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_CLOSEDIR = KJob::UserDefinedError + 35, ///< @deprecated Since 5.0, use ERR_CANNOT_CLOSEDIR #endif ERR_CANNOT_CLOSEDIR = KJob::UserDefinedError + 35, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_MKDIR = KJob::UserDefinedError + 37, ///< @deprecated Since 5.0, use ERR_CANNOT_MKDIR #endif ERR_CANNOT_MKDIR = KJob::UserDefinedError + 37, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_RMDIR = KJob::UserDefinedError + 38, ///< @deprecated Since 5.0, use ERR_CANNOT_RMDIR #endif ERR_CANNOT_RMDIR = KJob::UserDefinedError + 38, ERR_CANNOT_RESUME = KJob::UserDefinedError + 39, ERR_CANNOT_RENAME = KJob::UserDefinedError + 40, ERR_CANNOT_CHMOD = KJob::UserDefinedError + 41, ERR_CANNOT_DELETE = KJob::UserDefinedError + 42, // The text argument is the protocol that the dead slave supported. // This means for example: file, ftp, http, ... ERR_SLAVE_DIED = KJob::UserDefinedError + 43, ERR_OUT_OF_MEMORY = KJob::UserDefinedError + 44, ERR_UNKNOWN_PROXY_HOST = KJob::UserDefinedError + 45, #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) ERR_COULD_NOT_AUTHENTICATE = KJob::UserDefinedError + 46, ///< @deprecated Since 5.0, use ERR_CANNOT_AUTHENTICATE #endif ERR_CANNOT_AUTHENTICATE = KJob::UserDefinedError + 46, ERR_ABORTED = KJob::UserDefinedError + 47, ///< Action got aborted from application side ERR_INTERNAL_SERVER = KJob::UserDefinedError + 48, ERR_SERVER_TIMEOUT = KJob::UserDefinedError + 49, ERR_SERVICE_NOT_AVAILABLE = KJob::UserDefinedError + 50, ERR_UNKNOWN = KJob::UserDefinedError + 51, // (was a warning) ERR_CHECKSUM_MISMATCH = 52, ERR_UNKNOWN_INTERRUPT = KJob::UserDefinedError + 53, ERR_CANNOT_DELETE_ORIGINAL = KJob::UserDefinedError + 54, ERR_CANNOT_DELETE_PARTIAL = KJob::UserDefinedError + 55, ERR_CANNOT_RENAME_ORIGINAL = KJob::UserDefinedError + 56, ERR_CANNOT_RENAME_PARTIAL = KJob::UserDefinedError + 57, ERR_NEED_PASSWD = KJob::UserDefinedError + 58, ERR_CANNOT_SYMLINK = KJob::UserDefinedError + 59, ERR_NO_CONTENT = KJob::UserDefinedError + 60, ///< Action succeeded but no content will follow. ERR_DISK_FULL = KJob::UserDefinedError + 61, ERR_IDENTICAL_FILES = KJob::UserDefinedError + 62, ///< src==dest when moving/copying ERR_SLAVE_DEFINED = KJob::UserDefinedError + 63, ///< for slave specified errors that can be ///< rich text. Email links will be handled ///< by the standard email app and all hrefs ///< will be handled by the standard browser. ///< 2000-2009 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 as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. */ #ifndef KIO_JOB_BASE_H #define KIO_JOB_BASE_H #include #include namespace KIO { class JobUiDelegateExtension; class JobPrivate; /** * @class KIO::Job job_base.h * * The base class for all jobs. * For all jobs created in an application, the code looks like * * \code * KIO::Job* job = KIO::someoperation(some parameters); * connect(job, &KJob::result, this, &MyClass::slotResult); * \endcode * (other connects, specific to the job) * * And slotResult is usually at least: * * \code * void MyClass::slotResult(KJob *job) * { * if (job->error()) { * job->uiDelegate()->showErrorMessage(); * } * } * \endcode * @see KIO::Scheduler */ class KIOCORE_EXPORT Job : public KCompositeJob { Q_OBJECT protected: Job(); Job(JobPrivate &dd); public: virtual ~Job(); void start() override {} // Since KIO autostarts its jobs #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) /** * Retrieves the UI delegate of this job. * * @return the delegate used by the job to communicate with the UI * * @deprecated since 5.0, can now be replaced with uiDelegate() */ KIOCORE_DEPRECATED_VERSION(5, 0, "Use KJob::uiDelegate()") KJobUiDelegate *ui() const; #endif /** * Retrieves the UI delegate extension used by this job. * @since 5.0 */ JobUiDelegateExtension *uiDelegateExtension() const; /** * Sets the UI delegate extension to be used by this job. * The default UI delegate extension is KIO::defaultJobUiDelegateExtension() */ void setUiDelegateExtension(JobUiDelegateExtension *extension); protected: /** * Abort this job. * This kills all subjobs and deletes the job. * */ bool doKill() override; /** * Suspend this job * @see resume */ bool doSuspend() override; /** * Resume this job * @see suspend */ bool doResume() override; public: /** * Converts an error code and a non-i18n error message into an * error message in the current language. The low level (non-i18n) * error message (usually a url) is put into the translated error * message using %1. * * Example for errid == ERR_CANNOT_OPEN_FOR_READING: * \code * i18n( "Could not read\n%1" ).arg( errortext ); * \endcode * Use this to display the error yourself, but for a dialog box * use uiDelegate()->showErrorMessage(). Do not call it if error() * is not 0. * @return the error message and if there is no error, a message * telling the user that the app is broken, so check with * error() whether there is an error */ QString errorString() const override; /** * Converts an error code and a non-i18n error message into i18n * strings suitable for presentation in a detailed error message box. * * @param reqUrl the request URL that generated this error message * @param method the method that generated this error message * (unimplemented) * @return the following strings: caption, error + description, * causes+solutions */ QStringList detailedErrorStrings(const QUrl *reqUrl = nullptr, int method = -1) const; /** * Set the parent Job. * One example use of this is when FileCopyJob calls RenameDialog::open, * it must pass the correct progress ID of the parent CopyJob * (to hide the progress dialog). * You can set the parent job only once. By default a job does not * have a parent job. * @param parentJob the new parent job */ void setParentJob(Job *parentJob); /** * Returns the parent job, if there is one. * @return the parent job, or @c nullptr if there is none * @see setParentJob */ Job *parentJob() const; /** * Set meta data to be sent to the slave, replacing existing * meta data. * @param metaData the meta data to set * @see addMetaData() * @see mergeMetaData() */ void setMetaData(const KIO::MetaData &metaData); /** * Add key/value pair to the meta data that is sent to the slave. * @param key the key of the meta data * @param value the value of the meta data * @see setMetaData() * @see mergeMetaData() */ void addMetaData(const QString &key, const QString &value); /** * Add key/value pairs to the meta data that is sent to the slave. * If a certain key already existed, it will be overridden. * @param values the meta data to add * @see setMetaData() * @see mergeMetaData() */ void addMetaData(const QMap &values); /** * Add key/value pairs to the meta data that is sent to the slave. * If a certain key already existed, it will remain unchanged. * @param values the meta data to merge * @see setMetaData() * @see addMetaData() */ void mergeMetaData(const QMap &values); /** * @internal. For the scheduler. Do not use. */ MetaData outgoingMetaData() const; /** * Get meta data received from the slave. * (Valid when first data is received and/or slave is finished) * @return the job's meta data */ MetaData metaData() const; /** * Query meta data received from the slave. * (Valid when first data is received and/or slave is finished) * @param key the key of the meta data to retrieve * @return the value of the meta data, or QString() if the * @p key does not exist */ QString queryMetaData(const QString &key); protected: Q_SIGNALS: #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) /** * Emitted when the job is canceled. * Signal result() is emitted as well, and error() is, * in this case, ERR_USER_CANCELED. * @param job the job that emitted this signal * @deprecated Since 5.0. Don't use ! */ KIOCORE_DEPRECATED_VERSION(5, 0, "Do not use") void canceled(KJob *job); #endif /** * Emitted when the slave successfully connected to the host. * There is no guarantee the slave will send this, and this is * currently unused (in the applications). * @param job the job that emitted this signal */ void connected(KIO::Job *job); protected: /** * Add a job that has to be finished before a result * is emitted. This has obviously to be called before * the finish signal is emitted by the slave. * * @param job the subjob to add */ bool addSubjob(KJob *job) override; /** * Mark a sub job as being done. * * Note that this does not terminate the parent job, even if @p job * is the last subjob. emitResult must be called to indicate that * the job is complete. * * @param job the subjob to remove */ bool removeSubjob(KJob *job) override; protected: JobPrivate *const d_ptr; private: Q_DECLARE_PRIVATE(Job) }; /** * Flags for the job properties. * Not all flags are supported in all cases. Please see documentation of * the calling function! + * @see JobFlags */ enum JobFlag { /** * Show the progress info GUI, no Resume and no Overwrite */ DefaultFlags = 0, /** * Hide progress information dialog, i.e. don't show a GUI. */ HideProgressInfo = 1, /** * When set, automatically append to the destination file if it exists already. * WARNING: this is NOT the builtin support for offering the user to resume a previous * partial download. The Resume option is much less used, it allows to append * to an existing file. * This is used by KIO::put(), KIO::file_copy(), KIO::file_move(). */ Resume = 2, /** * When set, automatically overwrite the destination if it exists already. * This is used by KIO::rename(), KIO::put(), KIO::file_copy(), KIO::file_move(), KIO::symlink(). * Otherwise the operation will fail with ERR_FILE_ALREADY_EXIST or ERR_DIR_ALREADY_EXIST. */ Overwrite = 4, /** * When set, notifies the slave that application/job does not want privilege execution. * So in case of failure due to insufficient privileges show an error without attempting * to run the operation as root first. * * @since 5.43 */ NoPrivilegeExecution = 8, }; +/** + * Stores a combination of #JobFlag values. + */ Q_DECLARE_FLAGS(JobFlags, JobFlag) Q_DECLARE_OPERATORS_FOR_FLAGS(JobFlags) enum LoadType { Reload, NoReload }; } #endif diff --git a/src/core/jobuidelegateextension.h b/src/core/jobuidelegateextension.h index f2761e37..38830d61 100644 --- a/src/core/jobuidelegateextension.h +++ b/src/core/jobuidelegateextension.h @@ -1,288 +1,296 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Stephan Kulow Copyright (C) 2000-2013 David Faure Copyright (C) 2006 Kevin Ottens This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. */ #ifndef KIO_JOBUIDELEGATEEXTENSION_H #define KIO_JOBUIDELEGATEEXTENSION_H #include "kiocore_export.h" #include #include class KJob; namespace KIO { class Job; class ClipboardUpdater; /** + * @see RenameDialog_Options * @since 5.0 */ enum RenameDialog_Option { RenameDialog_Overwrite = 1, ///< We have an existing destination, show details about it and offer to overwrite it. RenameDialog_OverwriteItself = 2, ///< Warn that the current operation would overwrite a file with itself, which is not allowed. RenameDialog_Skip = 4, ///< Offer a "Skip" button, to skip other files too. Requires RenameDialog_MultipleItems. RenameDialog_MultipleItems = 8, ///< Set if the current operation concerns multiple files, so it makes sense to offer buttons that apply the user's choice to all files/folders. RenameDialog_Resume = 16, ///< Offer a "Resume" button (plus "Resume All" if RenameDialog_MultipleItems). RenameDialog_NoRename = 64, ///< Don't offer a "Rename" button. RenameDialog_IsDirectory = 128 ///< The destination is a directory, the dialog updates labels and tooltips accordingly. }; +/** + * Stores a combination of #RenameDialog_Option values. + */ Q_DECLARE_FLAGS(RenameDialog_Options, RenameDialog_Option) // For compat #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) /** * @deprecated since 5.0, use the RenameDialog_Option enum values */ enum { M_OVERWRITE = RenameDialog_Overwrite, M_OVERWRITE_ITSELF = RenameDialog_OverwriteItself, M_SKIP = RenameDialog_Skip, M_MULTI = RenameDialog_MultipleItems, M_RESUME = RenameDialog_Resume, M_NORENAME = RenameDialog_NoRename, M_ISDIR = RenameDialog_IsDirectory }; /** * @deprecated since 5.0, use RenameDialog_Options */ KIOCORE_DEPRECATED_VERSION(5, 0, "Use KIO::RenameDialog_Options") typedef RenameDialog_Options RenameDialog_Mode; #endif /** * SkipDialog_MultipleItems: Set if the current operation concerns multiple files, so it makes sense * to offer buttons that apply the user's choice to all files/folders. + * @see SkipDialog_Options * @since 5.0 */ enum SkipDialog_Option { SkipDialog_MultipleItems = 8 }; +/** + * Stores a combination of #SkipDialog_Option values. + */ Q_DECLARE_FLAGS(SkipDialog_Options, SkipDialog_Option) /** * The result of a rename or skip dialog */ enum RenameDialog_Result { Result_Cancel = 0, Result_Rename = 1, Result_Skip = 2, Result_AutoSkip = 3, Result_Overwrite = 4, Result_OverwriteAll = 5, Result_Resume = 6, Result_ResumeAll = 7, Result_AutoRename = 8, Result_Retry = 9, // @deprecated since 5.0, use the RenameDialog_Option enum values #if KIOCORE_ENABLE_DEPRECATED_SINCE(5, 0) R_CANCEL = Result_Cancel, R_RENAME = Result_Rename, R_SKIP = Result_Skip, R_AUTO_SKIP = Result_AutoSkip, R_OVERWRITE = Result_Overwrite, R_OVERWRITE_ALL = Result_OverwriteAll, R_RESUME = Result_Resume, R_RESUME_ALL = Result_ResumeAll, R_AUTO_RENAME = Result_AutoRename, R_RETRY = Result_Retry, S_CANCEL = Result_Cancel, S_SKIP = Result_Skip, S_AUTO_SKIP = Result_AutoSkip, S_RETRY = Result_Retry #endif }; typedef RenameDialog_Result SkipDialog_Result; /** * @class KIO::JobUiDelegateExtension jobuidelegateextension.h * * An abstract class defining interaction with users from KIO jobs: * \li asking what to do in case of a conflict while copying/moving files or directories * \li asking what to do in case of an error while copying/moving files or directories * \li asking for confirmation before deleting files or directories * \li popping up message boxes when the slave requests it * @since 5.0 */ class KIOCORE_EXPORT JobUiDelegateExtension { protected: /** * Constructor */ JobUiDelegateExtension(); /** * Destructor */ virtual ~JobUiDelegateExtension(); public: /** * \relates KIO::RenameDialog * Construct a modal, parent-less "rename" dialog, and return * a result code, as well as the new dest. Much easier to use than the * class RenameDialog directly. * * @param caption the caption for the dialog box * @param src the URL of the file/dir we're trying to copy, as it's part of the text message * @param dest the URL of the destination file/dir, i.e. the one that already exists * @param options parameters for the dialog (which buttons to show...) * @param newDest the new destination path, valid if R_RENAME was returned. * @param sizeSrc size of source file * @param sizeDest size of destination file * @param ctimeSrc creation time of source file * @param ctimeDest creation time of destination file * @param mtimeSrc modification time of source file * @param mtimeDest modification time of destination file * @return the result */ virtual KIO::RenameDialog_Result askFileRename(KJob *job, const QString &caption, const QUrl &src, const QUrl &dest, KIO::RenameDialog_Options options, QString &newDest, KIO::filesize_t sizeSrc = KIO::filesize_t(-1), KIO::filesize_t sizeDest = KIO::filesize_t(-1), const QDateTime &ctimeSrc = QDateTime(), const QDateTime &ctimeDest = QDateTime(), const QDateTime &mtimeSrc = QDateTime(), const QDateTime &mtimeDest = QDateTime()) = 0; /** * @internal * See skipdialog.h */ virtual KIO::SkipDialog_Result askSkip(KJob *job, KIO::SkipDialog_Options options, const QString &error_text) = 0; /** * The type of deletion: real deletion, moving the files to the trash * or emptying the trash * Used by askDeleteConfirmation. */ enum DeletionType { Delete, Trash, EmptyTrash }; /** * ForceConfirmation: always ask the user for confirmation * DefaultConfirmation: don't ask the user if he/she said "don't ask again". * * Used by askDeleteConfirmation. */ enum ConfirmationType { DefaultConfirmation, ForceConfirmation }; /** * Ask for confirmation before deleting/trashing @p urls. * * Note that this method is not called automatically by KIO jobs. It's the application's * responsibility to ask the user for confirmation before calling KIO::del() or KIO::trash(). * * @param urls the urls about to be deleted/trashed * @param deletionType the type of deletion (Delete for real deletion, Trash otherwise) * @param confirmationType see ConfirmationType. Normally set to DefaultConfirmation. * Note: the window passed to setWindow is used as the parent for the message box. * @return true if confirmed */ virtual bool askDeleteConfirmation(const QList &urls, DeletionType deletionType, ConfirmationType confirmationType) = 0; /** * Message box types. * * Should be kept in sync with SlaveBase::MessageBoxType. * * @since 4.11 */ enum MessageBoxType { QuestionYesNo = 1, WarningYesNo = 2, WarningContinueCancel = 3, WarningYesNoCancel = 4, Information = 5, SSLMessageBox = 6, //In KMessageBox::DialogType; Sorry = 7, Error = 8, QuestionYesNoCancel = 9 WarningContinueCancelDetailed = 10, }; /** * This function allows for the delegation user prompts from the ioslaves. * * @param type the desired type of message box. * @param text the message shown to the user. * @param caption the caption of the message dialog box. * @param buttonYes the text for the YES button. * @param buttonNo the text for the NO button. * @param iconYes the icon shown on the YES button. * @param iconNo the icon shown on the NO button. * @param dontAskAgainName the name used to store result from 'Do not ask again' checkbox. * @param sslMetaData SSL information used by the SSLMessageBox. */ virtual int requestMessageBox(MessageBoxType type, const QString &text, const QString &caption, const QString &buttonYes, const QString &buttonNo, const QString &iconYes = QString(), const QString &iconNo = QString(), const QString &dontAskAgainName = QString(), const KIO::MetaData &sslMetaData = KIO::MetaData()) = 0; enum ClipboardUpdaterMode { UpdateContent, OverwriteContent, RemoveContent }; /** * Creates a clipboard updater as a child of the given job. */ virtual ClipboardUpdater *createClipboardUpdater(Job *job, ClipboardUpdaterMode mode); /** * Update URL in clipboard, if present */ virtual void updateUrlInClipboard(const QUrl &src, const QUrl &dest); private: class Private; Private *const d; }; /** * Returns the default job UI delegate extension to be used by all KIO jobs (in which HideProgressInfo is not set) * Can return nullptr, if no kio GUI library is loaded. * @since 5.0 */ KIOCORE_EXPORT JobUiDelegateExtension *defaultJobUiDelegateExtension(); /** * Internal. Allows the KIO widgets library to register its widget-based job UI delegate extension * automatically. * @since 5.0 */ KIOCORE_EXPORT void setDefaultJobUiDelegateExtension(JobUiDelegateExtension *extension); } // namespace KIO Q_DECLARE_OPERATORS_FOR_FLAGS(KIO::RenameDialog_Options) Q_DECLARE_OPERATORS_FOR_FLAGS(KIO::SkipDialog_Options) #endif diff --git a/src/core/kcoredirlister.h b/src/core/kcoredirlister.h index 28516aee..024e188e 100644 --- a/src/core/kcoredirlister.h +++ b/src/core/kcoredirlister.h @@ -1,630 +1,636 @@ /* This file is part of the KDE project Copyright (C) 1999 David Faure 2001, 2002, 2004-2006 Michael Brade This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. */ #ifndef KCOREDIRLISTER_H #define KCOREDIRLISTER_H #include "kfileitem.h" #include "kdirnotify.h" // TODO SIC: remove #include #include #include class KJob; namespace KIO { class Job; class ListJob; } /** * @class KCoreDirLister kcoredirlister.h * * @short Helper class for the kiojob used to list and update a directory. * * The dir lister deals with the kiojob used to list and update a directory * and has signals for the user of this class (e.g. konqueror view or * kdesktop) to create/destroy its items when asked. * * This class is independent from the graphical representation of the dir * (icon container, tree view, ...) and it stores the items (as KFileItems). * * Typical usage : * @li Create an instance. * @li Connect to at least update, clear, itemsAdded, and itemsDeleted. * @li Call openUrl - the signals will be called. * @li Reuse the instance when opening a new url (openUrl). * @li Destroy the instance when not needed anymore (usually destructor). * * Advanced usage : call openUrl with OpenUrlFlag::Keep to list directories * without forgetting the ones previously read (e.g. for a tree view) * * @author Michael Brade */ class KIOCORE_EXPORT KCoreDirLister : public QObject { friend class KCoreDirListerCache; friend struct KCoreDirListerCacheDirectoryData; Q_OBJECT Q_PROPERTY(bool autoUpdate READ autoUpdate WRITE setAutoUpdate) Q_PROPERTY(bool showingDotFiles READ showingDotFiles WRITE setShowingDotFiles) Q_PROPERTY(bool dirOnlyMode READ dirOnlyMode WRITE setDirOnlyMode) Q_PROPERTY(bool delayedMimeTypes READ delayedMimeTypes WRITE setDelayedMimeTypes) Q_PROPERTY(QString nameFilter READ nameFilter WRITE setNameFilter) Q_PROPERTY(QStringList mimeFilter READ mimeFilters WRITE setMimeFilter RESET clearMimeFilter) public: + /** + * @see OpenUrlFlags + */ enum OpenUrlFlag { NoFlags = 0x0, ///< No additional flags specified. Keep = 0x1, ///< Previous directories aren't forgotten ///< (they are still watched by kdirwatch and their items ///< are kept for this KCoreDirLister). This is useful for e.g. ///< a treeview. Reload = 0x2 ///< Indicates whether to use the cache or to reread ///< the directory from the disk. ///< Use only when opening a dir not yet listed by this lister ///< without using the cache. Otherwise use updateDirectory. }; + /** + * Stores a combination of #OpenUrlFlag values. + */ Q_DECLARE_FLAGS(OpenUrlFlags, OpenUrlFlag) /** * Create a directory lister. */ KCoreDirLister(QObject *parent = nullptr); /** * Destroy the directory lister. */ virtual ~KCoreDirLister(); /** * Run the directory lister on the given url. * * This method causes KCoreDirLister to emit _all_ the items of @p _url, in any case. * Depending on _flags, either clear() or clear(const QUrl &) will be * emitted first. * * The newItems() signal may be emitted more than once to supply you * with KFileItems, up until the signal completed() is emitted * (and isFinished() returns true). * * @param _url the directory URL. * @param _flags whether to keep previous directories, and whether to reload, see OpenUrlFlags * @return true if successful, * false otherwise (e.g. invalid @p _url) */ virtual bool openUrl(const QUrl &_url, OpenUrlFlags _flags = NoFlags); /** * Stop listing all directories currently being listed. * * Emits canceled() if there was at least one job running. * Emits canceled( const QUrl& ) for each stopped job if * there are at least two directories being watched by KCoreDirLister. */ virtual void stop(); /** * Stop listing the given directory. * * Emits canceled() if the killed job was the last running one. * Emits canceled( const QUrl& ) for the killed job if * there are at least two directories being watched by KCoreDirLister. * No signal is emitted if there was no job running for @p _url. * @param _url the directory URL */ virtual void stop(const QUrl &_url); /** * @return true if the "delayed mimetypes" feature was enabled * @see setDelayedMimeTypes */ bool delayedMimeTypes() const; /** * Delayed mimetypes feature: * If enabled, mime types will be fetched on demand, which leads to a * faster initial directory listing, where icons get progressively replaced * with the correct one while KMimeTypeResolver is going through the items * with unknown or imprecise mimetype (e.g. files with no extension or an * unknown extension). */ void setDelayedMimeTypes(bool delayedMimeTypes); /** * Checks whether KDirWatch will automatically update directories. This is * enabled by default. * @return true if KDirWatch is used to automatically update directories. */ bool autoUpdate() const; /** * Enable/disable automatic directory updating, when a directory changes * (using KDirWatch). * @param enable true to enable, false to disable */ virtual void setAutoUpdate(bool enable); /** * Checks whether hidden files (files beginning with a dot) will be * shown. * By default this option is disabled (hidden files will be not shown). * @return true if dot files are shown, false otherwise * @see setShowingDotFiles() */ bool showingDotFiles() const; /** * Changes the "is viewing dot files" setting. * You need to call emitChanges() afterwards. * By default this option is disabled (hidden files will not be shown). * @param _showDotFiles true to enable showing hidden files, false to * disable * @see showingDotFiles() */ virtual void setShowingDotFiles(bool _showDotFiles); /** * Checks whether the KCoreDirLister only lists directories or all * files. * By default this option is disabled (all files will be shown). * @return true if setDirOnlyMode(true) was called */ bool dirOnlyMode() const; /** * Call this to list only directories. * You need to call emitChanges() afterwards. * By default this option is disabled (all files will be shown). * @param dirsOnly true to list only directories */ virtual void setDirOnlyMode(bool dirsOnly); /** * Returns the top level URL that is listed by this KCoreDirLister. * It might be different from the one given with openUrl() if there was a * redirection. If you called openUrl() with OpenUrlFlag::Keep this is the * first url opened (e.g. in a treeview this is the root). * * @return the url used by this instance to list the files. */ QUrl url() const; /** * Returns all URLs that are listed by this KCoreDirLister. This is only * useful if you called openUrl() with OpenUrlFlag::Keep, as it happens in a * treeview, for example. (Note that the base url is included in the list * as well, of course.) * * @return the list of all listed URLs */ QList directories() const; /** * Actually emit the changes made with setShowingDotFiles, setDirOnlyMode, * setNameFilter and setMimeFilter. */ virtual void emitChanges(); /** * Update the directory @p _dir. This method causes KCoreDirLister to _only_ emit * the items of @p _dir that actually changed compared to the current state in the * cache and updates the cache. * * The current implementation calls updateDirectory automatically for * local files, using KDirWatch (if autoUpdate() is true), but it might be * useful to force an update manually. * * @param _dir the directory URL */ virtual void updateDirectory(const QUrl &_dir); /** * Returns true if no io operation is currently in progress. * @return true if finished, false otherwise */ bool isFinished() const; /** * Returns the file item of the URL. * * Can return an empty KFileItem. * @return the file item for url() itself (".") */ KFileItem rootItem() const; /** * Find an item by its URL. * @param _url the item URL * @return the KFileItem */ virtual KFileItem findByUrl(const QUrl &_url) const; /** * Find an item by its name. * @param name the item name * @return the KFileItem */ virtual KFileItem findByName(const QString &name) const; /** * Set a name filter to only list items matching this name, e.g. "*.cpp". * * You can set more than one filter by separating them with whitespace, e.g * "*.cpp *.h". * Note: the directory is not automatically reloaded. * You need to call emitChanges() afterwards. * * @param filter the new filter, QString() to disable filtering * @see matchesFilter */ virtual void setNameFilter(const QString &filter); /** * Returns the current name filter, as set via setNameFilter() * @return the current name filter, can be QString() if filtering * is turned off */ QString nameFilter() const; /** * Set mime-based filter to only list items matching the given mimetypes. * * NOTE: setting the filter does not automatically reload directory. * Also calling this function will not affect any named filter already set. * * You need to call emitChanges() afterwards. * * @param mimeList a list of mime-types. * * @see clearMimeFilter * @see matchesMimeFilter */ virtual void setMimeFilter(const QStringList &mimeList); /** * Filtering should be done with KFileFilter. This will be implemented in a later * revision of KCoreDirLister. This method may be removed then. * * Set mime-based exclude filter to only list items not matching the given mimetypes * * NOTE: setting the filter does not automatically reload directory. * Also calling this function will not affect any named filter already set. * * @param mimeList a list of mime-types. * @see clearMimeFilter * @see matchesMimeFilter * @internal */ void setMimeExcludeFilter(const QStringList &mimeList); /** * Clears the mime based filter. * * You need to call emitChanges() afterwards. * * @see setMimeFilter */ virtual void clearMimeFilter(); /** * Returns the list of mime based filters, as set via setMimeFilter(). * @return the list of mime based filters. Empty, when no mime filter is set. */ QStringList mimeFilters() const; /** * Checks whether @p name matches a filter in the list of name filters. * @return true if @p name matches a filter in the list, * otherwise false. * @see setNameFilter */ bool matchesFilter(const QString &name) const; /** * Checks whether @p mime matches a filter in the list of mime types * @param mime the mimetype to find in the filter list. * @return true if @p name matches a filter in the list, * otherwise false. * @see setMimeFilter. */ bool matchesMimeFilter(const QString &mime) const; /** * Used by items() and itemsForDir() to specify whether you want * all items for a directory or just the filtered ones. */ enum WhichItems { AllItems = 0, FilteredItems = 1 }; /** * Returns the items listed for the current url(). * This method will NOT start listing a directory, you should only call * this when receiving the finished() signal. * * The items in the KFileItemList are copies of the items used * by KCoreDirLister. * * @param which specifies whether the returned list will contain all entries * or only the ones that passed the nameFilter(), mimeFilter(), * etc. Note that the latter causes iteration over all the * items, filtering them. If this is too slow for you, use the * newItems() signal, sending out filtered items in chunks. * @return the items listed for the current url(). */ KFileItemList items(WhichItems which = FilteredItems) const; /** * Returns the items listed for the given @p dir. * This method will NOT start listing @p dir, you should only call * this when receiving the finished() signal. * * The items in the KFileItemList are copies of the items used * by KCoreDirLister. * * @param dir specifies the url for which the items should be returned. This * is only useful if you use KCoreDirLister with multiple URLs * i.e. using bool OpenUrlFlag::Keep in openUrl(). * @param which specifies whether the returned list will contain all entries * or only the ones that passed the nameFilter, mimeFilter, etc. * Note that the latter causes iteration over all the items, * filtering them. If this is too slow for you, use the * newItems() signal, sending out filtered items in chunks. * @return the items listed for @p dir. */ KFileItemList itemsForDir(const QUrl &dir, WhichItems which = FilteredItems) const; /** * Return the KFileItem for the given URL, if we listed it recently * and it's still in the cache - which is always the case if a directory * view is currently showing this item. If not, then it might be in the * cache, or it might not, in which case you get a null KFileItem. * If you really need a KFileItem for this URL in all cases, then use * KIO::stat() instead. * * @since 4.2 */ static KFileItem cachedItemForUrl(const QUrl &url); Q_SIGNALS: /** * Tell the view that we started to list @p _url. NOTE: this does _not_ imply that there * is really a job running! I.e. KCoreDirLister::jobs() may return an empty list. In this case * the items are taken from the cache. * * The view knows that openUrl should start it, so it might seem useless, * but the view also needs to know when an automatic update happens. * @param _url the URL to list */ void started(const QUrl &_url); /** * Tell the view that listing is finished. There are no jobs running anymore. */ void completed(); /** * Tell the view that the listing of the directory @p _url is finished. * There might be other running jobs left. * @param _url the directory URL */ void completed(const QUrl &_url); /** * Tell the view that the user canceled the listing. No running jobs are left. */ void canceled(); /** * Tell the view that the listing of the directory @p _url was canceled. * There might be other running jobs left. * @param _url the directory URL */ void canceled(const QUrl &_url); /** * Signal a redirection. * Only emitted if there's just one directory to list, i.e. most * probably openUrl() has been called without OpenUrlFlag::Keep. * @param _url the new URL */ void redirection(const QUrl &_url); /** * Signal a redirection. * @param oldUrl the original URL * @param newUrl the new URL */ void redirection(const QUrl &oldUrl, const QUrl &newUrl); /** * Signal to clear all items. * Make sure to connect to this signal to avoid doubled items. */ void clear(); /** * Signal to empty the directory @p _url. * It is only emitted if the lister is holding more than one directory. * @param _url the directory that will be emptied */ void clear(const QUrl &_url); /** * Signal new items. * * @param items a list of new items */ void newItems(const KFileItemList &items); /** * Signal that new items were found during directory listing. * Alternative signal emitted at the same time as newItems(), * but itemsAdded also passes the url of the parent directory. * * @param items a list of new items * @since 4.2 */ void itemsAdded(const QUrl &directoryUrl, const KFileItemList &items); /** * Send a list of items filtered-out by mime-type. * @param items the list of filtered items */ void itemsFilteredByMime(const KFileItemList &items); /** * Signal that items have been deleted * * @since 4.1.2 * @param items the list of deleted items */ void itemsDeleted(const KFileItemList &items); /** * Signal an item to refresh (its mimetype/icon/name has changed). * Note: KFileItem::refresh has already been called on those items. * @param items the items to refresh. This is a list of pairs, where * the first item in the pair is the OLD item, and the second item is the * NEW item. This allows to track which item has changed, especially after * a renaming. */ void refreshItems(const QList > &items); /** * Emitted to display information about running jobs. * Examples of message are "Resolving host", "Connecting to host...", etc. * @param msg the info message */ void infoMessage(const QString &msg); /** * Progress signal showing the overall progress of the KCoreDirLister. * This allows using a progress bar very easily. (see QProgressBar) * @param percent the progress in percent */ void percent(int percent); /** * Emitted when we know the size of the jobs. * @param size the total size in bytes */ void totalSize(KIO::filesize_t size); /** * Regularly emitted to show the progress of this KCoreDirLister. * @param size the processed size in bytes */ void processedSize(KIO::filesize_t size); /** * Emitted to display information about the speed of the jobs. * @param bytes_per_second the speed in bytes/s */ void speed(int bytes_per_second); protected: #if KIOCORE_ENABLE_DEPRECATED_SINCE(4, 3) /// @deprecated Since 4.3, and unused, ignore this enum Changes { NONE = 0, NAME_FILTER = 1, MIME_FILTER = 2, DOT_FILES = 4, DIR_ONLY_MODE = 8 }; #endif /** * Called for every new item before emitting newItems(). * You may reimplement this method in a subclass to implement your own * filtering. * The default implementation filters out ".." and everything not matching * the name filter(s) * @return true if the item is "ok". * false if the item shall not be shown in a view, e.g. * files not matching a pattern *.cpp ( KFileItem::isHidden()) * @see matchesFilter * @see setNameFilter */ virtual bool matchesFilter(const KFileItem &) const; /** * Called for every new item before emitting newItems(). * You may reimplement this method in a subclass to implement your own * filtering. * The default implementation filters out ".." and everything not matching * the name filter(s) * @return true if the item is "ok". * false if the item shall not be shown in a view, e.g. * files not matching a pattern *.cpp ( KFileItem::isHidden()) * @see matchesMimeFilter * @see setMimeFilter */ virtual bool matchesMimeFilter(const KFileItem &) const; /** * Called by the public matchesFilter() to do the * actual filtering. Those methods may be reimplemented to customize * filtering. * @param name the name to filter * @param filters a list of regular expressions for filtering */ // TODO KF6 remove virtual bool doNameFilter(const QString &name, const QList &filters) const; /** * Called by the public matchesMimeFilter() to do the * actual filtering. Those methods may be reimplemented to customize * filtering. * @param mime the mime type to filter * @param filters the list of mime types to filter */ // TODO KF6 remove virtual bool doMimeFilter(const QString &mime, const QStringList &filters) const; /** * Reimplement to customize error handling */ virtual void handleError(KIO::Job *); /** * Reimplement to customize error handling * @since 5.0 */ virtual void handleErrorMessage(const QString &message); /** * Reimplemented by KDirLister to associate windows with jobs * @since 5.0 */ virtual void jobStarted(KIO::ListJob *); private: class Private; Private *const d; friend class Private; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KCoreDirLister::OpenUrlFlags) #endif diff --git a/src/core/kmountpoint.h b/src/core/kmountpoint.h index 81a7fbf6..f11052b2 100644 --- a/src/core/kmountpoint.h +++ b/src/core/kmountpoint.h @@ -1,167 +1,171 @@ /* This file is part of the KDE libraries Copyright (c) 2003 Waldo Bastian 2007 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. */ #ifndef KMOUNTPOINT_H #define KMOUNTPOINT_H #include "kiocore_export.h" #include #include /** * @class KMountPoint kmountpoint.h * * The KMountPoint class provides information about mounted and unmounted disks. * It provides a system independent interface to fstab. * * @author Waldo Bastian */ class KIOCORE_EXPORT KMountPoint : public QSharedData { public: typedef QExplicitlySharedDataPointer Ptr; /** * List of mount points. */ class KIOCORE_EXPORT List : public QList { public: List(); /** * Find the mountpoint on which resides @p path * For instance if /home is a separate partition, findByPath("/home/user/blah") * will return /home * @param path the path to check * @return the mount point of the given file */ Ptr findByPath(const QString &path) const; /** * Returns the mount point associated with @p device, * i.e. the one where mountedFrom() == @p device * (after symlink resolution). * @return the mountpoint, or @c nullptr if this device doesn't exist or isn't mounted */ Ptr findByDevice(const QString &device) const; }; public: /** * Flags that specify which additional details should be fetched for each mountpoint. * BasicInfoNeeded: only the basic details: mountedFrom, mountPoint, mountType. * NeedMountOptions: also fetch the options used when mounting, see mountOptions. * NeedRealDeviceName: also fetch the device name (with symlinks resolved), see realDeviceName. + * @see DetailsNeededFlags */ enum DetailsNeededFlag { BasicInfoNeeded = 0, NeedMountOptions = 1, NeedRealDeviceName = 2 }; + /** + * Stores a combination of #DetailsNeededFlag values. + */ Q_DECLARE_FLAGS(DetailsNeededFlags, DetailsNeededFlag) /** * This function gives a list of all possible mountpoints. (fstab) * @param infoNeeded Flags that specify which additional information * should be fetched. */ static List possibleMountPoints(DetailsNeededFlags infoNeeded = BasicInfoNeeded); /** * This function gives a list of all currently used mountpoints. (mtab) * @param infoNeeded Flags that specify which additional information * should be fetched. * * @note this method will return an empty list on Android */ static List currentMountPoints(DetailsNeededFlags infoNeeded = BasicInfoNeeded); /** * Where this filesystem gets mounted from. * This can refer to a device, a remote server or something else. */ QString mountedFrom() const; /** * Canonical name of the device where the filesystem got mounted from. * (Or empty, if not a device) * Only available when the NeedRealDeviceName flag was set. */ QString realDeviceName() const; /** * Path where the filesystem is mounted or can be mounted. */ QString mountPoint() const; /** * Type of filesystem */ QString mountType() const; /** * Options used to mount the filesystem. * Only available when the NeedMountOptions flag was set. */ QStringList mountOptions() const; /** * Checks if the filesystem that is probably slow (network mounts). * @return true if the filesystem is probably slow */ bool probablySlow() const; enum FileSystemFlag { SupportsChmod, SupportsChown, SupportsUTime, SupportsSymlinks, CaseInsensitive }; /** * Checks the capabilities of the filesystem. * @param flag the flag to check * @return true if the filesystem has that flag, false if not * * The available flags are: * @li SupportsChmod: returns true if the filesystem supports chmod * (e.g. msdos filesystems return false) * @li SupportsChown: returns true if the filesystem supports chown * (e.g. msdos filesystems return false) * @li SupportsUtime: returns true if the filesystems supports utime * (e.g. msdos filesystems return false) * @li SupportsSymlinks: returns true if the filesystems supports symlinks * (e.g. msdos filesystems return false) * @li CaseInsensitive: returns true if the filesystem treats * "foo" and "FOO" as being the same file (true for msdos systems) * */ bool testFileSystemFlag(FileSystemFlag flag) const; /** * Destructor */ ~KMountPoint(); private: /** * Constructor */ KMountPoint(); class Private; Private *const d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KMountPoint::DetailsNeededFlags) #endif // KMOUNTPOINT_H diff --git a/src/gui/applicationlauncherjob.h b/src/gui/applicationlauncherjob.h index ef989215..ccddebfe 100644 --- a/src/gui/applicationlauncherjob.h +++ b/src/gui/applicationlauncherjob.h @@ -1,160 +1,166 @@ /* This file is part of the KDE libraries Copyright (c) 2020 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 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 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 Lesser 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. */ #ifndef KIO_APPLICATIONLAUNCHERJOB_H #define KIO_APPLICATIONLAUNCHERJOB_H #include "kiogui_export.h" #include #include #include class KRunPrivate; // KF6 REMOVE class ApplicationLauncherJobTest; // KF6 REMOVE namespace KIO { class ApplicationLauncherJobPrivate; /** * @class ApplicationLauncherJob applicationlauncherjob.h * * @brief ApplicationLauncherJob runs an application and watches it while running. * * It creates a startup notification and finishes it on success or on error (for the taskbar). * It also emits an error message if necessary (e.g. "program not found"). * * Note that this class doesn't support warning the user if a desktop file or a binary * does not have the executable bit set and offering to make it so. Therefore file managers * should use KRun::runApplication rather than using ApplicationLauncherJob directly. * * When passing multiple URLs to an application that doesn't support opening * multiple files, the application will be launched once for each URL. * * The job finishes when the application is successfully started. At that point you can * query the PID(s). * * For error handling, either connect to the result() signal, or for a simple messagebox on error, * you can do * @code * job->setUiDelegate(new KDialogJobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, this)); * @endcode * * @since 5.69 */ class KIOGUI_EXPORT ApplicationLauncherJob : public KJob { public: /** * Creates an ApplicationLauncherJob. * @param service the service (application desktop file) to run * @param parent the parent QObject */ explicit ApplicationLauncherJob(const KService::Ptr &service, QObject *parent = nullptr); /** * Creates an ApplicationLauncherJob. * @param serviceAction the service action to run * @param parent the parent QObject */ explicit ApplicationLauncherJob(const KServiceAction &serviceAction, QObject *parent = nullptr); /** * Destructor * * Note that jobs auto-delete themselves after emitting result. * Deleting/killing the job will not stop the started application. */ ~ApplicationLauncherJob() override; /** * Specifies the URLs to be passed to the application. * @param urls list of files (local or remote) to open * * Note that when passing multiple URLs to an application that doesn't support opening * multiple files, the application will be launched once for each URL. */ void setUrls(const QList &urls); + /** + * @see RunFlag + */ enum RunFlag { DeleteTemporaryFiles = 0x1, ///< the URLs passed to the service will be deleted when it exits (if the URLs are local files) }; + /** + * Stores a combination of #RunFlag values. + */ Q_DECLARE_FLAGS(RunFlags, RunFlag) /** * Specifies various flags. * @param runFlags the flags to be set. For instance, whether the URLs are temporary files that should be deleted after execution. */ void setRunFlags(RunFlags runFlags); /** * Sets the file name to use in the case of downloading the file to a tempfile * in order to give to a non-URL-aware application. * Some apps rely on the extension to determine the mimetype of the file. * Usually the file name comes from the URL, but in the case of the * HTTP Content-Disposition header, we need to override the file name. * @param suggestedFileName the file name */ void setSuggestedFileName(const QString &suggestedFileName); /** * Sets the startup notification id of the application launch. * @param startupId startup notification id, if any (otherwise ""). */ void setStartupId(const QByteArray &startupId); /** * Starts the job. * You must call this, after having done all the setters. */ void start() override; /** * @return the PID of the application that was started * * Convenience method for pids().at(0). You should only use this when specifying zero or one URL, * or when you are sure that the application supports opening multiple files. Otherwise use pids(). * Available after the job emits result(). */ qint64 pid() const; /** * @return the PIDs of the applications that were started * * Available after the job emits result(). */ QVector pids() const; private: friend class ::KRunPrivate; // KF6 REMOVE friend class ::ApplicationLauncherJobTest; // KF6 REMOVE /** * Blocks until the process has started. Only exists for KRun, will disappear in KF6. */ bool waitForStarted(); friend class ApplicationLauncherJobPrivate; QScopedPointer d; }; } // namespace KIO #endif diff --git a/src/kntlm/kntlm.h b/src/kntlm/kntlm.h index d9cfc652..16d218d5 100644 --- a/src/kntlm/kntlm.h +++ b/src/kntlm/kntlm.h @@ -1,222 +1,228 @@ /* This file is part of the KDE libraries. Copyright (c) 2004 Szombathelyi György 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. */ #ifndef KNTLM_H #define KNTLM_H #include #include #include "kntlm_export.h" /** * @short KNTLM class implements the NTLM authentication protocol. * * The KNTLM class is useful for creating the authentication structures which * can be used for various servers which implements NTLM type authentication. * A comprehensive description of the NTLM authentication protocol can be found * at http://davenport.sourceforge.net/ntlm.html * The class also contains methods to create the LanManager and NT (MD4) hashes * of a password. * This class doesn't maintain any state information, so all methods are static. */ class KNTLM_EXPORT KNTLM { public: enum Flags { Negotiate_Unicode = 0x00000001, Negotiate_OEM = 0x00000002, Request_Target = 0x00000004, Negotiate_Sign = 0x00000010, Negotiate_Seal = 0x00000020, Negotiate_Datagram_Style = 0x00000040, Negotiate_LM_Key = 0x00000080, Negotiate_Netware = 0x00000100, Negotiate_NTLM = 0x00000200, Negotiate_Domain_Supplied = 0x00001000, Negotiate_WS_Supplied = 0x00002000, Negotiate_Local_Call = 0x00004000, Negotiate_Always_Sign = 0x00008000, Target_Type_Domain = 0x00010000, Target_Type_Server = 0x00020000, Target_Type_Share = 0x00040000, Negotiate_NTLM2_Key = 0x00080000, Request_Init_Response = 0x00100000, Request_Accept_Response = 0x00200000, Request_NonNT_Key = 0x00400000, Negotiate_Target_Info = 0x00800000, Negotiate_128 = 0x20000000, Negotiate_Key_Exchange = 0x40000000, Negotiate_56 = 0x80000000 }; + /** + * @see AuthFlags + */ enum AuthFlag { Force_V1 = 0x1, Force_V2 = 0x2, Add_LM = 0x4 }; + /** + * Stores a combination of #AuthFlag values. + */ Q_DECLARE_FLAGS(AuthFlags, AuthFlag) typedef struct { quint16 len; quint16 maxlen; quint32 offset; } SecBuf; /** * The NTLM Type 1 structure */ typedef struct { char signature[8]; /* "NTLMSSP\0" */ quint32 msgType; /* 1 */ quint32 flags; SecBuf domain; SecBuf workstation; } Negotiate; /** * The NTLM Type 2 structure */ typedef struct { char signature[8]; quint32 msgType; /* 2 */ SecBuf targetName; quint32 flags; quint8 challengeData[8]; quint32 context[2]; SecBuf targetInfo; } Challenge; /** * The NTLM Type 3 structure */ typedef struct { char signature[8]; quint32 msgType; /* 3 */ SecBuf lmResponse; SecBuf ntResponse; SecBuf domain; SecBuf user; SecBuf workstation; SecBuf sessionKey; quint32 flags; } Auth; typedef struct { quint32 signature; quint32 reserved; quint64 timestamp; quint8 challenge[8]; quint8 unknown[4]; //Target info block - variable length } Blob; /** * Creates the initial message (type 1) which should be sent to the server. * * @param negotiate - a buffer where the Type 1 message will returned. * @param domain - the domain name which should be send with the message. * @param workstation - the workstation name which should be send with the message. * @param flags - various flags, in most cases the defaults will good. * * @return true if creating the structure succeeds, false otherwise. */ static bool getNegotiate(QByteArray &negotiate, const QString &domain = QString(), const QString &workstation = QString(), quint32 flags = Negotiate_Unicode | Request_Target | Negotiate_NTLM); /** * Creates the type 3 message which should be sent to the server after * the challenge (type 2) received. * * @param auth - a buffer where the Type 3 message will returned. * @param challenge - the Type 2 message returned by the server. * @param user - user's name. * @param password - user's password. * @param domain - the target domain. If left NULL (i.e. QString()), it will be extracted * from the challenge. If set to an empty string (QString("")) an empty domain will be used. * @param workstation - the user's workstation. * @param authflags - AuthFlags flags that changes the response generation behavior. * Force_V1 or Force_V2 forces (NT)LMv1 or (NT)LMv2 responses generation, otherwise it's * autodetected from the challenge. Add_LM adds LMv1 or LMv2 responses additional to the * NTLM response. * * @return true if auth filled with the Type 3 message, false if an error occurred * (challenge data invalid, NTLMv2 authentication forced, but the challenge data says * no NTLMv2 supported, or no NTLM supported at all, and Add_LM not specified). */ static bool getAuth(QByteArray &auth, const QByteArray &challenge, const QString &user, const QString &password, const QString &domain = QString(), const QString &workstation = QString(), AuthFlags authflags = Add_LM); /** * Returns the LanManager response from the password and the server challenge. */ static QByteArray getLMResponse(const QString &password, const unsigned char *challenge); /** * Calculates the LanManager hash of the specified password. */ static QByteArray lmHash(const QString &password); /** * Calculates the LanManager response from the LanManager hash and the server challenge. */ static QByteArray lmResponse(const QByteArray &hash, const unsigned char *challenge); /** * Returns the NTLM response from the password and the server challenge. */ static QByteArray getNTLMResponse(const QString &password, const unsigned char *challenge); /** * Returns the NTLM hash (MD4) from the password. */ static QByteArray ntlmHash(const QString &password); /** * Calculates the NTLMv2 response. */ static QByteArray getNTLMv2Response(const QString &target, const QString &user, const QString &password, const QByteArray &targetInformation, const unsigned char *challenge); /** * Calculates the LMv2 response. */ static QByteArray getLMv2Response(const QString &target, const QString &user, const QString &password, const unsigned char *challenge); /** * Returns the NTLMv2 hash. */ static QByteArray ntlmv2Hash(const QString &target, const QString &user, const QString &password); /** * Calculates the LMv2 response. */ static QByteArray lmv2Response(const QByteArray &hash, const QByteArray &clientData, const unsigned char *challenge); }; Q_DECLARE_OPERATORS_FOR_FLAGS(KNTLM::AuthFlags) #endif /* KNTLM_H */ diff --git a/src/widgets/dropjob.h b/src/widgets/dropjob.h index 658c436c..58deef57 100644 --- a/src/widgets/dropjob.h +++ b/src/widgets/dropjob.h @@ -1,168 +1,172 @@ /* This file is part of the KDE libraries Copyright (C) 2014 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 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 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 Lesser 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. */ #ifndef DROPJOB_H #define DROPJOB_H #include #include "kiowidgets_export.h" #include class QAction; class QDropEvent; class KFileItemListProperties; namespace KIO { /** * Special flag of DropJob in addition to KIO::JobFlag * +* @see DropJobFlags * @since 5.67 */ enum DropJobFlag { DropJobDefaultFlags = 0, ShowMenuManually = 1, ///< show the menu manually with DropJob::showMenu }; +/** + * Stores a combination of #DropJobFlag values. + */ Q_DECLARE_FLAGS(DropJobFlags, DropJobFlag) Q_DECLARE_OPERATORS_FOR_FLAGS(DropJobFlags) class CopyJob; class DropJobPrivate; /** * @class KIO::DropJob dropjob.h * * A KIO job that handles dropping into a file-manager-like view. * @see KIO::drop * * The popupmenu that can appear on drop, can be customized with plugins, * see KIO::DndPopupMenuPlugin. * * @since 5.6 */ class KIOWIDGETS_EXPORT DropJob : public Job { Q_OBJECT public: virtual ~DropJob(); /** * Allows the application to set additional actions in the drop popup menu. * For instance, the application handling the desktop might want to add * "set as wallpaper" if the dropped url is an image file. * This can be called upfront, or for convenience, when popupMenuAboutToShow is emitted. */ void setApplicationActions(const QList &actions); /** * Allows the application to show the menu manually. * DropJob instance has to be created with the KIO::ShowMenuManually flag * * @since 5.67 */ void showMenu(const QPoint &p, QAction *atAction = nullptr); Q_SIGNALS: /** * Signals that a file or directory was created. */ void itemCreated(const QUrl &url); /** * Emitted when a copy job was started as subjob after user selection. * * You can use @p job to monitor the progress of the copy/move/link operation. Note that a * CopyJob isn't always started by DropJob. For instance dropping files onto an executable will * simply launch the executable. * * @param job the job started for moving, copying or symlinking files * @since 5.30 */ void copyJobStarted(KIO::CopyJob *job); /** * Signals that the popup menu is about to be shown. * Applications can use the information provided about the dropped URLs * (e.g. the mimetype) to decide whether to call setApplicationActions. * @param itemProps properties of the dropped items */ void popupMenuAboutToShow(const KFileItemListProperties &itemProps); protected Q_SLOTS: void slotResult(KJob *job) override; protected: DropJob(DropJobPrivate &dd); private: Q_DECLARE_PRIVATE(DropJob) Q_PRIVATE_SLOT(d_func(), void slotStart()) }; /** * Drops the clipboard contents. * * If the mime data contains URLs, a popup appears to choose between * Move, Copy, Link and Cancel * which is then implemented by the job, using KIO::move, KIO::copy or KIO::link * Additional actions provided by the application or by plugins can be shown in the popup. * * If the mime data contains data other than URLs, it is saved into a file after asking * the user to choose a filename and the preferred data format. * * This job takes care of recording the subjob in the FileUndoManager, and emits * itemCreated for every file or directory being created, so that the view can select * these items. * * @param dropEvent the drop event, from which the job will extract mimeData, dropAction, etc. The application should take care of calling dropEvent->acceptProposedAction(). * @param destUrl The URL of the target file or directory * @param flags passed to the sub job * * @return A pointer to the job handling the operation. * @warning Don't forget to call KJobWidgets::setWindow() on this job, otherwise the popup * menu won't be properly positioned with Wayland compositors. * @since 5.4 */ KIOWIDGETS_EXPORT DropJob *drop(const QDropEvent *dropEvent, const QUrl &destUrl, JobFlags flags = DefaultFlags); /** * Similar to KIO::drop * * @param dropEvent the drop event, from which the job will extract mimeData, dropAction, etc. The application should take care of calling dropEvent->acceptProposedAction(). * @param destUrl The URL of the target file or directory * @param dropjobFlags Show the menu immediately or manually. * @param flags passed to the sub job * * @return A pointer to the job handling the operation. * @warning Don't forget to call DropJob::showMenu on this job, otherwise the popup will never be shown * * @since 5.67 */ KIOWIDGETS_EXPORT DropJob *drop(const QDropEvent *dropEvent, const QUrl &destUrl, DropJobFlags dropjobFlags, JobFlags flags = DefaultFlags); // TODO KF6: merge with DropJobFlags dropjobFlag = DropJobDefaultFlags } #endif diff --git a/src/widgets/kdirmodel.h b/src/widgets/kdirmodel.h index c56e1842..af785c15 100644 --- a/src/widgets/kdirmodel.h +++ b/src/widgets/kdirmodel.h @@ -1,307 +1,317 @@ /* This file is part of the KDE project Copyright (C) 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 as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. */ #ifndef KDIRMODEL_H #define KDIRMODEL_H #include #include "kiowidgets_export.h" #include class KDirLister; class KDirModelPrivate; class JobUrlCache; /** * @class KDirModel kdirmodel.h * * @short A model for a KIO-based directory tree. * * KDirModel implements the QAbstractItemModel interface (for use with Qt's model/view widgets) * around the directory listing for one directory or a tree of directories. * * Note that there are some cases when using QPersistentModelIndexes from this model will not give * expected results. QPersistentIndexes will remain valid and updated if its siblings are added or * removed. However, if the QPersistentIndex or one of its ancestors is moved, the QPersistentIndex will become * invalid. For example, if a file or directory is renamed after storing a QPersistentModelIndex for it, * the index (along with any stored children) will become invalid even though it is still in the model. The reason * for this is that moves of files and directories are treated as separate insert and remove actions. * * @see KDirSortFilterProxyModel * * @author David Faure * Based on work by Hamish Rodda and Pascal Letourneau */ class KIOWIDGETS_EXPORT KDirModel : public QAbstractItemModel { Q_OBJECT public: /** * @param parent parent qobject */ explicit KDirModel(QObject *parent = nullptr); ~KDirModel(); /** * Flags for the openUrl() method + * @see OpenUrlFlags * @since 5.69 */ enum OpenUrlFlag { NoFlags = 0x0, ///< No additional flags specified. Reload = 0x1, ///< Indicates whether to use the cache or to reread ///< the directory from the disk. ///< Use only when opening a dir not yet listed by our dirLister() ///< without using the cache. Otherwise use dirLister()->updateDirectory(). ShowRoot = 0x2, ///< Display a root node for the URL being opened. }; + /** + * Stores a combination of #OpenUrlFlag values. + */ Q_DECLARE_FLAGS(OpenUrlFlags, OpenUrlFlag) /** * Display the contents of @p url in the model. * Apart from the support for the ShowRoot flag, this is equivalent to dirLister()->openUrl(url, flags) * @param url the URL of the directory whose contents should be listed. * Unless ShowRoot is set, the item for this directory will NOT be shown, the model starts at its children. * @param flags see OpenUrlFlag * @since 5.69 */ void openUrl(const QUrl &url, OpenUrlFlags flags = NoFlags); /** * Set the directory lister to use by this model, instead of the default KDirLister created internally. * The model takes ownership. */ void setDirLister(KDirLister *dirLister); /** * Return the directory lister used by this model. */ KDirLister *dirLister() const; /** * Return the fileitem for a given index. This is O(1), i.e. fast. */ KFileItem itemForIndex(const QModelIndex &index) const; #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 0) /** * Return the index for a given kfileitem. This can be slow. * @deprecated Since 4.0, use the method that takes a KFileItem by value */ KIOWIDGETS_DEPRECATED_VERSION(4, 0, "Use KDirModel::indexForItem(const KFileItem &)") QModelIndex indexForItem(const KFileItem *) const; #endif /** * Return the index for a given kfileitem. This can be slow. */ QModelIndex indexForItem(const KFileItem &) const; /** * Return the index for a given url. This can be slow. */ QModelIndex indexForUrl(const QUrl &url) const; /** * @short Lists subdirectories using fetchMore() as needed until the given @p url exists in the model. * * When the model is used by a treeview, call KDirLister::openUrl with the base url of the tree, * then the treeview will take care of calling fetchMore() when the user opens directories. * However if you want the tree to show a given URL (i.e. open the tree recursively until that URL), * call expandToUrl(). * Note that this is asynchronous; the necessary listing of subdirectories will take time so * the model will not immediately have this url available. * The model emits the signal expand() when an index has become available; this can be connected * to the treeview in order to let it open that index. * @param url the url of a subdirectory of the directory model (or a file in a subdirectory) */ void expandToUrl(const QUrl &url); /** * Notify the model that the item at this index has changed. * For instance because KMimeTypeResolver called determineMimeType on it. * This makes the model emit its dataChanged signal at this index, so that views repaint. * Note that for most things (renaming, changing size etc.), KDirLister's signals tell the model already. */ void itemChanged(const QModelIndex &index); /** * Forget all previews (optimization for turning previews off). * The items will again have their default appearance (not controlled by the model). * @since 5.28 */ void clearAllPreviews(); /** * Useful "default" columns. Views can use a proxy to have more control over this. */ enum ModelColumns { Name = 0, Size, ModifiedTime, Permissions, Owner, Group, Type, ColumnCount }; /// Possible return value for data(ChildCountRole), meaning the item isn't a directory, /// or we haven't calculated its child count yet enum { ChildCountUnknown = -1 }; enum AdditionalRoles { // Note: use printf "0x%08X\n" $(($RANDOM*$RANDOM)) // to define additional roles. FileItemRole = 0x07A263FF, ///< returns the KFileItem for a given index ChildCountRole = 0x2C4D0A40, ///< returns the number of items in a directory, or ChildCountUnknown HasJobRole = 0x01E555A5 ///< returns whether or not there is a job on an item (file/directory) }; + /** + * @see DropsAllowed + */ enum DropsAllowedFlag { NoDrops = 0, DropOnDirectory = 1, ///< allow drops on any directory DropOnAnyFile = 2, ///< allow drops on any file DropOnLocalExecutable = 4 ///< allow drops on local executables, shell scripts and desktop files. Can be used with DropOnDirectory. }; + /** + * Stores a combination of #DropsAllowedFlag values. + */ Q_DECLARE_FLAGS(DropsAllowed, DropsAllowedFlag) /// Set whether dropping onto items should be allowed, and for which kind of item /// Drops are disabled by default. void setDropsAllowed(DropsAllowed dropsAllowed); /// Reimplemented from QAbstractItemModel. Returns true for empty directories. bool canFetchMore(const QModelIndex &parent) const override; /// Reimplemented from QAbstractItemModel. Returns ColumnCount. int columnCount(const QModelIndex &parent = QModelIndex()) const override; /// Reimplemented from QAbstractItemModel. QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; /// Reimplemented from QAbstractItemModel. Not implemented yet. bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override; /// Reimplemented from QAbstractItemModel. Lists the subdirectory. void fetchMore(const QModelIndex &parent) override; /// Reimplemented from QAbstractItemModel. Qt::ItemFlags flags(const QModelIndex &index) const override; /// Reimplemented from QAbstractItemModel. Returns true for directories. bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; /// Reimplemented from QAbstractItemModel. Returns the column titles. QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; /// Reimplemented from QAbstractItemModel. O(1) QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; /// Reimplemented from QAbstractItemModel. QMimeData *mimeData(const QModelIndexList &indexes) const override; /// Reimplemented from QAbstractItemModel. QStringList mimeTypes() const override; /// Reimplemented from QAbstractItemModel. QModelIndex parent(const QModelIndex &index) const override; /// Reimplemented from QAbstractItemModel. QModelIndex sibling(int row, int column, const QModelIndex &index) const override; /// Reimplemented from QAbstractItemModel. int rowCount(const QModelIndex &parent = QModelIndex()) const override; /// Reimplemented from QAbstractItemModel. /// Call this to set a new icon, e.g. a preview bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; /// Reimplemented from QAbstractItemModel. Not implemented. @see KDirSortFilterProxyModel void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; /** * Remove urls from the list if an ancestor is present on the list. This can * be used to delete only the ancestor url and skip a potential error of a non-existent url. * * For example, for a list of "/home/foo/a", "/home/foo/a/a.txt", "/home/foo/a/a/a.txt", "/home/foo/a/b/b.txt", * "home/foo/b/b.txt", this method will return the list "/home/foo/a", "/home/foo/b/b.txt". * * @return the list @p urls without parented urls inside. * @since 4.2 */ static QList simplifiedUrlList(const QList &urls); /** * This emits the needSequenceIcon signal, requesting another sequence icon * * If there is a KFilePreviewGenerator attached to this model, that generator will care * about creating another preview. * * @param index Index of the item that should get another icon * @param sequenceIndex Index in the sequence. If it is zero, the standard icon will be assigned. * For higher indices, arbitrary different meaningful icons will be generated. * @since 4.3 */ void requestSequenceIcon(const QModelIndex &index, int sequenceIndex); /** * Enable/Disable the displaying of an animated overlay that is shown for any destination * urls (in the view). When enabled, the animations (if any) will be drawn automatically. * * Only the files/folders that are visible and have jobs associated with them * will display the animation. * You would likely not want this enabled if you perform some kind of custom painting * that takes up a whole item, and will just make this(and what you paint) look funky. * * Default is disabled. * * Note: KFileItemDelegate needs to have it's method called with the same * value, when you make the call to this method. * * @since 4.5 */ void setJobTransfersVisible(bool value); /** * Returns whether or not displaying job transfers has been enabled. * @since 4.5 */ bool jobTransfersVisible() const; Qt::DropActions supportedDropActions() const override; Q_SIGNALS: /** * Emitted for each subdirectory that is a parent of a url passed to expandToUrl * This allows to asynchronously open a tree view down to a given directory. * Also emitted for the final file, if expandToUrl is called with a file * (for instance so that it can be selected). */ void expand(const QModelIndex &index); /** * Emitted when another icon sequence index is requested * @param index Index of the item that should get another icon * @param sequenceIndex Index in the sequence. If it is zero, the standard icon should be assigned. * For higher indices, arbitrary different meaningful icons should be generated. * This is usually slowly counted up while the user hovers the icon. * If no meaningful alternative icons can be generated, this should be ignored. * @since 4.3 */ void needSequenceIcon(const QModelIndex &index, int sequenceIndex); private: // Make those private, they shouldn't be called by applications bool insertRows(int, int, const QModelIndex & = QModelIndex()) override; bool insertColumns(int, int, const QModelIndex & = QModelIndex()) override; bool removeRows(int, int, const QModelIndex & = QModelIndex()) override; bool removeColumns(int, int, const QModelIndex & = QModelIndex()) override; private: friend class KDirModelPrivate; KDirModelPrivate *const d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KDirModel::DropsAllowed) Q_DECLARE_OPERATORS_FOR_FLAGS(KDirModel::OpenUrlFlags) #endif /* KDIRMODEL_H */ diff --git a/src/widgets/kfile.h b/src/widgets/kfile.h index d46d6d3a..9e46848e 100644 --- a/src/widgets/kfile.h +++ b/src/widgets/kfile.h @@ -1,116 +1,120 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Carsten Pfeiffer 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. */ #ifndef KFILE_H #define KFILE_H #include #include "kiowidgets_export.h" /** * @class KFile kfile.h * * KFile is a class which provides a namespace for some enumerated * values associated with the kfile library. You will never need to * construct a KFile object itself. */ class KIOWIDGETS_EXPORT KFile { Q_GADGET public: /** * Modes of operation for the dialog. * @li @p File - Get a single file name from the user. * @li @p Directory - Get a directory name from the user. * @li @p Files - Get multiple file names from the user. * @li @p ExistingOnly - Never return a filename which does not exist yet * @li @p LocalOnly - Don't return remote filenames + * @see Modes */ enum Mode { File = 1, Directory = 2, Files = 4, ExistingOnly = 8, LocalOnly = 16, ModeMax = 65536 }; + /** + * Stores a combination of #Mode values. + */ Q_DECLARE_FLAGS(Modes, Mode) Q_FLAG(Modes) enum FileView { Default = 0, Simple = 1, Detail = 2, SeparateDirs = 4, PreviewContents = 8, PreviewInfo = 16, Tree = 32, DetailTree = 64, FileViewMax = 65536 }; enum SelectionMode { Single = 1, Multi = 2, Extended = 4, NoSelection = 8 }; // // some bittests // // sorting specific static bool isSortByName(const QDir::SortFlags &sort); static bool isSortBySize(const QDir::SortFlags &sort); static bool isSortByDate(const QDir::SortFlags &sort); static bool isSortByType(const QDir::SortFlags &sort); static bool isSortDirsFirst(const QDir::SortFlags &sort); static bool isSortCaseInsensitive(const QDir::SortFlags &sort); // view specific static bool isDefaultView(const FileView &view); static bool isSimpleView(const FileView &view); static bool isDetailView(const FileView &view); static bool isSeparateDirs(const FileView &view); static bool isPreviewContents(const FileView &view); static bool isPreviewInfo(const FileView &view); static bool isTreeView(const FileView &view); static bool isDetailTreeView(const FileView &view); private: KFile(); // forbidden }; Q_DECLARE_OPERATORS_FOR_FLAGS(KFile::Modes) #endif // KFILE_H diff --git a/src/widgets/krun.h b/src/widgets/krun.h index bc4a1a52..5bba8bf5 100644 --- a/src/widgets/krun.h +++ b/src/widgets/krun.h @@ -1,675 +1,681 @@ /* This file is part of the KDE project Copyright (C) 1998, 1999 Torben Weis Copyright (C) 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 as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. */ #ifndef KRUN_H #define KRUN_H #include "kiowidgets_export.h" #include #include #include class KService; class KJob; class QTimer; class KRunPrivate; namespace KIO { class Job; } /** * @class KRun krun.h * * To open files with their associated applications in KDE, use KRun. * * It can execute any desktop entry, as well as any file, using * the default application or another application "bound" to the file type * (or URL protocol). * * In that example, the mimetype of the file is not known by the application, * so a KRun instance must be created. It will determine the mimetype by itself. * If the mimetype is known, or if you even know the service (application) to * use for this file, use one of the static methods. * * By default KRun uses auto deletion. It causes the KRun instance to delete * itself when the it finished its task. If you allocate the KRun * object on the stack you must disable auto deletion, otherwise it will crash. * * This respects the "shell_access", "openwith" and "run_desktop_files" Kiosk * action restrictions (see KAuthorized::authorize()). * * @short Opens files with their associated applications in KDE */ class KIOWIDGETS_EXPORT KRun : public QObject { Q_OBJECT public: /** * @param url the URL of the file or directory to 'run' * * @param window * The top-level widget of the app that invoked this object. * It is used to make sure private information like passwords * are properly handled per application. * * @param showProgressInfo * Whether to show progress information when determining the * type of the file (i.e. when using KIO::stat and KIO::mimetype) * Before you set this to false to avoid a dialog box, think about * a very slow FTP server... * It is always better to provide progress info in such cases. * * @param asn * Application startup notification id, if available (otherwise ""). * * Porting note: kdelibs 4 had mode_t mode and bool isLocalFile arguments after * window and before showProgressInfo. Removed in KF5. */ KRun(const QUrl &url, QWidget *window, bool showProgressInfo = true, const QByteArray &asn = QByteArray()); /** * Destructor. Don't call it yourself, since a KRun object auto-deletes * itself. */ virtual ~KRun(); /** * Abort this KRun. This kills any jobs launched by it, * and leads to deletion if auto-deletion is on. * This is much safer than deleting the KRun (in case it's * currently showing an error dialog box, for instance) */ void abort(); /** * Returns true if the KRun instance has an error. * @return true when an error occurred * @see error() */ bool hasError() const; /** * Returns true if the KRun instance has finished. * @return true if the KRun instance has finished * @see finished() */ bool hasFinished() const; /** * Checks whether auto delete is activated. * Auto-deletion causes the KRun instance to delete itself * when it finished its task. * By default auto deletion is on. * @return true if auto deletion is on, false otherwise */ bool autoDelete() const; /** * Enables or disabled auto deletion. * Auto deletion causes the KRun instance to delete itself * when it finished its task. If you allocate the KRun * object on the stack you must disable auto deletion. * By default auto deletion is on. * @param b true to enable auto deletion, false to disable */ void setAutoDelete(bool b); /** * Set the preferred service for opening this URL, after * its mimetype will have been found by KRun. IMPORTANT: the service is * only used if its configuration says it can handle this mimetype. * This is used for instance for the X-KDE-LastOpenedWith key in * the recent documents list, or for the app selection in * KParts::BrowserOpenOrSaveQuestion. * @param desktopEntryName the desktopEntryName of the service, e.g. "kate". */ void setPreferredService(const QString &desktopEntryName); /** * Sets whether executables, .desktop files or shell scripts should * be run by KRun. This is enabled by default. * @param b whether to run executable files or not. * @see isExecutable() */ void setRunExecutables(bool b); /** * Sets whether KRun should follow URLs redirections. * This is enabled by default * @param b whether to follow redirections or not. * @since 5.55 */ void setFollowRedirections(bool b); /** * Sets whether the external webbrowser setting should be honoured. * This is enabled by default. * This should only be disabled in webbrowser applications. * @param b whether to enable the external browser or not. */ void setEnableExternalBrowser(bool b); /** * Sets the file name to use in the case of downloading the file to a tempfile * in order to give to a non-url-aware application. Some apps rely on the extension * to determine the mimetype of the file. Usually the file name comes from the URL, * but in the case of the HTTP Content-Disposition header, we need to override the * file name. */ void setSuggestedFileName(const QString &fileName); /** * Sets whether a prompt should be shown before executing scripts or desktop files. * If enabled, KRun uses the "kiorc" configuration file to decide whether to open the * file, execute it or show a prompt. * @since 5.4 */ void setShowScriptExecutionPrompt(bool showPrompt); /** * Suggested file name given by the server (e.g. HTTP content-disposition) */ QString suggestedFileName() const; /** * Associated window, as passed to the constructor * @since 4.9.3 */ QWidget *window() const; #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(5, 6) /** * Open a list of URLs with a certain service (application). * * @param service the service to run * @param urls the list of URLs, can be empty (app launched * without argument) * @param window The top-level widget of the app that invoked this object. * @param tempFiles if true and urls are local files, they will be deleted * when the application exits. * @param suggestedFileName see setSuggestedFileName * @param asn Application startup notification id, if any (otherwise ""). * @return @c true on success, @c false on error * * @deprecated since 5.6, use runApplication instead. No change needed on the application side, * the only difference is the return value (qint64 instead of bool). */ KIOWIDGETS_DEPRECATED_VERSION(5, 6, "Use KRun::runApplication(const KService &, const QList &, QWidget *, RunFlags, const QString &, const QByteArray &") static bool run(const KService &service, const QList &urls, QWidget *window, bool tempFiles = false, const QString &suggestedFileName = QString(), const QByteArray &asn = QByteArray()); #endif /** * Open a list of URLs with a certain service (application). * * Prefer runApplication(), unless you need to wait for the application * to register to D-Bus before this method returns (but that should rather * be done with D-Bus activation). * * @param service the service to run * @param urls the list of URLs, can be empty (app launched * without argument) * @param window The top-level widget of the app that invoked this object. * @param tempFiles if true and urls are local files, they will be deleted * when the application exits. * @param suggestedFileName see setSuggestedFileName * @param asn Application startup notification id, if any (otherwise ""). * @return 0 on error, the process ID on success * @since 5.6 */ static qint64 runService(const KService &service, const QList &urls, QWidget *window, bool tempFiles = false, const QString &suggestedFileName = QString(), const QByteArray &asn = QByteArray()); // TODO KF6: deprecate/remove + /** + * @see RunFlags + */ enum RunFlag { DeleteTemporaryFiles = 0x1, ///< the URLs passed to the service will be deleted when it exits (if the URLs are local files) RunExecutables = 0x2, ///< Whether to run URLs that are executable scripts or binaries @see isExecutableFile() @since 5.31 }; + /** + * Stores a combination of #RunFlag values. + */ Q_DECLARE_FLAGS(RunFlags, RunFlag) /** * Run an application (known from its .desktop file, i.e. as a KService) * * If you need to wait for the application to register to D-Bus, use D-Bus activation instead. * * If you don't need the prompt for asking the user whether to add the executable bit for * desktop files or binaries that don't have it, you can use KIO::ApplicationLauncherJob from KIOGui directly. * * @param service the service to run * @param urls the list of URLs, can be empty (app launched * without argument) * @param window The top-level widget of the app that invoked this object. * @param flags various flags * @param suggestedFileName see setSuggestedFileName * @param asn Application startup notification id, if any (otherwise ""). * @return 0 on error, the process ID on success * @since 5.24 */ static qint64 runApplication(const KService &service, const QList &urls, QWidget *window, RunFlags flags = RunFlags(), const QString &suggestedFileName = QString(), const QByteArray &asn = QByteArray()); /** * Open a list of URLs with an executable. * * @param exec the name of the executable, for example * "/usr/bin/netscape %u". * Don't forget to include the %u if you know that the applications * supports URLs. Otherwise, non-local urls will first be downloaded * to a temp file (using kioexec). * @param urls the list of URLs to open, can be empty (app launched without argument) * @param window The top-level widget of the app that invoked this object. * @param name the logical name of the application, for example * "Netscape 4.06". * @param icon the icon which should be used by the application. * @param asn Application startup notification id, if any (otherwise ""). * @return @c true on success, @c false on error */ static bool run(const QString &exec, const QList &urls, QWidget *window, const QString &name = QString(), const QString &icon = QString(), const QByteArray &asn = QByteArray()); #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(5, 31) /** * Open the given URL. * * This function is used after the mime type * is found out. It will search for all services which can handle * the mime type and call run() afterwards. * @param url the URL to open * @param mimetype the mime type of the resource * @param window The top-level widget of the app that invoked this object. * @param tempFile if true and url is a local file, it will be deleted * when the launched application exits. * @param runExecutables if false then local .desktop files, * executables and shell scripts will not be run. * See also isExecutable(). * @param suggestedFileName see setSuggestedFileName * @param asn Application startup notification id, if any (otherwise ""). * @return @c true on success, @c false on error * @deprecated since 5.31, use runUrl() with RunFlags instead. */ KIOWIDGETS_DEPRECATED_VERSION(5, 31, "Use KRun::const QUrl &, const QString &, QWidget *, RunFlags, const QString &, const QByteArray &") static bool runUrl(const QUrl &url, const QString &mimetype, QWidget *window, bool tempFile = false, bool runExecutables = true, const QString &suggestedFileName = QString(), const QByteArray &asn = QByteArray()); #endif /** * Open the given URL. * * This function can be used after the mime type has been found out. * It will search for all services which can handle the mime type and call run() afterwards. * * @param url The URL to open. * @param mimetype The mime type of the resource. * @param window The top-level widget of the app that invoked this object. * @param flags Various run flags. * @param suggestedFileName See setSuggestedFileName() * @param asn Application startup notification id, if any (otherwise ""). * @return @c true on success, @c false on error * @since 5.31 */ static bool runUrl(const QUrl &url, const QString &mimetype, QWidget *window, RunFlags flags, const QString &suggestedFileName = QString(), const QByteArray &asn = QByteArray()); /** * Run the given shell command and notifies KDE of the starting * of the application. If the program to be called doesn't exist, * an error box will be displayed. * * Use only when you know the full command line. Otherwise use the other * static methods, or KRun's constructor. * * @param cmd must be a shell command. You must not append "&" * to it, since the function will do that for you. * @param window The top-level widget of the app that invoked this object. * @param workingDirectory directory to use for relative paths, so that * a command like "kwrite file.txt" finds file.txt from the right place * * @return @c true on success, @c false on error */ static bool runCommand(const QString &cmd, QWidget *window, const QString &workingDirectory = QString()); /** * Same as the other runCommand(), but it also takes the name of the * binary, to display an error message in case it couldn't find it. * * @param cmd must be a shell command. You must not append "&" * to it, since the function will do that for you. * @param execName the name of the executable * @param icon icon for app starting notification * @param window The top-level widget of the app that invoked this object. * @param asn Application startup notification id, if any (otherwise ""). * @return @c true on success, @c false on error */ static bool runCommand(const QString &cmd, const QString &execName, const QString &icon, QWidget *window, const QByteArray &asn = QByteArray()); /** * Overload that also takes a working directory, so that a command like * "kwrite file.txt" finds file.txt from the right place. * @param workingDirectory the working directory for the started process. The default * (if passing an empty string) is the user's document path. * @since 4.4 */ static bool runCommand(const QString &cmd, const QString &execName, const QString &icon, QWidget *window, const QByteArray &asn, const QString &workingDirectory); // TODO KDE5: merge the above with 5-args runCommand, using QString() /** * Display the Open-With dialog for those URLs, and run the chosen application. * @param lst the list of applications to run * @param window The top-level widget of the app that invoked this object. * @param tempFiles if true and lst are local files, they will be deleted * when the application exits. * @param suggestedFileName see setSuggestedFileName * @param asn Application startup notification id, if any (otherwise ""). * @return false if the dialog was canceled */ static bool displayOpenWithDialog(const QList &lst, QWidget *window, bool tempFiles = false, const QString &suggestedFileName = QString(), const QByteArray &asn = QByteArray()); // TODO deprecate and provide RunFlags() overload #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 0) /** * Quotes a string for the shell. * An empty string will @em not be quoted. * * @param str the string to quote. The quoted string will be written here * * @deprecated Since 4.0, use KShell::quoteArg() instead. @em Note that this function * behaves differently for empty arguments and returns the result * differently. */ KIOWIDGETS_DEPRECATED_VERSION(4, 0, "Use KShell::quoteArg(...)") static void shellQuote(QString &str); #endif #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(5, 0) /** * Processes a Exec= line as found in .desktop files. * @param _service the service to extract information from. * @param _urls The urls the service should open. * @param tempFiles if true and urls are local files, they will be deleted * when the application exits. * @param suggestedFileName see setSuggestedFileName * * @return a list of arguments suitable for QProcess. * @deprecated since 5.0, use KIO::DesktopExecParser */ KIOWIDGETS_DEPRECATED_VERSION(5, 0, "Use KIO::DesktopExecParser") static QStringList processDesktopExec(const KService &_service, const QList &_urls, bool tempFiles = false, const QString &suggestedFileName = QString()); #endif #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(5, 0) /** * Given a full command line (e.g. the Exec= line from a .desktop file), * extract the name of the binary being run. * @param execLine the full command line * @param removePath if true, remove a (relative or absolute) path. E.g. /usr/bin/ls becomes ls. * @return the name of the executable to run * @deprecated since 5.0, use KIO::DesktopExecParser::executableName if removePath was true, * or KIO::DesktopExecParser::executablePath if removePath was false. */ KIOWIDGETS_DEPRECATED_VERSION(5, 0, "See API docs") static QString binaryName(const QString &execLine, bool removePath); #endif /** * Returns whether @p mimeType refers to an executable program instead * of a data file. */ static bool isExecutable(const QString &mimeType); /** * Returns whether the @p url of @p mimetype is executable. * To be executable the file must pass the following rules: * -# Must reside on the local filesystem. * -# Must be marked as executable for the user by the filesystem. * -# The mime type must inherit application/x-executable, application/x-executable-script or application/x-sharedlib. * To allow a script to run when the above rules are satisfied add the entry * @code * X-KDE-IsAlso=application/x-executable-script * @endcode * to the mimetype's desktop file. */ static bool isExecutableFile(const QUrl &url, const QString &mimetype); /** * @internal */ static bool checkStartupNotify(const QString &binName, const KService *service, bool *silent_arg, QByteArray *wmclass_arg); Q_SIGNALS: /** * Emitted when the operation finished. * This signal is emitted in all cases of completion, whether successful or with error. * @see hasFinished() */ void finished(); /** * Emitted when the operation had an error. * @see hasError() */ void error(); protected Q_SLOTS: /** * All following protected slots are used by subclasses of KRun! */ /** * This slot is called whenever the internal timer fired, * in order to move on to the next step. */ void slotTimeout(); // KDE5: rename to slotNextStep() or something like that /** * This slot is called when the scan job is finished. */ void slotScanFinished(KJob *); /** * This slot is called when the scan job has found out * the mime type. */ void slotScanMimeType(KIO::Job *, const QString &type); /** * Call this from subclasses when you have determined the mimetype. * It will call foundMimeType, but also sets up protection against deletion during message boxes. * @since 4.0.2 */ void mimeTypeDetermined(const QString &mimeType); /** * This slot is called when the 'stat' job has finished. */ virtual void slotStatResult(KJob *); protected: /** * All following protected methods are used by subclasses of KRun! */ /** * Initializes the krun object. */ virtual void init(); /** * Start scanning a file. */ virtual void scanFile(); /** * Called if the mimetype has been detected. The function runs * the application associated with this mimetype. * Reimplement this method to implement a different behavior, * like opening the component for displaying the URL embedded. * * Important: call setFinished(true) once you are done! * Usually at the end of the foundMimeType reimplementation, but if the * reimplementation is asynchronous (e.g. uses KIO jobs) then * it can be called later instead. */ virtual void foundMimeType(const QString &type); /** * Kills the file scanning job. */ virtual void killJob(); /** * Called when KRun detects an error during the init phase. * * The default implementation shows a message box. * @since 5.0 */ virtual void handleInitError(int kioErrorCode, const QString &errorMsg); /** * Called when a KIO job started by KRun gives an error. * * The default implementation shows a message box. */ virtual void handleError(KJob *job); /** * Sets the url. */ void setUrl(const QUrl &url); /** * Returns the url. */ QUrl url() const; /** * Sets whether an error has occurred. */ void setError(bool error); /** * Sets whether progress information shall be shown. */ void setProgressInfo(bool progressInfo); /** * Returns whether progress information are shown. */ bool progressInfo() const; /** * Marks this 'KRun' instance as finished. */ void setFinished(bool finished); /** * Sets the job. */ void setJob(KIO::Job *job); /** * Returns the job. */ KIO::Job *job(); #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 4) /** * Returns the timer object. * @deprecated Since 4.4. setFinished(true) now takes care of the timer().start(0), * so this can be removed. */ KIOWIDGETS_DEPRECATED_VERSION(4, 4, "See API docs") QTimer &timer(); #endif #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 1) /** * Indicate that the next action is to scan the file. * @deprecated Since 4.1. Not useful in public API */ KIOWIDGETS_DEPRECATED_VERSION(4, 1, "Do not use") void setDoScanFile(bool scanFile); #endif #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 1) /** * Returns whether the file shall be scanned. * @deprecated Since 4.1. Not useful in public API */ KIOWIDGETS_DEPRECATED_VERSION(4, 1, "Do not use") bool doScanFile() const; #endif #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 1) /** * Sets whether it is a directory. * @deprecated Since 4.1. Typo in the name, and not useful as a public method */ KIOWIDGETS_DEPRECATED_VERSION(4, 1, "Do not use") void setIsDirecory(bool isDirectory); #endif /** * Returns whether it is a directory. */ bool isDirectory() const; #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 1) /** * @deprecated Since 4.1. Not useful in public API */ KIOWIDGETS_DEPRECATED_VERSION(4, 1, "Do not use") void setInitializeNextAction(bool initialize); #endif #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 1) /** * @deprecated Since 4.1. Not useful in public API */ KIOWIDGETS_DEPRECATED_VERSION(4, 1, "Do not use") bool initializeNextAction() const; #endif /** * Returns whether it is a local file. */ bool isLocalFile() const; private: friend class KRunPrivate; KRunPrivate *const d; }; #endif diff --git a/src/widgets/kurifilter.h b/src/widgets/kurifilter.h index a2f4962b..efbeeee1 100644 --- a/src/widgets/kurifilter.h +++ b/src/widgets/kurifilter.h @@ -1,1014 +1,1023 @@ /* * This file is part of the KDE libraries * Copyright (C) 2000-2001,2003,2010 Dawit Alemayehu * * Original author * Copyright (C) 2000 Yves Arrouye * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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. **/ #ifndef KURIFILTER_H #define KURIFILTER_H #include "kiowidgets_export.h" #include #include #include #include #include #ifdef Q_OS_WIN #undef ERROR #endif class KUriFilterPrivate; class KUriFilterDataPrivate; class KCModule; class QHostInfo; /** * @class KUriFilterSearchProvider kurifilter.h * * Class that holds information about a search provider. * * @since 4.6 */ class KIOWIDGETS_EXPORT KUriFilterSearchProvider { public: /** * Default constructor. */ KUriFilterSearchProvider(); /** * Copy constructor. */ KUriFilterSearchProvider(const KUriFilterSearchProvider &); /** * Destructor. */ virtual ~KUriFilterSearchProvider(); /** * Returns the desktop filename of the search provider without any extension. * * For example, if the desktop filename of the search provider was * "foobar.desktop", this function will return "foobar". */ QString desktopEntryName() const; /** * Returns the descriptive name of the search provider, e.g. "Google News". * * This name comes from the "Name=" property entry in the desktop file that * contains the search provider's information. */ QString name() const; /** * Returns the icon name associated with the search provider when available. */ virtual QString iconName() const; /** * Returns all the web shortcut keys associated with this search provider. * * @see defaultKey */ QStringList keys() const; /** * Returns the default web shortcut key for this search provider. * * Right now this is the same as doing keys().first(), it might however * change based on what the backend plugins do. * * @see keys */ QString defaultKey() const; /** * Assignment operator. */ KUriFilterSearchProvider &operator=(const KUriFilterSearchProvider &); protected: void setDesktopEntryName(const QString &); void setIconName(const QString &); void setKeys(const QStringList &); void setName(const QString &); private: friend class KUriFilterPlugin; class KUriFilterSearchProviderPrivate; KUriFilterSearchProviderPrivate *const d; }; /** * @class KUriFilterData kurifilter.h * * This class is a basic messaging class used to exchange filtering information * between the filter plugins and the application requesting the filtering * service. * * Use this object if you require a more detailed information about the URI you * want to filter. Any application can create an instance of this class and send * it to KUriFilter to have the plugins fill out all possible information about * the URI. * * On successful filtering you can use @ref uriType() to determine what type * of resource the request was filtered into. See @ref KUriFilter::UriTypes for * details. If an error is encountered, then @ref KUriFilter::Error is returned. * You can use @ref errorMsg to obtain the error information. * * The functions in this class are not reentrant. * * \b Example * * Here is a basic example of how this class is used with @ref KUriFilter: * \code * KUriFilterData filterData (QLatin1String("kde.org")); * bool filtered = KUriFilter::self()->filterUri(filterData); * \endcode * * If you are only interested in getting the list of preferred search providers, * then you can do the following: * * \code * KUriFilterData data; * data.setData(""); * data.setSearchFilteringOption(KUriFilterData::RetrievePreferredSearchProvidersOnly); * bool filtered = KUriFilter::self()->filterSearchUri(data, KUriFilter::NormalTextFilter); * \endcode * * @short A class for exchanging filtering information. * @author Dawit Alemayehu */ class KIOWIDGETS_EXPORT KUriFilterData { public: /** * Describes the type of the URI that was filtered. * Here is a brief description of the types: * * @li NetProtocol - Any network protocol: http, ftp, nttp, pop3, etc... * @li LocalFile - A local file whose executable flag is not set * @li LocalDir - A local directory * @li Executable - A local file whose executable flag is set * @li Help - A man or info page * @li Shell - A shell executable (ex: echo "Test..." >> ~/testfile) * @li Blocked - A URI that should be blocked/filtered (ex: ad filtering) * @li Error - An incorrect URI (ex: "~johndoe" when user johndoe * does not exist in that system ) * @li Unknown - A URI that is not identified. Default value when * a KUriFilterData is first created. */ enum UriTypes { NetProtocol = 0, LocalFile, LocalDir, Executable, Help, Shell, Blocked, Error, Unknown }; /** * This enum describes the search filtering options to be used. * * @li SearchFilterOptionNone * No search filter options are set and normal filtering is performed * on the input data. * @li RetrieveSearchProvidersOnly * If set, the list of all available search providers are returned without * any input filtering. This flag only applies when used in conjunction * with the @ref KUriFilter::NormalTextFilter flag. * @li RetrievePreferredSearchProvidersOnly * If set, the list of preferred search providers are returned without * any input filtering. This flag only applies when used in conjunction * with the @ref KUriFilter::NormalTextFilter flag. * @li RetrieveAvailableSearchProvidersOnly * Same as doing RetrievePreferredSearchProvidersOnly | RetrieveSearchProvidersOnly, * where all available search providers are returned if no preferred ones * ones are available. No input filtering will be performed. * * @see setSearchFilteringOptions * @see KUriFilter::filterSearchUri + * @see SearchFilterOptions * @since 4.6 */ enum SearchFilterOption { SearchFilterOptionNone = 0x0, RetrieveSearchProvidersOnly = 0x01, RetrievePreferredSearchProvidersOnly = 0x02, RetrieveAvailableSearchProvidersOnly = (RetrievePreferredSearchProvidersOnly | RetrieveSearchProvidersOnly) }; + /** + * Stores a combination of #SearchFilterOption values. + */ Q_DECLARE_FLAGS(SearchFilterOptions, SearchFilterOption) /** * Default constructor. * * Creates a UriFilterData object. */ KUriFilterData(); /** * Creates a KUriFilterData object from the given URL. * * @param url is the URL to be filtered. */ explicit KUriFilterData(const QUrl &url); /** * Creates a KUriFilterData object from the given string. * * @param url is the string to be filtered. */ explicit KUriFilterData(const QString &url); /** * Copy constructor. * * Creates a KUriFilterData object from another KURIFilterData object. * * @param other the uri filter data to be copied. */ KUriFilterData(const KUriFilterData &other); /** * Destructor. */ ~KUriFilterData(); /** * Returns the filtered or the original URL. * * If one of the plugins successfully filtered the original input, this * function returns it. Otherwise, it will return the input itself. * * @return the filtered or original url. */ QUrl uri() const; /** * Returns an error message. * * This functions returns the error message set by the plugin whenever the * uri type is set to KUriFilterData::ERROR. Otherwise, it returns a nullptr * string. * * @return the error message or a nullptr when there is none. */ QString errorMsg() const; /** * Returns the URI type. * * This method always returns KUriFilterData::UNKNOWN if the given URL was * not filtered. * * @return the type of the URI */ UriTypes uriType() const; /** * Returns the absolute path if one has already been set. * * @return the absolute path, or QString() * * @see hasAbsolutePath() */ QString absolutePath() const; /** * Checks whether the supplied data had an absolute path. * * @return true if the supplied data has an absolute path * * @see absolutePath() */ bool hasAbsolutePath() const; /** * Returns the command line options and arguments for a local resource * when present. * * @return options and arguments when present, otherwise QString() */ QString argsAndOptions() const; /** * Checks whether the current data is a local resource with command line * options and arguments. * * @return true if the current data has command line options and arguments */ bool hasArgsAndOptions() const; /** * @return true if the filters should attempt to check whether the * supplied uri is an executable. False otherwise. */ bool checkForExecutables() const; /** * The string as typed by the user, before any URL processing is done. */ QString typedString() const; /** * Returns the search term portion of the typed string. * * If the @ref typedString was not filtered by a search filter plugin, this * function returns an empty string. * * @see typedString * @since 4.5 */ QString searchTerm() const; /** * Returns the character that is used to separate the search term from the * keyword. * * If @ref typedString was not filtered by a search filter plugin, this * function returns a null character. * * @see typedString * @since 4.5 */ QChar searchTermSeparator() const; /** * Returns the name of the search service provider, e.g. Google. * * If @ref typedString was not filtered by a search filter plugin, this * function returns an empty string. * * @see typedString * @since 4.5 */ QString searchProvider() const; /** * Returns a list of the names of preferred or available search providers. * * This function returns the list of providers marked as preferred whenever * the input data, i.e. @ref typedString, is successfully filtered. * * If no default search provider has been selected prior to a filter request, * this function will return an empty list. To avoid this problem you must * either set an alternate default search provider using @ref setAlternateDefaultSearchProvider * or set one of the @ref SearchFilterOption flags if you are only interested * in getting the list of providers and not filtering the input. * * Additionally, you can also provide alternate search providers in case * there are no preferred ones already selected. * * You can use @ref queryForPreferredServiceProvider to obtain the query * associated with the list of search providers returned by this function. * * @see setAlternateSearchProviders * @see setAlternateDefaultSearchProvider * @see setSearchFilteringOption * @see queryForPreferredServiceProvider * @since 4.5 */ QStringList preferredSearchProviders() const; /** * Returns information about @p provider. * * You can use this function to obtain the more information about the search * providers returned by @ref preferredSearchProviders. * * @see preferredSearchProviders * @see KUriFilterSearchProvider * @since 4.6 */ KUriFilterSearchProvider queryForSearchProvider(const QString &provider) const; /** * Returns the web shortcut url for the given preferred search provider. * * You can use this function to obtain the query for the preferred search * providers returned by @ref preferredSearchProviders. * * The query returned by this function is in web shortcut format, i.e. * "gg:foo bar", and must be re-filtered through KUriFilter to obtain a * valid url. * * @see preferredSearchProviders * @since 4.5 */ QString queryForPreferredSearchProvider(const QString &provider) const; /** * Returns all the query urls for the given search provider. * * Use this function to obtain all the different queries that can be used * for the given provider. For example, if a search engine provider named * "foobar" has web shortcuts named "foobar", "foo" and "bar", then this * function, unlike @ref queryForPreferredSearchProvider, will return a * a query for each and every web shortcut. * * @see queryForPreferredSearchProvider * @since 4.6 */ QStringList allQueriesForSearchProvider(const QString &provider) const; /** * Returns the icon associated with the given preferred search provider. * * You can use this function to obtain the icon names associated with the * preferred search providers returned by @ref preferredSearchProviders. * * @see preferredSearchProviders * @since 4.5 */ QString iconNameForPreferredSearchProvider(const QString &provider) const; /** * Returns the list of alternate search providers. * * This function returns an empty list if @ref setAlternateSearchProviders * was not called to set the alternate search providers to be when no * preferred providers have been chosen by the user through the search * configuration module. * * @see setAlternatteSearchProviders * @see preferredSearchProviders * @since 4.5 */ QStringList alternateSearchProviders() const; /** * Returns the search provider to use when a default provider is not available. * * This function returns an empty string if @ref setAlternateDefaultSearchProvider * was not called to set the default search provider to be used when none has been * chosen by the user through the search configuration module. * * @see setAlternateDefaultSearchProvider * @since 4.5 */ QString alternateDefaultSearchProvider() const; /** * Returns the default protocol to use when filtering potentially valid url inputs. * * By default this function will return an empty string. * * @see setDefaultUrlScheme * @since 4.6 */ QString defaultUrlScheme() const; /** * Returns the specified search filter options. * * By default this function returns @ref SearchFilterOptionNone. * * @see setSearchFilteringOptions * @since 4.6 */ SearchFilterOptions searchFilteringOptions() const; /** * The name of the icon that matches the current filtered URL. * * This function returns a null string by default and when no icon is found * for the filtered URL. */ QString iconName(); /** * Check whether the provided uri is executable or not. * * Setting this to false ensures that typing the name of an executable does * not start that application. This is useful in the location bar of a * browser. The default value is true. */ void setCheckForExecutables(bool check); /** * Same as above except the argument is a URL. * * Use this function to set the string to be filtered when you construct an * empty filter object. * * @param url the URL to be filtered. */ void setData(const QUrl &url); /** * Sets the URL to be filtered. * * Use this function to set the string to be * filtered when you construct an empty filter * object. * * @param url the string to be filtered. */ void setData(const QString &url); /** * Sets the absolute path to be used whenever the supplied data is a * relative local URL. * * NOTE: This function should only be used for local resources, i.e. the * "file:/" protocol. It is useful for specifying the absolute path in * cases where the actual URL might be relative. If deriving the path from * a QUrl, make sure you set the argument for this function to the result * of calling path () instead of url (). * * @param abs_path the absolute path to the local resource. * * @return true if absolute path is successfully set. Otherwise, false. */ bool setAbsolutePath(const QString &abs_path); /** * Sets a list of search providers to use in case no preferred search * providers are available. * * The list of preferred search providers set using this function will only * be used if the default and favorite search providers have not yet been * selected by the user. Otherwise, the providers specified through this * function will be ignored. * * @see alternateSearchProviders * @see preferredSearchProviders * @since 4.5 */ void setAlternateSearchProviders(const QStringList &providers); /** * Sets the search provider to use in case no default provider is available. * * The default search provider set using this function will only be used if * the default and favorite search providers have not yet been selected by * the user. Otherwise, the default provider specified by through function * will be ignored. * * @see alternateDefaultSearchProvider * @see preferredSearchProviders * @since 4.5 */ void setAlternateDefaultSearchProvider(const QString &provider); /** * Sets the default scheme used when filtering potentially valid url inputs. * * Use this function to change the default protocol used when filtering * potentially valid url inputs. The default protocol is http. * * If the scheme is specified without a separator, then "://" will be used * as the separator by default. For example, if the default url scheme was * simply set to "ftp", then a potentially valid url input such as "kde.org" * will be filtered to "ftp://kde.org". * * @see defaultUrlScheme * @since 4.6 */ void setDefaultUrlScheme(const QString &); /** * Sets the options used by search filter plugins to filter requests. * * The default search filter option is @ref SearchFilterOptionNone. See * @ref SearchFilterOption for the description of the other flags. * * It is important to note that the options set through this function can * prevent any filtering from being performed by search filter plugins. * As such, @ref uriTypes can return KUriFilterData::Unknown and @ref uri * can return an invalid url even though the filtering request returned * a successful response. * * @see searchFilteringOptions * @since 4.6 */ void setSearchFilteringOptions(SearchFilterOptions options); /** * Overloaded assignment operator. * * This function allows you to easily assign a QUrl * to a KUriFilterData object. * * @return an instance of a KUriFilterData object. */ KUriFilterData &operator=(const QUrl &url); /** * Overloaded assignment operator. * * This function allows you to easily assign a QString to a KUriFilterData * object. * * @return an instance of a KUriFilterData object. */ KUriFilterData &operator=(const QString &url); private: friend class KUriFilterPlugin; KUriFilterDataPrivate *const d; }; /** * @class KUriFilterPlugin kurifilter.h * * Base class for URI filter plugins. * * This class applies a single filter to a URI. All plugins designed to provide * URI filtering service should inherit from this abstract class and provide a * concrete implementation. * * All inheriting classes need to implement the pure virtual function * @ref filterUri. * * @short Abstract class for URI filter plugins. */ class KIOWIDGETS_EXPORT KUriFilterPlugin : public QObject { Q_OBJECT public: #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 6) /** * List for holding the following search provider information: * ([search provider name], [search query, search query icon name]) * * @since 4.5 * @deprecated Since 4.6, use @ref KUriFilterSearchProvider instead. See @ref setSearchProviders; */ KIOWIDGETS_DEPRECATED_VERSION(4, 6, "Use KUriFilterSearchProvider") typedef QHash > ProviderInfoList; #endif /** * Constructs a filter plugin with a given name * * @param parent the parent object, or @c nullptr for no parent * @param name the name of the plugin, mandatory */ explicit KUriFilterPlugin(const QString &name, QObject *parent = nullptr); // KF6 TODO ~KUriFilterPlugin(); /** * Filters a URI. * * @param data the URI data to be filtered. * @return A boolean indicating whether the URI has been changed. */ virtual bool filterUri(KUriFilterData &data) const = 0; /** * Creates a configuration module for the filter. * * It is the responsibility of the caller to delete the module once it is * not needed anymore. * * @return A configuration module, or @c nullptr if the filter isn't configurable. */ virtual KCModule *configModule(QWidget *, const char *) const; /** * Returns the name of the configuration module for the filter. * * @return the name of a configuration module or QString() if none. */ virtual QString configName() const; protected: /** * Sets the URL in @p data to @p uri. */ void setFilteredUri(KUriFilterData &data, const QUrl &uri) const; /** * Sets the error message in @p data to @p errormsg. */ void setErrorMsg(KUriFilterData &data, const QString &errmsg) const; /** * Sets the URI type in @p data to @p type. */ void setUriType(KUriFilterData &data, KUriFilterData::UriTypes type) const; /** * Sets the arguments and options string in @p data to @p args if any were * found during filtering. */ void setArguments(KUriFilterData &data, const QString &args) const; /** * Sets the name of the search provider, the search term and keyword/term * separator in @p data. * * @since 4.5 */ void setSearchProvider(KUriFilterData &data, const QString &provider, const QString &term, const QChar &separator) const; /** * Sets the information about the search @p providers in @p data. * * @since 4.6 */ void setSearchProviders(KUriFilterData &data, const QList &providers) const; /** * Returns the icon name for the given @p url and URI @p type. * * @since 4.5 */ QString iconNameFor(const QUrl &url, KUriFilterData::UriTypes type) const; /** * Performs a DNS lookup for @p hostname and returns the result. * * This function uses the KIO/KHTML DNS cache to speed up the * lookup. It also avoids doing a reverse lookup if the given * host name is already an ip address. * * \note All uri filter plugins that need to perform a hostname * lookup should use this function. * * @param hostname the hostname to lookup. * @param timeout the amount of time in msecs to wait for the lookup. * @return the result of the host name lookup. * * @since 4.7 */ QHostInfo resolveName(const QString &hostname, unsigned long timeout) const; private: class KUriFilterPluginPrivate *const d; }; /** * @class KUriFilter kurifilter.h * * KUriFilter applies a number of filters to a URI and returns a filtered version if any * filter matches. * A simple example is "kde.org" to "http://www.kde.org", which is commonplace in web browsers. * * The filters are implemented as plugins in @ref KUriFilterPlugin subclasses. * * KUriFilter is a singleton object: obtain the instance by calling * @p KUriFilter::self() and use the public member functions to * perform the filtering. * * \b Example * * To simply filter a given string: * * \code * QString url("kde.org"); * bool filtered = KUriFilter::self()->filteredUri( url ); * \endcode * * You can alternatively use a QUrl: * * \code * QUrl url("kde.org"); * bool filtered = KUriFilter::self()->filterUri( url ); * \endcode * * If you have a constant string or a constant URL, simply invoke the * corresponding function to obtain the filtered string or URL instead * of a boolean flag: * * \code * QString filteredText = KUriFilter::self()->filteredUri( "kde.org" ); * \endcode * * All of the above examples should result in "kde.org" being filtered into * "http://kde.org". * * You can also restrict the filters to be used by supplying the name of the * filters you want to use. By default all available filters are used. * * To use specific filters, add the names of the filters you want to use to a * QStringList and invoke the appropriate filtering function. * * The examples below show the use of specific filters. KDE ships with the * following filter plugins by default: * * kshorturifilter: * This is used for filtering potentially valid url inputs such as "kde.org" * Additionally it filters shell variables and shortcuts such as $HOME and * ~ as well as man and info page shortcuts, # and ## respectively. * * kuriikwsfilter: * This is used for filtering normal input text into a web search url using the * configured fallback search engine selected by the user. * * kurisearchfilter: * This is used for filtering KDE webshortcuts. For example "gg:KDE" will be * converted to a url for searching the work "KDE" using the Google search * engine. * * localdomainfilter: * This is used for doing a DNS lookup to determine whether the input is a valid * local address. * * fixuphosturifilter: * This is used to append "www." to the host name of a pre filtered http url * if the original url cannot be resolved. * * \code * QString text ("kde.org"); * bool filtered = KUriFilter::self()->filterUri(text, QLatin1String("kshorturifilter")); * \endcode * * The above code should result in "kde.org" being filtered into "http://kde.org". * * \code * QStringList list; * list << QLatin1String("kshorturifilter") << QLatin1String("localdomainfilter"); * bool filtered = KUriFilter::self()->filterUri( text, list ); * \endcode * * Additionally if you only want to do search related filtering, you can use the * search specific function, @ref filterSearchUri, that is available in KDE * 4.5 and higher. For example, to search for a given input on the web you * can do the following: * * KUriFilterData filterData ("foo"); * bool filtered = KUriFilter::self()->filterSearchUri(filterData, KUriFilterData::NormalTextFilter); * * KUriFilter converts all filtering requests to use @ref KUriFilterData * internally. The use of this bi-directional class allows you to send specific * instructions to the filter plugins as well as receive detailed information * about the filtered request from them. See the documentation of KUriFilterData * class for more examples and details. * * All functions in this class are thread safe and reentrant. * * @short Filters the given input into a valid url whenever possible. */ class KIOWIDGETS_EXPORT KUriFilter { public: /** * This enum describes the types of search plugin filters available. * * @li NormalTextFilter The plugin used to filter normal text, e.g. "some term to search". * @li WebShortcutFilter The plugin used to filter web shortcuts, e.g. gg:KDE. + * + * @see SearchFilterTypes */ enum SearchFilterType { NormalTextFilter = 0x01, WebShortcutFilter = 0x02 }; + /** + * Stores a combination of #SearchFilterType values. + */ Q_DECLARE_FLAGS(SearchFilterTypes, SearchFilterType) /** * Destructor */ ~KUriFilter(); /** * Returns an instance of KUriFilter. */ static KUriFilter *self(); /** * Filters @p data using the specified @p filters. * * If no named filters are specified, the default, then all the * URI filter plugins found will be used. * * @param data object that contains the URI to be filtered. * @param filters specify the list of filters to be used. * * @return a boolean indicating whether the URI has been changed */ bool filterUri(KUriFilterData &data, const QStringList &filters = QStringList()); /** * Filters the URI given by the URL. * * The given URL is filtered based on the specified list of filters. * If the list is empty all available filters would be used. * * @param uri the URI to filter. * @param filters specify the list of filters to be used. * * @return a boolean indicating whether the URI has been changed */ bool filterUri(QUrl &uri, const QStringList &filters = QStringList()); /** * Filters a string representing a URI. * * The given URL is filtered based on the specified list of filters. * If the list is empty all available filters would be used. * * @param uri The URI to filter. * @param filters specify the list of filters to be used. * * @return a boolean indicating whether the URI has been changed */ bool filterUri(QString &uri, const QStringList &filters = QStringList()); /** * Returns the filtered URI. * * The given URL is filtered based on the specified list of filters. * If the list is empty all available filters would be used. * * @param uri The URI to filter. * @param filters specify the list of filters to be used. * * @return the filtered URI or null if it cannot be filtered */ QUrl filteredUri(const QUrl &uri, const QStringList &filters = QStringList()); /** * Return a filtered string representation of a URI. * * The given URL is filtered based on the specified list of filters. * If the list is empty all available filters would be used. * * @param uri the URI to filter. * @param filters specify the list of filters to be used. * * @return the filtered URI or null if it cannot be filtered */ QString filteredUri(const QString &uri, const QStringList &filters = QStringList()); #if KIOWIDGETS_ENABLE_DEPRECATED_SINCE(4, 6) /** * See @ref filterSearchUri(KUriFilterData&, SearchFilterTypes) * * @since 4.5 * @deprecated Since 4.6, use filterSearchUri(KUriFilterData&, SearchFilterTypes) instead. */ KIOWIDGETS_DEPRECATED_VERSION(4, 6, "Use KUriFilter::filterSearchUri(KUriFilterData &, SearchFilterTypes)") bool filterSearchUri(KUriFilterData &data); #endif /** * Filter @p data using the criteria specified by @p types. * * The search filter type can be individual value of @ref SearchFilterTypes * or a combination of those types using the bitwise OR operator. * * You can also use the flags from @ref KUriFilterData::SearchFilterOption * to alter the filtering mechanisms of the search filter providers. * * @param data object that contains the URI to be filtered. * @param types the search filters used to filter the request. * @return true if the specified @p data was successfully filtered. * * @see KUriFilterData::setSearchFilteringOptions * @since 4.6 */ bool filterSearchUri(KUriFilterData &data, SearchFilterTypes types); /** * Return a list of the names of all loaded plugins. * * @return a QStringList of plugin names */ QStringList pluginNames() const; protected: /** * Constructor. * * Creates a KUriFilter object and calls @ref loadPlugins to load all * available URI filter plugins. */ KUriFilter(); /** * Loads all allowed plugins. * * This function only loads URI filter plugins that have not been disabled. */ void loadPlugins(); private: KUriFilterPrivate *const d; friend class KUriFilterSingleton; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KUriFilterData::SearchFilterOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KUriFilter::SearchFilterTypes) #endif