diff --git a/src/kdebugdialog/kabstractdebugdialog.h b/src/kdebugdialog/kabstractdebugdialog.h index 25f0bd42..d5a612a2 100644 --- a/src/kdebugdialog/kabstractdebugdialog.h +++ b/src/kdebugdialog/kabstractdebugdialog.h @@ -1,57 +1,57 @@ /* This file is part of the KDE libraries Copyright (C) 2000 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 KABSTRACTDEBUGDIALOG__H #define KABSTRACTDEBUGDIALOG__H #include class QCheckBox; class KConfig; class QVBoxLayout; class KPushButton; class KAbstractDebugDialog : public KDialog { Q_OBJECT public: - explicit KAbstractDebugDialog(QWidget *parent); + KDELIBS4SUPPORT_DEPRECATED explicit KAbstractDebugDialog(QWidget *parent); virtual ~KAbstractDebugDialog(); void buildButtons(); void load(); void save(); virtual void doLoad() = 0; virtual void doSave() = 0; KConfig * config() { return pConfig; } typedef QMap AreaMap; protected Q_SLOTS: void slotShowHelp(); void slotApply(); protected: KConfig* pConfig; QCheckBox* m_disableAll; }; #endif diff --git a/src/kdebugdialog/kdebugdialog.h b/src/kdebugdialog/kdebugdialog.h index cd5816fe..d3a31b3e 100644 --- a/src/kdebugdialog/kdebugdialog.h +++ b/src/kdebugdialog/kdebugdialog.h @@ -1,66 +1,66 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org) 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 _KDEBUGDIALOG #define _KDEBUGDIALOG #include "kabstractdebugdialog.h" #include "ui_kdebugdialog.h" class QLineEdit; class QComboBox; class QLabel; class QGroupBox; class QCheckBox; /** * Control debug/warning/error/fatal output of KDE applications * * This dialog allows control of debugging output for all KDE apps. * * @author Kalle Dalheimer (kalle@kde.org) */ class KDebugDialog : public KAbstractDebugDialog, public Ui_KDebugDialog { Q_OBJECT public: - explicit KDebugDialog(const AreaMap& areaMap, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDebugDialog(const AreaMap& areaMap, QWidget *parent = nullptr); virtual ~KDebugDialog(); void doLoad() Q_DECL_OVERRIDE {} void doSave() Q_DECL_OVERRIDE; protected Q_SLOTS: void slotDebugAreaChanged(QTreeWidgetItem*); void slotDestinationChanged(); void disableAllClicked(); private: void showArea(const QString& areaName); QString mCurrentDebugArea; private: // Disallow assignment and copy-construction KDebugDialog( const KDebugDialog& ); KDebugDialog& operator= ( const KDebugDialog& ); }; #endif diff --git a/src/kdebugdialog/klistdebugdialog.h b/src/kdebugdialog/klistdebugdialog.h index f3b8896f..18c99644 100644 --- a/src/kdebugdialog/klistdebugdialog.h +++ b/src/kdebugdialog/klistdebugdialog.h @@ -1,61 +1,61 @@ /* This file is part of the KDE libraries Copyright (C) 2000 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 KLISTDEBUGDIALOG__H #define KLISTDEBUGDIALOG__H #include "kabstractdebugdialog.h" #include class KTreeWidgetSearchLineWidget; class QTreeWidget; /** * Control debug output of KDE applications * This dialog offers a reduced functionality compared to the full KDebugDialog * class, but allows to set debug output on or off to several areas much more easily. * * @author David Faure */ class KListDebugDialog : public KAbstractDebugDialog { Q_OBJECT public: - explicit KListDebugDialog(const AreaMap& areaMap, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KListDebugDialog(const AreaMap& areaMap, QWidget *parent = nullptr); virtual ~KListDebugDialog() {} void activateArea( const QByteArray& area, bool activate ); protected Q_SLOTS: void selectAll(); void deSelectAll(); void disableAllClicked(); protected: void doSave() Q_DECL_OVERRIDE; void doLoad() Q_DECL_OVERRIDE; private: QTreeWidget* m_areaWidget; KTreeWidgetSearchLineWidget *m_incrSearch; QWidget* m_buttonContainer; }; #endif diff --git a/src/kdecore/k3bufferedsocket.h b/src/kdecore/k3bufferedsocket.h index b7a5bf37..b1343c67 100644 --- a/src/kdecore/k3bufferedsocket.h +++ b/src/kdecore/k3bufferedsocket.h @@ -1,215 +1,215 @@ /* -*- C++ -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KBUFFEREDSOCKET_H #define KBUFFEREDSOCKET_H #include #include "k3streamsocket.h" #include #include #include namespace KNetwork { class KBufferedSocketPrivate; /** @class KBufferedSocket k3bufferedsocket.h k3bufferedsocket.h * @brief Buffered stream sockets. * * This class allows the user to create and operate buffered stream sockets * such as those used in most Internet connections. This class is * also the one that resembles the most to the old QSocket * implementation. * * Objects of this type operate only in non-blocking mode. A call to * setBlocking(true) will result in an error. * * @note Buffered sockets only make sense if you're using them from * the main (event-loop) thread. This is actually a restriction * imposed by Qt's QSocketNotifier. If you want to use a socket * in an auxiliary thread, please use KStreamSocket. * * @see KNetwork::KStreamSocket, KNetwork::KServerSocket * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KBufferedSocket: public KStreamSocket { Q_OBJECT public: /** * Default constructor. * * @param node destination host * @param service destination service to connect to * @param parent the parent object for this object */ - explicit KBufferedSocket(const QString &node = QString(), const QString &service = QString(), + KDELIBS4SUPPORT_DEPRECATED explicit KBufferedSocket(const QString &node = QString(), const QString &service = QString(), QObject *parent = nullptr); /** * Destructor. */ virtual ~KBufferedSocket(); /** * Be sure to catch new devices. */ void setSocketDevice(KSocketDevice *device) Q_DECL_OVERRIDE; protected: /** * Buffered sockets can only operate in non-blocking mode. */ bool setSocketOptions(int opts) Q_DECL_OVERRIDE; public: /** * Closes the socket for new data, but allow data that had been buffered * for output with writeData() to be still be written. * * @sa closeNow */ void close() Q_DECL_OVERRIDE; /** * Make use of the buffers. */ qint64 bytesAvailable() const Q_DECL_OVERRIDE; /** * Make use of buffers. */ qint64 waitForMore(int msecs, bool *timeout = nullptr) Q_DECL_OVERRIDE; /** * Catch changes. */ void enableRead(bool enable) Q_DECL_OVERRIDE; /** * Catch changes. */ void enableWrite(bool enable) Q_DECL_OVERRIDE; /** * Sets the use of input buffering. */ void setInputBuffering(bool enable); /** * Sets the use of output buffering. */ void setOutputBuffering(bool enable); /** * Returns the length of the output buffer. */ qint64 bytesToWrite() const Q_DECL_OVERRIDE; /** * Closes the socket and discards any output data that had been buffered * with writeData() but that had not yet been written. * * @sa close */ virtual void closeNow(); /** * Returns true if a line can be read with readLine() */ bool canReadLine() const Q_DECL_OVERRIDE; // KDE4: make virtual, add timeout to match the Qt4 signature // and move to another class up the hierarchy /** * Blocks until the connection is either established, or completely * failed. */ void waitForConnect(); protected: /** * Reads data from a socket. * * The @p from parameter is always set to peerAddress() */ qint64 readData(char *data, qint64 maxlen, KSocketAddress *from) Q_DECL_OVERRIDE; /** * Peeks data from the socket. * * The @p from parameter is always set to peerAddress() */ qint64 peekData(char *data, qint64 maxlen, KSocketAddress *from) Q_DECL_OVERRIDE; /** * Writes data to the socket. * * The @p to parameter is discarded. */ qint64 writeData(const char *data, qint64 len, const KSocketAddress *to) Q_DECL_OVERRIDE; /** * Improve the readLine performance */ qint64 readLineData(char *data, qint64 maxSize) Q_DECL_OVERRIDE; /** * Catch connection to clear the buffers */ void stateChanging(SocketState newState) Q_DECL_OVERRIDE; protected Q_SLOTS: /** * Slot called when there's read activity. */ void slotReadActivity() Q_DECL_OVERRIDE; /** * Slot called when there's write activity. */ void slotWriteActivity() Q_DECL_OVERRIDE; #if 0 // Already present in QIODevice Q_SIGNALS: /** * This signal is emitted whenever data is written. */ void bytesWritten(int bytes); #endif private: KBufferedSocket(const KBufferedSocket &); KBufferedSocket &operator=(const KBufferedSocket &); KBufferedSocketPrivate *const d; }; } // namespace KNetwork #endif diff --git a/src/kdecore/k3resolver.h b/src/kdecore/k3resolver.h index cb2f9a32..57a2960f 100644 --- a/src/kdecore/k3resolver.h +++ b/src/kdecore/k3resolver.h @@ -1,956 +1,956 @@ /* -*- mode: C++; coding: utf-8; -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KRESOLVER_H #define KRESOLVER_H ////////////////// // Needed includes #include #include #include #include "k3socketaddress.h" #include "kdemacros.h" //////////////////////// // Forward declarations struct sockaddr; class QString; class QByteArray; template class QSet; ////////////////// // Our definitions namespace KNetwork { namespace Internal { class KResolverManager; } class KResolverEntryPrivate; /** @class KResolverEntry k3resolver.h k3resolver.h * @brief One resolution entry. * * This class is one element in the resolution results list. * It contains the socket address for connecting, as well as * a bit more of information: the socket type, address family * and protocol numbers. * * This class contains all the information required for creating, * binding and connecting a socket. * * KResolverEntry objects implicitly share data, so copying them * is quite efficient. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KResolverEntry { public: /** * Default constructor * */ KResolverEntry(); /** * Constructs a new KResolverEntry from a KSocketAddress * and other data. * * The KSocketAddress @p addr parameter will be deep-copied. * * @param addr the address that was resolved * @param socktype the socket type of the resolved address * @param protocol the protocol of the resolved address * @param canonName the canonical name of the resolved hostname * @param encodedName the ASCII-compatible encoding of the hostname */ KResolverEntry(const KSocketAddress &addr, int socktype, int protocol, const QString &canonName = QString(), const QByteArray &encodedName = QByteArray()); /** * Constructs a new KResolverEntry from raw forms of * socket addresses and other data. * * This constructor instead creates an internal KSocketAddress object. * * @param sa the sockaddr structure containing the raw address * @param salen the length of the sockaddr structure * @param socktype the socket type of the resolved address * @param protocol the protocol of the resolved address * @param canonName the canonical name of the resolved hostname * @param encodedName the ASCII-compatible encoding of the hostname */ KResolverEntry(const struct sockaddr *sa, quint16 salen, int socktype, int protocol, const QString &canonName = QString(), const QByteArray &encodedName = QByteArray()); /** * Copy constructor. * * This constructor performs a shallow-copy of the other object. */ KResolverEntry(const KResolverEntry &other); /** * Destructor. * * The destructor frees associated resources with this object. It does * not destroy shared data. */ ~KResolverEntry(); /** * Retrieves the socket address associated with this entry. */ KSocketAddress address() const; /** * Retrieves the length of the socket address structure. */ quint16 length() const; /** * Retrieves the family associated with this socket address. */ int family() const; /** * Retrieves the canonical name associated with this entry, if there is any. * If the canonical name was not found, this function returns QString(). */ QString canonicalName() const; /** * Retrieves the encoded domain name associated with this entry, if there is * any. If this domain has been resolved through DNS, this will be the * the ACE-encoded hostname. * * Returns a null QByteArray if such information is not available. * * Please note that this information is NOT to be presented to the user, * unless requested. */ QByteArray encodedName() const; /** * Retrieves the socket type associated with this entry. */ int socketType() const; /** * Retrieves the protocol associated with this entry. */ int protocol() const; /** * Assignment operator * * This function copies the contents of the other object into this one. * Data will be shared between the two of them. */ KResolverEntry &operator=(const KResolverEntry &other); /** * Dummy operator== for compilers which need a complete * instantiated class when exporting to a shared lib */ KDE_DUMMY_COMPARISON_OPERATOR(KResolverEntry) private: QSharedDataPointer d; }; KDE_DUMMY_QHASH_FUNCTION(KResolverEntry) class KResolverResultsPrivate; /** * @class KResolverResults k3resolver.h k3resolver.h * @brief Name and service resolution results. * * This object contains the results of a name and service resolution, as * those performed by KResolver. It is also a descendant of QValueList, so * you may use all its member functions here to access the elements. * * A KResolverResults object is associated with a resolution, so, in addition * to the resolved elements, you can also retrieve information about the * resolution process itself, like the nodename that was resolved or an error * code. * * Note Resolver also uses KResolverResults objects to indicate failure, so * you should test for failure. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KResolverResults: public QList { public: /** * Default constructor. * * Constructs an empty list. */ KResolverResults(); /** * Copy constructor * * Creates a new object with the contents of the other one. Data will be * shared by the two objects, like QValueList */ KResolverResults(const KResolverResults &other); /** * Destructor * * Destroys the object and frees associated resources. */ virtual ~KResolverResults(); /** * Assignment operator * * Copies the contents of the other container into this one, discarding * our current values. */ KResolverResults &operator=(const KResolverResults &other); /** * Retrieves the error code associated with this resolution. The values * here are the same as in KResolver::ErrorCodes. */ int error() const; /** * Retrieves the system error code, if any. * @see KResolver::systemError for more information */ int systemError() const; /** * Sets the error codes * * @param errorcode the error code in KResolver::ErrorCodes * @param systemerror the system error code associated, if any */ void setError(int errorcode, int systemerror = 0); /** * The nodename to which the resolution was performed. */ QString nodeName() const; /** * The service name to which the resolution was performed. */ QString serviceName() const; /** * Sets the new nodename and service name */ void setAddress(const QString &host, const QString &service); protected: /** Standard hack to add virtuals later. @internal */ virtual void virtual_hook(int id, void *data); private: QSharedDataPointer d; }; class KResolverPrivate; /** * @class KResolver k3resolver.h k3resolver.h * @brief Name and service resolution class. * * This class provides support for doing name-to-binary resolution * for nodenames and service ports. You should use this class if you * need specific resolution techniques when creating a socket or if you * want to inspect the results before calling the socket functions. * * You can either create an object and set the options you want in it * or you can simply call the static member functions, which will create * standard Resolver objects and dispatch the resolution for you. Normally, * the static functions will be used, except in cases where specific options * must be set. * * A Resolver object defaults to the following: * @li address family: any address family * @li socket type: streaming socket * @li protocol: implementation-defined. Generally, TCP * @li host and service: unset * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KResolver: public QObject { Q_OBJECT public: /** * Address family selection types * * These values can be OR-ed together to form a composite family selection. * * @li UnknownFamily: a family that is unknown to the current implementation * @li KnownFamily: a family that is known to the implementation (the exact * opposite of UnknownFamily) * @li AnyFamilies: any address family is acceptable * @li InternetFamily: an address for connecting to the Internet * @li InetFamily: alias for InternetFamily * @li IPv6Family: an IPv6 address only * @li IPv4Family: an IPv4 address only * @li UnixFamily: an address for the local Unix namespace (i.e., Unix sockets) * @li LocalFamily: alias for UnixFamily */ enum SocketFamilies { UnknownFamily = 0x0001, UnixFamily = 0x0002, LocalFamily = UnixFamily, IPv4Family = 0x0004, IPv6Family = 0x0008, InternetFamily = IPv4Family | IPv6Family, InetFamily = InternetFamily, KnownFamily = ~UnknownFamily, AnyFamily = KnownFamily | UnknownFamily }; /** * Flags for the resolution. * * These flags are used for setting the resolution behaviour for this * object: * @li Passive: resolve to a passive socket (i.e., one that can be used for * binding to a local interface) * @li CanonName: request that the canonical name for the given nodename * be found and recorded * @li NoResolve: request that no external resolution be performed. The given * nodename and servicename will be resolved locally only. * @li NoSrv: don't try to use SRV-based name-resolution. * @li Multiport: the port/service argument is a list of port numbers and * ranges. (future extension) * * @note SRV-based lookup and Multiport are not implemented yet. */ enum Flags { Passive = 0x01, CanonName = 0x02, NoResolve = 0x04, NoSrv = 0x08, Multiport = 0x10 }; /** * Error codes * * These are the possible error values that objects of this class * may return. See errorString() for getting a string representation * for these errors. * * @li AddrFamily: Address family for the given nodename is not supported. * @li TryAgain: Temporary failure in name resolution. You should try again. * @li NonRecoverable: Non-recoverable failure in name resolution. * @li BadFlags: Invalid flags were given. * @li Memory: Memory allocation failure. * @li NoName: The specified name or service doesn't exist. * @li UnsupportedFamily: The requested socket family is not supported. * @li UnsupportedService: The requested service is not supported for this * socket type (i.e., a datagram service in a streaming socket). * @li UnsupportedSocketType: The requested socket type is not supported. * @li UnknownError: An unknown, unexpected error occurred. * @li SystemError: A system error occurred. See systemError(). * @li Canceled: This request was canceled by the user. */ enum ErrorCodes { // note: if you change this enum, take a look at KResolver::errorString NoError = 0, AddrFamily = -1, TryAgain = -2, NonRecoverable = -3, BadFlags = -4, Memory = -5, NoName = -6, UnsupportedFamily = -7, UnsupportedService = -8, UnsupportedSocketType = -9, UnknownError = -10, SystemError = -11, Canceled = -100 }; /** * Status codes. * * These are the possible status for a Resolver object. A value * greater than zero indicates normal behaviour, while negative * values either indicate failure or error. * * @li Idle: resolution has not yet been started. * @li Queued: resolution is queued but not yet in progress. * @li InProgress: resolution is in progress. * @li PostProcessing: resolution is in progress. * @li Success: resolution is done; you can retrieve the results. * @li Canceled: request canceled by the user. * @li Failed: resolution is done, but failed. * * Note: the status Canceled and the error code Canceled are the same. * * Note 2: the status Queued and InProgress might not be distinguishable. * Some implementations might not differentiate one from the other. */ enum StatusCodes { Idle = 0, Queued = 1, InProgress = 5, PostProcessing = 6, Success = 10, //Canceled = -100, // already defined above Failed = -101 }; /** * Default constructor. * * Creates an empty Resolver object. You should set the wanted * names and flags using the member functions before starting * the name resolution. * * @param parent the parent object (see QObject) */ KResolver(QObject *parent = nullptr); /** * Constructor with host and service names. * * Creates a Resolver object with the given host and * service names. Flags are initialised to 0 and any address family * will be accepted. * * @param nodename the host name we want resolved * @param servicename the service name associated, like "http" * @param parent the parent object (see QObject) */ - explicit KResolver(const QString &nodename, const QString &servicename = QString(), + KDELIBS4SUPPORT_DEPRECATED explicit KResolver(const QString &nodename, const QString &servicename = QString(), QObject *parent = nullptr); /** * Destructor. * * When this object is deleted, it'll destroy all associated * resources. If the resolution is still in progress, it will be * canceled and the signal will \b not be emitted. */ virtual ~KResolver(); /** * Retrieve the current status of this object. * * @see StatusCodes for the possible status codes. */ int status() const; /** * Retrieve the error code in this object. * * This function will return NoError if we are not in * an error condition. See status() and StatusCodes to * find out what the current status is. * * @see errorString for getting a textual representation of * this error */ int error() const; /** * Retrieve the associated system error code in this object. * * Many resolution operations may generate an extra error code * as given by the C errno variable. That value is stored in the * object and can be retrieved by this function. */ int systemError() const; /** * Returns the textual representation of the error in this object. */ QString errorString() const; /** * Returns true if this object is currently running */ bool isRunning() const; /** * The nodename to which the resolution was/is to be performed. */ QString nodeName() const; /** * The service name to which the resolution was/is to be performed. */ QString serviceName() const; /** * Sets the nodename for the resolution. * * Set the nodename to QString() to unset it. * @param nodename The nodename to be resolved. */ void setNodeName(const QString &nodename); /** * Sets the service name to be resolved. * * Set it to QString() to unset it. * @param service The service to be resolved. */ void setServiceName(const QString &service); /** * Sets both the host and the service names. * * Setting either value to QString() will unset them. * @param node The nodename * @param service The service name */ void setAddress(const QString &node, const QString &service); /** * Retrieves the flags set for the resolution. * * @see Flags for an explanation on what flags are possible */ int flags() const; /** * Sets the flags. * * @param flags the new flags * @return the old flags * @see Flags for an explanation on the flags */ int setFlags(int flags); /** * Sets the allowed socket families. * * @param families the families that we want/accept * @see SocketFamilies for possible values */ void setFamily(int families); /** * Sets the socket type we want. * * The values for the @p type parameter are the SOCK_* * constants, defined in . The most common * values are: * @li SOCK_STREAM streaming socket (= reliable, sequenced, * connection-based) * @li SOCK_DGRAM datagram socket (= unreliable, connectionless) * @li SOCK_RAW raw socket, with direct access to the * container protocol (such as IP) * * These three are the only values to which it is guaranteed that * resolution will work. Some systems may define other constants (such as * SOCK_RDM for reliable datagrams), but support is implementation-defined. * * @param type the wanted socket type (SOCK_* constants). Set * 0 to use the default. */ void setSocketType(int type); /** * Sets the protocol we want. * * Protocols are dependent on the selected address family, so you should know * what you are doing if you use this function. Besides, protocols generally * are either stream-based or datagram-based, so the value of the socket * type is also important. The resolution will fail if these values don't match. * * When using an Internet socket, the values for the protocol are the * IPPROTO_* constants, defined in . * * You may choose to set the protocol either by its number or by its name, or * by both. If you set: * @li the number and the name: both values will be stored internally; you * may set the name to an empty value, if wanted * @li the number only (name = NULL): the name will be searched in the * protocols database * @li the name only (number = 0): the number will be searched in the * database * @li neither name nor number: reset to default behaviour * * @param protonum the protocol number we want * @param name the protocol name */ void setProtocol(int protonum, const char *name = nullptr); /** * Starts the name resolution asynchronously. * * This function will queue this object for resolution * and will return immediately. The status upon exit will either be * Queued or InProgress or Failed. * * This function does nothing if the object is already queued. But if * it had already succeeded or failed, this function will re-start it. * * Note: if both the nodename and the servicename are unset, this function * will not queue, but will set a success state and emit the signal. Also * note that in this case and maybe others, the signal finished() might * be emitted before this function returns. * * @return true if this request was successfully queued for asynchronous * resolution */ bool start(); /** * Waits for a request to finish resolving. * * This function will wait on a running request for its termination. The * status upon exit will either be Success or Failed or Canceled. * * This function may be called from any thread, even one that is not the * GUI thread or the one that started the resolution process. But note this * function is not thread-safe nor reentrant: i.e., only one thread can be * waiting on one given object. * * Also note that this function ensures that the finished() signal is * emitted before it returns. That means that, as a side-effect, whenever * wait() is called, the signal is emitted on the thread calling wait(). * * @param msec the time to wait, in milliseconds or 0 to * wait forever * @return true if the resolution has finished processing, even when it * failed or was canceled. False means the wait timed out and * the resolution is still running. */ bool wait(int msec = 0); /** * Cancels a running request * * This function will cancel a running request. If the request is not * currently running or queued, this function does nothing. * * Note: if you tell the signal to be emitted, be aware that it might * or might not be emitted before this function returns. * * @param emitSignal whether to emit the finished() signal or not */ void cancel(bool emitSignal = true); /** * Retrieves the results of this resolution * * Use this function to retrieve the results of the resolution. If no * data was resolved (yet) or if we failed, this function will return * an empty object. * * @return the resolved data * @see status for information on finding out if the resolution was successful */ KResolverResults results() const; /** * Handles events. Reimplemented from QObject. * * This function handles the events generated by the manager indicating that * this object has finished processing. * * Do not post events to this object. */ bool event(QEvent *) Q_DECL_OVERRIDE; Q_SIGNALS: // signals /** * This signal is emitted whenever the resolution is finished, one * way or another (success or failure). The @p results parameter * will contain the resolved data. * * Note: if you are doing multiple resolutions, you can use the * QObject::sender() function to distinguish one Resolver object from * another. * * @param results the resolved data; might be empty if the resolution * failed * @see results for information on what the results are * * @note This signal is @b always delivered in the GUI event thread, even for * resolutions that were started in secondary threads. */ void finished(const KNetwork::KResolverResults &results); private: void emitFinished(); public: // Static functions /** * Returns the string representation of this error code. * * @param errorcode the error code. See ErrorCodes. * @param syserror the system error code associated. * @return the string representation. This is already * i18n'ed. */ static QString errorString(int errorcode, int syserror = 0); /** * Resolve the nodename and service name synchronously * * This static function is provided as convenience for simplifying * name resolution. It resolves the given host and service names synchronously * and returns the results it found. It is equivalent to the following code: * * \code * KResolver qres(host, service); * qres.setFlags(flags); * qres.setFamily(families) * qres.start(); * qres.wait(); * return qres.results(); * \endcode * * @param host the nodename to resolve * @param service the service to resolve * @param flags flags to be used * @param families the families to be searched * @return a KResolverResults object containing the results * @see KResolverResults for information on how to obtain the error code */ static KResolverResults resolve(const QString &host, const QString &service, int flags = 0, int families = KResolver::InternetFamily); /** * Start an asynchronous name resolution * * This function is provided as a convenience to simplify the resolution * process. It creates an internal KResolver object, connects the * finished() signal to the given slot and starts the resolution * asynchronously. It is more or less equivalent to the following code: * * \b Note: this function may trigger the signal before it returns, so * your code must be prepared for this situation. * * \code * KResolver* qres = new KResolver(host, service); * QObject::connect(qres, SIGNAL(finished(const KNetwork::KResolverResults&)), * userObj, userSlot); * qres->setFlags(flags); * qres->setFamily(families); * return qres->start(); * \endcode * * You should use it like this in your code: * \code * KResolver::resolveAsync(myObj, SLOT(mySlot(KResolverResults)), host, service); * \endcode * * @param userObj the object whose slot @p userSlot we will connect * @param userSlot the slot to which we'll connect * @param host the nodename to resolve * @param service the service to resolve * @param flags flags to be used * @param families families to be searcheed * @return true if the queuing was successful, false if not * @see KResolverResults for information on how to obtain the error code */ static bool resolveAsync(QObject *userObj, const char *userSlot, const QString &host, const QString &service, int flags = 0, int families = KResolver::InternetFamily); /** * Returns the domain name in an ASCII Compatible Encoding form, suitable * for DNS lookups. This is the base for International Domain Name support * over the Internet. * * Note this function may fail, in which case it'll return a null * QByteArray. Reasons for failure include use of unknown code * points (Unicode characters). * * Note that the encoding is illegible and, thus, should not be presented * to the user, except if requested. * * @param unicodeDomain the domain name to be encoded * @return the ACE-encoded suitable for DNS queries if successful, a null * QByteArray if failure. */ static QByteArray domainToAscii(const QString &unicodeDomain); /** * Does the inverse of domainToAscii() and return an Unicode domain * name from the given ACE-encoded domain. * * This function may fail if the given domain cannot be successfully * converted back to Unicode. Reasons for failure include a malformed * domain name or good ones whose reencoding back to ACE don't match * the form given here (e.g., ACE-encoding of an already * ASCII-compatible domain). * * It is, however, guaranteed that domains returned * by domainToAscii() will work. * * @param asciiDomain the ACE-encoded domain name to be decoded * @return the Unicode representation of the given domain name * if successful, the original string if not * @note ACE = ASCII-Compatible Encoding, i.e., 7-bit */ static QString domainToUnicode(const QByteArray &asciiDomain); /** * The same as above, but taking a QString argument. * * @param asciiDomain the ACE-encoded domain name to be decoded * @return the Unicode representation of the given domain name * if successful, QString() if not. */ static QString domainToUnicode(const QString &asciiDomain); /** * Normalise a domain name. * * In order to prevent simple mistakes in International Domain * Names (IDN), it has been decided that certain code points * (characters in Unicode) would be instead converted to others. * This includes turning them all to lower case, as well certain * other specific operations, as specified in the documents. * * For instance, the German 'ß' will be changed into 'ss', while * the micro symbol 'µ' will be changed to the Greek mu 'μ'. * * Two equivalent domains have the same normalised form. And the * normalised form of a normalised domain is itself (i.e., if * d is normalised, the following is true: d == normalizeDomain(d) ) * * This operation is equivalent to encoding and the decoding a Unicode * hostname. * * @param domain a domain to be normalised * @return the normalised domain, or QString() if the domain is * invalid. */ static QString normalizeDomain(const QString &domain); /** * Resolves a protocol number to its names * * Note: the returned QStrList operates on deep-copies. * * @param protonum the protocol number to be looked for * @return all the protocol names in a list. The first is the "proper" * name. */ static QList protocolName(int protonum); /** * Finds all aliases for a given protocol name * * @param protoname the protocol name to be looked for * @return all the protocol names in a list. The first is the "proper" * name. */ static QList protocolName(const char *protoname); /** * Resolves a protocol name to its number * * @param protoname the protocol name to be looked for * @return the protocol number or -1 if we couldn't locate it */ static int protocolNumber(const char *protoname); /** * Resolves a service name to its port number * * @param servname the service name to be looked for * @param protoname the protocol it is associated with * @return the port number in host byte-order or -1 in case of error */ static int servicePort(const char *servname, const char *protoname); /** * Finds all the aliases for a given service name * * Note: the returned QList operates on deep-copies. * * @param servname the service alias to be looked for * @param protoname the protocol it is associated with * @return all the service names in a list. The first is the "proper" * name. */ static QList serviceName(const char *servname, const char *protoname); /** * Resolves a port number to its names * * Note: the returned QList operates on deep copies. * * @param port the port number, in host byte-order * @param protoname the protocol it is associated with * @return all the service names in a list. The first is the "proper" * name. */ static QList serviceName(int port, const char *protoname); /** * Returns this machine's local hostname. * * @return this machine's local hostname */ static QString localHostName(); protected: /** * Sets the error codes */ void setError(int errorcode, int systemerror = 0); /** Standard hack to add virtuals later. @internal */ virtual void virtual_hook(int id, void *data); private: KResolverPrivate *const d; friend class KResolverResults; friend class ::KNetwork::Internal::KResolverManager; }; } // namespace KNetwork #endif diff --git a/src/kdecore/k3resolver_p.h b/src/kdecore/k3resolver_p.h index caab157f..db0508c2 100644 --- a/src/kdecore/k3resolver_p.h +++ b/src/kdecore/k3resolver_p.h @@ -1,347 +1,347 @@ /* -*- C++ -*- * Copyright (C) 2003-2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KRESOLVER_P_H #define KRESOLVER_P_H #include #include #include #include #include #include #include #include #include #include "k3resolver.h" /* decide whether we need a mutex */ #if !HAVE_GETPROTOBYNAME_R || !HAVE_GETSERVBYNAME_R || !HAVE_GETHOSTBYNAME_R || !HAVE_GETSERVBYPORT_R # define NEED_MUTEX extern QMutex getXXbyYYmutex; #endif /* some systems have the functions, but don't declare them */ #if HAVE_GETSERVBYNAME_R && !HAVE_GETSERVBYNAME_R_PROTO extern "C" { struct servent; extern int getservbyname_r(const char *serv, const char *proto, struct servent *servbuf, char *buf, size_t buflen, struct servent **result); extern int getservbyport_r(int port, const char *proto, struct servent *servbuf, char *buf, size_t buflen, struct servent **result); struct protoent; extern int getprotobyname_r(const char *proto, struct protoent *protobuf, char *buf, size_t buflen, struct protoent **result); extern int getprotobynumber_r(int proto, struct protoent *protobuf, char *buf, size_t buflen, struct protoent **result); } #endif /* decide whether res_init is thread-safe or not */ #if defined(__GLIBC__) # undef RES_INIT_THREADSAFE #endif namespace KNetwork { // defined in network/qresolverworkerbase.h class KResolverWorkerBase; class KResolverWorkerFactoryBase; class KResolverPrivate; namespace Internal { class KResolverManager; class KResolverThread; struct RequestData; struct InputData { QString node, service; QByteArray protocolName; int flags; int familyMask; int socktype; int protocol; }; } class KResolverPrivate { public: // parent class. Should never be changed! KResolver *parent; bool deleteWhenDone : 1; bool waiting : 1; // class status. Should not be changed by worker threads! volatile int status; volatile int errorcode, syserror; // input data. Should not be changed by worker threads! Internal::InputData input; // mutex QMutex mutex; // output data KResolverResults results; - explicit KResolverPrivate(KResolver *_parent, + KDELIBS4SUPPORT_DEPRECATED explicit KResolverPrivate(KResolver *_parent, const QString &_node = QString(), const QString &_service = QString()) : parent(_parent), deleteWhenDone(false), waiting(false), status(0), errorcode(0), syserror(0) { input.node = _node; input.service = _service; input.flags = 0; input.familyMask = KResolver::AnyFamily; input.socktype = 0; input.protocol = 0; results.setAddress(_node, _service); } }; namespace Internal { struct RequestData { // worker threads should not change values in the input data KNetwork::KResolverPrivate *obj; const KNetwork::Internal::InputData *input; KNetwork::KResolverWorkerBase *worker; // worker class RequestData *requestor; // class that requested us volatile int nRequests; // how many requests that we made we still have left }; /* * @internal * This class is the resolver manager */ class KResolverManager { public: enum EventTypes { ResolutionCompleted = 1576 }; // arbitrary value; /* * This wait condition is used to notify wait states (KResolver::wait) that * the resolver manager has finished processing one or more objects. All * objects in wait state will be woken up and will check if they are done. * If they aren't, they will go back to sleeping. */ QWaitCondition notifyWaiters; private: /* * This variable is used to count the number of threads that are running */ volatile unsigned short runningThreads; /* * This variable is used to count the number of threads that are currently * waiting for data. */ unsigned short availableThreads; /* * This wait condition is used to notify worker threads that there is new * data available that has to be processed. All worker threads wait on this * waitcond for a limited amount of time. */ QWaitCondition feedWorkers; // this mutex protects the data in this object QMutex mutex; // hold a list of all the current threads we have QList workers; // hold a list of all the new requests we have QList newRequests; // hold a list of all the requests in progress we have QList currentRequests; // hold a list of all the workers we have QList workerFactories; // private constructor KResolverManager(); public: static KResolverManager *manager(); // creates and returns the global manager // destructor ~KResolverManager(); /* * Register this thread in the pool */ void registerThread(KResolverThread *id); /* * Unregister this thread from the pool */ void unregisterThread(KResolverThread *id); /* * Requests new data to work on. * * This function should only be called from a worker thread. This function * is thread-safe. * * If there is data to be worked on, this function will return it. If there is * none, this function will return a null pointer. */ RequestData *requestData(KResolverThread *id, int maxWaitTime); /* * Releases the resources and returns the resolved data. * * This function should only be called from a worker thread. It is * thread-safe. It does not post the event to the manager. */ void releaseData(KResolverThread *id, RequestData *data); /* * Registers a new worker class by way of its factory. * * This function is NOT thread-safe. */ void registerNewWorker(KNetwork::KResolverWorkerFactoryBase *factory); /* * Enqueues new resolutions. */ void enqueue(KNetwork::KResolver *obj, RequestData *requestor); /* * Dispatch a new request */ void dispatch(RequestData *data); /* * Dequeues a resolution. */ void dequeue(KNetwork::KResolver *obj); /* * Notifies the manager that the given resolution is about to * be deleted. This function should only be called by the * KResolver destructor. */ void aboutToBeDeleted(KNetwork::KResolver *obj); /* * Notifies the manager that new events are ready. */ void newEvent(); /* * This function is called by the manager to receive a new event. It operates * on the eventSemaphore() semaphore, which means it will block till there * is at least one event to go. */ void receiveEvent(); private: /* * finds a suitable worker for this request */ KNetwork::KResolverWorkerBase *findWorker(KNetwork::KResolverPrivate *p); /* * finds data for this request */ RequestData *findData(KResolverThread *); /* * Handle completed requests. * * This function is called by releaseData above */ void handleFinished(); /* * Handle one completed request. * * This function is called by handleFinished above. */ bool handleFinishedItem(RequestData *item); /* * Notifies the parent class that this request is done. * * This function deletes the request */ void doNotifying(RequestData *p); /* * Dequeues and notifies an object that is in Queued state * Returns true if the object is no longer queued; false if it could not * be dequeued (i.e., it's running) */ bool dequeueNew(KNetwork::KResolver *obj); }; /* * @internal * This class is a worker thread in the resolver system. * This class must be thread-safe. */ class KResolverThread: public QThread { private: // private constructor. Only the manager can create worker threads KResolverThread(); RequestData *data; protected: void run() Q_DECL_OVERRIDE; // here the thread starts friend class KNetwork::Internal::KResolverManager; friend class KNetwork::KResolverWorkerBase; public: bool checkResolver(); // see KResolverWorkerBase::checkResolver void acquireResolver(); // see KResolverWorkerBase::acquireResolver void releaseResolver(); // see KResolverWorkerBase::releaseResolver }; } // namespace Internal } // namespace KNetwork #endif diff --git a/src/kdecore/k3reverseresolver.h b/src/kdecore/k3reverseresolver.h index 07c3bafe..ed2f1712 100644 --- a/src/kdecore/k3reverseresolver.h +++ b/src/kdecore/k3reverseresolver.h @@ -1,197 +1,197 @@ /* -*- C++ -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KREVERSERESOLVER_H #define KREVERSERESOLVER_H ////////////////// // Needed includes #include #include #include "k3socketaddress.h" namespace KNetwork { class KReverseResolverPrivate; /** @class KReverseResolver k3reverseresolver.h k3reverseresolver.h * @brief Run a reverse-resolution on a socket address. * * This class is provided as a counterpart to KResolver in such a way * as it produces a reverse resolution: it resolves a socket address * from its binary representations into a textual representation. * * Most users will use the static functions resolve(), which work * both synchronously (blocking) and asynchronously (non-blocking). * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KReverseResolver: public QObject { Q_OBJECT public: /** * Flags for the reverse resolution. * * These flags are used by the reverse resolution functions for * setting resolution parameters. The possible values are: * @li NumericHost: don't try to resolve the host address to a text form. * Instead, convert the address to its numeric textual representation. * @li NumericService: the same as NumericHost, but for the service name * @li NodeNameOnly: returns the node name only (i.e., not the Fully * Qualified Domain Name) * @li Datagram: in case of ambiguity in the service name, prefer the * name associated with the datagram protocol * @li NumericScope: for those addresses which have the concept of scope, * resolve using the numeric value instead of the proper scope name. * @li ResolutionRequired: normally, when resolving, if the name resolution * fails, the process normally converts the numeric address into its * presentation forms. This flag causes the function to return * with error instead. */ enum Flags { NumericHost = 0x01, NumericService = 0x02, NodeNameOnly = 0x04, Datagram = 0x08, NumericScope = 0x10, ResolutionRequired = 0x20 }; /** * Constructs this object to resolve the given socket address. * * @param addr the address to resolve * @param flags the flags to use, see Flags * @param parent the parent object (see QObject) */ - explicit KReverseResolver(const KSocketAddress &addr, int flags = 0, + KDELIBS4SUPPORT_DEPRECATED explicit KReverseResolver(const KSocketAddress &addr, int flags = 0, QObject *parent = nullptr); /** * Destructor. */ virtual ~KReverseResolver(); /** * This function returns 'true' if the processing is still running. */ bool isRunning() const; /** * This function returns true if the processing has finished with * success, false if it's still running or failed. */ bool success() const; /** * This function returns true if the processing has finished with * failure, false if it's still running or succeeded. */ bool failure() const; /** * Returns the resolved node name, if the resolution has finished * successfully, or QString() otherwise. */ QString node() const; /** * Returns the resolved service name, if the resolution has finished * successfully, or QString() otherwise. */ QString service() const; /** * Returns the socket address which was subject to resolution. */ const KSocketAddress &address() const; /** * Starts the resolution. This function returns 'true' * if the resolution has started successfully. */ bool start(); /** * Overrides event handling */ bool event(QEvent *) Q_DECL_OVERRIDE; Q_SIGNALS: /** * This signal is emitted when the resolution has finished. * * @param obj this class, which contains the results */ void finished(const KNetwork::KReverseResolver &obj); public: /** * Resolves a socket address to its textual representation * * FIXME!! How can we do this in a non-blocking manner!? * * This function is used to resolve a socket address from its * binary representation to a textual form, even if numeric only. * * @param addr the socket address to be resolved * @param node the QString where we will store the resolved node * @param serv the QString where we will store the resolved service * @param flags flags to be used for this resolution. * @return true if the resolution succeeded, false if not * @see ReverseFlags for the possible values for @p flags */ static bool resolve(const KSocketAddress &addr, QString &node, QString &serv, int flags = 0); /** * Resolves a socket address to its textual representation * * FIXME!! How can we do this in a non-blocking manner!? * * This function behaves just like the above one, except it takes * a sockaddr structure and its size as parameters. * * @param sa the sockaddr structure containing the address to be resolved * @param salen the length of the sockaddr structure * @param node the QString where we will store the resolved node * @param serv the QString where we will store the resolved service * @param flags flags to be used for this resolution. * @return true if the resolution succeeded, false if not * @see ReverseFlags for the possible values for @p flags */ static bool resolve(const struct sockaddr *sa, quint16 salen, QString &node, QString &serv, int flags = 0); private: KReverseResolverPrivate *const d; }; } // namespace KNetwork #endif diff --git a/src/kdecore/k3serversocket.h b/src/kdecore/k3serversocket.h index 40bdafcd..4da952ce 100644 --- a/src/kdecore/k3serversocket.h +++ b/src/kdecore/k3serversocket.h @@ -1,429 +1,429 @@ /* -*- C++ -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KSERVERSOCKET_H #define KSERVERSOCKET_H #include #include "k3socketbase.h" #include "k3streamsocket.h" namespace KNetwork { class KStreamSocket; class KResolver; class KResolverResults; class KServerSocketPrivate; /** * @class KServerSocket k3serversocket.h k3serversocket.h * @brief A server socket for accepting connections. * * This class provides functionality for creating a socket to * listen for incoming connections and subsequently accept them. * * To use this class, you must first set the parameters for the listening * socket's address, then place it in listening mode. * * A typical example would look like: * \code * QString service = "http"; * KServerSocket *ss = new KServerSocket(service); * connect(ss, SIGNAL(readyAccept()), this, SLOT(slotReadyAccept())); * connect(ss, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int))); * ss->listen(); * \endcode * * In this case, this class will place the socket into listening mode on the * service pointed to by @p service and will emit the readyAccept() signal * when a connection is ready for accepting. The called slot is responsible for * calling accept(). * * The location of the services file (where @p service is looked up) * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is * usually set to /etc/services. * See RFC 1700 for more information on services. * You can specify @p service as a port number directly, rather than as a service * name. This is discouraged as it prevents the end user from easily modifying * the port number. * * For another example of usage, this below code attempts to make a connection on any port within a range: * \code * KServerSocket *ss = new KServerSocket(); * ss->setFamily(KResolver::InetFamily); * bool found = false; * for( unsigned int port = firstport; port <= lastport; ++port) { * ss->setAddress( QString::number( port ) ); * bool success = ss->listen(); * if( found = ( success && ss->error() == * KSocketBase::NoError ) ) * break; * ss->close(); * } * if( !found ) { * // Couldn't connect to any port. * } else { * connect(ss, SIGNAL(readyAccept()), this, SLOT(slotReadyAccept())); * connect(ss, SIGNAL(gotError(int)), this, SLOT(slotSocketError(int))); * ss->listen(); * } * \endcode * * The called slot slotReadyAccept() is responsible for calling * accept(). * * It is important to note that accept() can return either an * object of type KNetwork::KStreamSocket or * KNetwork::KBufferedSocket (default). If you want to accept a * non-buffered socket, you must first call setAcceptBuffered. * * @warning If you use KServerSocket in an auxiliary (non-GUI) thread, * you need to accept only KNetwork::KStreamSocket objects. * * @see KNetwork::KStreamSocket, KNetwork::KBufferedSocket * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KServerSocket: public QObject, public KPassiveSocketBase { Q_OBJECT public: /** * Default constructor. * * If the binding address isn't changed by setAddress, this socket will * bind to all interfaces on this node and the port will be selected by the * operating system. * * @param parent the parent QObject object */ KServerSocket(QObject *parent = nullptr); /** * Construct this object specifying the service to listen on. * * If the binding address isn't changed by setAddress, this socket will * bind to all interfaces and will listen on the port specified by * @p service. This is either a service name (e.g. 'www') or a port * number (e.g. '80'). * * The location of the services file (where @p service is looked up) * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is * usually set to /etc/services. * See RFC 1700 for more information on services. * * @param service the service name to listen on * @param parent the parent QObject object */ - explicit KServerSocket(const QString &service, QObject *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KServerSocket(const QString &service, QObject *parent = nullptr); /** * Construct this object specifying the node and service names to listen on. * * If the binding address isn't changed by setAddress, this socket will * bind to the interface specified by @p node and the port specified by * @p service. This is either a service name (e.g. 'www') or a port * number (e.g. '80'). * * The location of the services file (where @p service is looked up) * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is * usually set to /etc/services. * See RFC 1700 for more information on services. * * @param node the node to bind to * @param service the service port to listen on * @param parent the parent QObject object */ KServerSocket(const QString &node, const QString &service, QObject *parent = nullptr); /** * Destructor. This will close the socket, if open. * * Note, however, that accepted sockets do not get closed when this * object closes. */ ~KServerSocket(); protected: /** * Sets the socket options. Reimplemented from KSocketBase. */ bool setSocketOptions(int opts) Q_DECL_OVERRIDE; public: /** * Returns the internal KResolver object used for * looking up the host name and service. * * This can be used to set extra options to the * lookup process other than the default values, as well * as obtaining the error codes in case of lookup failure. */ KResolver &resolver() const; /** * Returns the internal list of resolved results for the binding address. */ const KResolverResults &resolverResults() const; /** * Enables or disables name resolution. If this flag is set to true, * the bind() operation will trigger name lookup * operations (i.e., converting a hostname into its binary form). * If the flag is set to false, those operations will instead * try to convert a string representation of an address without * attempting name resolution. * * This is useful, for instance, when IP addresses are in * their string representation (such as "1.2.3.4") or come * from other sources like KSocketAddress. * * @param enable whether to enable */ void setResolutionEnabled(bool enable); /** * Sets the allowed families for the resolutions. * * @param families the families that we want/accept * @see KResolver::SocketFamilies for possible values */ void setFamily(int families); /** * Sets the address on which we will listen. The port to listen on is given by * @p service, and we will bind to all interfaces. To let the operating system choose a * port, set the service to "0". @p service can either be a service name * (e.g. 'www') or a port number (e.g. '80'). * * The location of the services file (where @p service is looked up) * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is * usually set to /etc/services. * See RFC 1700 for more information on services. * * @param service the service name to listen on */ void setAddress(const QString &service); /** * @overload * Sets the address on which we will listen. This will cause the socket to listen * only on the interface given by @p node and on the port given by @p service. * @p service can either be a service name (e.g. 'www') or a port number * (e.g. '80'). * * The location of the services file (where @p service is looked up) * is defined by _PATH_SERVICES in /usr/include/netdb.h. This is * usually set to /etc/services. * See RFC 1700 for more information on services. * * @param node the node to bind to * @param service the service port to listen on */ void setAddress(const QString &node, const QString &service); /** * Sets the timeout for accepting. When you call accept(), * it will wait at most @p msecs milliseconds or return with an error * (returning a NULL object). * * @param msecs the time in milliseconds to wait, 0 to wait forever */ void setTimeout(int msecs); /** * Starts the lookup for peer and local hostnames as * well as their services. * * If the blocking mode for this object is on, this function will * wait for the lookup results to be available (by calling the * KResolver::wait() method on the resolver objects). * * When the lookup is done, the signal hostFound() will be * emitted (only once, even if we're doing a double lookup). * If the lookup failed (for any of the two lookups) the * gotError() signal will be emitted with the appropriate * error condition (see KSocketBase::SocketError). * * This function returns true on success and false on error. Note that * this is not the lookup result! */ virtual bool lookup(); /** * Binds this socket to the given nodename and service, * or use the default ones if none are given. * * Upon successful binding, the bound() signal will be * emitted. If an error is found, the gotError() * signal will be emitted. * * This function returns true on success. * * @param node the nodename * @param service the service */ virtual bool bind(const QString &node, const QString &service); /** * Binds the socket to the given service name. * @overload * * @param service the service */ virtual bool bind(const QString &service); /** * Binds the socket to the addresses previously set with setAddress(). * @overload * */ virtual bool bind(); /** * Connect this socket to this specific address. Reimplemented from KSocketBase. * * Unlike bind(const QString&, const QString&) above, this function * really does bind the socket. No lookup is performed. The bound() signal * will be emitted. */ bool bind(const KResolverEntry &address) Q_DECL_OVERRIDE; /** * Puts this socket into listening mode. Reimplemented from KPassiveSocketBase. * * Placing a socket into listening mode means it will be able to receive incoming * connections through the accept() method. * * If you do not call this method but call accept() directly, the socket will * be placed into listening mode automatically. * * @param backlog the number of connection the system is to * queue without accept() being called * @returns true if the socket is now in listening mode. */ bool listen(int backlog = 5) Q_DECL_OVERRIDE; // 5 is arbitrary /** * Closes this socket. */ void close() Q_DECL_OVERRIDE; /** * Toggles whether the accepted socket will be buffered or not. * That is, the accept() function will always return a KStreamSocket * object or descended from it. If buffering is enabled, the class * to be returned will be KBufferedSocket. * * By default, this flag is set to true. * * @param enable whether to set the accepted socket to * buffered mode */ void setAcceptBuffered(bool enable); /** * Accepts one incoming connection and return the associated, open * socket. * * If this function cannot accept a new connection, it will return NULL. * The specific object class returned by this function may vary according * to the implementation: derived classes may return specialized objects * descended from KStreamSocket. * * @sa KBufferedSocket * @sa setAcceptBuffered */ KStreamSocket *accept() Q_DECL_OVERRIDE; /** * Returns this socket's local address. */ KSocketAddress localAddress() const Q_DECL_OVERRIDE; /** * Returns this socket's externally-visible address if know. */ KSocketAddress externalAddress() const Q_DECL_OVERRIDE; private Q_SLOTS: void lookupFinishedSlot(); Q_SIGNALS: /** * This signal is emitted when this object finds an error. * The @p code parameter contains the error code that can * also be found by calling error(). */ void gotError(int code); /** * This signal is emitted when the lookup is successfully completed. */ void hostFound(); /** * This signal is emitted when the socket successfully binds * to an address. * * @param local the local address we bound to */ void bound(const KNetwork::KResolverEntry &local); /** * This signal is emitted when the socket completes the * closing/shut down process. */ void closed(); /** * This signal is emitted whenever the socket is ready for * accepting -- i.e., there is at least one connection waiting to * be accepted. */ void readyAccept(); protected: /** * Convenience function to set this object's error code to match * that of the socket device. */ void copyError(); private: bool doBind(); bool doListen(); private: KServerSocket(const KServerSocket &); KServerSocket &operator=(const KServerSocket &); KServerSocketPrivate *const d; }; } // namespace KNetwork #endif diff --git a/src/kdecore/k3socketaddress.h b/src/kdecore/k3socketaddress.h index 6f855684..7f024a3b 100644 --- a/src/kdecore/k3socketaddress.h +++ b/src/kdecore/k3socketaddress.h @@ -1,972 +1,972 @@ //krazy:excludeall=dpointer,inline (lightweight classes; kde3 support) /* -*- C++ -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KSOCKETADDRESS_H #define KSOCKETADDRESS_H #include #include struct sockaddr; struct sockaddr_in; struct sockaddr_in6; struct sockaddr_un; namespace KNetwork { class KIpAddress; class KSocketAddress; class KInetSocketAddress; class KUnixSocketAddress; /** @class KIpAddress k3socketaddress.h k3socketaddress.h * @brief An IP address. * * This class represents one IP address, version 4 or 6. This is only * the address, not including port information or other data. * * It is not a good programming practice to create address from objects * like this. Instead, prefer a more thorough function like * KResolver::resolve(), which also handle extra information like scope * ids. * * This is a light-weight class. Most of the member functions are inlined and * there are no virtual functions. This object's size should be less than 20 * bytes. Also note that there is no sharing of data. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KIpAddress { public: /** * Default constructor. Creates an empty address. * It defaults to IP version 4. */ inline KIpAddress() : m_version(0) { } /** * Copy constructor. Copies the data from the other * object. * * Data is not shared. * * @param other the other */ inline KIpAddress(const KIpAddress &other) { *this = other; } /** * Creates an object from the given string representation. * * The IP version is guessed from the address format. * * @param addr the address */ inline KIpAddress(const QString &addr) { setAddress(addr); } /** * Creates an object from the given string representation. * * The IP version is guessed from the address format. * * @param addr the address */ inline KIpAddress(const char *addr) { setAddress(addr); } /** * Creates an object from the given raw data and IP version. * * @param addr the raw data * @param version the IP version (4 or 6) */ inline KIpAddress(const void *addr, int version = 4) { setAddress(addr, version); } /** * This is a convenience constructor. Constructs an object * from the given IPv4 address in the form of an integer. * * Note: do not write code to depend on IPv4 addresses being * integer types. Instead, treat them as a special type, like * a KIpAddress or the system's in_addr. * * @param ip4addr the IPv4 address */ inline KIpAddress(quint32 ip4addr) { setAddress(&ip4addr, 4); } /** * Destructor. This frees resources associated with this object. * * Note: destructor is non-virtual. The compiler will happily optimize it * out of the way. */ inline ~KIpAddress() { } /** * Copy operator. * * Copies the data from the other object into this one. * * @param other the object to copy */ KIpAddress &operator =(const KIpAddress &other); /** * Returns true if the two addresses match. * This function performs a v4-mapped check. * @see compare */ inline bool operator ==(const KIpAddress &other) const { return compare(other, true); } /** * Compares this address against the other, supplied one and return * true if they match. The @p checkMapped parameter controls whether * a check for an IPv6 v4-mapped address will be performed. * * An IPv6 v4-mapped address is an IPv6 address that is, for all purposes, * equivalent to an IPv4 one. The default behaviour of this function * is to take that into account. If you want a strict matching, * pass @b false to the @p checkMapped parameter. * * @param other the other IP address * @param checkMapped whether v4-mapped addresses will be taken into account */ bool compare(const KIpAddress &other, bool checkMapped = true) const; /** * Retrieves the IP version in this object. * * @returns the version: 4 or 6 */ inline int version() const { return m_version; } /** * Returns true if this is an IPv4 address. */ inline bool isIPv4Addr() const { return version() == 4; } /** * Returns true if this is an IPv6 address. */ inline bool isIPv6Addr() const { return version() == 6; } /** * Sets the address to the given string representation. * * @return true if the address was successfully parsed; otherwise returns * false and leaves the object unchanged. */ bool setAddress(const QString &address); /** * Sets the address to the given string representation. * * @return true if the address was successfully parsed; otherwise returns * false and leaves the object unchanged. */ bool setAddress(const char *address); /** * Sets the address to the given raw binary representation. * * @param raw a pointer to the raw binary data * @param version the IP version * @return true if the address was successfully parsed; otherwise returns * false and leaves the object unchanged. */ bool setAddress(const void *raw, int version = 4); /** * Returns the address as a string. */ QString toString() const; /** * Returns a pointer to binary raw data representing the address. */ inline const void *addr() const { return m_data; } /** * This is a convenience function. Returns the IPv4 address in a * 32-bit integer. The result is only valid if isIPv4Addr() returns * true. Alternatively, if the contained IPv6 address is a v4-mapped one * and the @p convertMapped parameter is true, the result will also be * valid. * * Note: you should not treat IP addresses as integers. Instead, * use types defined for that purpose, such as KIpAddress or the * system's in_addr type. * * @bug Check if byte ordering is done right */ inline quint32 IPv4Addr(bool convertMapped = true) const { return (convertMapped && isV4Mapped()) ? m_data[3] : m_data[0]; } /*-- tests --*/ /** * Returns true if this is the IPv4 or IPv6 unspecified address. */ inline bool isUnspecified() const { return version() == 0 ? true : (*this == anyhostV4 || *this == anyhostV6); } /** * Returns true if this is either the IPv4 or the IPv6 localhost address. */ inline bool isLocalhost() const { return version() == 0 ? false : (*this == localhostV4 || *this == localhostV6); } /** * This is an alias for isLocalhost(). */ inline bool isLoopback() const { return isLocalhost(); } /** * Returns true if this is an IPv4 class A address, i.e., * from 0.0.0.0 to 127.255.255.255. * * This function does not test for v4-mapped addresses. */ inline bool isClassA() const { return version() != 4 ? false : (IPv4Addr() & 0x80000000) == 0; } /** * Returns true if this is an IPv4 class B address, i.e., one from * 128.0.0.0 to 191.255.255.255. * * This function does not test for v4-mapped addresses. */ inline bool isClassB() const { return version() != 4 ? false : (IPv4Addr() & 0xc0000000) == 0x80000000; } /** * Returns true if this is an IPv4 class C address, i.e., one from * 192.0.0.0 to 223.255.255.255. * * This function does not test for v4-mapped addresses. */ inline bool isClassC() const { return version() != 4 ? false : (IPv4Addr() & 0xe0000000) == 0xc0000000; } /** * Returns true if this is an IPv4 class D (a.k.a. multicast) address. * * Note: this function is not the same as isMulticast(). isMulticast also * tests for IPv6 multicast addresses. */ inline bool isClassD() const { return version() != 4 ? false : (IPv4Addr() & 0xf0000000) == 0xe0000000; } /** * Returns true if this is a multicast address, be it IPv4 or IPv6. */ inline bool isMulticast() const { if (version() == 4) { return isClassD(); } if (version() == 6) { return ((quint8 *)addr())[0] == 0xff; } return false; } /** * Returns true if this is an IPv6 link-local address. */ inline bool isLinkLocal() const { if (version() != 6) { return false; } quint8 *addr = (quint8 *)this->addr(); return (addr[0] & 0xff) == 0xfe && (addr[1] & 0xc0) == 0x80; } /** * Returns true if this is an IPv6 site-local address. */ inline bool isSiteLocal() const { if (version() != 6) { return false; } quint8 *addr = (quint8 *)this->addr(); return (addr[0] & 0xff) == 0xfe && (addr[1] & 0xc0) == 0xc0; } /** * Returns true if this is a global IPv6 address. */ inline bool isGlobal() const { return version() != 6 ? false : !(isMulticast() || isLinkLocal() || isSiteLocal()); } /** * Returns true if this is a v4-mapped IPv6 address. */ inline bool isV4Mapped() const { if (version() != 6) { return false; } quint32 *addr = (quint32 *)this->addr(); return addr[0] == 0 && addr[1] == 0 && ((quint16 *)&addr[2])[0] == 0 && ((quint16 *)&addr[2])[1] == 0xffff; } /** * Returns true if this is a v4-compat IPv6 address. */ inline bool isV4Compat() const { if (version() != 6 || isLocalhost()) { return false; } quint32 *addr = (quint32 *)this->addr(); return addr[0] == 0 && addr[1] == 0 && addr[2] == 0 && addr[3] != 0; } /** * Returns true if this is an IPv6 node-local multicast address. */ inline bool isMulticastNodeLocal() const { return version() == 6 && isMulticast() && (((quint32 *)addr())[0] & 0xf) == 0x1; } /** * Returns true if this is an IPv6 link-local multicast address. */ inline bool isMulticastLinkLocal() const { return version() == 6 && isMulticast() && (((quint32 *)addr())[0] & 0xf) == 0x2; } /** * Returns true if this is an IPv6 site-local multicast address. */ inline bool isMulticastSiteLocal() const { return version() == 6 && isMulticast() && (((quint32 *)addr())[0] & 0xf) == 0x5; } /** * Returns true if this is an IPv6 organisational-local multicast address. */ inline bool isMulticastOrgLocal() const { return version() == 6 && isMulticast() && (((quint32 *)addr())[0] & 0xf) == 0x8; } /** * Returns true if this is an IPv6 global multicast address. */ inline bool isMulticastGlobal() const { return version() == 6 && isMulticast() && (((quint32 *)addr())[0] & 0xf) == 0xe; } protected: quint32 m_data[4]; // 16 bytes, needed for an IPv6 address char m_version; public: /// localhost in IPv4 (127.0.0.1) static const KIpAddress localhostV4; /// the any host or undefined address in IPv4 (0.0.0.0) static const KIpAddress anyhostV4; /// localhost in IPv6 (::1) static const KIpAddress localhostV6; /// the any host or undefined address in IPv6 (::) static const KIpAddress anyhostV6; }; class KSocketAddressData; /** @class KSocketAddress k3socketaddress.h k3socketaddress.h * @brief A generic socket address. * * This class holds one generic socket address. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KSocketAddress //krazy:exclude=dpointer (we got one, just not called Private) { public: /** * Default constructor. * * Creates an empty object */ KSocketAddress(); /** * Creates this object with the given data. * The raw socket address is copied into this object. * * @param sa the socket address structure * @param len the socket address length */ KSocketAddress(const sockaddr *sa, quint16 len); /** * Copy constructor. This creates a copy of the other * object. * * Data is not shared. * * @param other the object to copy from */ KSocketAddress(const KSocketAddress &other); /** * Destructor. Frees any associated resources. */ virtual ~KSocketAddress(); /** * Performs a shallow copy of the other object into this one. * Data will be copied. * * @param other the object to copy from */ KSocketAddress &operator =(const KSocketAddress &other); /** * Returns the socket address structure, to be passed down to * low level functions. * * Note that this function returns NULL for invalid or empty sockets, * so you may use to to test for validity. */ const sockaddr *address() const; /** * Returns the socket address structure, to be passed down to * low level functions. * * Note that this function returns NULL for invalid or empty sockets, * so you may use to to test for validity. * * The returned value, if not NULL, is an internal buffer which is guaranteed * to be at least length() bytes long. */ sockaddr *address(); /** * Sets the address to the given address. * The raw socket address is copied into this object. * * @param sa the socket address structure * @param len the socket address length */ KSocketAddress &setAddress(const sockaddr *sa, quint16 len); /** * Returns the socket address structure, to be passed down to * low level functions. */ inline operator const sockaddr *() const { return address(); } /** * Returns the length of this socket address structure. */ quint16 length() const; /** * Sets the length of this socket structure. * * Use this function with care. It allows you to resize the internal * buffer to fit needs. This function should not be used except for handling * unknown socket address structures. * * Also note that this function may invalidate the socket if a known * family is set (Internet or Unix socket) and the new length would be * too small to hold the system's sockaddr_* structure. If unsure, reset * the family: * * \code * KSocketAddress qsa; * [...] * qsa.setFamily(AF_UNSPEC).setLength(newlen); * \endcode * * @param len the new length */ KSocketAddress &setLength(quint16 len); /** * Returns the family of this address. * @return the family of this address, AF_UNSPEC if it's undefined */ int family() const; /** * Sets the family of this object. * * Note: setting the family will probably invalidate any address data * contained in this object. Use this function with care. * * @param family the new family to set */ virtual KSocketAddress &setFamily(int family); /** * Returns the IANA family number of this address. * @return the IANA family number of this address (1 for AF_INET. * 2 for AF_INET6, otherwise 0) */ inline int ianaFamily() const { return ianaFamily(family()); } /** * Returns true if this equals the other socket. * * Socket addresses are considered matching if and only if all data is the same. * * @param other the other socket * @return true if both sockets are equal */ bool operator ==(const KSocketAddress &other) const; /** * Returns the node name of this socket. * * In the case of Internet sockets, this is string representation of the IP address. * The default implementation returns QString(). * * @return the node name, can be QString() * @bug use KResolver to resolve unknown families */ virtual QString nodeName() const; /** * Returns the service name for this socket. * * In the case of Internet sockets, this is the port number. * The default implementation returns QString(). * * @return the service name, can be QString() * @bug use KResolver to resolve unknown families */ virtual QString serviceName() const; /** * Returns this socket address as a string suitable for * printing. Family, node and service are part of this address. * * @bug use KResolver to resolve unknown families */ virtual QString toString() const; /** * Returns an object reference that can be used to manipulate this socket * as an Internet socket address. Both objects share the same data. */ KInetSocketAddress &asInet(); /** * Returns an object is equal to this object's data, but they don't share it. */ KInetSocketAddress asInet() const; /** * Returns an object reference that can be used to manipulate this socket * as a Unix socket address. Both objects share the same data. */ KUnixSocketAddress &asUnix(); /** * Returns an object is equal to this object's data, but they don't share it. */ KUnixSocketAddress asUnix() const; protected: /// @internal /// private data KSocketAddressData *d; /// @internal /// extra constructor KSocketAddress(KSocketAddressData *d); public: // static /** * Returns the IANA family number of the given address family. * Returns 0 if there is no corresponding IANA family number. * @param af the address family, in AF_* constants * @return the IANA family number of this address (1 for AF_INET. * 2 for AF_INET6, otherwise 0) */ static int ianaFamily(int af); /** * Returns the address family of the given IANA family number. * @return the address family, AF_UNSPEC for unknown IANA family numbers */ static int fromIanaFamily(int iana); }; /** @class KInetSocketAddress k3socketaddress.h k3socketaddress.h * @brief an Internet socket address * * An Inet (IPv4 or IPv6) socket address * * This is an IPv4 or IPv6 address of the Internet. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KInetSocketAddress: public KSocketAddress { friend class KSocketAddress; public: /** * Public constructor. Creates an empty object. */ KInetSocketAddress(); /** * Creates an object from raw data. * * Note: if the socket address @p sa does not contain a valid Internet * socket (IPv4 or IPv6), this object will be empty. * * @param sa the sockaddr structure * @param len the structure's length */ KInetSocketAddress(const sockaddr *sa, quint16 len); /** * Creates an object from an IP address and port. * * @param host the IP address * @param port the port number */ KInetSocketAddress(const KIpAddress &host, quint16 port); /** * Copy constructor. * * Data is not shared. * * @param other the other object */ KInetSocketAddress(const KInetSocketAddress &other); /** * Copy constructor. * * If the other, generic socket address contains an Internet address, * it will be copied. Otherwise, this object will be empty. * * @param other the other object */ KInetSocketAddress(const KSocketAddress &other); /** * Destroys this object. */ virtual ~KInetSocketAddress(); /** * Copy operator. * * Copies the other object into this one. * * @param other the other object */ KInetSocketAddress &operator =(const KInetSocketAddress &other); /** * Cast operator to sockaddr_in. */ inline operator const sockaddr_in *() const { return (const sockaddr_in *)address(); } /** * Cast operator to sockaddr_in6. */ inline operator const sockaddr_in6 *() const { return (const sockaddr_in6 *)address(); } /** * Returns the IP version of the address this object holds. * * @return 4 or 6, if IPv4 or IPv6, respectively; 0 if this object is empty */ int ipVersion() const; /** * Returns the IP address component. */ KIpAddress ipAddress() const; /** * Sets the IP address to the given raw address. * * This call will preserve port numbers across IP versions, but will lose * IPv6 specific data if the address is set to IPv4. * * @param addr the address to set to * @return a reference to itself */ KInetSocketAddress &setHost(const KIpAddress &addr); /** * Retrieves the port number stored in this object. * * @return a port number in the range 0 to 65535, inclusive. An empty or * invalid object will have a port number of 0. */ quint16 port() const; /** * Sets the port number. If this object is empty, this function will default to * creating an IPv4 address. * * @param port the port number to set * @return a reference to itself */ KInetSocketAddress &setPort(quint16 port); /** * Converts this object to an IPv4 socket address. It has no effect if the object * is already an IPv4 socket address. * * If this object is an IPv6 address, the port number is preserved. All other information * is lost. * * @return a reference to itself */ KInetSocketAddress &makeIPv4(); /** * Converts this object to an IPv6 socket address. It has no effect if the object * is already an IPv6 socket address. * * If this object is an IPv4 address, the port number is preserved. * * @return a reference to itself */ KInetSocketAddress &makeIPv6(); /** * Returns the flowinfo information from the IPv6 socket address. * * @return the flowinfo information or 0 if this object is empty or IPv4 */ quint32 flowinfo() const; /** * Sets the flowinfo information for an IPv6 socket address. If this is not * an IPv6 socket address, this function converts it to one. See makeIPv6. * * @param flowinfo the flowinfo to set * @return a reference to itself */ KInetSocketAddress &setFlowinfo(quint32 flowinfo); /** * Returns the scope id this IPv6 socket is bound to. * * @return the scope id, or 0 if this is not an IPv6 object */ int scopeId() const; /** * Sets the scope id for this IPv6 object. If this is not an IPv6 socket * address, this function converts it to one. See makeIPv6 * * @param scopeid the scopeid to set * @return a reference to itself */ KInetSocketAddress &setScopeId(int scopeid); protected: /// @internal /// extra constructor KInetSocketAddress(KSocketAddressData *d); private: void update(); }; /* * External definition */ /** @class KUnixSocketAddress k3socketaddress.h k3socketaddress.h * @brief A Unix (local) socket address. * * This is a Unix socket address. * * Note that this class uses QStrings to represent filenames, which means * the proper encoding is used to translate into valid filesystem file names. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KUnixSocketAddress: public KSocketAddress { friend class KSocketAddress; public: /** * Default constructor. Creates an empty object. */ KUnixSocketAddress(); /** * Creates this object with the given raw data. If * the sockaddr structure does not contain a Local namespace * (Unix) socket, this object will be created empty. * * @param sa the socket address structure * @param len the structure's length */ KUnixSocketAddress(const sockaddr *sa, quint16 len); /** * Copy constructor. Creates a copy of the other object, - * sharing the data explicitly. + * sharing the data KDELIBS4SUPPORT_DEPRECATED explicitly. * * @param other the other object */ KUnixSocketAddress(const KUnixSocketAddress &other); /** * Constructs an object from the given pathname. */ KUnixSocketAddress(const QString &pathname); /** * Destructor. */ virtual ~KUnixSocketAddress(); /** * Copy operator. Copies the contents of the other object into - * this one. Data is explicitly shared. + * this one. Data is KDELIBS4SUPPORT_DEPRECATED explicitly shared. * * @param other the other */ KUnixSocketAddress &operator =(const KUnixSocketAddress &other); /** * Cast operator to sockaddr_un. */ inline operator const sockaddr_un *() const { return (const sockaddr_un *)address(); } /** * Returns the pathname associated with this object. Will return * QString() if this object is empty. */ QString pathname() const; /** * Sets the pathname for the object. * * @return a reference to itself */ KUnixSocketAddress &setPathname(const QString &path); protected: /// @internal /// extra constructor KUnixSocketAddress(KSocketAddressData *d); }; } // namespace KNetwork #endif diff --git a/src/kdecore/k3socketdevice.h b/src/kdecore/k3socketdevice.h index fdff67c7..3d27fefc 100644 --- a/src/kdecore/k3socketdevice.h +++ b/src/kdecore/k3socketdevice.h @@ -1,419 +1,419 @@ /* -*- C++ -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KSOCKETDEVICE_H #define KSOCKETDEVICE_H #include #include "k3socketbase.h" namespace KNetwork { class KSocketDevice; class KSocketDeviceFactoryBase; class KSocketDevicePrivate; /** @class KSocketDevice k3socketdevice.h k3socketdevice.h * @brief Low-level socket functionality. * * This class provides low-level socket functionality. * * Most users will prefer "cooked" interfaces like those of KStreamSocket or * KServerSocket. * * Descended classes from this one provide some other kinds of socket functionality, * like proxying or specific socket types. * * @author Thiago Macieira * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KSocketDevice: public KActiveSocketBase, public KPassiveSocketBase { public: /** * Capabilities for the socket implementation. * * KSocketDevice-derived classes can implement certain capabilities that are not * available in the default class. These capabilities are described by these flags. * The default KSocketDevice class has none of these capabilities. * * For the negative capabilities (inabilities, the CanNot* forms), when a capability * is not present, the implementation will default to the original behaviour. */ enum Capabilities { /** Can connect to hostnames. * If this flag is present, the string form of connect() can be used. */ CanConnectString = 0x01, /** Can bind to hostnames. * If this flag is present, the string form of bind() can be used */ CanBindString = 0x02, /** Can not bind. * If this flag is present, this implementation cannot bind */ CanNotBind = 0x04, /** Can not listen. * If this flag is present, this implementation cannot listen */ CanNotListen = 0x08, /** * Can send multicast as well as join/leave multicast groups. */ CanMulticast = 0x10, /** * Can not use datagrams. * Note that this implies multicast capability not being available either. */ CanNotUseDatagrams = 0x20 }; protected: /// The socket file descriptor. It is used throughout the implementation /// and subclasses. int m_sockfd; public: /** * Default constructor. * * The parameter is used to specify which socket this object is used as * a device for. */ - explicit KSocketDevice(const KSocketBase * = nullptr, QObject *objparent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KSocketDevice(const KSocketBase * = nullptr, QObject *objparent = nullptr); /** * Constructs a new object around an already-open socket. * * Note: you should write programs that create sockets through * the classes whenever possible. */ - explicit KSocketDevice(int fd, OpenMode mode = ReadWrite); + KDELIBS4SUPPORT_DEPRECATED explicit KSocketDevice(int fd, OpenMode mode = ReadWrite); /** * QObject constructor */ KSocketDevice(QObject *parent); /** * Destructor. This closes the socket if it's open. */ virtual ~KSocketDevice(); /** * Returns the file descriptor for this socket. */ int socket() const; /** * Returns the set of capabilities this socket class implements. * The set of capabilities is defined as an OR-ed mask of * Capabilities bits. * * The default implementation is guaranteed to always return 0. That * is, derived implementations always return bits where they differ * from the system standard sockets. */ virtual int capabilities() const; /** * This implementation sets the options on the socket. */ bool setSocketOptions(int opts) Q_DECL_OVERRIDE; /** * Closes the socket. Reimplemented from QIODevice. * * Use this function to close the socket this object is holding open. */ void close() Q_DECL_OVERRIDE; /** * This call is not supported on sockets. Reimplemented from QIODevice. */ virtual bool flush(); /** * Creates a socket but don't connect or bind anywhere. * This function is the equivalent of the system call socket(2). */ virtual bool create(int family, int type, int protocol); /** * @overload * Creates a socket but don't connect or bind anywhere. */ bool create(const KResolverEntry &address); /** * Binds this socket to the given address. */ bool bind(const KResolverEntry &address) Q_DECL_OVERRIDE; /** * Puts this socket into listening mode. */ bool listen(int backlog = 5) Q_DECL_OVERRIDE; // 5 is arbitrary /** * Connect to a remote host. */ virtual bool connect(const KResolverEntry &address, OpenMode mode = ReadWrite) Q_DECL_OVERRIDE; /** * Accepts a new incoming connection. * Note: this function returns a socket of type KSocketDevice. */ KSocketDevice *accept() Q_DECL_OVERRIDE; /** * Disconnects this socket. */ bool disconnect() Q_DECL_OVERRIDE; /** * Returns the number of bytes available for reading without blocking. */ qint64 bytesAvailable() const Q_DECL_OVERRIDE; /** * Waits up to @p msecs for more data to be available on this socket. * * This function is a wrapper against poll(). This function will wait * for any read events. */ qint64 waitForMore(int msecs, bool *timeout = nullptr) Q_DECL_OVERRIDE; /** * Returns this socket's local address. */ KSocketAddress localAddress() const Q_DECL_OVERRIDE; /** * Returns this socket's peer address. If this implementation does proxying * of some sort, this is the real external address, not the proxy's address. */ KSocketAddress peerAddress() const Q_DECL_OVERRIDE; /** * Returns this socket's externally visible local address. * * If this socket has a local address visible externally different * from the normal local address (as returned by localAddress()), then * return it. * * Certain implementations will use proxies and thus have externally visible * addresses different from the local socket values. The default implementation * returns the same value as localAddress(). * * @note This function may return an empty KSocketAddress. In that case, the * externally visible address could/can not be determined. */ KSocketAddress externalAddress() const Q_DECL_OVERRIDE; /** * Returns a socket notifier for input on this socket. * The notifier is created only when requested. Whether * it is enabled or not depends on the implementation. * * This function might return NULL. */ QSocketNotifier *readNotifier() const; /** * Returns a socket notifier for output on this socket. * The is created only when requested. * * This function might return NULL. */ QSocketNotifier *writeNotifier() const; /** * Returns a socket notifier for exceptional events on this socket. * The is created only when requested. * * This function might return NULL. */ QSocketNotifier *exceptionNotifier() const; /** * Reads data and the source address from this socket. */ qint64 readData(char *data, qint64 maxlen, KSocketAddress *from = nullptr) Q_DECL_OVERRIDE; /** * Peeks the data in the socket and the source address. */ qint64 peekData(char *data, qint64 maxlen, KSocketAddress *from = nullptr) Q_DECL_OVERRIDE; /** * Writes the given data to the given destination address. */ virtual qint64 writeData(const char *data, qint64 len, const KSocketAddress *to = nullptr) Q_DECL_OVERRIDE; /** * Executes a poll in the socket, via select(2) or poll(2). * The events polled are returned in the parameters pointers. * Set any of them to NULL to disable polling of that event. * * On exit, @p input, @p output and @p exception will contain * true if an event of that kind is waiting on the socket or false * if not. If a timeout occurred, set @p timedout to true (all other * parameters are necessarily set to false). * * @param input if set, turns on polling for input events * @param output if set, turns on polling for output events * @param exception if set, turns on polling for exceptional events * @param timeout the time in milliseconds to wait for an event; * 0 for no wait and any negative value to wait forever * @param timedout on exit, will contain true if the polling timed out * @return true if the poll call succeeded and false if an error occurred */ virtual bool poll(bool *input, bool *output, bool *exception = nullptr, int timeout = -1, bool *timedout = nullptr); /** * Shorter version to poll for any events in a socket. This call * polls for input, output and exceptional events in a socket but * does not return their states. This is useful if you need to wait for * any event, but don't need to know which; or for timeouts. * * @param timeout the time in milliseconds to wait for an event; * 0 for no wait and any negative value to wait forever * @param timedout on exit, will contain true if the polling timed out * @return true if the poll call succeeded and false if an error occurred */ bool poll(int timeout = -1, bool *timedout = nullptr); protected: /** * Special constructor. This constructor will cause the internal * socket device NOT to be set. Use this if your socket device class * takes another underlying socket device. * * @param parent the parent, if any */ - explicit KSocketDevice(bool, const KSocketBase *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KSocketDevice(bool, const KSocketBase *parent = nullptr); /** * Creates a socket notifier of the given type. * * This function is called by readNotifier(), writeNotifier() and * exceptionNotifier() when they need to create a socket notifier * (i.e., the first call to those functions after the socket is open). * After that call, those functions cache the socket notifier and will * not need to call this function again. * * Reimplement this function in your derived class if your socket type * requires a different kind of QSocketNotifier. The return value should * be deleteable with delete. (close() deletes them). * * @param type the socket notifier type */ virtual QSocketNotifier *createNotifier(QSocketNotifier::Type type) const; public: /** * Creates a new default KSocketDevice object given * the parent object. * * The capabilities flag indicates the desired capabilities the object being * created should possess. Those capabilities are not guaranteed: if no factory * can provide such an object, a default object will be created. * * @param parent the KSocketBase parent */ static KSocketDevice *createDefault(KSocketBase *parent); /** * @overload * * This will create an object only if the requested capabilities match. * * @param parent the parent * @param capabilities the requested capabilities */ static KSocketDevice *createDefault(KSocketBase *parent, int capabilities); /** * Sets the default KSocketDevice implementation to use and * return the old factory. * * @param factory the factory object for the implementation */ static KSocketDeviceFactoryBase *setDefaultImpl(KSocketDeviceFactoryBase *factory); /** * Adds a factory of KSocketDevice objects to the list, along with its * capabilities flag. */ static void addNewImpl(KSocketDeviceFactoryBase *factory, int capabilities); private: KSocketDevice(const KSocketDevice &); KSocketDevice &operator=(const KSocketDevice &); KSocketDevicePrivate *const d; }; /** @internal * This class provides functionality for creating and registering * socket implementations. */ class KSocketDeviceFactoryBase { public: KSocketDeviceFactoryBase() {} virtual ~KSocketDeviceFactoryBase() {} virtual KSocketDevice *create(KSocketBase *) const = 0; }; /** * This class provides functionality for creating and registering * socket implementations. */ template class KSocketDeviceFactory: public KSocketDeviceFactoryBase { public: KSocketDeviceFactory() {} virtual ~KSocketDeviceFactory() {} /** Create the socket implementation. @param parent Parent socket for this implementation @todo Who owns the parent afterwards? */ KSocketDevice *create(KSocketBase *parent) const Q_DECL_OVERRIDE { return new Impl(parent); } }; } // namespaces #endif diff --git a/src/kdecore/k3streamsocket.h b/src/kdecore/k3streamsocket.h index 249cba7c..e281b1ca 100644 --- a/src/kdecore/k3streamsocket.h +++ b/src/kdecore/k3streamsocket.h @@ -1,252 +1,252 @@ /* -*- C++ -*- * Copyright (C) 2003,2005 Thiago Macieira * * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KSTREAMSOCKET_H #define KSTREAMSOCKET_H #include #include "k3clientsocketbase.h" /** A namespace to store all networking-related (socket) classes. */ namespace KNetwork { class KResolverEntry; class KServerSocket; class KBufferedSocket; class KStreamSocketPrivate; /** @class KStreamSocket k3streamsocket.h k3streamsocket.h * @brief Simple stream socket * * This class provides functionality to creating unbuffered, stream * sockets. In the case of Internet (IP) sockets, this class creates and * uses TCP/IP sockets. * * Objects of this class start, by default, on non-blocking mode. Call * setBlocking if you wish to change that. * * KStreamSocket objects are thread-safe and can be used in auxiliary * threads (i.e., not the thread in which the Qt event loop runs in). * Note that KBufferedSocket cannot be used reliably in an auxiliary thread. * * Sample usage: * \code * QByteArray httpGet(const QString& hostname) * { * KStreamSocket socket(hostname, "http"); * if (!socket.connect()) * return QByteArray(); * QByteArray data = socket.readAll(); * return data; * } * \endcode * * Here's another sample, showing asynchronous operation: * \code * DataRetriever::DataRetriever(const QString& hostname, const QString& port) * : socket(hostname, port) * { * // connect signals to our slots * QObject::connect(&socket, SIGNAL(connected(const KNetwork::KResolverEntry&)), * this, SLOT(slotSocketConnected())); * QObject::connect(&socket, SIGNAL(gotError(int)), * this, SLOT(slotSocketError(int))); * QObject::connect(&socket, SIGNAL(readyRead()), * this, SLOT(slotSocketReadyToRead())); * QObject::connect(&socket, SIGNAL(readyWrite()), * this, SLOT(slotSocketReadyToWrite())); * * // set non-blocking mode in order to work asynchronously * socket.setBlocking(false); * * // turn on signal emission * socket.enableRead(true); * socket.enableWrite(true); * * // start connecting * socket.connect(); * } * \endcode * * @see KNetwork::KBufferedSocket, KNetwork::KServerSocket * @author Thiago Macieira * @version 0.9 * @deprecated Use KSocketFactory or KLocalSocket instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KStreamSocket: public KClientSocketBase { Q_OBJECT public: /** * Default constructor. * * @param node destination host * @param service destination service to connect to * @param parent the parent QObject object */ - explicit KStreamSocket(const QString &node = QString(), const QString &service = QString(), + KDELIBS4SUPPORT_DEPRECATED explicit KStreamSocket(const QString &node = QString(), const QString &service = QString(), QObject *parent = nullptr); /** * Destructor. This closes the socket. */ virtual ~KStreamSocket(); /** * Retrieves the timeout value (in milliseconds). */ int timeout() const; /** * Retrieves the remaining timeout time (in milliseconds). This value * equals timeout() if there's no connection in progress. */ int remainingTimeout() const; /** * Sets the timeout value. Setting this value while a connection attempt * is in progress will reset the timer. * * Please note that the timeout value is valid for the connection attempt * only. No other operations are timed against this value -- including the * name lookup associated. * * @param msecs the timeout value in milliseconds */ void setTimeout(int msecs); /** * Binds this socket to the given nodename and service, * or use the default ones if none are given. In order to bind to a service * and allow the operating system to choose the interface, set @p node to * QString(). * * Reimplemented from KClientSocketBase. * * Upon successful binding, the bound() signal will be * emitted. If an error is found, the gotError() * signal will be emitted. * * @note Due to the internals of the name lookup and binding * mechanism, some (if not most) implementations of this function * do not actually bind the socket until the connection * is requested (see connect()). They only set the values * for future reference. * * This function returns true on success. * * @param node the nodename * @param service the service */ virtual bool bind(const QString &node = QString(), const QString &service = QString()) Q_DECL_OVERRIDE; /** * Reimplemented from KClientSocketBase. Connect this socket to this * specific address. * * Unlike bind(const QString&, const QString&) above, this function * really does bind the socket. No lookup is performed. The bound() * signal will be emitted. */ bool bind(const KResolverEntry &entry) Q_DECL_OVERRIDE; /** * Reimplemented from KClientSocketBase. * * Attempts to connect to the these hostname and service, * or use the default ones if none are given. If a connection attempt * is already in progress, check on its state and set the error status * (NoError, meaning the connection is completed, or InProgress). * * If the blocking mode for this object is on, this function will only * return when all the resolved peer addresses have been tried or when * a connection is established. * * Upon successfully connecting, the connected() signal * will be emitted. If an error is found, the gotError() * signal will be emitted. * * This function also implements timeout handling. * * @param node the remote node to connect to * @param service the service on the remote node to connect to * @param mode mode to operate this socket in */ virtual bool connect(const QString &node = QString(), const QString &service = QString(), OpenMode mode = ReadWrite) Q_DECL_OVERRIDE; /** * Unshadowing from KClientSocketBase. */ virtual bool connect(const KResolverEntry &entry, OpenMode mode = ReadWrite) Q_DECL_OVERRIDE; Q_SIGNALS: /** * This signal is emitted when a connection timeout occurs. */ void timedOut(); private Q_SLOTS: void hostFoundSlot(); void connectionEvent(); void timeoutSlot(); private: /** * @internal * If the user requested local bind before connection, bind the socket to one * suitable address and return true. Also sets d->local to the address used. * * Return false in case of error. */ bool bindLocallyFor(const KResolverEntry &peer); /** * @internal * Finishes the connection process by setting internal values and * emitting the proper signals. * * Note: assumes d->local iterator points to the address that we bound * to. */ void connectionSucceeded(const KResolverEntry &peer); KStreamSocket(const KStreamSocket &); KStreamSocket &operator=(const KStreamSocket &); KStreamSocketPrivate *const d; friend class KServerSocket; friend class KBufferedSocket; }; } // namespace KNetwork #endif diff --git a/src/kdecore/k4aboutdata.h b/src/kdecore/k4aboutdata.h index 3fe7158c..7009c2d1 100644 --- a/src/kdecore/k4aboutdata.h +++ b/src/kdecore/k4aboutdata.h @@ -1,985 +1,985 @@ /* * This file is part of the KDE Libraries * Copyright (C) 2000 Espen Sand (espen@kde.org) * Copyright (C) 2008 Friedrich W. H. Kossebau * Copyright (C) 2010 Teo Mrnjavac * * 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 K4ABOUTDATA_H #define K4ABOUTDATA_H #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif #include // Qt #include #include template class QList; class QVariant; class KAboutData; class K4AboutData; /** * This class is used to store information about a person or developer. * It can store the person's name, a task, an email address and a * link to a home page. This class is intended for use in the * K4AboutData class, but it can be used elsewhere as well. * Normally you should at least define the person's name. * Creating a K4AboutPerson object by yourself is relatively useless, * but the K4AboutData methods K4AboutData::authors() and K4AboutData::credits() * return lists of K4AboutPerson data objects which you can examine. * * Example usage within a main(), retrieving the list of people involved * with a program and re-using data from one of them: * * @code * K4AboutData about("khello", "khello", ki18n("KHello"), "0.1", * ki18n("A KDE version of Hello, world!"), * K4AboutData::License_LGPL, * ki18n("Copyright (C) 2003 Developer")); * * about.addAuthor(ki18n("Joe Developer"), ki18n("developer"), "joe@host.com", 0); * QList people = about.authors(); * about.addCredit(people[0].name(), people[0].task()); * @endcode * * @note Instead of the more usual i18n calls, for translatable text the ki18n * calls are used to produce KLocalizedStrings, which can delay the translation * lookup. This is necessary because the translation catalogs are usually not * yet initialized at the point where K4AboutData is constructed. * * @bc KDE4 * * @deprecated Instead, use KAboutData in KCoreAddons */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE K4AboutPerson { friend class K4AboutData; public: /** * Convenience constructor * * @param name The name of the person. * * @param task The task of this person. * * @param emailAddress The email address of the person. * * @param webAddress Home page of the person. */ - explicit K4AboutPerson(const KLocalizedString &name, + KDELIBS4SUPPORT_DEPRECATED explicit K4AboutPerson(const KLocalizedString &name, const KLocalizedString &task = KLocalizedString(), const QByteArray &emailAddress = QByteArray(), const QByteArray &webAddress = QByteArray()); /** * Convenience constructor with Open Collaboration Services data * * @param name The name of the person. * * @param task The task of this person. * * @param emailAddress The email address of the person. * * @param webAddress Home page of the person. * * @param ocsUsername Open Collaboration Services username of the person. */ - explicit K4AboutPerson(const KLocalizedString &name, + KDELIBS4SUPPORT_DEPRECATED explicit K4AboutPerson(const KLocalizedString &name, const KLocalizedString &task, const QByteArray &emailAddress, const QByteArray &webAddress, const QByteArray &ocsUsername); //KDE5: merge into main ctor /** * Copy constructor. Performs a deep copy. * @param other object to copy */ K4AboutPerson(const K4AboutPerson &other); ~K4AboutPerson(); /** * Assignment operator. Performs a deep copy. * @param other object to copy */ K4AboutPerson &operator=(const K4AboutPerson &other); /** * The person's name * @return the person's name (can be QString(), if it has been * constructed with an empty name) */ QString name() const; /** * The person's task * @return the person's task (can be QString(), if it has been * constructed with an empty task) */ QString task() const; /** * The person's email address * @return the person's email address (can be QString(), if it has been * constructed with an empty email) */ QString emailAddress() const; /** * The home page or a relevant link * @return the persons home page (can be QString(), if it has been * constructed with an empty home page) */ QString webAddress() const; /** * The person's Open Collaboration Services username * @return the persons OCS username (can be QString(), if it has been * constructed with an empty username) */ QString ocsUsername() const; private: /** * @internal Used by K4AboutData to construct translator data. */ - explicit K4AboutPerson(const QString &name, const QString &email); + KDELIBS4SUPPORT_DEPRECATED explicit K4AboutPerson(const QString &name, const QString &email); class Private; Private *const d; }; class K4AboutLicense; // KDE5: refactor together with KComponentData. // Like changing all property names which contain Program or App. /** * This class is used to store information about a program. It can store * such values as version number, program name, home page, email address * for bug reporting, multiple authors and contributors * (using K4AboutPerson), license and copyright information. * * Currently, the values set here are shown by the "About" box * (see K4AboutDialog), used by the bug report dialog (see KBugReport), * and by the help shown on command line (see KCmdLineArgs). * They are also used for the icon and the name of the program's windows. * * @note Instead of the more usual i18n calls, for translatable text the ki18n * calls are used to produce KLocalizedStrings, which can delay the translation * lookup. This is necessary because the translation catalogs are usually not * yet initialized at the point where K4AboutData is constructed. * * @short Holds information needed by the "About" box and other * classes. * @author Espen Sand (espen@kde.org), David Faure (faure@kde.org) */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE K4AboutData { public: /** * Describes the license of the software. */ enum LicenseKey { // KDE5: move to K4AboutLicense, cut License_ prefix License_Custom = -2, License_File = -1, License_Unknown = 0, License_GPL = 1, License_GPL_V2 = 1, License_LGPL = 2, License_LGPL_V2 = 2, License_BSD = 3, License_Artistic = 4, License_QPL = 5, License_QPL_V1_0 = 5, License_GPL_V3 = 6, License_LGPL_V3 = 7 }; /** * Format of the license name. */ enum NameFormat { // KDE5: move to K4AboutLicense ShortName, FullName }; public: /** * Constructor. * * @param appName The program name used internally. Example: "kedit" * * @param catalogName The translation catalog name; if null or empty, the * @p appName will be used. You may want the catalog name to * differ from program name, for example, when you want to group * translations of several smaller utilities under the same catalog. * * @param programName A displayable program name string. This string * should be marked for translation. Example: ki18n("KEdit") * * @param version The program version string. * * @param shortDescription A short description of what the program does. * This string should be marked for translation. * Example: ki18n("A simple text editor.") * * @param licenseType The license identifier. Use setLicenseText or setLicenseTextFile if you use a license not predefined here. * * @param copyrightStatement A copyright statement, that can look like this: * ki18n("Copyright (C) 1999-2000 Name"). The string specified here is * taken verbatim; the author information from addAuthor is not used. * * @param otherText Some free form text, that can contain any kind of * information. The text can contain newlines. This string * should be marked for translation. * * @param homePageAddress The program homepage string. * Start the address with "http://". "http://some.domain" is * is correct, "some.domain" is not. * IMPORTANT: if you set a home page address, this will change the "organization domain" * of the application, which is used for automatic D-Bus registration. * @see setOrganizationDomain * * @param bugsEmailAddress The bug report email address string. * This defaults to the kde.org bug system. * */ K4AboutData(const QByteArray &appName, const QByteArray &catalogName, const KLocalizedString &programName, const QByteArray &version, const KLocalizedString &shortDescription = KLocalizedString(), enum LicenseKey licenseType = License_Unknown, const KLocalizedString ©rightStatement = KLocalizedString(), const KLocalizedString &otherText = KLocalizedString(), const QByteArray &homePageAddress = QByteArray(), const QByteArray &bugsEmailAddress = "submit@bugs.kde.org" ); /** * Copy constructor. Performs a deep copy. * @param other object to copy */ K4AboutData(const K4AboutData &other); /** * Assignment operator. Performs a deep copy. * @param other object to copy */ K4AboutData &operator=(const K4AboutData &other); ~K4AboutData(); operator KAboutData() const; /** * Defines an author. * * You can call this function as many times as you need. Each entry is * appended to a list. The person in the first entry is assumed to be * the leader of the project. * * @param name The developer's name. It should be marked for translation * like this: ki18n("Developer Name") * * @param task What the person is responsible for. This text can contain * newlines. It should be marked for translation like this: * ki18n("Task description..."). Can be left empty. * * @param emailAddress An Email address where the person can be reached. * Can be left empty. * * @param webAddress The person's homepage or a relevant link. * Start the address with "http://". "http://some.domain" is * correct, "some.domain" is not. Can be left empty. * */ K4AboutData &addAuthor(const KLocalizedString &name, const KLocalizedString &task = KLocalizedString(), const QByteArray &emailAddress = QByteArray(), const QByteArray &webAddress = QByteArray()); /** * Defines an author. * * You can call this function as many times as you need. Each entry is * appended to a list. The person in the first entry is assumed to be * the leader of the project. * * @param name The developer's name. It should be marked for translation * like this: ki18n("Developer Name") * * @param task What the person is responsible for. This text can contain * newlines. It should be marked for translation like this: * ki18n("Task description..."). Can be left empty. * * @param emailAddress An Email address where the person can be reached. * Can be left empty. * * @param webAddress The person's homepage or a relevant link. * Start the address with "http://". "http://some.domain" is * correct, "some.domain" is not. Can be left empty. * * @param ocsUsername The person's Open Collaboration Services username. * The provider can be optionally specified with @see setOcsProvider. * */ K4AboutData &addAuthor(const KLocalizedString &name, const KLocalizedString &task, const QByteArray &emailAddress, const QByteArray &webAddress, const QByteArray &ocsUsername); //KDE5: merge with addAuthor /** * Defines a person that deserves credit. * * You can call this function as many times as you need. Each entry * is appended to a list. * * @param name The person's name. It should be marked for translation * like this: ki18n("Contributor Name") * * @param task What the person has done to deserve the honor. The * text can contain newlines. It should be marked for * translation like this: ki18n("Task description...") * Can be left empty. * * @param emailAddress An email address when the person can be reached. * Can be left empty. * * @param webAddress The person's homepage or a relevant link. * Start the address with "http://". "http://some.domain" is * is correct, "some.domain" is not. Can be left empty. * */ K4AboutData &addCredit(const KLocalizedString &name, const KLocalizedString &task = KLocalizedString(), const QByteArray &emailAddress = QByteArray(), const QByteArray &webAddress = QByteArray()); /** * Defines a person that deserves credit. * * You can call this function as many times as you need. Each entry * is appended to a list. * * @param name The person's name. It should be marked for translation * like this: ki18n("Contributor Name") * * @param task What the person has done to deserve the honor. The * text can contain newlines. It should be marked for * translation like this: ki18n("Task description...") * Can be left empty. * * @param emailAddress An email address when the person can be reached. * Can be left empty. * * @param webAddress The person's homepage or a relevant link. * Start the address with "http://". "http://some.domain" is * is correct, "some.domain" is not. Can be left empty. * * @param ocsUsername The person's Open Collaboration Services username. * The provider can be optionally specified with @see setOcsProvider. * */ K4AboutData &addCredit(const KLocalizedString &name, const KLocalizedString &task, const QByteArray &emailAddress, const QByteArray &webAddress, const QByteArray &ocsUsername); //KDE5: merge with addCredit /** * @brief Sets the name(s) of the translator(s) of the GUI. * * Since this depends on the language, just use a dummy text marked for * translation. * * The canonical use is: * * \code * setTranslator(ki18nc("NAME OF TRANSLATORS", "Your names"), * ki18nc("EMAIL OF TRANSLATORS", "Your emails")); * \endcode * * The translator can then translate this dummy text with his name * or with a list of names separated with ",". * If there is no translation or the application is used with the * default language, this function call is ignored. * * @param name the name(s) of the translator(s) * @param emailAddress the email address(es) of the translator(s) * @see K4AboutTranslator */ K4AboutData &setTranslator(const KLocalizedString &name, const KLocalizedString &emailAddress); /** * Defines a license text, which is marked for translation. * * Example: * \code * setLicenseText( ki18n("This is my license") ); * \endcode * * @param license The license text. */ K4AboutData &setLicenseText(const KLocalizedString &license); /** * Adds a license text, which is marked for translation. * * If there is only one unknown license set, e.g. by using the default * parameter in the constructor, that one is replaced. * * Example: * \code * addLicenseText( ki18n("This is my license") ); * \endcode * * @param license The license text. * @see setLicenseText, addLicense, addLicenseTextFile * @since 4.1 */ K4AboutData &addLicenseText(const KLocalizedString &license); /** * Defines a license text by pointing to a file where it resides. * The file format has to be plain text in an encoding compatible to the locale. * * @param file Path to the file in the local filesystem containing the license text. */ K4AboutData &setLicenseTextFile(const QString &file); /** * Adds a license text by pointing to a file where it resides. * The file format has to be plain text in an encoding compatible to the locale. * * If there is only one unknown license set, e.g. by using the default * parameter in the constructor, that one is replaced. * * @param file Path to the file in the local filesystem containing the license text. * @see addLicenseText, addLicense, setLicenseTextFile * @since 4.1 */ K4AboutData &addLicenseTextFile(const QString &file); /** * Defines the program name used internally. * * @param appName The application name. Example: "kate". */ K4AboutData &setAppName(const QByteArray &appName); /** * Defines the displayable program name string. * * @param programName The program name. This string should be * marked for translation. * Example: ki18n("Advanced Text Editor"). */ K4AboutData &setProgramName(const KLocalizedString &programName); /** * Defines the program icon. * * Use this if you need to have an application icon * whose name is different than the application name. * * @param iconName name of the icon. Example: "accessories-text-editor" * @see programIconName() * @since 4.1 */ K4AboutData &setProgramIconName(const QString &iconName); /** * Defines the program logo. * * Use this if you need to have an application logo * in AboutData other than the application icon. * * Because K4AboutData is in kdecore it cannot use QImage directly, * so this is a QVariant that should contain a QImage. * * @param image logo image. * @see programLogo() */ K4AboutData &setProgramLogo(const QVariant &image); /** * Specifies an Open Collaboration Services provider by URL. * A provider file must be available for the chosen provider. * * Use this if you need to override the default provider. * * If this method is not used, all the K4AboutPerson OCS usernames * will be used with the openDesktop.org entry from the default * provider file. * * @param providerUrl The provider URL as defined in the provider file. */ K4AboutData &setOcsProvider(const QByteArray &providerUrl); /** * Defines the program version string. * * @param version The program version. */ K4AboutData &setVersion(const QByteArray &version); /** * Defines a short description of what the program does. * * @param shortDescription The program description. This string should * be marked for translation. Example: ki18n("An advanced text * editor with syntax highlighting support."). */ K4AboutData &setShortDescription(const KLocalizedString &shortDescription); /** * Defines the translation catalog that the program uses. * * @param catalogName The translation catalog name. */ K4AboutData &setCatalogName(const QByteArray &catalogName); /** * Defines the license identifier. * * @param licenseKey The license identifier. * @see addLicenseText, setLicenseText, setLicenseTextFile */ K4AboutData &setLicense(LicenseKey licenseKey); /** * Adds a license identifier. * * If there is only one unknown license set, e.g. by using the default * parameter in the constructor, that one is replaced. * * @param licenseKey The license identifier. * @see setLicenseText, addLicenseText, addLicenseTextFile * @since 4.1 */ K4AboutData &addLicense(LicenseKey licenseKey); /** * Defines the copyright statement to show when displaying the license. * * @param copyrightStatement A copyright statement, that can look like * this: ki18n("Copyright (C) 1999-2000 Name"). The string specified here is * taken verbatim; the author information from addAuthor is not used. */ K4AboutData &setCopyrightStatement(const KLocalizedString ©rightStatement); /** * Defines the additional text to show in the about dialog. * * @param otherText Some free form text, that can contain any kind of * information. The text can contain newlines. This string * should be marked for translation. */ K4AboutData &setOtherText(const KLocalizedString &otherText); /** * Defines the program homepage. * * @param homepage The program homepage string. * Start the address with "http://". "http://kate.kde.org" * is correct but "kate.kde.org" is not. */ K4AboutData &setHomepage(const QByteArray &homepage); /** * Defines the address where bug reports should be sent. * * @param bugAddress The bug report email address string. * This defaults to the kde.org bug system. */ K4AboutData &setBugAddress(const QByteArray &bugAddress); /** * Defines the Internet domain of the organization that wrote this application. * The domain is set to kde.org by default, or the domain of the homePageAddress constructor argument, * if set. * * Make sure to call setOrganizationDomain if your product is developed out of the * kde.org version-control system. * * Used by the automatic registration to D-Bus done by KApplication and KUniqueApplication. * * IMPORTANT: if the organization domain is set, the .desktop file that describes your * application should have an entry like X-DBUS-ServiceName=reversed_domain.kmyapp * For instance kwrite passes "http://www.kate-editor.org" as the homePageAddress so it needs * X-DBUS-ServiceName=org.kate-editor.kwrite in its kwrite.desktop file. * * @param domain the domain name, for instance kde.org, koffice.org, kdevelop.org, etc. */ K4AboutData &setOrganizationDomain(const QByteArray &domain); /** * Defines the product name which will be used in the KBugReport dialog. * By default it's the appName, but you can overwrite it here to provide * support for special components e.g. in the form 'product/component', * such as 'kontact/summary'. * * @param name The name of product */ K4AboutData &setProductName(const QByteArray &name); /** * Returns the application's internal name. * @return the internal program name. */ QString appName() const; /** * Returns the application's product name, which will be used in KBugReport * dialog. By default it returns appName(), otherwise the one which is set * with setProductName() * * @return the product name. */ QString productName() const; /** * Returns the translated program name. * @return the program name (translated). */ QString programName() const; /** * Returns the domain name of the organization that wrote this application. * * Used by the automatic registration to D-Bus done by KApplication and KUniqueApplication. */ QString organizationDomain() const; /** * @internal * Provided for use by KCrash */ const char *internalProgramName() const; /** * @internal * Provided for use by KCrash */ void translateInternalProgramName() const; /** * Returns the program's icon name. * * The default value is appName(). * Use setProgramIconName() if you need to have an icon * whose name is different from the internal application name. * * @return the program's icon name. * @see setProgramIconName() * @since 4.1 */ QString programIconName() const; /** * Returns the program logo image. * * Because K4AboutData is in kdecore it cannot use QImage directly, * so this is a QVariant containing a QImage. * * @return the program logo data, or a null image if there is * no custom application logo defined. */ QVariant programLogo() const; /** * Returns the chosen Open Collaboration Services provider URL. * @return the provider URL. */ QString ocsProviderUrl() const; /** * Returns the program's version. * @return the version string. */ QString version() const; /** * @internal * Provided for use by KCrash */ const char *internalVersion() const; /** * Returns a short, translated description. * @return the short description (translated). Can be * QString() if not set. */ QString shortDescription() const; /** * Returns the program's translation catalog name. * @return the catalog name. */ QString catalogName() const; /** * Returns the application homepage. * @return the application homepage URL. Can be QString() if * not set. */ QString homepage() const; /** * Returns the email address for bugs. * @return the email address where to report bugs. */ QString bugAddress() const; /** * @internal * Provided for use by KCrash */ const char *internalBugAddress() const; /** * Returns a list of authors. * @return author information (list of persons). */ QList authors() const; /** * Returns a list of persons who contributed. * @return credit information (list of persons). */ QList credits() const; /** * Returns a list of translators. * @return translators information (list of persons) */ QList translators() const; /** * Returns a message about the translation team. * @return a message about the translation team */ static QString aboutTranslationTeam(); /** * Returns a translated, free form text. * @return the free form text (translated). Can be QString() if not set. */ QString otherText() const; /** * Returns the license. If the licenseType argument of the constructor has been * used, any text defined by setLicenseText is ignored, * and the standard text for the chosen license will be returned. * * @return The license text. * * @deprecated There could be multiple licenses, use licenses() instead. */ QString license() const; /** * Returns the license name. * * @return The license name as a string. * * @deprecated There could be multiple licenses, use licenses() instead. */ QString licenseName(NameFormat formatName) const; /** * Returns a list of licenses. * * @return licenses information (list of licenses) * @since 4.1 */ QList licenses() const; /** * Returns the copyright statement. * @return the copyright statement. Can be QString() if not set. */ QString copyrightStatement() const; /** * Returns the plain text displayed around the list of authors instead * of the default message telling users to send bug reports to bugAddress(). * * @return the plain text displayed around the list of authors instead * of the default message. Can be QString(). */ QString customAuthorPlainText() const; /** * Returns the rich text displayed around the list of authors instead * of the default message telling users to send bug reports to bugAddress(). * * @return the rich text displayed around the list of authors instead * of the default message. Can be QString(). */ QString customAuthorRichText() const; /** * Returns whether custom text should be displayed around the list of * authors. * * @return whether custom text should be displayed around the list of * authors. */ bool customAuthorTextEnabled() const; /** * Sets the custom text displayed around the list of authors instead * of the default message telling users to send bug reports to bugAddress(). * * @param plainText The plain text. * @param richText The rich text. * * Setting both to parameters to KLocalizedString() will cause no message to be * displayed at all. Call unsetCustomAuthorText() to revert to the default * message. */ K4AboutData &setCustomAuthorText(const KLocalizedString &plainText, const KLocalizedString &richText); /** * Clears any custom text displayed around the list of authors and falls * back to the default message telling users to send bug reports to * bugAddress(). */ K4AboutData &unsetCustomAuthorText(); private: class Private; Private *const d; }; /** * This class is used to store information about a license. * The license can be one of some predefined, one given as text or one * that can be loaded from a file. This class is used in the K4AboutData class. * Explicitly creating a K4AboutLicense object is not possible. * If the license is wanted for a KDE component having K4AboutData object, * use K4AboutData::licenses() to get the licenses for that component. * If the license is for a non-code resource and given by a keyword * (e.g. in .desktop files), try using K4AboutLicense::byKeyword(). * * @note Instead of the more usual i18n calls, for translatable text the ki18n * calls are used to produce KLocalizedStrings, which can delay the translation * lookup. This is necessary because the translation catalogs are usually not * yet initialized at the point where K4AboutData is constructed. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE K4AboutLicense { friend class K4AboutData; public: /** * Copy constructor. Performs a deep copy. * @param other object to copy */ K4AboutLicense(const K4AboutLicense &other); ~K4AboutLicense(); /** * Assignment operator. Performs a deep copy. * @param other object to copy */ K4AboutLicense &operator=(const K4AboutLicense &other); /** * Returns the full license text. If the licenseType argument of the * constructor has been used, any text defined by setLicenseText is ignored, * and the standard text for the chosen license will be returned. * * @return The license text. */ QString text() const; /** * Returns the license name. * * @return The license name as a string. */ QString name(K4AboutData::NameFormat formatName) const; /** * Returns the license key. * * @return The license key as element of K4AboutData::LicenseKey enum. * @since 4.1 */ K4AboutData::LicenseKey key() const; /** * Fetch a known license by a keyword. * * Frequently the license data is provided by a terse keyword-like string, * e.g. by a field in a .desktop file. Using this method, an application * can get hold of a proper K4AboutLicense object, providing that the * license is one of the several known to KDE, and use it to present * more human-readable information to the user. * * Keywords are matched by stripping all whitespace and lowercasing. * The known keywords correspond to the K4AboutData::LicenseKey enumeration, * e.g. any of "LGPLV3", "LGPLv3", "LGPL v3" would match License_LGPL_V3. * If there is no match for the keyword, a valid license object is still * returned, with its name and text informing about a custom license, * and its key equal to K4AboutData::License_Custom. * * @param keyword The license keyword. * @return The license object. * * @see K4AboutData::LicenseKey * @since 4.1 */ static K4AboutLicense byKeyword(const QString &keyword); private: /** * @internal Used by K4AboutData to construct a predefined license. */ - explicit K4AboutLicense(enum K4AboutData::LicenseKey licenseType, const K4AboutData *aboutData); + KDELIBS4SUPPORT_DEPRECATED explicit K4AboutLicense(enum K4AboutData::LicenseKey licenseType, const K4AboutData *aboutData); /** * @internal Used by K4AboutData to construct license by given text */ - explicit K4AboutLicense(const QString &pathToFile, const K4AboutData *aboutData); + KDELIBS4SUPPORT_DEPRECATED explicit K4AboutLicense(const QString &pathToFile, const K4AboutData *aboutData); /** * @internal Used by K4AboutData to construct license by given text */ - explicit K4AboutLicense(const KLocalizedString &licenseText, const K4AboutData *aboutData); + KDELIBS4SUPPORT_DEPRECATED explicit K4AboutLicense(const KLocalizedString &licenseText, const K4AboutData *aboutData); class Private; QSharedDataPointer d; }; #endif diff --git a/src/kdecore/kcalendarera_p.h b/src/kdecore/kcalendarera_p.h index d1564eac..7c6c40c8 100644 --- a/src/kdecore/kcalendarera_p.h +++ b/src/kdecore/kcalendarera_p.h @@ -1,77 +1,77 @@ /* Copyright 2010 John Layt 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 KCALENDARERA_H #define KCALENDARERA_H #include #include #include "klocale.h" class KCalendarSystemPrivate; /** * @internal * Class to hold details of a Calendar Era. Internal for now, but may later be * made public if user configuration of Era formatting via System Settings is * required, in which case a d-ptr will be needed. Details based on POSIX LC_TIME * format. * * @b license GNU-LGPL v.2 or later * * @see KCalendarSystem * * @author John Layt */ class KCalendarEra { public: - explicit KCalendarEra(); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarEra(); virtual ~KCalendarEra(); bool isValid() const; int sequence() const; QDate startDate() const; QDate endDate() const; QString name(KLocale::DateTimeComponentFormat format = KLocale::DefaultComponentFormat) const; QString format() const; int direction() const; int offset() const; bool isInEra(const QDate &date) const; int yearInEra(int year) const; int year(int yearInEra) const; private: friend class KCalendarSystemPrivate; int m_sequence; QDate m_startDate; int m_startYear; QDate m_endDate; QString m_longName; QString m_shortName; QString m_format; int m_direction; int m_offset; }; #endif // KCALENDARERA_H diff --git a/src/kdecore/kcalendarsystemcoptic_p.h b/src/kdecore/kcalendarsystemcoptic_p.h index 0577f5cd..965cd35d 100644 --- a/src/kdecore/kcalendarsystemcoptic_p.h +++ b/src/kdecore/kcalendarsystemcoptic_p.h @@ -1,70 +1,70 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMCOPTIC_H #define KCALENDARSYSTEMCOPTIC_H #include "kcalendarsystem.h" class KCalendarSystemCopticPrivate; /** * @internal * This is the Coptic calendar implementation which is also the Ethiopian calendar * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemCoptic: public KCalendarSystem { public: - explicit KCalendarSystemCoptic(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemCoptic(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemCoptic(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemCoptic(KCalendarSystemCopticPrivate &dd, const KSharedConfig::Ptr, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemCoptic) }; #endif // KCALENDARSYSTEMCOPTIC_H diff --git a/src/kdecore/kcalendarsystemcopticprivate_p.h b/src/kdecore/kcalendarsystemcopticprivate_p.h index 03108f22..8decb30c 100644 --- a/src/kdecore/kcalendarsystemcopticprivate_p.h +++ b/src/kdecore/kcalendarsystemcopticprivate_p.h @@ -1,47 +1,47 @@ /* Copyright 2010 John Layt 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 KCALENDARSYSTEMCOPTICPRIVATE_H #define KCALENDARSYSTEMCOPTICPRIVATE_H #include "kcalendarsystemprivate_p.h" class KCalendarSystemCopticPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemCopticPrivate(KCalendarSystemCoptic *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemCopticPrivate(KCalendarSystemCoptic *q); virtual ~KCalendarSystemCopticPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; }; #endif // KCALENDARSYSTEMCOPTICPRIVATE_H diff --git a/src/kdecore/kcalendarsystemethiopian.cpp b/src/kdecore/kcalendarsystemethiopian.cpp index 5cffb976..1fe62898 100644 --- a/src/kdecore/kcalendarsystemethiopian.cpp +++ b/src/kdecore/kcalendarsystemethiopian.cpp @@ -1,391 +1,391 @@ /* Copyright 2009, 2010 John Layt 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. */ #include "kcalendarsystemethiopian_p.h" #include "kcalendarsystemcopticprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include #include //Reuse the Coptic private implementation class KCalendarSystemEthiopianPrivate : public KCalendarSystemCopticPrivate { public: - explicit KCalendarSystemEthiopianPrivate(KCalendarSystemEthiopian *q) : KCalendarSystemCopticPrivate(q) + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemEthiopianPrivate(KCalendarSystemEthiopian *q) : KCalendarSystemCopticPrivate(q) { } virtual ~KCalendarSystemEthiopianPrivate() { } void loadDefaultEraList() Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; }; void KCalendarSystemEthiopianPrivate::loadDefaultEraList() { QString name, shortName, format; // Incarnation Era, Amätä Mehrät, "Year of Mercy". name = i18nc("Calendar Era: Ethiopian Incarnation Era, years > 0, LongFormat", "Amata Mehrat"); shortName = i18nc("Calendar Era: Ethiopian Incarnation Era, years > 0, ShortFormat", "AM"); format = i18nc("(kdedt-format) Ethiopian, AM, full era year format used for %EY, e.g. 2000 AM", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } // Names taken from http://www.ethiopianembassy.at/dates_cycles.htm, alternative transliterations exist QString KCalendarSystemEthiopianPrivate::monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const { Q_UNUSED(year); QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (month) { case 1: return ki18nc("Ethiopian month 1 - KLocale::NarrowName", "M").toString(languages); case 2: return ki18nc("Ethiopian month 2 - KLocale::NarrowName", "T").toString(languages); case 3: return ki18nc("Ethiopian month 3 - KLocale::NarrowName", "H").toString(languages); case 4: return ki18nc("Ethiopian month 4 - KLocale::NarrowName", "T").toString(languages); case 5: return ki18nc("Ethiopian month 5 - KLocale::NarrowName", "T").toString(languages); case 6: return ki18nc("Ethiopian month 6 - KLocale::NarrowName", "Y").toString(languages); case 7: return ki18nc("Ethiopian month 7 - KLocale::NarrowName", "M").toString(languages); case 8: return ki18nc("Ethiopian month 8 - KLocale::NarrowName", "M").toString(languages); case 9: return ki18nc("Ethiopian month 9 - KLocale::NarrowName", "G").toString(languages); case 10: return ki18nc("Ethiopian month 10 - KLocale::NarrowName", "S").toString(languages); case 11: return ki18nc("Ethiopian month 11 - KLocale::NarrowName", "H").toString(languages); case 12: return ki18nc("Ethiopian month 12 - KLocale::NarrowName", "N").toString(languages); case 13: return ki18nc("Ethiopian month 13 - KLocale::NarrowName", "P").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && possessive) { switch (month) { case 1: return ki18nc("Ethiopian month 1 - KLocale::ShortName Possessive", "of Mes").toString(languages); case 2: return ki18nc("Ethiopian month 2 - KLocale::ShortName Possessive", "of Teq").toString(languages); case 3: return ki18nc("Ethiopian month 3 - KLocale::ShortName Possessive", "of Hed").toString(languages); case 4: return ki18nc("Ethiopian month 4 - KLocale::ShortName Possessive", "of Tah").toString(languages); case 5: return ki18nc("Ethiopian month 5 - KLocale::ShortName Possessive", "of Ter").toString(languages); case 6: return ki18nc("Ethiopian month 6 - KLocale::ShortName Possessive", "of Yak").toString(languages); case 7: return ki18nc("Ethiopian month 7 - KLocale::ShortName Possessive", "of Mag").toString(languages); case 8: return ki18nc("Ethiopian month 8 - KLocale::ShortName Possessive", "of Miy").toString(languages); case 9: return ki18nc("Ethiopian month 9 - KLocale::ShortName Possessive", "of Gen").toString(languages); case 10: return ki18nc("Ethiopian month 10 - KLocale::ShortName Possessive", "of Sen").toString(languages); case 11: return ki18nc("Ethiopian month 11 - KLocale::ShortName Possessive", "of Ham").toString(languages); case 12: return ki18nc("Ethiopian month 12 - KLocale::ShortName Possessive", "of Neh").toString(languages); case 13: return ki18nc("Ethiopian month 13 - KLocale::ShortName Possessive", "of Pag").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && !possessive) { switch (month) { case 1: return ki18nc("Ethiopian month 1 - KLocale::ShortName", "Mes").toString(languages); case 2: return ki18nc("Ethiopian month 2 - KLocale::ShortName", "Teq").toString(languages); case 3: return ki18nc("Ethiopian month 3 - KLocale::ShortName", "Hed").toString(languages); case 4: return ki18nc("Ethiopian month 4 - KLocale::ShortName", "Tah").toString(languages); case 5: return ki18nc("Ethiopian month 5 - KLocale::ShortName", "Ter").toString(languages); case 6: return ki18nc("Ethiopian month 6 - KLocale::ShortName", "Yak").toString(languages); case 7: return ki18nc("Ethiopian month 7 - KLocale::ShortName", "Mag").toString(languages); case 8: return ki18nc("Ethiopian month 8 - KLocale::ShortName", "Miy").toString(languages); case 9: return ki18nc("Ethiopian month 9 - KLocale::ShortName", "Gen").toString(languages); case 10: return ki18nc("Ethiopian month 10 - KLocale::ShortName", "Sen").toString(languages); case 11: return ki18nc("Ethiopian month 11 - KLocale::ShortName", "Ham").toString(languages); case 12: return ki18nc("Ethiopian month 12 - KLocale::ShortName", "Neh").toString(languages); case 13: return ki18nc("Ethiopian month 13 - KLocale::ShortName", "Pag").toString(languages); default: return QString(); } } if (format == KLocale::LongName && possessive) { switch (month) { case 1: return ki18nc("Ethiopian month 1 - KLocale::LongName Possessive", "of Meskerem").toString(languages); case 2: return ki18nc("Ethiopian month 2 - KLocale::LongName Possessive", "of Tequemt").toString(languages); case 3: return ki18nc("Ethiopian month 3 - KLocale::LongName Possessive", "of Hedar").toString(languages); case 4: return ki18nc("Ethiopian month 4 - KLocale::LongName Possessive", "of Tahsas").toString(languages); case 5: return ki18nc("Ethiopian month 5 - KLocale::LongName Possessive", "of Ter").toString(languages); case 6: return ki18nc("Ethiopian month 6 - KLocale::LongName Possessive", "of Yakatit").toString(languages); case 7: return ki18nc("Ethiopian month 7 - KLocale::LongName Possessive", "of Magabit").toString(languages); case 8: return ki18nc("Ethiopian month 8 - KLocale::LongName Possessive", "of Miyazya").toString(languages); case 9: return ki18nc("Ethiopian month 9 - KLocale::LongName Possessive", "of Genbot").toString(languages); case 10: return ki18nc("Ethiopian month 10 - KLocale::LongName Possessive", "of Sene").toString(languages); case 11: return ki18nc("Ethiopian month 11 - KLocale::LongName Possessive", "of Hamle").toString(languages); case 12: return ki18nc("Ethiopian month 12 - KLocale::LongName Possessive", "of Nehase").toString(languages); case 13: return ki18nc("Ethiopian month 13 - KLocale::LongName Possessive", "of Pagumen").toString(languages); default: return QString(); } } // Default to LongName switch (month) { case 1: return ki18nc("Ethiopian month 1 - KLocale::LongName", "Meskerem").toString(languages); case 2: return ki18nc("Ethiopian month 2 - KLocale::LongName", "Tequemt").toString(languages); case 3: return ki18nc("Ethiopian month 3 - KLocale::LongName", "Hedar").toString(languages); case 4: return ki18nc("Ethiopian month 4 - KLocale::LongName", "Tahsas").toString(languages); case 5: return ki18nc("Ethiopian month 5 - KLocale::LongName", "Ter").toString(languages); case 6: return ki18nc("Ethiopian month 6 - KLocale::LongName", "Yakatit").toString(languages); case 7: return ki18nc("Ethiopian month 7 - KLocale::LongName", "Magabit").toString(languages); case 8: return ki18nc("Ethiopian month 8 - KLocale::LongName", "Miyazya").toString(languages); case 9: return ki18nc("Ethiopian month 9 - KLocale::LongName", "Genbot").toString(languages); case 10: return ki18nc("Ethiopian month 10 - KLocale::LongName", "Sene").toString(languages); case 11: return ki18nc("Ethiopian month 11 - KLocale::LongName", "Hamle").toString(languages); case 12: return ki18nc("Ethiopian month 12 - KLocale::LongName", "Nehase").toString(languages); case 13: return ki18nc("Ethiopian month 13 - KLocale::LongName", "Pagumen").toString(languages); default: return QString(); } } // Names taken from http://www.ethiopianembassy.at/dates_cycles.htm, alternative transliterations exist QString KCalendarSystemEthiopianPrivate::weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const { QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (weekDay) { case 1: return ki18nc("Ethiopian weekday 1 - KLocale::NarrowName ", "S").toString(languages); case 2: return ki18nc("Ethiopian weekday 2 - KLocale::NarrowName ", "M").toString(languages); case 3: return ki18nc("Ethiopian weekday 3 - KLocale::NarrowName ", "R").toString(languages); case 4: return ki18nc("Ethiopian weekday 4 - KLocale::NarrowName ", "H").toString(languages); case 5: return ki18nc("Ethiopian weekday 5 - KLocale::NarrowName ", "A").toString(languages); case 6: return ki18nc("Ethiopian weekday 6 - KLocale::NarrowName ", "Q").toString(languages); case 7: return ki18nc("Ethiopian weekday 7 - KLocale::NarrowName ", "E").toString(languages); default: return QString(); } } if (format == KLocale::ShortName || format == KLocale:: ShortNumber) { switch (weekDay) { case 1: return ki18nc("Ethiopian weekday 1 - KLocale::ShortName", "Seg").toString(languages); case 2: return ki18nc("Ethiopian weekday 2 - KLocale::ShortName", "Mak").toString(languages); case 3: return ki18nc("Ethiopian weekday 3 - KLocale::ShortName", "Rob").toString(languages); case 4: return ki18nc("Ethiopian weekday 4 - KLocale::ShortName", "Ham").toString(languages); case 5: return ki18nc("Ethiopian weekday 5 - KLocale::ShortName", "Arb").toString(languages); case 6: return ki18nc("Ethiopian weekday 6 - KLocale::ShortName", "Qed").toString(languages); case 7: return ki18nc("Ethiopian weekday 7 - KLocale::ShortName", "Ehu").toString(languages); default: return QString(); } } switch (weekDay) { case 1: return ki18nc("Ethiopian weekday 1 - KLocale::LongName", "Segno").toString(languages); case 2: return ki18nc("Ethiopian weekday 2 - KLocale::LongName", "Maksegno").toString(languages); case 3: return ki18nc("Ethiopian weekday 3 - KLocale::LongName", "Rob").toString(languages); case 4: return ki18nc("Ethiopian weekday 4 - KLocale::LongName", "Hamus").toString(languages); case 5: return ki18nc("Ethiopian weekday 5 - KLocale::LongName", "Arb").toString(languages); case 6: return ki18nc("Ethiopian weekday 6 - KLocale::LongName", "Qedame").toString(languages); case 7: return ki18nc("Ethiopian weekday 7 - KLocale::LongName", "Ehud").toString(languages); default: return QString(); } } KCalendarSystemEthiopian::KCalendarSystemEthiopian(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemCoptic(*new KCalendarSystemEthiopianPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemEthiopian::KCalendarSystemEthiopian(KCalendarSystemEthiopianPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemCoptic(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemEthiopian::~KCalendarSystemEthiopian() { } QString KCalendarSystemEthiopian::calendarType() const { return QLatin1String("ethiopian"); } KLocale::CalendarSystem KCalendarSystemEthiopian::calendarSystem() const { return KLocale::EthiopianCalendar; } QDate KCalendarSystemEthiopian::epoch() const { //0001-01-01, no Year 0. //0008-08-29 AD Julian return QDate::fromJulianDay(1724221); } QDate KCalendarSystemEthiopian::earliestValidDate() const { //0001-01-01, no Year 0. //0008-08-29 AD Julian return QDate::fromJulianDay(1724221); } QDate KCalendarSystemEthiopian::latestValidDate() const { // Set to last day of year 9999 until confirm date formats & widgets support > 9999 //9999-12-30 //100008-08-29 AD Julian return QDate::fromJulianDay(5376721); } QString KCalendarSystemEthiopian::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystemCoptic::monthName(month, year, format); } QString KCalendarSystemEthiopian::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystemCoptic::monthName(date, format); } QString KCalendarSystemEthiopian::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystemCoptic::weekDayName(weekDay, format); } QString KCalendarSystemEthiopian::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystemCoptic::weekDayName(date, format); } bool KCalendarSystemEthiopian::isLunar() const { return KCalendarSystemCoptic::isLunar(); } bool KCalendarSystemEthiopian::isLunisolar() const { return KCalendarSystemCoptic::isLunisolar(); } bool KCalendarSystemEthiopian::isSolar() const { return KCalendarSystemCoptic::isSolar(); } bool KCalendarSystemEthiopian::isProleptic() const { return false; } bool KCalendarSystemEthiopian::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { return KCalendarSystemCoptic::julianDayToDate(jd, year, month, day); } bool KCalendarSystemEthiopian::dateToJulianDay(int year, int month, int day, qint64 &jd) const { return KCalendarSystemCoptic::dateToJulianDay(year, month, day, jd); } diff --git a/src/kdecore/kcalendarsystemethiopian_p.h b/src/kdecore/kcalendarsystemethiopian_p.h index 34b2ccf3..642738f4 100644 --- a/src/kdecore/kcalendarsystemethiopian_p.h +++ b/src/kdecore/kcalendarsystemethiopian_p.h @@ -1,71 +1,71 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMETHIOPIAN_H #define KCALENDARSYSTEMETHIOPIAN_H #include "kcalendarsystemcoptic_p.h" class KCalendarSystemEthiopianPrivate; /** * @internal * This is the Ethiopian calendar implementation which is the Coptic calendar * but with a differenct Epoch and month/weekday names * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemEthiopian: public KCalendarSystemCoptic { public: - explicit KCalendarSystemEthiopian(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemEthiopian(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemEthiopian(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemEthiopian(KCalendarSystemEthiopianPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemEthiopian) }; #endif // KCALENDARSYSTEMETHIOPIAN_H diff --git a/src/kdecore/kcalendarsystemgregorian_p.h b/src/kdecore/kcalendarsystemgregorian_p.h index 60f630ce..6c8439cf 100644 --- a/src/kdecore/kcalendarsystemgregorian_p.h +++ b/src/kdecore/kcalendarsystemgregorian_p.h @@ -1,75 +1,75 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMGREGORIAN_H #define KCALENDARSYSTEMGREGORIAN_H #include "kcalendarsystem.h" class KCalendarSystemGregorianPrivate; /** * @internal * This is the pure Gregorian calendar implementation. * * Note: This is the traditional proleptic Gregorian calendar * that does not have a year 0, unlike the ISO version which does. * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemGregorian: public KCalendarSystem { public: - explicit KCalendarSystemGregorian(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemGregorian(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemGregorian(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; int yearStringToInteger(const QString &sNum, int &iLength) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemGregorian(KCalendarSystemGregorianPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemGregorian) }; #endif // KCALENDARSYSTEMGREGORIAN_H diff --git a/src/kdecore/kcalendarsystemgregorianprivate_p.h b/src/kdecore/kcalendarsystemgregorianprivate_p.h index 1f75c731..1f063500 100644 --- a/src/kdecore/kcalendarsystemgregorianprivate_p.h +++ b/src/kdecore/kcalendarsystemgregorianprivate_p.h @@ -1,51 +1,51 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMGREGORIANPRIVATE_H #define KCALENDARSYSTEMGREGORIANPRIVATE_H // Derived gregorian kde calendar class #include "kcalendarsystemprivate_p.h" class KCalendarSystemGregorianPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemGregorianPrivate(KCalendarSystemGregorian *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemGregorianPrivate(KCalendarSystemGregorian *q); virtual ~KCalendarSystemGregorianPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; bool m_useCommonEra; }; #endif // KCALENDARSYSTEMGREGORIANPRIVATE_H diff --git a/src/kdecore/kcalendarsystemhebrew.cpp b/src/kdecore/kcalendarsystemhebrew.cpp index 6c0239b6..43757aac 100644 --- a/src/kdecore/kcalendarsystemhebrew.cpp +++ b/src/kdecore/kcalendarsystemhebrew.cpp @@ -1,1001 +1,1001 @@ /* Copyright (c) 2003 Hans Petter Bieker Copyright 2007, 2009, 2010 John Layt Calendar conversion routines based on Hdate v6, by Amos Shapir 1978 (rev. 1985, 1992) 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. */ // Derived hebrew kde calendar class #include "kcalendarsystemhebrew_p.h" #include "kcalendarsystemprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include #include static int hebrewDaysElapsed(int y); class h_date { public: int hd_day; int hd_mon; int hd_year; int hd_dw; int hd_flg; }; /* * compute general date structure from hebrew date */ static class h_date *hebrewToGregorian(int y, int m, int d) { static class h_date h; int s; y -= 3744; s = hebrewDaysElapsed(y); d += s; s = hebrewDaysElapsed(y + 1) - s; /* length of year */ if (s > 365 && m > 6) { --m; d += 30; } d += (59 * (m - 1) + 1) / 2; /* regular months */ /* special cases */ if (s % 10 > 4 && m > 2) { /* long Heshvan */ d++; } if (s % 10 < 4 && m > 3) { /* short Kislev */ d--; } // ### HPB: Broken in leap years //if (s > 365 && m > 6) /* leap year */ // d += 30; d -= 6002; y = (d + 36525) * 4 / 146097 - 1; d -= y / 4 * 146097 + (y % 4) * 36524; y *= 100; /* compute year */ s = (d + 366) * 4 / 1461 - 1; d -= s / 4 * 1461 + (s % 4) * 365; y += s; /* compute month */ m = (d + 245) * 12 / 367 - 7; d -= m * 367 / 12 - 30; if (++m >= 12) { m -= 12; y++; } h.hd_day = d; h.hd_mon = m; h.hd_year = y; return (&h); } /* * compute date structure from no. of days since 1 Tishrei 3744 */ static class h_date *gregorianToHebrew(int y, int m, int d) { static class h_date h; int s; if ((m -= 2) <= 0) { m += 12; y--; } /* no. of days, Julian calendar */ d += 365 * y + y / 4 + 367 * m / 12 + 5968; /* Gregorian calendar */ d -= y / 100 - y / 400 - 2; h.hd_dw = (d + 1) % 7; /* compute the year */ y += 16; s = hebrewDaysElapsed(y); m = hebrewDaysElapsed(y + 1); while (d >= m) { /* computed year was underestimated */ s = m; y++; m = hebrewDaysElapsed(y + 1); } d -= s; s = m - s; /* size of current year */ y += 3744; h.hd_flg = s % 10 - 4; /* compute day and month */ if (d >= s - 236) { /* last 8 months are regular */ d -= s - 236; m = d * 2 / 59; d -= (m * 59 + 1) / 2; m += 4; if (s > 365 && m <= 5) { /* Adar of Meuberet */ m += 8; } } else { /* first 4 months have 117-119 days */ s = 114 + s % 10; m = d * 4 / s; d -= (m * s + 3) / 4; } h.hd_day = d; h.hd_mon = m; h.hd_year = y; return (&h); } /* constants, in 1/18th of minute */ static const int HOUR = 1080; static const int DAY = 24 * HOUR; static const int WEEK = 7 * DAY; #define M(h,p) ((h)*HOUR+p) #define MONTH (DAY+M(12,793)) /** * @internal * no. of days in y years */ static int hebrewDaysElapsed(int y) { int m, nm, dw, s, l; l = y * 7 + 1; // no. of leap months m = y * 12 + l / 19; // total no. of months l %= 19; nm = m * MONTH + M(1 + 6, 779); // molad new year 3744 (16BC) + 6 hours s = m * 28 + nm / DAY - 2; nm %= WEEK; dw = nm / DAY; nm %= DAY; // special cases of Molad Zaken if ((l < 12 && dw == 3 && nm >= M(9 + 6, 204)) || (l < 7 && dw == 2 && nm >= M(15 + 6, 589))) { s++, dw++; } /* ADU */ if (dw == 1 || dw == 4 || dw == 6) { s++; } return s; } /** * @internal * true if long Cheshvan */ static int long_cheshvan(int year) { QDate first, last; class h_date *gd; gd = hebrewToGregorian(year, 1, 1); first.setDate(gd->hd_year, gd->hd_mon + 1, gd->hd_day + 1); gd = hebrewToGregorian(year + 1, 1, 1); last.setDate(gd->hd_year, gd->hd_mon + 1, gd->hd_day + 1); return (first.daysTo(last) % 10 == 5); } /** * @internal * true if short Kislev */ static int short_kislev(int year) { QDate first, last; class h_date *gd; gd = hebrewToGregorian(year, 1, 1); first.setDate(gd->hd_year, gd->hd_mon + 1, gd->hd_day + 1); gd = hebrewToGregorian(year + 1, 1, 1); last.setDate(gd->hd_year, gd->hd_mon + 1, gd->hd_day + 1); return (first.daysTo(last) % 10 == 3); } // Ok static class h_date *toHebrew(const QDate &date) { class h_date *sd; sd = gregorianToHebrew(date.year(), date.month(), date.day()); ++sd->hd_mon; ++sd->hd_day; return sd; } class KCalendarSystemHebrewPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemHebrewPrivate(KCalendarSystemHebrew *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemHebrewPrivate(KCalendarSystemHebrew *q); virtual ~KCalendarSystemHebrewPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; int integerFromString(const QString &string, int maxLength, int &readLength) const Q_DECL_OVERRIDE; QString stringFromInteger(int number, int padWidth = 0, QChar padChar = QLatin1Char('0')) const Q_DECL_OVERRIDE; QString stringFromInteger(int number, int padWidth, QChar padChar, KLocale::DigitSet digitSet) const Q_DECL_OVERRIDE; virtual int monthNumberToMonthIndex(int year, int month) const; }; // Shared d pointer base class definitions KCalendarSystemHebrewPrivate::KCalendarSystemHebrewPrivate(KCalendarSystemHebrew *q) : KCalendarSystemPrivate(q) { } KCalendarSystemHebrewPrivate::~KCalendarSystemHebrewPrivate() { } void KCalendarSystemHebrewPrivate::loadDefaultEraList() { QString name, shortName, format; // Jewish Era, Anno Mundi, "Year of the World". name = i18nc("Calendar Era: Hebrew Era, years > 0, LongFormat", "Anno Mundi"); shortName = i18nc("Calendar Era: Hebrew Era, years > 0, ShortFormat", "AM"); format = i18nc("(kdedt-format) Hebrew, AM, full era year format used for %EY, e.g. 2000 AM", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemHebrewPrivate::monthsInYear(int year) const { if (isLeapYear(year)) { return 13; } else { return 12; } } int KCalendarSystemHebrewPrivate::daysInMonth(int year, int month) const { int mi = monthNumberToMonthIndex(year, month); if (mi == 2 && long_cheshvan(year)) { return 30; } if (mi == 3 && short_kislev(year)) { return 29; } if (mi % 2 == 0) { // Even number months have 29 days return 29; } else { // Odd number months have 30 days return 30; } } int KCalendarSystemHebrewPrivate::daysInYear(int year) const { int days; // Get Regular year length if (isLeapYear(year)) { // Has 13 months days = 384; } else { // Has 12 months days = 354; } // Check if is Deficient or Abundant year if (short_kislev(year)) { // Deficient days = days - 1; } else if (long_cheshvan(year)) { // Abundant days = days + 1; } return days; } bool KCalendarSystemHebrewPrivate::isLeapYear(int year) const { return ((((7 * year) + 1) % 19) < 7); } bool KCalendarSystemHebrewPrivate::hasLeapMonths() const { return true; } bool KCalendarSystemHebrewPrivate::hasYearZero() const { return false; } int KCalendarSystemHebrewPrivate::maxMonthsInYear() const { return 13; } int KCalendarSystemHebrewPrivate::earliestValidYear() const { return 5344; } int KCalendarSystemHebrewPrivate::latestValidYear() const { return 8119; } int KCalendarSystemHebrewPrivate::integerFromString(const QString &inputString, int maxLength, int &readLength) const { if (locale()->language() == QLatin1String("he")) { // Hebrew numbers are composed of combinations of normal letters which have a numeric value. // This is a non-positional system, the numeric values are simply added together, however // convention is for a RTL highest to lowest value ordering. There is also a degree of // ambiguity due to the lack of a letter for 0, hence 5 and 5000 are written the same. // Hebrew numbers are only used in dates. // See http://www.i18nguy.com/unicode/hebrew-numbers.html for more explaination /* Ref table for numbers to Hebrew chars Value 1 2 3 4 5 6 7 8 9 x 1 Alef א Bet ב Gimel ג Dalet ד He ה Vav ו Zayen ז Het ח Tet ט 0x05D0 0x05D1 0x05D2 0x05D3 0x05D4 0x05D5 0x05D6 0x05D7 0x05D8 x 10 Yod י Kaf כ Lamed ל Mem מ Nun נ Samekh ס Ayin ע Pe פ Tzadi צ 0x05D9 0x05DB 0x05DC 0x05DE 0x05E0 0x05E1 0x05E2 0x05E4 0x05E6 x 100 Qof ק Resh ר Shin ש Tav ת 0x05E7 0x05E8 0x05E9 0x05EA Note special cases 15 = 9 + 6 = 96 טו and 16 = 9 + 7 = 97 טז */ int decadeValues[14] = {10, 20, 20, 30, 40, 40, 50, 50, 60, 70, 80, 80, 90, 90}; QChar thisChar, nextChar; QString string = inputString; int stringLength = string.length(); readLength = 0; int position = 0; int result = 0; int value = 0; for (; position < stringLength; ++position) { thisChar = string[position]; if (position + 1 < stringLength) { nextChar = string[position + 1]; // Ignore any geresh or gershayim chars, we don't bother checking they are in the right place if (nextChar == QLatin1Char('\'') || nextChar == QChar(0x05F3) || // geresh nextChar == QLatin1Char('\"') || nextChar == QChar(0x05F4)) { // gershayim string.remove(position + 1, 1); stringLength = string.length(); if (position + 1 < stringLength) { nextChar = string[position + 1]; } else { nextChar = QChar(); } readLength = readLength + 1; } } else { nextChar = QChar(); } if (thisChar >= QChar(0x05D0) && thisChar <= QChar(0x05D7)) { // If this char Alef to Het, 1 to 8, א to ח // If next char is any valid digit char (Alef to Tav, 1 to 400, א to ת) // then this char is a thousands digit // else this char is a ones digit if (nextChar >= QChar(0x05D0) && nextChar <= QChar(0x05EA)) { value = (thisChar.unicode() - 0x05D0 + 1) * 1000; } else { value = thisChar.unicode() - 0x05D0 + 1; } } else if (thisChar == QChar(0x05D8)) { // If this char is Tet, 9, ט // If next char is any valid digit char (Alef to Tav, 1 to 400, א to ת) // and next char not 6 (Special case for 96 = 15) // and next char not 7 (Special case for 97 = 16) // then is a thousands digit else is 9 if (nextChar >= QChar(0x05D0) && nextChar <= QChar(0x05EA) && nextChar != QChar(0x05D5) && nextChar != QChar(0x05D6)) { value = 9000; } else { value = 9; } } else if (thisChar >= QChar(0x05D9) && thisChar <= QChar(0x05E6)) { // If this char Yod to Tsadi, 10 to 90, י to צ // If next char is a tens or hundreds char then is an error // Else is a tens digit if (nextChar >= QChar(0x05D9)) { return -1; } else { value = decadeValues[thisChar.unicode() - 0x05D9]; } } else if (thisChar >= QChar(0x05E7) && thisChar <= QChar(0x05EA)) { // If this char Qof to Tav, 100 to 400, ק to ת, then is hundreds digit value = (thisChar.unicode() - 0x05E7 + 1) * 100; } else { // If this char any non-digit char including whitespace or punctuation, we're done break; } result = result + value; value = 0; } readLength += position; return result; } else { return KCalendarSystemPrivate::integerFromString(inputString, maxLength, readLength); } } QString KCalendarSystemHebrewPrivate::stringFromInteger(int number, int padWidth, QChar padChar) const { return KCalendarSystemPrivate::stringFromInteger(number, padWidth, padChar); } QString KCalendarSystemHebrewPrivate::stringFromInteger(int number, int padWidth, QChar padChar, KLocale::DigitSet digitSet) const { if (locale()->language() == QLatin1String("he")) { // Hebrew numbers are composed of combinations of normal letters which have a numeric value. // This is a non-positional system, the numeric values are simply added together, however // convention is for a RTL highest to lowest value ordering. There is also a degree of // ambiguity due to the lack of a letter for 0, hence 5 and 5000 are written the same. // Hebrew numbers are only used in dates. // See http://www.i18nguy.com/unicode/hebrew-numbers.html for more explaination /* Ref table for numbers to Hebrew chars Value 1 2 3 4 5 6 7 8 9 x 1 Alef א Bet ב Gimel ג Dalet ד He ה Vav ו Zayen ז Het ח Tet ט 0x05D0 0x05D1 0x05D2 0x05D3 0x05D4 0x05D5 0x05D6 0x05D7 0x05D8 x 10 Yod י Kaf כ Lamed ל Mem מ Nun נ Samekh ס Ayin ע Pe פ Tzadi צ 0x05D9 0x05DB 0x05DC 0x05DE 0x05E0 0x05E1 0x05E2 0x05E4 0x05E6 x 100 Qof ק Resh ר Shin ש Tav ת 0x05E7 0x05E8 0x05E9 0x05EA Note special cases 15 = 9 + 6 = 96 טו and 16 = 9 + 7 = 97 טז */ const QChar decade[] = { // Tet = ט, Yod = י, Kaf = כ, Lamed = ל, Mem = מ // Nun = נ, Samekh = ס, Ayin = ע, Pe = פ, Tsadi = צ 0x05D8, 0x05D9, 0x05DB, 0x05DC, 0x05DE, 0x05E0, 0x05E1, 0x05E2, 0x05E4, 0x05E6 }; QString result; // We have no rules for coping with numbers outside this range if (number < 1 || number > 9999) { return KCalendarSystemPrivate::stringFromInteger(number, padWidth, padChar, digitSet); } // Translate the thousands digit, just uses letter for number 1..9 ( א to ט, Alef to Tet ) // Years 5001-5999 do not have the thousands by convention if (number >= 1000) { if (number <= 5000 || number >= 6000) { result += QChar(0x05D0 - 1 + number / 1000); // Alef א to Tet ט } number %= 1000; } // Translate the hundreds digit // Use traditional method where we only have letters assigned values for 100, 200, 300 and 400 // so may need to repeat 400 twice to make up the required number if (number >= 100) { while (number >= 500) { result += QChar(0x05EA); // Tav = ת number -= 400; } result += QChar(0x05E7 - 1 + number / 100); // Qof = ק to xxx number %= 100; } // Translate the tens digit // The numbers 15 and 16 translate to letters that spell out the name of God which is // forbidden, so require special treatment where 15 = 9 + 6 and 1 = 9 + 7. if (number >= 10) { if (number == 15 || number == 16) { number -= 9; } result += decade[number / 10]; number %= 10; } // Translate the ones digit, uses letter for number 1..9 ( א to ט, Alef to Tet ) if (number > 0) { result += QChar(0x05D0 - 1 + number); // Alef = א to xxx } // When used in a string with mixed names and numbers the numbers need special chars to // distinguish them from words composed of the same letters. // Single digit numbers are followed by a geresh symbol ? (Unicode = 0x05F3), but we use // single quote for convenience. // Multiple digit numbers have a gershayim symbol ? (Unicode = 0x05F4) as second-to-last // char, but we use double quote for convenience. if (result.length() == 1) { result += QLatin1Char('\''); } else { result.insert(result.length() - 1, QLatin1Char('\"')); } return result; } else { return KCalendarSystemPrivate::stringFromInteger(number, padWidth, padChar, digitSet); } } int KCalendarSystemHebrewPrivate::monthNumberToMonthIndex(int year, int month) const { if (isLeapYear(year)) { if (month == 6) { return 13; // Adar I } else if (month == 7) { return 14; // Adar II } else if (month > 7) { return month - 1; // Because of Adar II } } return month; } QString KCalendarSystemHebrewPrivate::monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const { // We must map month number to month index int monthIndex = monthNumberToMonthIndex(year, month); QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (monthIndex) { case 1: return ki18nc("Hebrew month 1 - KLocale::NarrowName", "T").toString(languages); case 2: return ki18nc("Hebrew month 2 - KLocale::NarrowName", "H").toString(languages); case 3: return ki18nc("Hebrew month 3 - KLocale::NarrowName", "K").toString(languages); case 4: return ki18nc("Hebrew month 4 - KLocale::NarrowName", "T").toString(languages); case 5: return ki18nc("Hebrew month 5 - KLocale::NarrowName", "S").toString(languages); case 6: return ki18nc("Hebrew month 6 - KLocale::NarrowName", "A").toString(languages); case 7: return ki18nc("Hebrew month 7 - KLocale::NarrowName", "N").toString(languages); case 8: return ki18nc("Hebrew month 8 - KLocale::NarrowName", "I").toString(languages); case 9: return ki18nc("Hebrew month 9 - KLocale::NarrowName", "S").toString(languages); case 10: return ki18nc("Hebrew month 10 - KLocale::NarrowName", "T").toString(languages); case 11: return ki18nc("Hebrew month 11 - KLocale::NarrowName", "A").toString(languages); case 12: return ki18nc("Hebrew month 12 - KLocale::NarrowName", "E").toString(languages); case 13: return ki18nc("Hebrew month 13 - KLocale::NarrowName", "A").toString(languages); case 14: return ki18nc("Hebrew month 14 - KLocale::NarrowName", "A").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && possessive) { switch (monthIndex) { case 1: return ki18nc("Hebrew month 1 - KLocale::ShortName Possessive", "of Tis").toString(languages); case 2: return ki18nc("Hebrew month 2 - KLocale::ShortName Possessive", "of Hes").toString(languages); case 3: return ki18nc("Hebrew month 3 - KLocale::ShortName Possessive", "of Kis").toString(languages); case 4: return ki18nc("Hebrew month 4 - KLocale::ShortName Possessive", "of Tev").toString(languages); case 5: return ki18nc("Hebrew month 5 - KLocale::ShortName Possessive", "of Shv").toString(languages); case 6: return ki18nc("Hebrew month 6 - KLocale::ShortName Possessive", "of Ada").toString(languages); case 7: return ki18nc("Hebrew month 7 - KLocale::ShortName Possessive", "of Nis").toString(languages); case 8: return ki18nc("Hebrew month 8 - KLocale::ShortName Possessive", "of Iya").toString(languages); case 9: return ki18nc("Hebrew month 9 - KLocale::ShortName Possessive", "of Siv").toString(languages); case 10: return ki18nc("Hebrew month 10 - KLocale::ShortName Possessive", "of Tam").toString(languages); case 11: return ki18nc("Hebrew month 11 - KLocale::ShortName Possessive", "of Av").toString(languages); case 12: return ki18nc("Hebrew month 12 - KLocale::ShortName Possessive", "of Elu").toString(languages); case 13: return ki18nc("Hebrew month 13 - KLocale::ShortName Possessive", "of Ad1").toString(languages); case 14: return ki18nc("Hebrew month 14 - KLocale::ShortName Possessive", "of Ad2").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && !possessive) { switch (monthIndex) { case 1: return ki18nc("Hebrew month 1 - KLocale::ShortName", "Tis").toString(languages); case 2: return ki18nc("Hebrew month 2 - KLocale::ShortName", "Hes").toString(languages); case 3: return ki18nc("Hebrew month 3 - KLocale::ShortName", "Kis").toString(languages); case 4: return ki18nc("Hebrew month 4 - KLocale::ShortName", "Tev").toString(languages); case 5: return ki18nc("Hebrew month 5 - KLocale::ShortName", "Shv").toString(languages); case 6: return ki18nc("Hebrew month 6 - KLocale::ShortName", "Ada").toString(languages); case 7: return ki18nc("Hebrew month 7 - KLocale::ShortName", "Nis").toString(languages); case 8: return ki18nc("Hebrew month 8 - KLocale::ShortName", "Iya").toString(languages); case 9: return ki18nc("Hebrew month 9 - KLocale::ShortName", "Siv").toString(languages); case 10: return ki18nc("Hebrew month 10 - KLocale::ShortName", "Tam").toString(languages); case 11: return ki18nc("Hebrew month 11 - KLocale::ShortName", "Av").toString(languages); case 12: return ki18nc("Hebrew month 12 - KLocale::ShortName", "Elu").toString(languages); case 13: return ki18nc("Hebrew month 13 - KLocale::ShortName", "Ad1").toString(languages); case 14: return ki18nc("Hebrew month 14 - KLocale::ShortName", "Ad2").toString(languages); default: return QString(); } } if (format == KLocale::LongName && possessive) { switch (monthIndex) { case 1: return ki18nc("Hebrew month 1 - KLocale::LongName Possessive", "of Tishrey").toString(languages); case 2: return ki18nc("Hebrew month 2 - KLocale::LongName Possessive", "of Heshvan").toString(languages); case 3: return ki18nc("Hebrew month 3 - KLocale::LongName Possessive", "of Kislev").toString(languages); case 4: return ki18nc("Hebrew month 4 - KLocale::LongName Possessive", "of Tevet").toString(languages); case 5: return ki18nc("Hebrew month 5 - KLocale::LongName Possessive", "of Shvat").toString(languages); case 6: return ki18nc("Hebrew month 6 - KLocale::LongName Possessive", "of Adar").toString(languages); case 7: return ki18nc("Hebrew month 7 - KLocale::LongName Possessive", "of Nisan").toString(languages); case 8: return ki18nc("Hebrew month 8 - KLocale::LongName Possessive", "of Iyar").toString(languages); case 9: return ki18nc("Hebrew month 9 - KLocale::LongName Possessive", "of Sivan").toString(languages); case 10: return ki18nc("Hebrew month 10 - KLocale::LongName Possessive", "of Tamuz").toString(languages); case 11: return ki18nc("Hebrew month 11 - KLocale::LongName Possessive", "of Av").toString(languages); case 12: return ki18nc("Hebrew month 12 - KLocale::LongName Possessive", "of Elul").toString(languages); case 13: return ki18nc("Hebrew month 13 - KLocale::LongName Possessive", "of Adar I").toString(languages); case 14: return ki18nc("Hebrew month 14 - KLocale::LongName Possessive", "of Adar II").toString(languages); default: return QString(); } } // Default to LongName switch (monthIndex) { case 1: return ki18nc("Hebrew month 1 - KLocale::LongName", "Tishrey").toString(languages); case 2: return ki18nc("Hebrew month 2 - KLocale::LongName", "Heshvan").toString(languages); case 3: return ki18nc("Hebrew month 3 - KLocale::LongName", "Kislev").toString(languages); case 4: return ki18nc("Hebrew month 4 - KLocale::LongName", "Tevet").toString(languages); case 5: return ki18nc("Hebrew month 5 - KLocale::LongName", "Shvat").toString(languages); case 6: return ki18nc("Hebrew month 6 - KLocale::LongName", "Adar").toString(languages); case 7: return ki18nc("Hebrew month 7 - KLocale::LongName", "Nisan").toString(languages); case 8: return ki18nc("Hebrew month 8 - KLocale::LongName", "Iyar").toString(languages); case 9: return ki18nc("Hebrew month 9 - KLocale::LongName", "Sivan").toString(languages); case 10: return ki18nc("Hebrew month 10 - KLocale::LongName", "Tamuz").toString(languages); case 11: return ki18nc("Hebrew month 11 - KLocale::LongName", "Av").toString(languages); case 12: return ki18nc("Hebrew month 12 - KLocale::LongName", "Elul").toString(languages); case 13: return ki18nc("Hebrew month 13 - KLocale::LongName", "Adar I").toString(languages); case 14: return ki18nc("Hebrew month 14 - KLocale::LongName", "Adar II").toString(languages); default: return QString(); } } // Use Western day names for now as that's what the old version did, // but wouldn't it be better to use the right Hebrew names like Shabbat? // Could make it switchable by adding new enums to WeekDayFormat, e.g. ShortNameWestern? QString KCalendarSystemHebrewPrivate::weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const { QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (weekDay) { case 1: return ki18nc("Gregorian weekday 1 - KLocale::NarrowName ", "M").toString(languages); case 2: return ki18nc("Gregorian weekday 2 - KLocale::NarrowName ", "T").toString(languages); case 3: return ki18nc("Gregorian weekday 3 - KLocale::NarrowName ", "W").toString(languages); case 4: return ki18nc("Gregorian weekday 4 - KLocale::NarrowName ", "T").toString(languages); case 5: return ki18nc("Gregorian weekday 5 - KLocale::NarrowName ", "F").toString(languages); case 6: return ki18nc("Gregorian weekday 6 - KLocale::NarrowName ", "S").toString(languages); case 7: return ki18nc("Gregorian weekday 7 - KLocale::NarrowName ", "S").toString(languages); default: return QString(); } } if (format == KLocale::ShortName || format == KLocale:: ShortNumber) { switch (weekDay) { case 1: return ki18nc("Gregorian weekday 1 - KLocale::ShortName", "Mon").toString(languages); case 2: return ki18nc("Gregorian weekday 2 - KLocale::ShortName", "Tue").toString(languages); case 3: return ki18nc("Gregorian weekday 3 - KLocale::ShortName", "Wed").toString(languages); case 4: return ki18nc("Gregorian weekday 4 - KLocale::ShortName", "Thu").toString(languages); case 5: return ki18nc("Gregorian weekday 5 - KLocale::ShortName", "Fri").toString(languages); case 6: return ki18nc("Gregorian weekday 6 - KLocale::ShortName", "Sat").toString(languages); case 7: return ki18nc("Gregorian weekday 7 - KLocale::ShortName", "Sun").toString(languages); default: return QString(); } } switch (weekDay) { case 1: return ki18nc("Gregorian weekday 1 - KLocale::LongName", "Monday").toString(languages); case 2: return ki18nc("Gregorian weekday 2 - KLocale::LongName", "Tuesday").toString(languages); case 3: return ki18nc("Gregorian weekday 3 - KLocale::LongName", "Wednesday").toString(languages); case 4: return ki18nc("Gregorian weekday 4 - KLocale::LongName", "Thursday").toString(languages); case 5: return ki18nc("Gregorian weekday 5 - KLocale::LongName", "Friday").toString(languages); case 6: return ki18nc("Gregorian weekday 6 - KLocale::LongName", "Saturday").toString(languages); case 7: return ki18nc("Gregorian weekday 7 - KLocale::LongName", "Sunday").toString(languages); default: return QString(); } } KCalendarSystemHebrew::KCalendarSystemHebrew(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(*new KCalendarSystemHebrewPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemHebrew::KCalendarSystemHebrew(KCalendarSystemHebrewPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemHebrew::~KCalendarSystemHebrew() { } QString KCalendarSystemHebrew::calendarType() const { return QLatin1String("hebrew"); } KLocale::CalendarSystem KCalendarSystemHebrew::calendarSystem() const { return KLocale::HebrewCalendar; } QDate KCalendarSystemHebrew::epoch() const { // Hebrew 0001-01-01 (Gregorian -3760-09-07, Julian -3761-10-07) return QDate::fromJulianDay(347998); } QDate KCalendarSystemHebrew::earliestValidDate() const { // Current formulas using direct Gregorian <-> Hebrew conversion using Qt // will return invalid results prior to the Gregorian switchover in 1582 // Next valid Hebrew year starts 5344-01-01 (Gregorian 1583-09-17) return QDate::fromJulianDay(2299498); } QDate KCalendarSystemHebrew::latestValidDate() const { // Testing shows current formulas only work up to 8119-13-29 (Gregorian 4359-10-07) return QDate::fromJulianDay(3313431); } QString KCalendarSystemHebrew::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystem::monthName(month, year, format); } QString KCalendarSystemHebrew::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystem::monthName(date, format); } QString KCalendarSystemHebrew::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(weekDay, format); } QString KCalendarSystemHebrew::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(date, format); } int KCalendarSystemHebrew::yearStringToInteger(const QString &string, int &readLength) const { int result = KCalendarSystem::yearStringToInteger(string, readLength); // Hebrew has no letter for 0, so 5 and 5000 are written the same // Assume if less than 10 then we are in an exact multiple of 1000 if (result < 10) { result = result * 1000; } // Not good just assuming, make configurable if (result < 1000) { result += 5000; // assume we're in the 6th millenium (y6k bug) } return result; } bool KCalendarSystemHebrew::isLunar() const { return false; } bool KCalendarSystemHebrew::isLunisolar() const { return true; } bool KCalendarSystemHebrew::isSolar() const { return false; } bool KCalendarSystemHebrew::isProleptic() const { return false; } bool KCalendarSystemHebrew::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { class h_date *sd = toHebrew(QDate::fromJulianDay(jd)); year = sd->hd_year; month = sd->hd_mon; if (isLeapYear(sd->hd_year)) { if (month == 13 /*AdarI*/) { month = 6; } else if (month == 14 /*AdarII*/) { month = 7; } else if (month > 6 && month < 13) { ++month; } } day = sd->hd_day; return true; } bool KCalendarSystemHebrew::dateToJulianDay(int year, int month, int day, qint64 &jd) const { class h_date *gd = hebrewToGregorian(year, month, day); QDate tempDate(gd->hd_year, gd->hd_mon + 1, gd->hd_day + 1); jd = tempDate.toJulianDay(); return true; } diff --git a/src/kdecore/kcalendarsystemhebrew_p.h b/src/kdecore/kcalendarsystemhebrew_p.h index 9f8c7522..50176d59 100644 --- a/src/kdecore/kcalendarsystemhebrew_p.h +++ b/src/kdecore/kcalendarsystemhebrew_p.h @@ -1,76 +1,76 @@ /* Copyright (c) 2002-2003 Carlos Moro Copyright (c) 2002-2003 Hans Petter Bieker Copyright 2007, 2010 John Layt Calendar conversion routines based on Hdate v6, by Amos Shapir 1978 (rev. 1985, 1992) 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 KCALENDARSYSTEMHEBREW_H #define KCALENDARSYSTEMHEBREW_H #include "kcalendarsystem.h" class KCalendarSystemHebrewPrivate; /** * @internal * This is the Hebrew calendar implementation. * * The Hebrew calendar is the traditional calendar used by the Jewish faith * * @see KLocale,KCalendarSystem,KCalendarSystemFactory * * @author Hans Petter Bieker */ class KCalendarSystemHebrew : public KCalendarSystem { public: - explicit KCalendarSystemHebrew(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemHebrew(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemHebrew(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; int yearStringToInteger(const QString &sNum, int &iLength) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 js, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemHebrew(KCalendarSystemHebrewPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemHebrew) }; #endif // KCALENDARSYSTEMHEBREW_H diff --git a/src/kdecore/kcalendarsystemindiannational.cpp b/src/kdecore/kcalendarsystemindiannational.cpp index 47eb6565..075e7ac6 100644 --- a/src/kdecore/kcalendarsystemindiannational.cpp +++ b/src/kdecore/kcalendarsystemindiannational.cpp @@ -1,508 +1,508 @@ /* Copyright 2009, 2010 John Layt 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. */ #include "kcalendarsystemindiannational_p.h" #include "kcalendarsystemprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include #include class KCalendarSystemIndianNationalPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemIndianNationalPrivate(KCalendarSystemIndianNational *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemIndianNationalPrivate(KCalendarSystemIndianNational *q); virtual ~KCalendarSystemIndianNationalPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; }; // Shared d pointer base class definitions KCalendarSystemIndianNationalPrivate::KCalendarSystemIndianNationalPrivate(KCalendarSystemIndianNational *q) : KCalendarSystemPrivate(q) { } KCalendarSystemIndianNationalPrivate::~KCalendarSystemIndianNationalPrivate() { } void KCalendarSystemIndianNationalPrivate::loadDefaultEraList() { QString name, shortName, format; // Saka Era name = i18nc("Calendar Era: Indian National Saka Era, years > 0, LongFormat", "Saka Era"); shortName = i18nc("Calendar Era: Indian National Saka Era, years > 0, ShortFormat", "SE"); format = i18nc("(kdedt-format) Indian National, SE, full era year format used for %EY, e.g. 2000 SE", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemIndianNationalPrivate::monthsInYear(int year) const { Q_UNUSED(year) return 12; } int KCalendarSystemIndianNationalPrivate::daysInMonth(int year, int month) const { if (month == 1) { if (isLeapYear(year)) { return 31; } else { return 30; } } if (month >= 2 && month <= 6) { return 31; } return 30; } int KCalendarSystemIndianNationalPrivate::daysInYear(int year) const { if (isLeapYear(year)) { return 366; } else { return 365; } } bool KCalendarSystemIndianNationalPrivate::isLeapYear(int year) const { - //Uses same rule as Gregorian, and is explicitly synchronized to Gregorian + //Uses same rule as Gregorian, and is KDELIBS4SUPPORT_DEPRECATED explicitly synchronized to Gregorian //so add 78 years to get Gregorian year and apply Gregorian calculation year = year + 78; if (!hasYearZero() && year < 1) { year = year + 1; } if (year % 4 == 0) { if (year % 100 != 0) { return true; } else if (year % 400 == 0) { return true; } } return false; } bool KCalendarSystemIndianNationalPrivate::hasLeapMonths() const { return false; } bool KCalendarSystemIndianNationalPrivate::hasYearZero() const { return true; } int KCalendarSystemIndianNationalPrivate::maxMonthsInYear() const { return 12; } int KCalendarSystemIndianNationalPrivate::earliestValidYear() const { return 0; } int KCalendarSystemIndianNationalPrivate::latestValidYear() const { return 9999; } QString KCalendarSystemIndianNationalPrivate::monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const { Q_UNUSED(year); QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (month) { case 1: return ki18nc("Indian National month 1 - KLocale::NarrowName", "C").toString(languages); case 2: return ki18nc("Indian National month 2 - KLocale::NarrowName", "V").toString(languages); case 3: return ki18nc("Indian National month 3 - KLocale::NarrowName", "J").toString(languages); case 4: return ki18nc("Indian National month 4 - KLocale::NarrowName", "Ā").toString(languages); case 5: return ki18nc("Indian National month 5 - KLocale::NarrowName", "S").toString(languages); case 6: return ki18nc("Indian National month 6 - KLocale::NarrowName", "B").toString(languages); case 7: return ki18nc("Indian National month 7 - KLocale::NarrowName", "Ā").toString(languages); case 8: return ki18nc("Indian National month 8 - KLocale::NarrowName", "K").toString(languages); case 9: return ki18nc("Indian National month 9 - KLocale::NarrowName", "A").toString(languages); case 10: return ki18nc("Indian National month 10 - KLocale::NarrowName", "P").toString(languages); case 11: return ki18nc("Indian National month 11 - KLocale::NarrowName", "M").toString(languages); case 12: return ki18nc("Indian National month 12 - KLocale::NarrowName", "P").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && possessive) { switch (month) { case 1: return ki18nc("Indian National month 1 - KLocale::ShortName Possessive", "of Cha").toString(languages); case 2: return ki18nc("Indian National month 2 - KLocale::ShortName Possessive", "of Vai").toString(languages); case 3: return ki18nc("Indian National month 3 - KLocale::ShortName Possessive", "of Jya").toString(languages); case 4: return ki18nc("Indian National month 4 - KLocale::ShortName Possessive", "of Āsh").toString(languages); case 5: return ki18nc("Indian National month 5 - KLocale::ShortName Possessive", "of Shr").toString(languages); case 6: return ki18nc("Indian National month 6 - KLocale::ShortName Possessive", "of Bhā").toString(languages); case 7: return ki18nc("Indian National month 7 - KLocale::ShortName Possessive", "of Āsw").toString(languages); case 8: return ki18nc("Indian National month 8 - KLocale::ShortName Possessive", "of Kār").toString(languages); case 9: return ki18nc("Indian National month 9 - KLocale::ShortName Possessive", "of Agr").toString(languages); case 10: return ki18nc("Indian National month 10 - KLocale::ShortName Possessive", "of Pau").toString(languages); case 11: return ki18nc("Indian National month 11 - KLocale::ShortName Possessive", "of Māg").toString(languages); case 12: return ki18nc("Indian National month 12 - KLocale::ShortName Possessive", "of Phā").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && !possessive) { switch (month) { case 1: return ki18nc("Indian National month 1 - KLocale::ShortName", "Cha").toString(languages); case 2: return ki18nc("Indian National month 2 - KLocale::ShortName", "Vai").toString(languages); case 3: return ki18nc("Indian National month 3 - KLocale::ShortName", "Jya").toString(languages); case 4: return ki18nc("Indian National month 4 - KLocale::ShortName", "Āsh").toString(languages); case 5: return ki18nc("Indian National month 5 - KLocale::ShortName", "Shr").toString(languages); case 6: return ki18nc("Indian National month 6 - KLocale::ShortName", "Bhā").toString(languages); case 7: return ki18nc("Indian National month 7 - KLocale::ShortName", "Āsw").toString(languages); case 8: return ki18nc("Indian National month 8 - KLocale::ShortName", "Kār").toString(languages); case 9: return ki18nc("Indian National month 9 - KLocale::ShortName", "Agr").toString(languages); case 10: return ki18nc("Indian National month 10 - KLocale::ShortName", "Pau").toString(languages); case 11: return ki18nc("Indian National month 11 - KLocale::ShortName", "Māg").toString(languages); case 12: return ki18nc("Indian National month 12 - KLocale::ShortName", "Phā").toString(languages); default: return QString(); } } if (format == KLocale::LongName && possessive) { switch (month) { case 1: return ki18nc("Indian National month 1 - KLocale::LongName Possessive", "of Chaitra").toString(languages); case 2: return ki18nc("Indian National month 2 - KLocale::LongName Possessive", "of Vaishākh").toString(languages); case 3: return ki18nc("Indian National month 3 - KLocale::LongName Possessive", "of Jyaishtha").toString(languages); case 4: return ki18nc("Indian National month 4 - KLocale::LongName Possessive", "of Āshādha").toString(languages); case 5: return ki18nc("Indian National month 5 - KLocale::LongName Possessive", "of Shrāvana").toString(languages); case 6: return ki18nc("Indian National month 6 - KLocale::LongName Possessive", "of Bhādrapad").toString(languages); case 7: return ki18nc("Indian National month 7 - KLocale::LongName Possessive", "of Āshwin").toString(languages); case 8: return ki18nc("Indian National month 8 - KLocale::LongName Possessive", "of Kārtik").toString(languages); case 9: return ki18nc("Indian National month 9 - KLocale::LongName Possessive", "of Agrahayana").toString(languages); case 10: return ki18nc("Indian National month 10 - KLocale::LongName Possessive", "of Paush").toString(languages); case 11: return ki18nc("Indian National month 11 - KLocale::LongName Possessive", "of Māgh").toString(languages); case 12: return ki18nc("Indian National month 12 - KLocale::LongName Possessive", "of Phālgun").toString(languages); default: return QString(); } } // Default to LongName switch (month) { case 1: return ki18nc("Indian National month 1 - KLocale::LongName", "Chaitra").toString(languages); case 2: return ki18nc("Indian National month 2 - KLocale::LongName", "Vaishākh").toString(languages); case 3: return ki18nc("Indian National month 3 - KLocale::LongName", "Jyaishtha").toString(languages); case 4: return ki18nc("Indian National month 4 - KLocale::LongName", "Āshādha").toString(languages); case 5: return ki18nc("Indian National month 5 - KLocale::LongName", "Shrāvana").toString(languages); case 6: return ki18nc("Indian National month 6 - KLocale::LongName", "Bhādrapad").toString(languages); case 7: return ki18nc("Indian National month 7 - KLocale::LongName", "Āshwin").toString(languages); case 8: return ki18nc("Indian National month 8 - KLocale::LongName", "Kārtik").toString(languages); case 9: return ki18nc("Indian National month 9 - KLocale::LongName", "Agrahayana").toString(languages); case 10: return ki18nc("Indian National month 10 - KLocale::LongName", "Paush").toString(languages); case 11: return ki18nc("Indian National month 11 - KLocale::LongName", "Māgh").toString(languages); case 12: return ki18nc("Indian National month 12 - KLocale::LongName", "Phālgun").toString(languages); default: return QString(); } } QString KCalendarSystemIndianNationalPrivate::weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const { QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (weekDay) { case 1: return ki18nc("Indian National weekday 1 - KLocale::NarrowName ", "S").toString(languages); case 2: return ki18nc("Indian National weekday 2 - KLocale::NarrowName ", "M").toString(languages); case 3: return ki18nc("Indian National weekday 3 - KLocale::NarrowName ", "B").toString(languages); case 4: return ki18nc("Indian National weekday 4 - KLocale::NarrowName ", "G").toString(languages); case 5: return ki18nc("Indian National weekday 5 - KLocale::NarrowName ", "S").toString(languages); case 6: return ki18nc("Indian National weekday 6 - KLocale::NarrowName ", "S").toString(languages); case 7: return ki18nc("Indian National weekday 7 - KLocale::NarrowName ", "R").toString(languages); default: return QString(); } } if (format == KLocale::ShortName || format == KLocale:: ShortNumber) { switch (weekDay) { case 1: return ki18nc("Indian National weekday 1 - KLocale::ShortName", "Som").toString(languages); case 2: return ki18nc("Indian National weekday 2 - KLocale::ShortName", "Mañ").toString(languages); case 3: return ki18nc("Indian National weekday 3 - KLocale::ShortName", "Bud").toString(languages); case 4: return ki18nc("Indian National weekday 4 - KLocale::ShortName", "Gur").toString(languages); case 5: return ki18nc("Indian National weekday 5 - KLocale::ShortName", "Suk").toString(languages); case 6: return ki18nc("Indian National weekday 6 - KLocale::ShortName", "San").toString(languages); case 7: return ki18nc("Indian National weekday 7 - KLocale::ShortName", "Rav").toString(languages); default: return QString(); } } switch (weekDay) { case 1: return ki18nc("Indian National weekday 1 - KLocale::LongName", "Somavãra").toString(languages); case 2: return ki18nc("Indian National weekday 2 - KLocale::LongName", "Mañgalvã").toString(languages); case 3: return ki18nc("Indian National weekday 3 - KLocale::LongName", "Budhavãra").toString(languages); case 4: return ki18nc("Indian National weekday 4 - KLocale::LongName", "Guruvãra").toString(languages); case 5: return ki18nc("Indian National weekday 5 - KLocale::LongName", "Sukravãra").toString(languages); case 6: return ki18nc("Indian National weekday 6 - KLocale::LongName", "Sanivãra").toString(languages); case 7: return ki18nc("Indian National weekday 7 - KLocale::LongName", "Raviãra").toString(languages); default: return QString(); } } KCalendarSystemIndianNational::KCalendarSystemIndianNational(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(*new KCalendarSystemIndianNationalPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemIndianNational::KCalendarSystemIndianNational(KCalendarSystemIndianNationalPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemIndianNational::~KCalendarSystemIndianNational() { } QString KCalendarSystemIndianNational::calendarType() const { return QLatin1String("indian-national"); } KLocale::CalendarSystem KCalendarSystemIndianNational::calendarSystem() const { return KLocale::IndianNationalCalendar; } QDate KCalendarSystemIndianNational::epoch() const { //0000-01-01, has Year 0. //0078-03-22 AD Gregorian / 0078-03-24 AD Julian return QDate::fromJulianDay(1749994); } QDate KCalendarSystemIndianNational::earliestValidDate() const { //0000-01-01, has Year 0. //0078-03-22 AD Gregorian / 0078-03-24 AD Julian //Don't do proleptic yet, need to check return QDate::fromJulianDay(1749630); } QDate KCalendarSystemIndianNational::latestValidDate() const { // Set to last day of year 9999 until confirm date formats & widgets support > 9999 //9999-12-30 //10078-03-21 AD Gregorian return QDate::fromJulianDay(5402054); } QString KCalendarSystemIndianNational::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystem::monthName(month, year, format); } QString KCalendarSystemIndianNational::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystem::monthName(date, format); } QString KCalendarSystemIndianNational::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(weekDay, format); } QString KCalendarSystemIndianNational::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(date, format); } bool KCalendarSystemIndianNational::isLunar() const { return false; } bool KCalendarSystemIndianNational::isLunisolar() const { return true; } bool KCalendarSystemIndianNational::isSolar() const { return false; } bool KCalendarSystemIndianNational::isProleptic() const { return false; } bool KCalendarSystemIndianNational::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { int L, N, I, J, D, M, Y; // "Explanatory Supplement to the Astronomical Almanac" 2006 section 12.94 pp 605-606 // Originally from "Report of the Calendar Reform Committee" 1955 L = jd + 68518; N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; I = (4000 * (L + 1)) / 1461001; L = L - (1461 * I) / 4 + 1; J = ((L - 1) / 31) * (1 - L / 185) + (L / 185) * ((L - 156) / 30 + 5) - L / 366; D = L - 31 * J + ((J + 2) / 8) * (J - 5); L = J / 11; M = J + 2 - 12 * L; Y = 100 * (N - 49) + L + I - 78; day = D; month = M; year = Y; return true; } bool KCalendarSystemIndianNational::dateToJulianDay(int year, int month, int day, qint64 &jd) const { int Y = year; int M = month; int D = day; // "Explanatory Supplement to the Astronomical Almanac" 2006 section 12.94 pp 605-606 // Originally from "Report of the Calendar Reform Committee" 1955 jd = 365 * Y + (Y + 78 - 1 / M) / 4 + 31 * M - (M + 9) / 11 - (M / 7) * (M - 7) - (3 * ((Y + 78 - 1 / M) / 100 + 1)) / 4 + D + 1749579; return true; } diff --git a/src/kdecore/kcalendarsystemindiannational_p.h b/src/kdecore/kcalendarsystemindiannational_p.h index 533a83df..222d1541 100644 --- a/src/kdecore/kcalendarsystemindiannational_p.h +++ b/src/kdecore/kcalendarsystemindiannational_p.h @@ -1,74 +1,74 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMINDIANNATIONAL_H #define KCALENDARSYSTEMINDIANNATIONAL_H #include "kcalendarsystem.h" class KCalendarSystemIndianNationalPrivate; /** * @internal * This is the Indian National / Civil / Saka calendar implementation. * * Note: This is is the purely civil arithmetic calendar, the religious * versions of the calendar will be implemented separately once * astronomical calendars are implemented. * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemIndianNational: public KCalendarSystem { public: - explicit KCalendarSystemIndianNational(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemIndianNational(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemIndianNational(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemIndianNational(KCalendarSystemIndianNationalPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemIndianNational) }; #endif // KCALENDARSYSTEMINDIANNATIONAL_H diff --git a/src/kdecore/kcalendarsystemislamiccivil.cpp b/src/kdecore/kcalendarsystemislamiccivil.cpp index 14be3e2b..5dda6da9 100644 --- a/src/kdecore/kcalendarsystemislamiccivil.cpp +++ b/src/kdecore/kcalendarsystemislamiccivil.cpp @@ -1,557 +1,557 @@ /* Copyright (c) 2002-2003 Carlos Moro Copyright (c) 2002-2003 Hans Petter Bieker Copyright 2007, 2008, 2009, 2010 John Layt 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. */ #include "kcalendarsystemislamiccivil_p.h" #include "kcalendarsystemprivate_p.h" #include #include class KCalendarSystemIslamicCivilPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemIslamicCivilPrivate(KCalendarSystemIslamicCivil *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemIslamicCivilPrivate(KCalendarSystemIslamicCivil *q); virtual ~KCalendarSystemIslamicCivilPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; }; // Shared d pointer base class definitions KCalendarSystemIslamicCivilPrivate::KCalendarSystemIslamicCivilPrivate(KCalendarSystemIslamicCivil *q) : KCalendarSystemPrivate(q) { } KCalendarSystemIslamicCivilPrivate::~KCalendarSystemIslamicCivilPrivate() { } void KCalendarSystemIslamicCivilPrivate::loadDefaultEraList() { QString name, shortName, format; // Islamic Era, Anno Hegirae, "Year of the Hijra". name = i18nc("Calendar Era: Hijri Islamic Era, years > 0, LongFormat", "Anno Hegirae"); shortName = i18nc("Calendar Era: Hijri Islamic Era, years > 0, ShortFormat", "AH"); format = i18nc("(kdedt-format) Hijri, AH, full era year format used for %EY, e.g. 2000 AH", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemIslamicCivilPrivate::monthsInYear(int year) const { Q_UNUSED(year) return 12; } int KCalendarSystemIslamicCivilPrivate::daysInMonth(int year, int month) const { if (month == 12 && isLeapYear(year)) { return 30; } if (month % 2 == 0) { // Even number months have 29 days return 29; } else { // Odd number months have 30 days return 30; } } int KCalendarSystemIslamicCivilPrivate::daysInYear(int year) const { if (isLeapYear(year)) { return 355; } else { return 354; } } bool KCalendarSystemIslamicCivilPrivate::isLeapYear(int year) const { // Years 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, 29 of the 30 year cycle /* The following C++ code is translated from the Lisp code in ``Calendrical Calculations'' by Nachum Dershowitz and Edward M. Reingold, Software---Practice & Experience, vol. 20, no. 9 (September, 1990), pp. 899--928. This code is in the public domain, but any use of it should publically acknowledge its source. */ if ((((11 * year) + 14) % 30) < 11) { return true; } else { return false; } // The following variations will be implemented in separate classes in 4.5 // May be cleaner to formally define using a case statement switch on (year % 30) // Variation used by Bar Habraeus / Graves / Birashk / Some Microsoft products // Years 2, 5, 7, 10, 13, 15, 18, 21, 24, 26, 29 of the 30 year cycle // if ( ( ( ( 11 * year ) + 15 ) % 30 ) < 11 ) { // Variation used by Bohras / Sahifa with epoch 15 July 622 jd = 1948440 // Years 2, 5, 8, 10, 13, 16, 19, 21, 24, 27, 29 of the 30 year cycle // if ( ( ( ( 11 * year ) + 1 ) % 30 ) < 11 ) { } bool KCalendarSystemIslamicCivilPrivate::hasLeapMonths() const { return false; } bool KCalendarSystemIslamicCivilPrivate::hasYearZero() const { return false; } int KCalendarSystemIslamicCivilPrivate::maxMonthsInYear() const { return 12; } int KCalendarSystemIslamicCivilPrivate::earliestValidYear() const { return 1; } int KCalendarSystemIslamicCivilPrivate::latestValidYear() const { return 9999; } QString KCalendarSystemIslamicCivilPrivate::monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const { Q_UNUSED(year); QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (month) { case 1: return ki18nc("Hijri month 1 - KLocale::NarrowName", "M").toString(languages); case 2: return ki18nc("Hijri month 2 - KLocale::NarrowName", "S").toString(languages); case 3: return ki18nc("Hijri month 3 - KLocale::NarrowName", "A").toString(languages); case 4: return ki18nc("Hijri month 4 - KLocale::NarrowName", "T").toString(languages); case 5: return ki18nc("Hijri month 5 - KLocale::NarrowName", "A").toString(languages); case 6: return ki18nc("Hijri month 6 - KLocale::NarrowName", "T").toString(languages); case 7: return ki18nc("Hijri month 7 - KLocale::NarrowName", "R").toString(languages); case 8: return ki18nc("Hijri month 8 - KLocale::NarrowName", "S").toString(languages); case 9: return ki18nc("Hijri month 9 - KLocale::NarrowName", "R").toString(languages); case 10: return ki18nc("Hijri month 10 - KLocale::NarrowName", "S").toString(languages); case 11: return ki18nc("Hijri month 11 - KLocale::NarrowName", "Q").toString(languages); case 12: return ki18nc("Hijri month 12 - KLocale::NarrowName", "H").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && possessive) { switch (month) { case 1: return ki18nc("Hijri month 1 - KLocale::ShortName Possessive", "of Muh").toString(languages); case 2: return ki18nc("Hijri month 2 - KLocale::ShortName Possessive", "of Saf").toString(languages); case 3: return ki18nc("Hijri month 3 - KLocale::ShortName Possessive", "of R.A").toString(languages); case 4: return ki18nc("Hijri month 4 - KLocale::ShortName Possessive", "of R.T").toString(languages); case 5: return ki18nc("Hijri month 5 - KLocale::ShortName Possessive", "of J.A").toString(languages); case 6: return ki18nc("Hijri month 6 - KLocale::ShortName Possessive", "of J.T").toString(languages); case 7: return ki18nc("Hijri month 7 - KLocale::ShortName Possessive", "of Raj").toString(languages); case 8: return ki18nc("Hijri month 8 - KLocale::ShortName Possessive", "of Sha").toString(languages); case 9: return ki18nc("Hijri month 9 - KLocale::ShortName Possessive", "of Ram").toString(languages); case 10: return ki18nc("Hijri month 10 - KLocale::ShortName Possessive", "of Shw").toString(languages); case 11: return ki18nc("Hijri month 11 - KLocale::ShortName Possessive", "of Qid").toString(languages); case 12: return ki18nc("Hijri month 12 - KLocale::ShortName Possessive", "of Hij").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && !possessive) { switch (month) { case 1: return ki18nc("Hijri month 1 - KLocale::ShortName", "Muh").toString(languages); case 2: return ki18nc("Hijri month 2 - KLocale::ShortName", "Saf").toString(languages); case 3: return ki18nc("Hijri month 3 - KLocale::ShortName", "R.A").toString(languages); case 4: return ki18nc("Hijri month 4 - KLocale::ShortName", "R.T").toString(languages); case 5: return ki18nc("Hijri month 5 - KLocale::ShortName", "J.A").toString(languages); case 6: return ki18nc("Hijri month 6 - KLocale::ShortName", "J.T").toString(languages); case 7: return ki18nc("Hijri month 7 - KLocale::ShortName", "Raj").toString(languages); case 8: return ki18nc("Hijri month 8 - KLocale::ShortName", "Sha").toString(languages); case 9: return ki18nc("Hijri month 9 - KLocale::ShortName", "Ram").toString(languages); case 10: return ki18nc("Hijri month 10 - KLocale::ShortName", "Shw").toString(languages); case 11: return ki18nc("Hijri month 11 - KLocale::ShortName", "Qid").toString(languages); case 12: return ki18nc("Hijri month 12 - KLocale::ShortName", "Hij").toString(languages); default: return QString(); } } if (format == KLocale::LongName && possessive) { switch (month) { case 1: return ki18nc("Hijri month 1 - KLocale::LongName Possessive", "of Muharram").toString(languages); case 2: return ki18nc("Hijri month 2 - KLocale::LongName Possessive", "of Safar").toString(languages); case 3: return ki18nc("Hijri month 3 - KLocale::LongName Possessive", "of Rabi` al-Awal").toString(languages); case 4: return ki18nc("Hijri month 4 - KLocale::LongName Possessive", "of Rabi` al-Thaani").toString(languages); case 5: return ki18nc("Hijri month 5 - KLocale::LongName Possessive", "of Jumaada al-Awal").toString(languages); case 6: return ki18nc("Hijri month 6 - KLocale::LongName Possessive", "of Jumaada al-Thaani").toString(languages); case 7: return ki18nc("Hijri month 7 - KLocale::LongName Possessive", "of Rajab").toString(languages); case 8: return ki18nc("Hijri month 8 - KLocale::LongName Possessive", "of Sha`ban").toString(languages); case 9: return ki18nc("Hijri month 9 - KLocale::LongName Possessive", "of Ramadan").toString(languages); case 10: return ki18nc("Hijri month 10 - KLocale::LongName Possessive", "of Shawwal").toString(languages); case 11: return ki18nc("Hijri month 11 - KLocale::LongName Possessive", "of Thu al-Qi`dah").toString(languages); case 12: return ki18nc("Hijri month 12 - KLocale::LongName Possessive", "of Thu al-Hijjah").toString(languages); default: return QString(); } } // Default to LongName switch (month) { case 1: return ki18nc("Hijri month 1 - KLocale::LongName", "Muharram").toString(languages); case 2: return ki18nc("Hijri month 2 - KLocale::LongName", "Safar").toString(languages); case 3: return ki18nc("Hijri month 3 - KLocale::LongName", "Rabi` al-Awal").toString(languages); case 4: return ki18nc("Hijri month 4 - KLocale::LongName", "Rabi` al-Thaani").toString(languages); case 5: return ki18nc("Hijri month 5 - KLocale::LongName", "Jumaada al-Awal").toString(languages); case 6: return ki18nc("Hijri month 6 - KLocale::LongName", "Jumaada al-Thaani").toString(languages); case 7: return ki18nc("Hijri month 7 - KLocale::LongName", "Rajab").toString(languages); case 8: return ki18nc("Hijri month 8 - KLocale::LongName", "Sha`ban").toString(languages); case 9: return ki18nc("Hijri month 9 - KLocale::LongName", "Ramadan").toString(languages); case 10: return ki18nc("Hijri month 10 - KLocale::LongName", "Shawwal").toString(languages); case 11: return ki18nc("Hijri month 11 - KLocale::LongName", "Thu al-Qi`dah").toString(languages); case 12: return ki18nc("Hijri month 12 - KLocale::LongName", "Thu al-Hijjah").toString(languages); default: return QString(); } } QString KCalendarSystemIslamicCivilPrivate::weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const { QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (weekDay) { case 1: return ki18nc("Hijri weekday 1 - KLocale::NarrowName ", "I").toString(languages); case 2: return ki18nc("Hijri weekday 2 - KLocale::NarrowName ", "T").toString(languages); case 3: return ki18nc("Hijri weekday 3 - KLocale::NarrowName ", "A").toString(languages); case 4: return ki18nc("Hijri weekday 4 - KLocale::NarrowName ", "K").toString(languages); case 5: return ki18nc("Hijri weekday 5 - KLocale::NarrowName ", "J").toString(languages); case 6: return ki18nc("Hijri weekday 6 - KLocale::NarrowName ", "S").toString(languages); case 7: return ki18nc("Hijri weekday 7 - KLocale::NarrowName ", "A").toString(languages); default: return QString(); } } if (format == KLocale::ShortName || format == KLocale:: ShortNumber) { switch (weekDay) { case 1: return ki18nc("Hijri weekday 1 - KLocale::ShortName", "Ith").toString(languages); case 2: return ki18nc("Hijri weekday 2 - KLocale::ShortName", "Thl").toString(languages); case 3: return ki18nc("Hijri weekday 3 - KLocale::ShortName", "Arb").toString(languages); case 4: return ki18nc("Hijri weekday 4 - KLocale::ShortName", "Kha").toString(languages); case 5: return ki18nc("Hijri weekday 5 - KLocale::ShortName", "Jum").toString(languages); case 6: return ki18nc("Hijri weekday 6 - KLocale::ShortName", "Sab").toString(languages); case 7: return ki18nc("Hijri weekday 7 - KLocale::ShortName", "Ahd").toString(languages); default: return QString(); } } switch (weekDay) { case 1: return ki18nc("Hijri weekday 1 - KLocale::LongName", "Yaum al-Ithnain").toString(languages); case 2: return ki18nc("Hijri weekday 2 - KLocale::LongName", "Yau al-Thulatha").toString(languages); case 3: return ki18nc("Hijri weekday 3 - KLocale::LongName", "Yaum al-Arbi'a").toString(languages); case 4: return ki18nc("Hijri weekday 4 - KLocale::LongName", "Yaum al-Khamees").toString(languages); case 5: return ki18nc("Hijri weekday 5 - KLocale::LongName", "Yaum al-Jumma").toString(languages); case 6: return ki18nc("Hijri weekday 6 - KLocale::LongName", "Yaum al-Sabt").toString(languages); case 7: return ki18nc("Hijri weekday 7 - KLocale::LongName", "Yaum al-Ahad").toString(languages); default: return QString(); } } KCalendarSystemIslamicCivil::KCalendarSystemIslamicCivil(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(*new KCalendarSystemIslamicCivilPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemIslamicCivil::KCalendarSystemIslamicCivil(KCalendarSystemIslamicCivilPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemIslamicCivil::~KCalendarSystemIslamicCivil() { } QString KCalendarSystemIslamicCivil::calendarType() const { return QLatin1String("hijri"); } KLocale::CalendarSystem KCalendarSystemIslamicCivil::calendarSystem() const { return KLocale::IslamicCivilCalendar; } QDate KCalendarSystemIslamicCivil::epoch() const { // 16 July 622 in the Julian calendar return QDate::fromJulianDay(1948440); } QDate KCalendarSystemIslamicCivil::earliestValidDate() const { return epoch(); } QDate KCalendarSystemIslamicCivil::latestValidDate() const { // Set to last day of year 9999 // Last day of Islamic Civil year 9999 is 9999-12-29 return QDate::fromJulianDay(5491751); } QString KCalendarSystemIslamicCivil::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystem::monthName(month, year, format); } QString KCalendarSystemIslamicCivil::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystem::monthName(date, format); } QString KCalendarSystemIslamicCivil::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(weekDay, format); } QString KCalendarSystemIslamicCivil::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(date, format); } bool KCalendarSystemIslamicCivil::isLunar() const { return true; } bool KCalendarSystemIslamicCivil::isLunisolar() const { return false; } bool KCalendarSystemIslamicCivil::isSolar() const { return false; } bool KCalendarSystemIslamicCivil::isProleptic() const { return false; } bool KCalendarSystemIslamicCivil::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { Q_D(const KCalendarSystemIslamicCivil); /* The following C++ code is translated from the Lisp code in ``Calendrical Calculations'' by Nachum Dershowitz and Edward M. Reingold, Software---Practice & Experience, vol. 20, no. 9 (September, 1990), pp. 899--928. This code is in the public domain, but any use of it should publically acknowledge its source. */ // Search forward year by year from approximate year year = (jd - epoch().toJulianDay()) / 355; qint64 testJd; dateToJulianDay(year, 12, d->daysInMonth(year, 12), testJd); while (jd > testJd) { year++; dateToJulianDay(year, 12, d->daysInMonth(year, 12), testJd); } // Search forward month by month from Muharram month = 1; dateToJulianDay(year, month, d->daysInMonth(year, month), testJd); while (jd > testJd) { month++; dateToJulianDay(year, month, d->daysInMonth(year, month), testJd); } dateToJulianDay(year, month, 1, testJd); day = jd - testJd + 1; return true; // Alternative implementations // More recent editions of "Calendrical Calculations" by Dershowitz & Reingold have a more // efficient direct calculation without recusrion, but this cannot be used due to licensing /* Formula from "Explanatory Supplement to the Astronomical Almanac" 2006, derived from Fliegel & Van Flandern 1968 int L = jd - epoch().toJulianDay() + 10632; int N = ( L - 1 ) / 10631; L = L - 10631 * N + 354; int J = ( ( 10985 - L ) / 5316 ) x ( ( 50* L ) / 17719 ) + ( L / 5670 ) * ( ( 43 * L ) / 15238 ); L = L - ( ( 30 - J ) / 15 ) * ( ( 17719 * J ) / 50 ) - ( J / 16 ) * ( ( 15238 * J ) / 43 ) + 29; year = ( 30 * N ) + J - 30; month = ( 24 * L ) / 709; day = L - ( ( 709 * month ) / 24 ); */ /* Formula from Fourmilab website jd = Math.floor(jd) + 0.5; year = Math.floor(((30 * (jd - epoch().toJulianDay())) + 10646) / 10631); month = qMin(12, Math.ceil((jd - (29 + islamic_to_jd(year, 1, 1))) / 29.5) + 1); day = (jd - islamic_to_jd(year, month, 1)) + 1; */ } bool KCalendarSystemIslamicCivil::dateToJulianDay(int year, int month, int day, qint64 &jd) const { /* The following C++ code is translated from the Lisp code in ``Calendrical Calculations'' by Nachum Dershowitz and Edward M. Reingold, Software---Practice & Experience, vol. 20, no. 9 (September, 1990), pp. 899--928. This code is in the public domain, but any use of it should publically acknowledge its source. */ jd = epoch().toJulianDay() - 1 + // days before start of calendar (year - 1) * 354 + // non-leap days in prior years (3 + (11 * year)) / 30 + // leap days in prior years 29 * (month - 1) + // days so far... month / 2 + // ...this year day; // days so far this month return true; // Alternative implementations /* Formula from "Explanatory Supplement to the Astronomical Almanac" 2006, derived from Fliegel & Van Flandern 1968 jd = ( 3 + ( 11 * year ) ) / 30 + 354 * year + 30 * month - ( month - 1 ) / 2 + day + epoch().toJulianDay() - 385; */ } diff --git a/src/kdecore/kcalendarsystemislamiccivil_p.h b/src/kdecore/kcalendarsystemislamiccivil_p.h index 7f67b4d5..6c4647ba 100644 --- a/src/kdecore/kcalendarsystemislamiccivil_p.h +++ b/src/kdecore/kcalendarsystemislamiccivil_p.h @@ -1,76 +1,76 @@ /* Copyright (c) 2002 Carlos Moro Copyright (c) 2002-2003 Hans Petter Bieker Copyright 2007, 2010 John Layt 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 KCALENDARSYSTEMISLAMICCIVIL_H #define KCALENDARSYSTEMISLAMICCIVIL_H #include "kcalendarsystem.h" class KCalendarSystemIslamicCivilPrivate; /** * @internal * This is the Islamic Civil calendar implementation. * * The Islamic or Hijri calendar is the traditional calendar used in the Middle * East. This implementation is of the civil calculation that does not take * observed sunset into account and so may vary from actual dates by 1-2 days. * * @b license GNU-LGPL v2+ * * @see KLocale,KCalendarSystem * * @author Carlos Moro */ class KCalendarSystemIslamicCivil : public KCalendarSystem { public: - explicit KCalendarSystemIslamicCivil(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemIslamicCivil(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemIslamicCivil(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemIslamicCivil(KCalendarSystemIslamicCivilPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemIslamicCivil) }; #endif // KCALENDARSYSTEMISLAMICCIVIL_H diff --git a/src/kdecore/kcalendarsystemjalali.cpp b/src/kdecore/kcalendarsystemjalali.cpp index 1e073b0f..754c9673 100644 --- a/src/kdecore/kcalendarsystemjalali.cpp +++ b/src/kdecore/kcalendarsystemjalali.cpp @@ -1,587 +1,587 @@ /* Copyright (C) 2002-2003 Arash Bijanzadeh and FarsiKDE Project Contact: Arash Bijanzadeh Copyright 2007, 2008, 2009, 2010 John Layt 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. */ /* This is an implementation of the artithmetic Persian calendar using the Birashk algorithm with adjustments to always be correct in the period 1244 and 1530 (1865 to 2152 Gregorian). In future this will be replaced with the correct astronomical calendar. */ #include "kcalendarsystemjalali_p.h" #include "kcalendarsystemprivate_p.h" #include #include class KCalendarSystemJalaliPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemJalaliPrivate(KCalendarSystemJalali *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemJalaliPrivate(KCalendarSystemJalali *q); virtual ~KCalendarSystemJalaliPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; }; // Shared d pointer base class definitions KCalendarSystemJalaliPrivate::KCalendarSystemJalaliPrivate(KCalendarSystemJalali *q) : KCalendarSystemPrivate(q) { } KCalendarSystemJalaliPrivate::~KCalendarSystemJalaliPrivate() { } void KCalendarSystemJalaliPrivate::loadDefaultEraList() { QString name, shortName, format; // Islamic Era (Hijri), Anno Persico. name = i18nc("Calendar Era: Jalali Islamic Era, years > 0, LongFormat", "Anno Persico"); shortName = i18nc("Calendar Era: Jalali Islamic Era, years > 0, ShortFormat", "AP"); format = i18nc("(kdedt-format) Jalali, AP, full era year format used for %EY, e.g. 2000 AP", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemJalaliPrivate::monthsInYear(int year) const { Q_UNUSED(year) return 12; } int KCalendarSystemJalaliPrivate::daysInMonth(int year, int month) const { if (month == 12) { if (isLeapYear(year)) { return 30; } else { return 29; } } if (month <= 6) { return 31; } return 30; } int KCalendarSystemJalaliPrivate::daysInYear(int year) const { if (isLeapYear(year)) { return 366; } else { return 365; } } bool KCalendarSystemJalaliPrivate::isLeapYear(int year) const { // From formilab Public Domain code http://www.fourmilab.ch/documents/calendar/ // Use Birashk algorithm as it matches the to/from jd code below // Birashk algorithm is incorrect in two years in period AP 1244 to 1531, // 1403/1404 and 1436/1437, and so catch them here first if (year == 1403 || year == 1436) { return true; } else if (year == 1404 || year == 1437) { return false; } if (year >= 0) { year = year - 474; } else { year = year - 473; } if ((((((year % 2820) + 474) + 38) * 682) % 2816) < 682) { return true; } else { return false; } } bool KCalendarSystemJalaliPrivate::hasLeapMonths() const { return false; } bool KCalendarSystemJalaliPrivate::hasYearZero() const { return false; } int KCalendarSystemJalaliPrivate::maxMonthsInYear() const { return 12; } int KCalendarSystemJalaliPrivate::earliestValidYear() const { return 1244; } int KCalendarSystemJalaliPrivate::latestValidYear() const { return 1530; } QString KCalendarSystemJalaliPrivate::monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const { Q_UNUSED(year); QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (month) { case 1: return ki18nc("Jalali month 1 - KLocale::NarrowName", "F").toString(languages); case 2: return ki18nc("Jalali month 2 - KLocale::NarrowName", "O").toString(languages); case 3: return ki18nc("Jalali month 3 - KLocale::NarrowName", "K").toString(languages); case 4: return ki18nc("Jalali month 4 - KLocale::NarrowName", "T").toString(languages); case 5: return ki18nc("Jalali month 5 - KLocale::NarrowName", "M").toString(languages); case 6: return ki18nc("Jalali month 6 - KLocale::NarrowName", "S").toString(languages); case 7: return ki18nc("Jalali month 7 - KLocale::NarrowName", "M").toString(languages); case 8: return ki18nc("Jalali month 8 - KLocale::NarrowName", "A").toString(languages); case 9: return ki18nc("Jalali month 9 - KLocale::NarrowName", "A").toString(languages); case 10: return ki18nc("Jalali month 10 - KLocale::NarrowName", "D").toString(languages); case 11: return ki18nc("Jalali month 11 - KLocale::NarrowName", "B").toString(languages); case 12: return ki18nc("Jalali month 12 - KLocale::NarrowName", "E").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && possessive) { switch (month) { case 1: return ki18nc("Jalali month 1 - KLocale::ShortName Possessive", "of Far").toString(languages); case 2: return ki18nc("Jalali month 2 - KLocale::ShortName Possessive", "of Ord").toString(languages); case 3: return ki18nc("Jalali month 3 - KLocale::ShortName Possessive", "of Kho").toString(languages); case 4: return ki18nc("Jalali month 4 - KLocale::ShortName Possessive", "of Tir").toString(languages); case 5: return ki18nc("Jalali month 5 - KLocale::ShortName Possessive", "of Mor").toString(languages); case 6: return ki18nc("Jalali month 6 - KLocale::ShortName Possessive", "of Sha").toString(languages); case 7: return ki18nc("Jalali month 7 - KLocale::ShortName Possessive", "of Meh").toString(languages); case 8: return ki18nc("Jalali month 8 - KLocale::ShortName Possessive", "of Aba").toString(languages); case 9: return ki18nc("Jalali month 9 - KLocale::ShortName Possessive", "of Aza").toString(languages); case 10: return ki18nc("Jalali month 10 - KLocale::ShortName Possessive", "of Dei").toString(languages); case 11: return ki18nc("Jalali month 11 - KLocale::ShortName Possessive", "of Bah").toString(languages); case 12: return ki18nc("Jalali month 12 - KLocale::ShortName Possessive", "of Esf").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && !possessive) { switch (month) { case 1: return ki18nc("Jalali month 1 - KLocale::ShortName", "Far").toString(languages); case 2: return ki18nc("Jalali month 2 - KLocale::ShortName", "Ord").toString(languages); case 3: return ki18nc("Jalali month 3 - KLocale::ShortName", "Kho").toString(languages); case 4: return ki18nc("Jalali month 4 - KLocale::ShortName", "Tir").toString(languages); case 5: return ki18nc("Jalali month 5 - KLocale::ShortName", "Mor").toString(languages); case 6: return ki18nc("Jalali month 6 - KLocale::ShortName", "Sha").toString(languages); case 7: return ki18nc("Jalali month 7 - KLocale::ShortName", "Meh").toString(languages); case 8: return ki18nc("Jalali month 8 - KLocale::ShortName", "Aba").toString(languages); case 9: return ki18nc("Jalali month 9 - KLocale::ShortName", "Aza").toString(languages); case 10: return ki18nc("Jalali month 10 - KLocale::ShortName", "Dei").toString(languages); case 11: return ki18nc("Jalali month 11 - KLocale::ShortName", "Bah").toString(languages); case 12: return ki18nc("Jalali month 12 - KLocale::ShortName", "Esf").toString(languages); default: return QString(); } } if (format == KLocale::LongName && possessive) { switch (month) { case 1: return ki18nc("Jalali month 1 - KLocale::LongName Possessive", "of Farvardin").toString(languages); case 2: return ki18nc("Jalali month 2 - KLocale::LongName Possessive", "of Ordibehesht").toString(languages); case 3: return ki18nc("Jalali month 3 - KLocale::LongName Possessive", "of Khordad").toString(languages); case 4: return ki18nc("Jalali month 4 - KLocale::LongName Possessive", "of Tir").toString(languages); case 5: return ki18nc("Jalali month 5 - KLocale::LongName Possessive", "of Mordad").toString(languages); case 6: return ki18nc("Jalali month 6 - KLocale::LongName Possessive", "of Shahrivar").toString(languages); case 7: return ki18nc("Jalali month 7 - KLocale::LongName Possessive", "of Mehr").toString(languages); case 8: return ki18nc("Jalali month 8 - KLocale::LongName Possessive", "of Aban").toString(languages); case 9: return ki18nc("Jalali month 9 - KLocale::LongName Possessive", "of Azar").toString(languages); case 10: return ki18nc("Jalali month 10 - KLocale::LongName Possessive", "of Dei").toString(languages); case 11: return ki18nc("Jalali month 11 - KLocale::LongName Possessive", "of Bahman").toString(languages); case 12: return ki18nc("Jalali month 12 - KLocale::LongName Possessive", "of Esfand").toString(languages); default: return QString(); } } // Default to LongName switch (month) { case 1: return ki18nc("Jalali month 1 - KLocale::LongName", "Farvardin").toString(languages); case 2: return ki18nc("Jalali month 2 - KLocale::LongName", "Ordibehesht").toString(languages); case 3: return ki18nc("Jalali month 3 - KLocale::LongName", "Khordad").toString(languages); case 4: return ki18nc("Jalali month 4 - KLocale::LongName", "Tir").toString(languages); case 5: return ki18nc("Jalali month 5 - KLocale::LongName", "Mordad").toString(languages); case 6: return ki18nc("Jalali month 6 - KLocale::LongName", "Shahrivar").toString(languages); case 7: return ki18nc("Jalali month 7 - KLocale::LongName", "Mehr").toString(languages); case 8: return ki18nc("Jalali month 8 - KLocale::LongName", "Aban").toString(languages); case 9: return ki18nc("Jalali month 9 - KLocale::LongName", "Azar").toString(languages); case 10: return ki18nc("Jalali month 10 - KLocale::LongName", "Dei").toString(languages); case 11: return ki18nc("Jalali month 11 - KLocale::LongName", "Bahman").toString(languages); case 12: return ki18nc("Jalali month 12 - KLocale::LongName", "Esfand").toString(languages); default: return QString(); } } QString KCalendarSystemJalaliPrivate::weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const { QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (weekDay) { case 1: return ki18nc("Jalali weekday 1 - KLocale::NarrowName ", "2").toString(languages); case 2: return ki18nc("Jalali weekday 2 - KLocale::NarrowName ", "3").toString(languages); case 3: return ki18nc("Jalali weekday 3 - KLocale::NarrowName ", "4").toString(languages); case 4: return ki18nc("Jalali weekday 4 - KLocale::NarrowName ", "5").toString(languages); case 5: return ki18nc("Jalali weekday 5 - KLocale::NarrowName ", "J").toString(languages); case 6: return ki18nc("Jalali weekday 6 - KLocale::NarrowName ", "S").toString(languages); case 7: return ki18nc("Jalali weekday 7 - KLocale::NarrowName ", "1").toString(languages); default: return QString(); } } if (format == KLocale::ShortName || format == KLocale:: ShortNumber) { switch (weekDay) { case 1: return ki18nc("Jalali weekday 1 - KLocale::ShortName", "2sh").toString(languages); case 2: return ki18nc("Jalali weekday 2 - KLocale::ShortName", "3sh").toString(languages); case 3: return ki18nc("Jalali weekday 3 - KLocale::ShortName", "4sh").toString(languages); case 4: return ki18nc("Jalali weekday 4 - KLocale::ShortName", "5sh").toString(languages); case 5: return ki18nc("Jalali weekday 5 - KLocale::ShortName", "Jom").toString(languages); case 6: return ki18nc("Jalali weekday 6 - KLocale::ShortName", "Shn").toString(languages); case 7: return ki18nc("Jalali weekday 7 - KLocale::ShortName", "1sh").toString(languages); default: return QString(); } } switch (weekDay) { case 1: return ki18nc("Jalali weekday 1 - KLocale::LongName", "Do shanbe").toString(languages); case 2: return ki18nc("Jalali weekday 2 - KLocale::LongName", "Se shanbe").toString(languages); case 3: return ki18nc("Jalali weekday 3 - KLocale::LongName", "Chahar shanbe").toString(languages); case 4: return ki18nc("Jalali weekday 4 - KLocale::LongName", "Panj shanbe").toString(languages); case 5: return ki18nc("Jalali weekday 5 - KLocale::LongName", "Jumee").toString(languages); case 6: return ki18nc("Jalali weekday 6 - KLocale::LongName", "Shanbe").toString(languages); case 7: return ki18nc("Jalali weekday 7 - KLocale::LongName", "Yek-shanbe").toString(languages); default: return QString(); } } KCalendarSystemJalali::KCalendarSystemJalali(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(*new KCalendarSystemJalaliPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemJalali::KCalendarSystemJalali(KCalendarSystemJalaliPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemJalali::~KCalendarSystemJalali() { } QString KCalendarSystemJalali::calendarType() const { return QLatin1String("jalali"); } KLocale::CalendarSystem KCalendarSystemJalali::calendarSystem() const { return KLocale::JalaliCalendar; } QDate KCalendarSystemJalali::epoch() const { // 19 March 622 in the Julian calendar return QDate::fromJulianDay(1948321); } QDate KCalendarSystemJalali::earliestValidDate() const { // Using the Birashk formula which is accurate in period AP 1244 to 1530 (AD 1865 to 2152) // 1244-01-01 Jalali 1865-03-21 Gregorian return QDate::fromJulianDay(2402317); } QDate KCalendarSystemJalali::latestValidDate() const { // Using the Birashk formula which is accurate in period AP 1244 to 1530 (AD 1865 to 2152) // 1530-12-29 Jalali 2152-03-19 Gregorian return QDate::fromJulianDay(2507140); } QString KCalendarSystemJalali::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystem::monthName(month, year, format); } QString KCalendarSystemJalali::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystem::monthName(date, format); } QString KCalendarSystemJalali::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(weekDay, format); } QString KCalendarSystemJalali::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(date, format); } bool KCalendarSystemJalali::isLunar() const { return false; } bool KCalendarSystemJalali::isLunisolar() const { return false; } bool KCalendarSystemJalali::isSolar() const { return true; } bool KCalendarSystemJalali::isProleptic() const { return false; } bool KCalendarSystemJalali::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { // Birashk algorithm is incorrect in two years in period AP 1244 to 1531. // This results in a leap day being added to the end of 1404 instead of 1403 // and to the end of 1437 instead of 1436. Check for these dates first and // return accordingly. Relies on later use of dateToJulianDay() to correctly // calculate firstDayOfYear in 1404 and 1437, so no other adjustments needed. if (jd == 2460755) { year = 1403; month = 12; day = 30; return true; } if (jd == 2472808) { year = 1436; month = 12; day = 30; return true; } // From original KDE3 code, source unknown? Unable to contact author or committer to confirm // Matches Fermilab code, EMACS and D&R so check for PD source, likely Birashk's book qint64 jdCycleStart; int daysSinceCycleStart; int cycle; int dayInCycle; int yearInCycle; dateToJulianDay(475, 1, 1, jdCycleStart); daysSinceCycleStart = jd - jdCycleStart; cycle = daysSinceCycleStart / 1029983; dayInCycle = daysSinceCycleStart % 1029983; if (dayInCycle == 1029982) { yearInCycle = 2820; } else { int aux1 = dayInCycle / 366; int aux2 = dayInCycle % 366; yearInCycle = (((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) + aux1 + 1; } year = yearInCycle + (2820 * cycle) + 474; if (year <= 0) { year = year - 1; } qint64 firstDayOfYear; dateToJulianDay(year, 1, 1, firstDayOfYear); int dayinYear = jd - firstDayOfYear + 1; if (dayinYear <= 186) { month = ((dayinYear - 1) / 31) + 1; day = dayinYear - ((month - 1) * 31); } else { month = ((dayinYear - 7) / 30) + 1; day = dayinYear - ((month - 1) * 30) - 6; } return true; } bool KCalendarSystemJalali::dateToJulianDay(int year, int month, int day, qint64 &jd) const { Q_D(const KCalendarSystemJalali); // Birashk algorithm is incorrect in two years in period AP 1244 to 1531. // This results in a leap day being added to the end of 1404 instead of 1403 // and to the end of 1437 instead of 1436. Thus all dates in 1404 and 1437 // are off by 1 JD. Check for these dates first and adjust accordingly. if (year == 1403 && month == 12 && day == 30) { jd = 2460755; return true; } if (year == 1436 && month == 12 && day == 30) { jd = 2472808; return true; } if (year == 1404 || year == 1437) { if (month < 12 && day + 1 > d->daysInMonth(year, month)) { day = 1; month = month + 1; } else { day = day + 1; } } // From original KDE3 code, source unknown? Unable to contact author or committer to confirm // Matches Fermilab code, EMACS and D&R so check for PD source, likely Birashk's book int epbase; long epyear; long monthDays; if (year >= 0) { epbase = year - 474; } else { epbase = year - 473; } epyear = 474 + (epbase % 2820); if (month <= 7) { monthDays = (month - 1) * 31; } else { monthDays = ((month - 1) * 30) + 6; } jd = (epoch().toJulianDay() - 1) + // days before epoch (epyear - 1) * 365 + // normal days in previous years (((epyear * 682) - 110) / 2816) + // leap days in previous years (epbase / 2820) * 1029983 + monthDays + // days in previous months this year day; // days in this month return true; } diff --git a/src/kdecore/kcalendarsystemjalali_p.h b/src/kdecore/kcalendarsystemjalali_p.h index 817ea7eb..5b609683 100644 --- a/src/kdecore/kcalendarsystemjalali_p.h +++ b/src/kdecore/kcalendarsystemjalali_p.h @@ -1,65 +1,65 @@ /* Copyright (C) 2002-2003 Arash Bijanzadeh and FarsiKDE Project Contact: Arash Bijanzadeh Copyright 2007, 2010 John Layt 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 KCALENDARSYSTEMJALALI_H #define KCALENDARSYSTEMJALALI_H #include "kcalendarsystem.h" class KCalendarSystemJalaliPrivate; /** Jalali calendar type implementation */ class KCalendarSystemJalali : public KCalendarSystem { public: - explicit KCalendarSystemJalali(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemJalali(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemJalali(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemJalali(KCalendarSystemJalaliPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemJalali) }; #endif // KCALENDARSYSTEMJALALI_H diff --git a/src/kdecore/kcalendarsystemjapanese.cpp b/src/kdecore/kcalendarsystemjapanese.cpp index 0e21e7d4..faa2cc39 100644 --- a/src/kdecore/kcalendarsystemjapanese.cpp +++ b/src/kdecore/kcalendarsystemjapanese.cpp @@ -1,201 +1,201 @@ /* Copyright 2009, 2010 John Layt 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. */ #include "kcalendarsystemjapanese_p.h" #include "kcalendarsystemgregorianprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include //Reuse the Gregorian private implementation class KCalendarSystemJapanesePrivate : public KCalendarSystemGregorianPrivate { public: - explicit KCalendarSystemJapanesePrivate(KCalendarSystemJapanese *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemJapanesePrivate(KCalendarSystemJapanese *q); virtual ~KCalendarSystemJapanesePrivate(); void loadDefaultEraList() Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; }; //Override only a few of the Gregorian private methods KCalendarSystemJapanesePrivate::KCalendarSystemJapanesePrivate(KCalendarSystemJapanese *q) : KCalendarSystemGregorianPrivate(q) { } KCalendarSystemJapanesePrivate::~KCalendarSystemJapanesePrivate() { } void KCalendarSystemJapanesePrivate::loadDefaultEraList() { QString name, shortName, format; // Nengō, Only do most recent for now, use AD for the rest. // Feel free to add more, but have mercy on the translators :-) name = i18nc("Calendar Era: Gregorian Christian Era, years > 0, LongFormat", "Anno Domini"); shortName = i18nc("Calendar Era: Gregorian Christian Era, years > 0, ShortFormat", "AD"); format = i18nc("(kdedt-format) Gregorian, AD, full era year format used for %EY, e.g. 2000 AD", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, QDate(1868, 9, 7), name, shortName, format); name = i18nc("Calendar Era: Japanese Nengō, Meiji Era, LongFormat", "Meiji"); shortName = name; format = i18nc("(kdedt-format) Japanese, Meiji, full era year format used for %EY, year = 1, e.g. Meiji 1", "%EC Gannen"); addEra('+', 1, QDate(1868, 9, 8), 1868, QDate(1868, 12, 31), name, shortName, format); format = i18nc("(kdedt-format) Japanese, Meiji, full era year format used for %EY, year > 1, e.g. Meiji 22", "%EC %Ey"); addEra('+', 2, QDate(1869, 1, 1), 1869, QDate(1912, 7, 29), name, shortName, format); name = i18nc("Calendar Era: Japanese Nengō, Taishō Era, LongFormat", "Taishō"); shortName = name; format = i18nc("(kdedt-format) Japanese, Taishō, full era year format used for %EY, year = 1, e.g. Taishō 1", "%EC Gannen"); addEra('+', 1, QDate(1912, 7, 30), 1912, QDate(1912, 12, 31), name, shortName, format); format = i18nc("(kdedt-format) Japanese, Taishō, full era year format used for %EY, year > 1, e.g. Taishō 22", "%EC %Ey"); addEra('+', 2, QDate(1913, 1, 1), 1913, QDate(1926, 12, 24), name, shortName, format); name = i18nc("Calendar Era: Japanese Nengō, Shōwa Era, LongFormat", "Shōwa"); shortName = name; format = i18nc("(kdedt-format) Japanese, Shōwa, full era year format used for %EY, year = 1, e.g. Shōwa 1", "%EC Gannen"); addEra('+', 1, QDate(1926, 12, 25), 1926, QDate(1926, 12, 31), name, shortName, format); format = i18nc("(kdedt-format) Japanese, Shōwa, full era year format used for %EY, year > 1, e.g. Shōwa 22", "%EC %Ey"); addEra('+', 2, QDate(1927, 1, 1), 1927, QDate(1989, 1, 7), name, shortName, format); name = i18nc("Calendar Era: Japanese Nengō, Heisei Era, LongFormat", "Heisei"); shortName = name; format = i18nc("(kdedt-format) Japanese, Heisei, full era year format used for %EY, year = 1, e.g. Heisei 1", "%EC Gannen"); addEra('+', 1, QDate(1989, 1, 8), 1989, QDate(1989, 12, 31), name, shortName, format); format = i18nc("(kdedt-format) Japanese, Heisei, full era year format used for %EY, year > 1, e.g. Heisei 22", "%EC %Ey"); addEra('+', 2, QDate(1990, 1, 1), 1990, q->latestValidDate(), name, shortName, format); } int KCalendarSystemJapanesePrivate::earliestValidYear() const { return 1; } KCalendarSystemJapanese::KCalendarSystemJapanese(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemGregorian(*new KCalendarSystemJapanesePrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemJapanese::KCalendarSystemJapanese(KCalendarSystemJapanesePrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemGregorian(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemJapanese::~KCalendarSystemJapanese() { } QString KCalendarSystemJapanese::calendarType() const { return QLatin1String("japanese"); } KLocale::CalendarSystem KCalendarSystemJapanese::calendarSystem() const { return KLocale::JapaneseCalendar; } QDate KCalendarSystemJapanese::epoch() const { // 0001-01-01 Gregorian for now return QDate::fromJulianDay(1721426); } QDate KCalendarSystemJapanese::earliestValidDate() const { // 0001-01-01 Gregorian for now return QDate::fromJulianDay(1721426); } QDate KCalendarSystemJapanese::latestValidDate() const { // Set to last day of year 9999 until confirm date formats & widgets support > 9999 // 9999-12-31 Gregorian return QDate::fromJulianDay(5373484); } QString KCalendarSystemJapanese::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystemGregorian::monthName(month, year, format); } QString KCalendarSystemJapanese::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystemGregorian::monthName(date, format); } QString KCalendarSystemJapanese::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystemGregorian::weekDayName(weekDay, format); } QString KCalendarSystemJapanese::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystemGregorian::weekDayName(date, format); } int KCalendarSystemJapanese::yearStringToInteger(const QString &sNum, int &iLength) const { QString gannen = i18nc("Japanese year 1 of era", "Gannen"); if (sNum.startsWith(gannen, Qt::CaseInsensitive)) { iLength = gannen.length(); return 1; } else { return KCalendarSystemGregorian::yearStringToInteger(sNum, iLength); } } bool KCalendarSystemJapanese::isLunar() const { return KCalendarSystemGregorian::isLunar(); } bool KCalendarSystemJapanese::isLunisolar() const { return KCalendarSystemGregorian::isLunisolar(); } bool KCalendarSystemJapanese::isSolar() const { return KCalendarSystemGregorian::isSolar(); } bool KCalendarSystemJapanese::isProleptic() const { return false; } bool KCalendarSystemJapanese::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { return KCalendarSystemGregorian::julianDayToDate(jd, year, month, day); } bool KCalendarSystemJapanese::dateToJulianDay(int year, int month, int day, qint64 &jd) const { return KCalendarSystemGregorian::dateToJulianDay(year, month, day, jd); } diff --git a/src/kdecore/kcalendarsystemjapanese_p.h b/src/kdecore/kcalendarsystemjapanese_p.h index 6c7caebe..f392eae1 100644 --- a/src/kdecore/kcalendarsystemjapanese_p.h +++ b/src/kdecore/kcalendarsystemjapanese_p.h @@ -1,73 +1,73 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMJAPANESE_H #define KCALENDARSYSTEMJAPANESE_H #include "kcalendarsystemgregorian_p.h" class KCalendarSystemJapanesePrivate; /** * @internal * This is the Japanese calendar implementation which is the Gregorian calendar * but using the Japanese Era (Nengô) instead of the Christian/Common Era * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemJapanese: public KCalendarSystemGregorian { public: - explicit KCalendarSystemJapanese(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemJapanese(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemJapanese(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; int yearStringToInteger(const QString &sNum, int &iLength) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemJapanese(KCalendarSystemJapanesePrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemJapanese) }; #endif // KCALENDARSYSTEMJAPANESE_H diff --git a/src/kdecore/kcalendarsystemjulian.cpp b/src/kdecore/kcalendarsystemjulian.cpp index 278171c2..93e90c80 100644 --- a/src/kdecore/kcalendarsystemjulian.cpp +++ b/src/kdecore/kcalendarsystemjulian.cpp @@ -1,527 +1,527 @@ /* Copyright 2009, 2010 John Layt 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. */ #include "kcalendarsystemjulian_p.h" #include "kcalendarsystemprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include "kconfiggroup.h" #include #include class KCalendarSystemJulianPrivate : public KCalendarSystemPrivate { public: - explicit KCalendarSystemJulianPrivate(KCalendarSystemJulian *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemJulianPrivate(KCalendarSystemJulian *q); virtual ~KCalendarSystemJulianPrivate(); // Virtual methods each calendar system must re-implement void loadDefaultEraList() Q_DECL_OVERRIDE; int monthsInYear(int year) const Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasLeapMonths() const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int maxMonthsInYear() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; int latestValidYear() const Q_DECL_OVERRIDE; QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const Q_DECL_OVERRIDE; bool m_useCommonEra; }; // Shared d pointer base class definitions KCalendarSystemJulianPrivate::KCalendarSystemJulianPrivate(KCalendarSystemJulian *q) : KCalendarSystemPrivate(q) { } KCalendarSystemJulianPrivate::~KCalendarSystemJulianPrivate() { } void KCalendarSystemJulianPrivate::loadDefaultEraList() { QString name, shortName, format; KConfigGroup cg(config(), QString::fromLatin1("KCalendarSystem %1").arg(q->calendarType())); m_useCommonEra = cg.readEntry("UseCommonEra", false); if (m_useCommonEra) { name = i18nc("Calendar Era: Julian Common Era, years < 0, LongFormat", "Before Common Era"); shortName = i18nc("Calendar Era: Julian Common Era, years < 0, ShortFormat", "BCE"); } else { name = i18nc("Calendar Era: Julian Christian Era, years < 0, LongFormat", "Before Christ"); shortName = i18nc("Calendar Era: Julian Christian Era, years < 0, ShortFormat", "BC"); } format = i18nc("(kdedt-format) Julian, BC, full era year format used for %EY, e.g. 2000 BC", "%Ey %EC"); addEra('-', 1, q->epoch().addDays(-1), -1, q->earliestValidDate(), name, shortName, format); if (m_useCommonEra) { name = i18nc("Calendar Era: Julian Common Era, years > 0, LongFormat", "Common Era"); shortName = i18nc("Calendar Era: Julian Common Era, years > 0, ShortFormat", "CE"); } else { name = i18nc("Calendar Era: Julian Christian Era, years > 0, LongFormat", "Anno Domini"); shortName = i18nc("Calendar Era: Julian Christian Era, years > 0, ShortFormat", "AD"); } format = i18nc("(kdedt-format) Julian, AD, full era year format used for %EY, e.g. 2000 AD", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemJulianPrivate::monthsInYear(int year) const { Q_UNUSED(year) return 12; } int KCalendarSystemJulianPrivate::daysInMonth(int year, int month) const { if (month == 2) { if (isLeapYear(year)) { return 29; } else { return 28; } } if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } return 31; } int KCalendarSystemJulianPrivate::daysInYear(int year) const { if (isLeapYear(year)) { return 366; } else { return 365; } } bool KCalendarSystemJulianPrivate::isLeapYear(int year) const { if (year < 1) { year = year + 1; } if (year % 4 == 0) { return true; } return false; } bool KCalendarSystemJulianPrivate::hasLeapMonths() const { return false; } bool KCalendarSystemJulianPrivate::hasYearZero() const { return false; } int KCalendarSystemJulianPrivate::maxMonthsInYear() const { return 12; } int KCalendarSystemJulianPrivate::earliestValidYear() const { return -4712; } int KCalendarSystemJulianPrivate::latestValidYear() const { return 9999; } QString KCalendarSystemJulianPrivate::monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive) const { Q_UNUSED(year); QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (month) { case 1: return ki18nc("Julian month 1 - KLocale::NarrowName", "J").toString(languages); case 2: return ki18nc("Julian month 2 - KLocale::NarrowName", "F").toString(languages); case 3: return ki18nc("Julian month 3 - KLocale::NarrowName", "M").toString(languages); case 4: return ki18nc("Julian month 4 - KLocale::NarrowName", "A").toString(languages); case 5: return ki18nc("Julian month 5 - KLocale::NarrowName", "M").toString(languages); case 6: return ki18nc("Julian month 6 - KLocale::NarrowName", "J").toString(languages); case 7: return ki18nc("Julian month 7 - KLocale::NarrowName", "J").toString(languages); case 8: return ki18nc("Julian month 8 - KLocale::NarrowName", "A").toString(languages); case 9: return ki18nc("Julian month 9 - KLocale::NarrowName", "S").toString(languages); case 10: return ki18nc("Julian month 10 - KLocale::NarrowName", "O").toString(languages); case 11: return ki18nc("Julian month 11 - KLocale::NarrowName", "N").toString(languages); case 12: return ki18nc("Julian month 12 - KLocale::NarrowName", "D").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && possessive) { switch (month) { case 1: return ki18nc("Julian month 1 - KLocale::ShortName Possessive", "of Jan").toString(languages); case 2: return ki18nc("Julian month 2 - KLocale::ShortName Possessive", "of Feb").toString(languages); case 3: return ki18nc("Julian month 3 - KLocale::ShortName Possessive", "of Mar").toString(languages); case 4: return ki18nc("Julian month 4 - KLocale::ShortName Possessive", "of Apr").toString(languages); case 5: return ki18nc("Julian month 5 - KLocale::ShortName Possessive", "of May").toString(languages); case 6: return ki18nc("Julian month 6 - KLocale::ShortName Possessive", "of Jun").toString(languages); case 7: return ki18nc("Julian month 7 - KLocale::ShortName Possessive", "of Jul").toString(languages); case 8: return ki18nc("Julian month 8 - KLocale::ShortName Possessive", "of Aug").toString(languages); case 9: return ki18nc("Julian month 9 - KLocale::ShortName Possessive", "of Sep").toString(languages); case 10: return ki18nc("Julian month 10 - KLocale::ShortName Possessive", "of Oct").toString(languages); case 11: return ki18nc("Julian month 11 - KLocale::ShortName Possessive", "of Nov").toString(languages); case 12: return ki18nc("Julian month 12 - KLocale::ShortName Possessive", "of Dec").toString(languages); default: return QString(); } } if (format == KLocale::ShortName && !possessive) { switch (month) { case 1: return ki18nc("Julian month 1 - KLocale::ShortName", "Jan").toString(languages); case 2: return ki18nc("Julian month 2 - KLocale::ShortName", "Feb").toString(languages); case 3: return ki18nc("Julian month 3 - KLocale::ShortName", "Mar").toString(languages); case 4: return ki18nc("Julian month 4 - KLocale::ShortName", "Apr").toString(languages); case 5: return ki18nc("Julian month 5 - KLocale::ShortName", "May").toString(languages); case 6: return ki18nc("Julian month 6 - KLocale::ShortName", "Jun").toString(languages); case 7: return ki18nc("Julian month 7 - KLocale::ShortName", "Jul").toString(languages); case 8: return ki18nc("Julian month 8 - KLocale::ShortName", "Aug").toString(languages); case 9: return ki18nc("Julian month 9 - KLocale::ShortName", "Sep").toString(languages); case 10: return ki18nc("Julian month 10 - KLocale::ShortName", "Oct").toString(languages); case 11: return ki18nc("Julian month 11 - KLocale::ShortName", "Nov").toString(languages); case 12: return ki18nc("Julian month 12 - KLocale::ShortName", "Dec").toString(languages); default: return QString(); } } if (format == KLocale::LongName && possessive) { switch (month) { case 1: return ki18nc("Julian month 1 - KLocale::LongName Possessive", "of January").toString(languages); case 2: return ki18nc("Julian month 2 - KLocale::LongName Possessive", "of February").toString(languages); case 3: return ki18nc("Julian month 3 - KLocale::LongName Possessive", "of March").toString(languages); case 4: return ki18nc("Julian month 4 - KLocale::LongName Possessive", "of April").toString(languages); case 5: return ki18nc("Julian month 5 - KLocale::LongName Possessive", "of May").toString(languages); case 6: return ki18nc("Julian month 6 - KLocale::LongName Possessive", "of June").toString(languages); case 7: return ki18nc("Julian month 7 - KLocale::LongName Possessive", "of July").toString(languages); case 8: return ki18nc("Julian month 8 - KLocale::LongName Possessive", "of August").toString(languages); case 9: return ki18nc("Julian month 9 - KLocale::LongName Possessive", "of September").toString(languages); case 10: return ki18nc("Julian month 10 - KLocale::LongName Possessive", "of October").toString(languages); case 11: return ki18nc("Julian month 11 - KLocale::LongName Possessive", "of November").toString(languages); case 12: return ki18nc("Julian month 12 - KLocale::LongName Possessive", "of December").toString(languages); default: return QString(); } } // Default to LongName switch (month) { case 1: return ki18nc("Julian month 1 - KLocale::LongName", "January").toString(languages); case 2: return ki18nc("Julian month 2 - KLocale::LongName", "February").toString(languages); case 3: return ki18nc("Julian month 3 - KLocale::LongName", "March").toString(languages); case 4: return ki18nc("Julian month 4 - KLocale::LongName", "April").toString(languages); case 5: return ki18nc("Julian month 5 - KLocale::LongName", "May").toString(languages); case 6: return ki18nc("Julian month 6 - KLocale::LongName", "June").toString(languages); case 7: return ki18nc("Julian month 7 - KLocale::LongName", "July").toString(languages); case 8: return ki18nc("Julian month 8 - KLocale::LongName", "August").toString(languages); case 9: return ki18nc("Julian month 9 - KLocale::LongName", "September").toString(languages); case 10: return ki18nc("Julian month 10 - KLocale::LongName", "October").toString(languages); case 11: return ki18nc("Julian month 11 - KLocale::LongName", "November").toString(languages); case 12: return ki18nc("Julian month 12 - KLocale::LongName", "December").toString(languages); default: return QString(); } } QString KCalendarSystemJulianPrivate::weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const { QStringList languages = locale()->languageList(); if (format == KLocale::NarrowName) { switch (weekDay) { case 1: return ki18nc("Julian weekday 1 - KLocale::NarrowName ", "M").toString(languages); case 2: return ki18nc("Julian weekday 2 - KLocale::NarrowName ", "T").toString(languages); case 3: return ki18nc("Julian weekday 3 - KLocale::NarrowName ", "W").toString(languages); case 4: return ki18nc("Julian weekday 4 - KLocale::NarrowName ", "T").toString(languages); case 5: return ki18nc("Julian weekday 5 - KLocale::NarrowName ", "F").toString(languages); case 6: return ki18nc("Julian weekday 6 - KLocale::NarrowName ", "S").toString(languages); case 7: return ki18nc("Julian weekday 7 - KLocale::NarrowName ", "S").toString(languages); default: return QString(); } } if (format == KLocale::ShortName || format == KLocale:: ShortNumber) { switch (weekDay) { case 1: return ki18nc("Julian weekday 1 - KLocale::ShortName", "Mon").toString(languages); case 2: return ki18nc("Julian weekday 2 - KLocale::ShortName", "Tue").toString(languages); case 3: return ki18nc("Julian weekday 3 - KLocale::ShortName", "Wed").toString(languages); case 4: return ki18nc("Julian weekday 4 - KLocale::ShortName", "Thu").toString(languages); case 5: return ki18nc("Julian weekday 5 - KLocale::ShortName", "Fri").toString(languages); case 6: return ki18nc("Julian weekday 6 - KLocale::ShortName", "Sat").toString(languages); case 7: return ki18nc("Julian weekday 7 - KLocale::ShortName", "Sun").toString(languages); default: return QString(); } } switch (weekDay) { case 1: return ki18nc("Julian weekday 1 - KLocale::LongName", "Monday").toString(languages); case 2: return ki18nc("Julian weekday 2 - KLocale::LongName", "Tuesday").toString(languages); case 3: return ki18nc("Julian weekday 3 - KLocale::LongName", "Wednesday").toString(languages); case 4: return ki18nc("Julian weekday 4 - KLocale::LongName", "Thursday").toString(languages); case 5: return ki18nc("Julian weekday 5 - KLocale::LongName", "Friday").toString(languages); case 6: return ki18nc("Julian weekday 6 - KLocale::LongName", "Saturday").toString(languages); case 7: return ki18nc("Julian weekday 7 - KLocale::LongName", "Sunday").toString(languages); default: return QString(); } } KCalendarSystemJulian::KCalendarSystemJulian(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(*new KCalendarSystemJulianPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemJulian::KCalendarSystemJulian(KCalendarSystemJulianPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystem(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemJulian::~KCalendarSystemJulian() { } QString KCalendarSystemJulian::calendarType() const { return QLatin1String("julian"); } KLocale::CalendarSystem KCalendarSystemJulian::calendarSystem() const { return KLocale::JulianCalendar; } QDate KCalendarSystemJulian::epoch() const { return QDate::fromJulianDay(1721426); } QDate KCalendarSystemJulian::earliestValidDate() const { // 1 Jan 4712 BC, no year zero, cant be 4713BC due to error in QDate that day 0 is not valid // and we really need the first in each year to be valid for the date maths return QDate::fromJulianDay(366); } QDate KCalendarSystemJulian::latestValidDate() const { // Set to last day of year 9999 until confirm date formats & widgets support > 9999 // 31 Dec 9999 AD, no year zero return QDate::fromJulianDay(5373557); } QString KCalendarSystemJulian::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystem::monthName(month, year, format); } QString KCalendarSystemJulian::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystem::monthName(date, format); } QString KCalendarSystemJulian::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(weekDay, format); } QString KCalendarSystemJulian::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystem::weekDayName(date, format); } bool KCalendarSystemJulian::isLunar() const { return false; } bool KCalendarSystemJulian::isLunisolar() const { return false; } bool KCalendarSystemJulian::isSolar() const { return true; } bool KCalendarSystemJulian::isProleptic() const { return true; } bool KCalendarSystemJulian::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { // Formula from The Calendar FAQ by Claus Tondering // http://www.tondering.dk/claus/cal/node3.html#SECTION003161000000000000000 // NOTE: Coded from scratch from mathematical formulas, not copied from // the Boost licensed source code int b = 0; int c = jd + 32082; int d = ((4 * c) + 3) / 1461; int e = c - ((1461 * d) / 4); int m = ((5 * e) + 2) / 153; day = e - (((153 * m) + 2) / 5) + 1; month = m + 3 - (12 * (m / 10)); year = (100 * b) + d - 4800 + (m / 10); // If year is -ve then is BC. In Julian there is no year 0, but the maths // is easier if we pretend there is, so internally year of 0 = 1BC = -1 outside if (year < 1) { year = year - 1; } return true; } bool KCalendarSystemJulian::dateToJulianDay(int year, int month, int day, qint64 &jd) const { // Formula from The Calendar FAQ by Claus Tondering // http://www.tondering.dk/claus/cal/node3.html#SECTION003161000000000000000 // NOTE: Coded from scratch from mathematical formulas, not copied from // the Boost licensed source code // If year is -ve then is BC. In Julian there is no year 0, but the maths // is easier if we pretend there is, so internally year of -1 = 1BC = 0 internally int y; if (year < 1) { y = year + 1; } else { y = year; } int a = (14 - month) / 12; y = y + 4800 - a; int m = month + (12 * a) - 3; jd = day + (((153 * m) + 2) / 5) + (365 * y) + (y / 4) - 32083; return true; } diff --git a/src/kdecore/kcalendarsystemjulian_p.h b/src/kdecore/kcalendarsystemjulian_p.h index c32440c8..a2356dd7 100644 --- a/src/kdecore/kcalendarsystemjulian_p.h +++ b/src/kdecore/kcalendarsystemjulian_p.h @@ -1,74 +1,74 @@ /* Copyright 2009, 2010 John Layt 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 KCALENDARSYSTEMJULIAN_H #define KCALENDARSYSTEMJULIAN_H #include "kcalendarsystem.h" class KCalendarSystemJulianPrivate; /** * @internal * This is the Julian calendar implementation. * * WARNING: This is a proleptic version of the Julian calendar, it does not * reflect the historic marking of leap years prior to 4 AD and always * uses New Style years with 1 Jan for the start of the year. * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemJulian: public KCalendarSystem { public: - explicit KCalendarSystemJulian(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemJulian(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemJulian(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemJulian(KCalendarSystemJulianPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemJulian) }; #endif // KCALENDARSYSTEMJULIAN_H diff --git a/src/kdecore/kcalendarsystemminguo.cpp b/src/kdecore/kcalendarsystemminguo.cpp index aedc4cc1..2968fbcc 100644 --- a/src/kdecore/kcalendarsystemminguo.cpp +++ b/src/kdecore/kcalendarsystemminguo.cpp @@ -1,179 +1,179 @@ /* Copyright 2010 John Layt 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. */ #include "kcalendarsystemminguo_p.h" #include "kcalendarsystemgregorianprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include //Reuse the Gregorian private implementation class KCalendarSystemMinguoPrivate : public KCalendarSystemGregorianPrivate { public: - explicit KCalendarSystemMinguoPrivate(KCalendarSystemMinguo *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemMinguoPrivate(KCalendarSystemMinguo *q); virtual ~KCalendarSystemMinguoPrivate(); void loadDefaultEraList() Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; }; //Override only a few of the Gregorian private methods KCalendarSystemMinguoPrivate::KCalendarSystemMinguoPrivate(KCalendarSystemMinguo *q) : KCalendarSystemGregorianPrivate(q) { } KCalendarSystemMinguoPrivate::~KCalendarSystemMinguoPrivate() { } void KCalendarSystemMinguoPrivate::loadDefaultEraList() { QString name, shortName, format; name = i18nc("Calendar Era: Taiwan Republic of China Era, years > 0, LongFormat", "Republic of China Era"); shortName = i18nc("Calendar Era: Taiwan Republic of China Era, years > 0, ShortFormat", "ROC"); format = i18nc("(kdedt-format) Taiwan, ROC, full era year format used for %EY, e.g. ROC 99", "%EC %Ey"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemMinguoPrivate::daysInMonth(int year, int month) const { return KCalendarSystemGregorianPrivate::daysInMonth(year + 1911, month); } int KCalendarSystemMinguoPrivate::daysInYear(int year) const { return KCalendarSystemGregorianPrivate::daysInYear(year + 1911); } bool KCalendarSystemMinguoPrivate::isLeapYear(int year) const { return KCalendarSystemGregorianPrivate::isLeapYear(year + 1911); } int KCalendarSystemMinguoPrivate::earliestValidYear() const { return 1; } KCalendarSystemMinguo::KCalendarSystemMinguo(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemGregorian(*new KCalendarSystemMinguoPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemMinguo::KCalendarSystemMinguo(KCalendarSystemMinguoPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemGregorian(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemMinguo::~KCalendarSystemMinguo() { } QString KCalendarSystemMinguo::calendarType() const { return QLatin1String("minguo"); } KLocale::CalendarSystem KCalendarSystemMinguo::calendarSystem() const { return KLocale::MinguoCalendar; } QDate KCalendarSystemMinguo::epoch() const { // 0001-01-01 = 1912-01-01 AD Gregorian return QDate::fromJulianDay(2419403); } QDate KCalendarSystemMinguo::earliestValidDate() const { return epoch(); } QDate KCalendarSystemMinguo::latestValidDate() const { // Set to last day of year 9999 until confirm date formats & widgets support > 9999 // 9999-12-31 = 11910-12-31 AD Gregorian return QDate::fromJulianDay(6071462); } QString KCalendarSystemMinguo::monthName(int month, int year, MonthNameFormat format) const { return KCalendarSystemGregorian::monthName(month, year, format); } QString KCalendarSystemMinguo::monthName(const QDate &date, MonthNameFormat format) const { return KCalendarSystemGregorian::monthName(date, format); } QString KCalendarSystemMinguo::weekDayName(int weekDay, WeekDayNameFormat format) const { return KCalendarSystemGregorian::weekDayName(weekDay, format); } QString KCalendarSystemMinguo::weekDayName(const QDate &date, WeekDayNameFormat format) const { return KCalendarSystemGregorian::weekDayName(date, format); } bool KCalendarSystemMinguo::isLunar() const { return KCalendarSystemGregorian::isLunar(); } bool KCalendarSystemMinguo::isLunisolar() const { return KCalendarSystemGregorian::isLunisolar(); } bool KCalendarSystemMinguo::isSolar() const { return KCalendarSystemGregorian::isSolar(); } bool KCalendarSystemMinguo::isProleptic() const { return false; } bool KCalendarSystemMinguo::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { bool result = KCalendarSystemGregorian::julianDayToDate(jd, year, month, day); year = year - 1911; return result; } bool KCalendarSystemMinguo::dateToJulianDay(int year, int month, int day, qint64 &jd) const { return KCalendarSystemGregorian::dateToJulianDay(year + 1911, month, day, jd); } diff --git a/src/kdecore/kcalendarsystemminguo_p.h b/src/kdecore/kcalendarsystemminguo_p.h index 0883df90..ec561426 100644 --- a/src/kdecore/kcalendarsystemminguo_p.h +++ b/src/kdecore/kcalendarsystemminguo_p.h @@ -1,71 +1,71 @@ /* Copyright 2010 John Layt 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 KCALENDARSYSTEMMINGUO_H #define KCALENDARSYSTEMMINGUO_H #include "kcalendarsystemgregorian_p.h" class KCalendarSystemMinguoPrivate; /** * @internal * This is the Minguo / Taiwanese / Republic of China calendar implementation * which is the Gregorian calendar but using a different Epoch * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemMinguo: public KCalendarSystemGregorian { public: - explicit KCalendarSystemMinguo(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemMinguo(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemMinguo(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; QString monthName(int month, int year, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString monthName(const QDate &date, MonthNameFormat format = LongName) const Q_DECL_OVERRIDE; QString weekDayName(int weekDay, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; QString weekDayName(const QDate &date, WeekDayNameFormat format = LongDayName) const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemMinguo(KCalendarSystemMinguoPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemMinguo) }; #endif // KCALENDARSYSTEMMINGUO_H diff --git a/src/kdecore/kcalendarsystemprivate_p.h b/src/kdecore/kcalendarsystemprivate_p.h index 61c91640..4fff3477 100644 --- a/src/kdecore/kcalendarsystemprivate_p.h +++ b/src/kdecore/kcalendarsystemprivate_p.h @@ -1,105 +1,105 @@ /* Copyright 2010 John Layt 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 KCALENDARSYSTEMPRIVATE_H #define KCALENDARSYSTEMPRIVATE_H class QChar; class QString; class QDate; class KCalendarSystem; class KCalendarEra; class KLocale; class KCalendarSystemPrivate { public: - explicit KCalendarSystemPrivate(KCalendarSystem *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemPrivate(KCalendarSystem *q); virtual ~KCalendarSystemPrivate(); // Virtual methods each calendar system must re-implement virtual void loadDefaultEraList() = 0; virtual int monthsInYear(int year) const = 0; virtual int daysInMonth(int year, int month) const = 0; virtual int daysInYear(int year) const = 0; virtual bool isLeapYear(int year) const = 0; virtual bool hasLeapMonths() const = 0; virtual bool hasYearZero() const = 0; virtual int maxMonthsInYear() const = 0; virtual int earliestValidYear() const = 0; virtual int latestValidYear() const = 0; virtual QString monthName(int month, int year, KLocale::DateTimeComponentFormat format, bool possessive = false) const = 0; virtual QString weekDayName(int weekDay, KLocale::DateTimeComponentFormat format) const = 0; // Virtual methods to re-implement if special maths needed // Currently only Hebrew may need special conversion, rest should be OK virtual int yearsDifference(const QDate &fromDate, const QDate &toDate) const; virtual int monthsDifference(const QDate &fromDate, const QDate &toDate) const; virtual void dateDifference(const QDate &fromDate, const QDate &toDate, int *yearsDiff, int *monthsDiff, int *daysDiff, int *direction) const; // Virtual methods to re-implement if special number/string conversion needed // Currently only Hebrew needs special conversion, rest use KLocale DigitSet virtual int integerFromString(const QString &string, int maxLength, int &readLength) const; virtual QString stringFromInteger(int number, int padWidth = 0, QChar padChar = QLatin1Char('0')) const; virtual QString stringFromInteger(int number, int padWidth, QChar padChar, KLocale::DigitSet digitSet) const; // Utility functions int addYears(int startYear, int yearsToAdd) const; int differenceYearNumbers(int fromYear, int toYear) const; QString simpleDateString(const QString &str) const; int daysInWeek() const; int dayOfYear(const QDate &date) const; int dayOfWeek(const QDate &date) const; QDate firstDayOfYear(int year) const; QDate lastDayOfYear(int year) const; QDate firstDayOfMonth(int year, int month) const; QDate lastDayOfMonth(int year, int month) const; const KLocale *locale() const; void loadEraList(const KConfigGroup &cg); void addEra(char direction, int offset, const QDate &startDate, int startYear, const QDate &endDate, const QString &name, const QString &shortName, const QString &format); QList *eraList() const; KCalendarEra era(const QDate &eraDate) const; KCalendarEra era(const QString &eraName, int yearInEra) const; int shortYearWindowStartYear() const; int applyShortYearWindow(int inputYear) const; void loadShortYearWindowStartYear(const KConfigGroup &cg); KSharedConfig::Ptr config(); void loadConfig(const QString &calendarType); // Week utility functions int isoWeekNumber(const QDate &date, int *yearNum) const; int regularWeekNumber(const QDate &date, int weekStartDay, int firstWeekNumber, int *weekYear) const; int simpleWeekNumber(const QDate &date, int *yearNum) const; int isoWeeksInYear(int year) const; int regularWeeksInYear(int year, int weekStartDay, int firstWeekNumber) const; int simpleWeeksInYear(int year) const; // Global variables each calendar system must initialise const KCalendarSystem *q; const KLocale *m_locale; KSharedConfig::Ptr m_config; QList *m_eraList; int m_shortYearWindowStartYear; }; #endif // KCALENDARSYSTEMPRIVATE_H diff --git a/src/kdecore/kcalendarsystemthai.cpp b/src/kdecore/kcalendarsystemthai.cpp index 4193c5d7..d0eda8c9 100644 --- a/src/kdecore/kcalendarsystemthai.cpp +++ b/src/kdecore/kcalendarsystemthai.cpp @@ -1,165 +1,165 @@ /* Copyright 2009, 2010 John Layt 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. */ #include "kcalendarsystemthai_p.h" #include "kcalendarsystemgregorianprivate_p.h" #include "klocale.h" #include "klocalizedstring.h" #include //Reuse the Gregorian private implementation class KCalendarSystemThaiPrivate : public KCalendarSystemGregorianPrivate { public: - explicit KCalendarSystemThaiPrivate(KCalendarSystemThai *q); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemThaiPrivate(KCalendarSystemThai *q); virtual ~KCalendarSystemThaiPrivate(); void loadDefaultEraList() Q_DECL_OVERRIDE; int daysInMonth(int year, int month) const Q_DECL_OVERRIDE; int daysInYear(int year) const Q_DECL_OVERRIDE; bool isLeapYear(int year) const Q_DECL_OVERRIDE; bool hasYearZero() const Q_DECL_OVERRIDE; int earliestValidYear() const Q_DECL_OVERRIDE; }; //Override only a few of the Gregorian private methods KCalendarSystemThaiPrivate::KCalendarSystemThaiPrivate(KCalendarSystemThai *q) : KCalendarSystemGregorianPrivate(q) { } KCalendarSystemThaiPrivate::~KCalendarSystemThaiPrivate() { } void KCalendarSystemThaiPrivate::loadDefaultEraList() { QString name, shortName, format; name = i18nc("Calendar Era: Thai Buddhist Era, years > 0, LongFormat", "Buddhist Era"); shortName = i18nc("Calendar Era: Thai Buddhist Era, years > 0, ShortFormat", "BE"); format = i18nc("(kdedt-format) Thai, BE, full era year format used for %EY, e.g. 2000 BE", "%Ey %EC"); addEra('+', 1, q->epoch(), 1, q->latestValidDate(), name, shortName, format); } int KCalendarSystemThaiPrivate::daysInMonth(int year, int month) const { return KCalendarSystemGregorianPrivate::daysInMonth(year - 543, month); } int KCalendarSystemThaiPrivate::daysInYear(int year) const { return KCalendarSystemGregorianPrivate::daysInYear(year - 543); } bool KCalendarSystemThaiPrivate::isLeapYear(int year) const { return KCalendarSystemGregorianPrivate::isLeapYear(year - 543); } bool KCalendarSystemThaiPrivate::hasYearZero() const { return true; } int KCalendarSystemThaiPrivate::earliestValidYear() const { return 0; } KCalendarSystemThai::KCalendarSystemThai(const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemGregorian(*new KCalendarSystemThaiPrivate(this), config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemThai::KCalendarSystemThai(KCalendarSystemThaiPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale) : KCalendarSystemGregorian(dd, config, locale) { d_ptr->loadConfig(calendarType()); } KCalendarSystemThai::~KCalendarSystemThai() { } QString KCalendarSystemThai::calendarType() const { return QLatin1String("thai"); } KLocale::CalendarSystem KCalendarSystemThai::calendarSystem() const { return KLocale::ThaiCalendar; } QDate KCalendarSystemThai::epoch() const { // 0000-01-01 = 0544-01-01 BC Gregorian = 0544-01-07 BC Julian return QDate::fromJulianDay(1522734); } QDate KCalendarSystemThai::earliestValidDate() const { return epoch(); } QDate KCalendarSystemThai::latestValidDate() const { // Set to last day of year 9999 until confirm date formats & widgets support > 9999 // 9999-12-31 = 9456-12-31 AD Gregorian return QDate::fromJulianDay(5175158); } bool KCalendarSystemThai::isLunar() const { return KCalendarSystemGregorian::isLunar(); } bool KCalendarSystemThai::isLunisolar() const { return KCalendarSystemGregorian::isLunisolar(); } bool KCalendarSystemThai::isSolar() const { return KCalendarSystemGregorian::isSolar(); } bool KCalendarSystemThai::isProleptic() const { return false; } bool KCalendarSystemThai::julianDayToDate(qint64 jd, int &year, int &month, int &day) const { bool result = KCalendarSystemGregorian::julianDayToDate(jd, year, month, day); year = year + 543; return result; } bool KCalendarSystemThai::dateToJulianDay(int year, int month, int day, qint64 &jd) const { return KCalendarSystemGregorian::dateToJulianDay(year - 543, month, day, jd); } diff --git a/src/kdecore/kcalendarsystemthai_p.h b/src/kdecore/kcalendarsystemthai_p.h index 81a0c9a2..9d72f39a 100644 --- a/src/kdecore/kcalendarsystemthai_p.h +++ b/src/kdecore/kcalendarsystemthai_p.h @@ -1,65 +1,65 @@ /* Copyright 2010 John Layt 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 KCALENDARSYSTEMTHAI_H #define KCALENDARSYSTEMTHAI_H #include "kcalendarsystemgregorian_p.h" class KCalendarSystemThaiPrivate; /** * @internal * This is the Thai calendar implementation which is the Gregorian calendar * but using a different Epoch * * @b license GNU-LGPL v.2 or later * * @see KLocale,KCalendarSystem * * @author John Layt */ class KCalendarSystemThai: public KCalendarSystemGregorian { public: - explicit KCalendarSystemThai(const KSharedConfig::Ptr config, const KLocale *locale); + KDELIBS4SUPPORT_DEPRECATED explicit KCalendarSystemThai(const KSharedConfig::Ptr config, const KLocale *locale); virtual ~KCalendarSystemThai(); QString calendarType() const Q_DECL_OVERRIDE; KLocale::CalendarSystem calendarSystem() const Q_DECL_OVERRIDE; QDate epoch() const Q_DECL_OVERRIDE; QDate earliestValidDate() const Q_DECL_OVERRIDE; QDate latestValidDate() const Q_DECL_OVERRIDE; bool isLunar() const Q_DECL_OVERRIDE; bool isLunisolar() const Q_DECL_OVERRIDE; bool isSolar() const Q_DECL_OVERRIDE; bool isProleptic() const Q_DECL_OVERRIDE; protected: bool julianDayToDate(qint64 jd, int &year, int &month, int &day) const Q_DECL_OVERRIDE; bool dateToJulianDay(int year, int month, int day, qint64 &jd) const Q_DECL_OVERRIDE; KCalendarSystemThai(KCalendarSystemThaiPrivate &dd, const KSharedConfig::Ptr config, const KLocale *locale); private: Q_DECLARE_PRIVATE(KCalendarSystemThai) }; #endif // KCALENDARSYSTEMTHAI_H diff --git a/src/kdecore/kcomponentdata.h b/src/kdecore/kcomponentdata.h index 3e24a205..81ab2b13 100644 --- a/src/kdecore/kcomponentdata.h +++ b/src/kdecore/kcomponentdata.h @@ -1,237 +1,237 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Torben Weis Copyright (C) 2007 Matthias Kretz 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 KCOMPONENTDATA_H #define KCOMPONENTDATA_H #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif #include #include class QByteArray; class QString; class K4AboutData; class KComponentDataPrivate; /** * @short Per component data. * * This class holds a K4AboutData object or only a component name, and a KSharedConfig object. * Those objects normally are different per component but the same per * instance of one component. * * The application component data can always be accessed using KComponentData::mainComponent() (or the * convenience function KGlobal::dirs() and KSharedConfig::openConfig()) while the * component data of the currently active component (mainly used for KParts) can be accessed using * KGlobal::activeComponent(). * * @author Torben Weis * @author Matthias Kretz */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE KComponentData // krazy:exclude=dpointer (implicitly shared) { public: /** * Creates an invalid KComponentData object. * * @see isValid() */ KComponentData(); /** * Copy constructor. * * It does not copy the data. The data is shared between the old and new objects. */ KComponentData(const KComponentData &); /** * Assignment operator. * * It does not copy the data. The data is shared between the old and new objects. * * If the data of the left hand side object was only referenced * from this object and no referenced KSharedConfig object needs * it anymore, it is deleted */ KComponentData &operator=(const KComponentData &); /** * Returns whether two KComponentData objects reference the same data. */ bool operator==(const KComponentData &) const; /** * Returns whether two KComponentData objects do not reference the same data. */ bool operator!=(const KComponentData &rhs) const; enum MainComponentRegistration { RegisterAsMainComponent, SkipMainComponentRegistration }; /** * Constructor. * * @param componentName the name of the component. * @param catalogName the name of the translation catalog; * if left empty @p componentName is used * @param registerAsMain whether to register the component as the main component * of the application. This has no effect, if the application * already has a main component. * @see KComponentData::mainComponent */ - explicit KComponentData(const QByteArray &componentName, const QByteArray &catalogName = QByteArray(), + KDELIBS4SUPPORT_DEPRECATED explicit KComponentData(const QByteArray &componentName, const QByteArray &catalogName = QByteArray(), MainComponentRegistration registerAsMain = RegisterAsMainComponent); /** * Constructor. * * A copy of the aboutData object is made. * * @param aboutData data about this component * @param registerAsMain whether to register the component as the main component * of the application. This has no effect, if the application * already has a main component. * @see KComponentData::mainComponent * * @see K4AboutData */ - explicit KComponentData(const K4AboutData &aboutData, MainComponentRegistration registerAsMain = RegisterAsMainComponent); - explicit KComponentData(const K4AboutData *aboutData, MainComponentRegistration registerAsMain = RegisterAsMainComponent); + KDELIBS4SUPPORT_DEPRECATED explicit KComponentData(const K4AboutData &aboutData, MainComponentRegistration registerAsMain = RegisterAsMainComponent); + KDELIBS4SUPPORT_DEPRECATED explicit KComponentData(const K4AboutData *aboutData, MainComponentRegistration registerAsMain = RegisterAsMainComponent); /** * Destructor. */ virtual ~KComponentData(); /** * Implicit conversion to KAboutData, to be able to call setComponentData(myComponentData) * even if the method is now setComponentData(const KAboutData &) */ operator KAboutData() const; /** * Returns whether this is a valid object. * * Don't call any functions on invalid objects, that will crash. Assignment (and of course * destruction) is the only valid operation you may do. */ bool isValid() const; /** * Returns the general config object ("appnamerc"). * @return the KConfig object for the component. */ const KSharedConfig::Ptr &config() const; //krazy:exclude=constref /** * Returns the about data of this component. * * @return The about data of the component. If none has been set in the * constructor but a component name was set, a default constructed * K4AboutData object is returned. */ KDELIBS4SUPPORT_DEPRECATED const K4AboutData *aboutData() const; /** * Sets the about data of this component. * * @since 4.5 */ KDELIBS4SUPPORT_DEPRECATED void setAboutData(const K4AboutData &aboutData); /** * Returns the name of the component. * * @return The component name. */ QString componentName() const; /** * Returns the name of the translation catalog. * * @return The catalog name. */ QString catalogName() const; /** * @internal * Returns whether a main KComponentData is available. * @since 5.0 */ static bool hasMainComponent(); /** * Returns the global component data, if one was set. * @since 5.0 */ static const KComponentData &mainComponent(); //krazy:exclude=constref (don't mess up ref-counting) /** * The component currently active (useful in a multi-component * application, such as a KParts application). * Don't use this - it was mainly for KAboutDialog and KBugReport. * * They now use KAboutData::applicationData() by default, or a specific KAboutData can be given * to them. KHelpMenu always creates them with the application data. * So this is now obsolete, the about-app and bug-report dialog simply use the app data * rather than the active plugin data. * * @internal * @since 5.0 (moved from KGlobal, but later on KComponentData was deprecated anyway) */ static const KComponentData &activeComponent(); //krazy:exclude=constref (don't mess up ref-counting) /** * Set the active component for use by KAboutDialog and KBugReport. * To be used only by a multi-component (KParts) application. * * Since 5.0, KAboutDialog and KBugReport don't look at this anymore, * so consider just removing the call. See activeComponent() for more details. * * @see activeComponent() * @since 5.0 (moved from KGlobal, but later on KComponentData was deprecated anyway) */ static void setActiveComponent(const KComponentData &d); protected: friend class KApplicationPrivate; /** * Set name of default config file. * @param name the name of the default config file */ void setConfigName(const QString &name); /** Standard trick to add virtuals later. @internal */ virtual void virtual_hook(int id, void *data); private: // Ref-counted data KComponentDataPrivate *d; friend class KComponentDataPrivate; }; #endif // KCOMPONENTDATA_H diff --git a/src/kdecore/kcurrencycode.h b/src/kdecore/kcurrencycode.h index 4c2017f8..c3e201ff 100644 --- a/src/kdecore/kcurrencycode.h +++ b/src/kdecore/kcurrencycode.h @@ -1,342 +1,342 @@ /* Copyright (c) 2009 John Layt 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 KCURRENCYCODE_H #define KCURRENCYCODE_H #include #include #include class QDate; class QStringList; class QFileInfo; class KCurrencyCodePrivate; /** * @since 4.4 * * This is a class to implement the ISO 4217 Currency Code standard * * @b license GNU-LGPL v.2 or later * * @see KLocale * * @author John Layt * * @deprecated since 5.0, a replacement will be provided by the KStandards * framework (not available in KDE Frameworks 5.0) */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KCurrencyCode { public: /** * The Status of the Currency * * @see CurrencyStatusFlags * @see currencyStatus() */ enum CurrencyStatus { ActiveCurrency = 0x01, /**< Currency is currently in use */ SuspendedCurrency = 0x02, /**< Currency is not currently in use but has not been replaced */ ObsoleteCurrency = 0x04 /**< Currency is no longer in use and has been replaced */ }; Q_DECLARE_FLAGS(CurrencyStatusFlags, CurrencyStatus) /** * Constructs a KCurrencyCode for a given ISO Currency Code. * * If the supplied Currency Code is not known then the KCurrencyCode will return isValid() == false * * @param isoCurrencyCode the ISO Currency Code to construct, defaults to USD * @param language the language to use for translations, default to the Locale language * */ - explicit KCurrencyCode(const QString &isoCurrencyCode, const QString &language = QString()); + KDELIBS4SUPPORT_DEPRECATED explicit KCurrencyCode(const QString &isoCurrencyCode, const QString &language = QString()); /** * Constructs a KCurrencyCode for a given config file and Language. * * Note that any translations must be supplied in the config file, none will be provided. * * If the supplied config file is not valid then the KCurrencyCode will return isValid() == false * * @param currencyCodeFile the ISO Currency Code to construct, defaults to USD * @param language the language to use for translations, default to the Locale language * */ - explicit KCurrencyCode(const QFileInfo ¤cyCodeFile, const QString &language = QString()); + KDELIBS4SUPPORT_DEPRECATED explicit KCurrencyCode(const QFileInfo ¤cyCodeFile, const QString &language = QString()); /** * Copy Constructor * * @param rhs KCurrencyCode to copy * */ KCurrencyCode(const KCurrencyCode &rhs); /** * Destructor. */ virtual ~KCurrencyCode(); /** * Assignment operator * * @param rhs KCurrencyCode to assign * */ KCurrencyCode &operator=(const KCurrencyCode &rhs); /** * Return the ISO 4217 Currency Code in Alpha 3 format, e.g. USD * * @return the ISO Currency Code * * @see isoCurrencyCodeNumeric() */ QString isoCurrencyCode() const; /** * Return the ISO 4217 Currency Code in Numeric 3 format, e.g. 840 * * @return the ISO Currency Code * * @see isoCurrencyCode() */ QString isoCurrencyCodeNumeric() const; /** * Return translated Currency Code Name in a standard display format * e.g. United States Dollar * * @return the display Currency Code Name * * @see isoName() */ QString name() const; /** * Return untranslated official ISO Currency Code Name * * This name is not translated and should only be used where appropriate. * For displaying the name to a user, use name() instead. * * @return the official ISO Currency Code Name * * @see name() */ QString isoName() const; /** * Return Currency Status for the currency, if Active, Suspended or Obsolete * * @return the Currency Status * * @see CurrencyStatus */ CurrencyStatus status() const; /** * Return the date the currency was introduced * * @return the date the currency was introduced * * @see status() * @see dateSuspended() * @see dateWithdrawn() */ QDate dateIntroduced() const; /** * Return the date the currency was suspended * * @return the date the currency was suspended, QDate() if active * * @see status() * @see dateIntroduced() * @see dateWithdrawn() */ QDate dateSuspended() const; /** * Return the date the currency was withdrawn from circulation * * @return the date the currency was withdrawn, QDate() if active * * @see status() * @see dateIntroduced() * @see dateSuspended() */ QDate dateWithdrawn() const; /** * Return a list of valid Symbols for the Currency in order of preference * * This list will normally contain the Default and Unambiguous symbols and the ISO Currency Code * * @return list of Currency Symbols * * @see defaultSymbol() * @see unambiguousSymbol() */ QStringList symbolList() const; /** * Return the default Symbol for the Currency, e.g. $ or £ * * @return the default Currency Symbol * * @see symbols() * @see unambiguousSymbol() */ QString defaultSymbol() const; /** * Return the unambiguous Symbol for the Currency, e.g. US$ or NZ$ * * @return the unambiguous Currency Symbol * * @see symbols() * @see defaultSymbol() */ QString unambiguousSymbol() const; /** * Return if the Currency has subunits or not, * e.g. USD has cents, VUV has none * * @return true if the Currency has subunits * * @see hasSubunitsInCirculation() * @see subunitName() * @see subunitSymbol() * @see subunitsPerUnit() */ bool hasSubunits() const; /** * Return if the Currency has subunits in circulation, * e.g. JPY has sen but these are no longer used due to inflation * * @return true if the Currency has subunits in circulation * * @see hasSubunits() */ bool hasSubunitsInCirculation() const; /** * Return the Currency subunit symbol if it has one * e.g. ¢ for USD cent * * @return the currency subunit symbol * * @see hasSubunits() */ QString subunitSymbol() const; /** * Return the number of subunits in every unit, e.g. 100 cents in the dollar * * @return number of subunits per unit, 0 if no subunits * * @see hasSubunits() */ int subunitsPerUnit() const; /** * Return the number of decimal places required to display the currency subunits * * @return number of decimal places */ int decimalPlaces() const; /** * Return a list of countries known to be using the currency * * @return list of ISO Country Codes using the currency */ QStringList countriesUsingCurrency() const; /** * Return if the currency object loaded/initialised correctly * * @return true if valid KCurrencyCode object */ bool isValid() const; /** * Return if a given Currency Code is supported in KDE. * Optionally validate if an Active, Suspended, or Obsolete currency, default is if any. * * @param currencyCode the Currency Code to validate * @param currencyStatus the CurrencyStatus to validate * * @return true if valid currency code */ static bool isValid(const QString ¤cyCode, CurrencyStatusFlags currencyStatus = CurrencyStatusFlags(ActiveCurrency | SuspendedCurrency | ObsoleteCurrency)); /** * Provides list of all known ISO Currency Codes. * * Use currencyCodeToName(currencyCode) to get human readable, localized currency names. * * By default returns all Active, Suspended and Obsolete currencies, set the currencyStatus * flags as appropriate to return required status currencies * * @param currencyStatus which status currencies to return * * @return a list of all ISO Currency Codes * * @see currencyCodeToName */ static QStringList allCurrencyCodesList(CurrencyStatusFlags currencyStatus = CurrencyStatusFlags(ActiveCurrency | SuspendedCurrency | ObsoleteCurrency)); /** * Convert a known ISO Currency Code to a human readable, localized form. * * If an unknown Currency Code is supplied, empty string is returned; * this will never happen if the code has been obtained by one of the * KCurrencyCode methods. * * @param currencyCode the ISO Currency Code * @param language the language to use for translations, default to the Locale language * * @return the human readable and localized form of the Currency name * * @see currencyCode * @see allCurrencyCodesList */ static QString currencyCodeToName(const QString ¤cyCode, const QString &language = QString()); private: QSharedDataPointer d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KCurrencyCode::CurrencyStatusFlags) #endif // KCURRENCYCODE_H diff --git a/src/kdecore/kdatetime.h b/src/kdecore/kdatetime.h index 1e62bf61..584f2365 100644 --- a/src/kdecore/kdatetime.h +++ b/src/kdecore/kdatetime.h @@ -1,1626 +1,1626 @@ /* This file is part of the KDE libraries Copyright (c) 2005-2011 David Jarvie 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. */ /** @file * Date/times with associated time zone * @author David Jarvie . */ #ifndef _KDATETIME_H_ #define _KDATETIME_H_ #include #include #include class QDataStream; class KDateTimePrivate; class KDateTimeSpecPrivate; class KTimeZone; class KTimeZones; /** * @short A class representing a date and time with an associated time zone * * Topics: * - @ref intro * - @ref manipulation * - @ref compatibility * * @section intro Introduction * * The class KDateTime combines a date and time with support for an * associated time zone or UTC offset. When manipulating KDateTime objects, * their time zones or UTC offsets are automatically taken into account. KDateTime * can also be set to represent a date-only value with no associated time. * * The class uses QDateTime internally to represent date/time values, and * therefore uses the Gregorian calendar retroactively. If you need the Julian * calendar for historical dates (as commonly used prior to some date between 1582 * and 1923 depending on nation), please use @c KCalendarSystem and related classes. * * The time specification types which KDateTime supports are: * - the UTC time zone * - a local time with a specified offset from UTC * - a local time in a specified time zone * - a local time using the current system time zone (a special case of the * previous item) * - local clock time, using whatever the local system clock says on whichever * computer it happens to be on. In this case, the equivalent UTC time will * vary depending on system. As a result, calculations involving local clock * times do not necessarily produce reliable results. * * These characteristics are more fully described in the description of the * SpecType enumeration. Also see * W3C: Working with Time Zones * for a good overview of the different ways of representing times. * * To set the time specification, use one of the setTimeSpec() methods, to get * the time specification, call timeSpec(), isUtc(), isLocalZone(), * isOffsetFromUtc() or isClockTime(). To determine whether two KDateTime * instances have the same time specification, call timeSpec() on each and * compare the returned values using KDateTime::Spec::operator==(). * * @section manipulation Date and Time Manipulation * * A KDateTime object can be created by passing a date and time in its * constructor, together with a time specification. * * If both the date and time are null, isNull() returns true. If the date, time * and time specification are all valid, isValid() returns true. * * A KDateTime object can be converted to a different time specification by * using toUtc(), toLocalZone() or toClockTime(). It can be converted to a * specific time zone by toZone(). To return the time as an elapsed time since * 1 January 1970 (as used by time(2)), use toTime_t(). The results of time * zone conversions are cached to minimize the need for recalculation. Each * KDateTime object caches its UTC equivalent and the last time zone * conversion performed. * * The date and time can be set either in the constructor, or afterwards by * calling setDate(), setTime() or setDateTime(). To return the date and/or * time components of the KDateTime, use date(), time() and dateTime(). You * can determine whether the KDateTime represents a date and time, or a date * only, by isDateOnly(). You can change between a date and time or a date only * value using setDateOnly(). * * You can increment or decrement the date/time using addSecs(), addDays(), * addMonths() and addYears(). The interval between two date/time values can * be found using secsTo() or daysTo(). * * The comparison operators (operator==(), operator<(), etc.) all take the time * zone properly into account; if the two KDateTime objects have different time * zones, they are first converted to UTC before the comparison is * performed. An alternative to the comparison operators is compare() which will * in addition tell you if a KDateTime object overlaps with another when one or * both are date-only values. * * KDateTime values may be converted to and from a string representation using * the toString() and fromString() methods. These handle a variety of text * formats including ISO 8601 and RFC 2822. * * KDateTime uses Qt's facilities to implicitly share data. Copying instances * is very efficient, and copied instances share cached UTC and time zone * conversions even after the copy is performed. A separate copy of the data is * created whenever a non-const method is called. If you want to force the * creation of a separate copy of the data (e.g. if you want two copies to * cache different time zone conversions), call detach(). * * @section compatibility QDateTime Considerations * * KDateTime's interface is designed to be as compatible as possible with that * of QDateTime, but with adjustments to cater for time zone handling. Because * QDateTime lacks virtual methods, KDateTime is not inherited from QDateTime, * but instead is implemented using a private QDateTime object. * * @section simulation Simulation Facility * * This class provides a facility to simulate the local system time, which * affects all functions using or returning the system time. This facility is * provided for testing purposes only, and is only available if the library is * compiled with debug enabled. In release mode, simulation is inoperative and * the real local system time is used at all times. Use * setSimulatedSystemTime() to set or clear the simulated time. To read the * real (not simulated) system time, use realCurrentLocalDateTime(). * * @see KTimeZone, KSystemTimeZones, QDateTime, QDate, QTime * @see W3C: Working with Time Zones * @author David Jarvie \. */ class KDELIBS4SUPPORT_EXPORT KDateTime //krazy:exclude=dpointer (implicitly shared) { public: /** * The time specification type of a KDateTime instance. * This specifies how the date/time component of the KDateTime instance * should be interpreted, i.e. what type of time zone (if any) the date/time * is expressed in. For the full time specification (including time zone * details), see KDateTime::Spec. */ enum SpecType { Invalid, /**< an invalid time specification. */ UTC, /**< a UTC time. */ OffsetFromUTC, /**< a local time which has a fixed offset from UTC. */ TimeZone, /**< a time in a specified time zone. If the time zone is * the current system time zone (i.e. that returned by * KSystemTimeZones::local()), LocalZone may be used * instead. */ LocalZone, /**< a time in the current system time zone. * When used to initialize a KDateTime or KDateTime::Spec * instance, this is simply a shorthand for calling the * setting method with a time zone parameter * KSystemTimeZones::local(). Note that if the system is * changed to a different time zone afterwards, the * KDateTime instance will still use the original system * time zone rather than adopting the new zone. * When returned by a method, it indicates that the time * zone stored in the instance is that currently returned * by KSystemTimeZones::local(). */ ClockTime /**< a clock time which ignores time zones and simply uses * whatever the local system clock says the time is. You * could, for example, set a wake-up time of 07:30 on * some date, and then no matter where you were in the * world, you would be in time for breakfast as long as * your computer was aligned with the local time. * * Note that any calculations which involve clock times * cannot be guaranteed to be accurate, since by * definition they contain no information about time * zones or daylight savings changes. */ }; /** * The full time specification of a KDateTime instance. * This specifies how the date/time component of the KDateTime instance * should be interpreted, i.e. which time zone (if any) the date/time is * expressed in. */ class KDELIBS4SUPPORT_EXPORT Spec { public: /** * Constructs an invalid time specification. */ Spec(); /** * Constructs a time specification for a given time zone. * If @p tz is KTimeZone::utc(), the time specification type is set to @c UTC. * * @param tz time zone */ Spec(const KTimeZone &tz); // allow implicit conversion /** * Constructs a time specification. * * @param type time specification type, which should not be @c TimeZone * @param utcOffset number of seconds to add to UTC to get the local * time. Ignored if @p type is not @c OffsetFromUTC. */ Spec(SpecType type, int utcOffset = 0); // allow implicit conversion /** * Copy constructor. */ Spec(const Spec &spec); /** * Assignment operator. */ Spec &operator=(const Spec &spec); /** * Destructor */ ~Spec(); /** * Returns whether the time specification is valid. * * @return @c true if valid, else @c false */ bool isValid() const; /** * Returns the time zone for the date/time, according to the time * specification type as follows: * - @c TimeZone : the specified time zone is returned. * - @c UTC : a UTC time zone is returned. * - @c LocalZone : the current local time zone is returned. * * @return time zone as defined above, or invalid in all other cases * @see isUtc(), isLocal() */ KTimeZone timeZone() const; /** * Returns the time specification type, i.e. whether it is * UTC, has a time zone, etc. If the type is the local time zone, * @c TimeZone is returned; use isLocalZone() to check for the * local time zone. * * @return specification type * @see isLocalZone(), isClockTime(), isUtc(), timeZone() */ SpecType type() const; /** * Returns whether the time specification is the current local * system time zone. * * @return @c true if local system time zone * @see isUtc(), isOffsetFromUtc(), timeZone() */ bool isLocalZone() const; /** * Returns whether the time specification is a local clock time. * * @return @c true if local clock time * @see isUtc(), timeZone() */ bool isClockTime() const; /** * Returns whether the time specification is a UTC time. * It is considered to be a UTC time if it is either type @c UTC, * or is type @c OffsetFromUTC with a zero UTC offset. * * @return @c true if UTC * @see isLocal(), isOffsetFromUtc(), timeZone() */ bool isUtc() const; /** * Returns whether the time specification is a local time at a fixed * offset from UTC. * * @return @c true if local time at fixed offset from UTC * @see isLocal(), isUtc(), utcOffset() */ bool isOffsetFromUtc() const; /** * Returns the UTC offset associated with the time specification. The * UTC offset is the number of seconds to add to UTC to get the local time. * * @return UTC offset in seconds if type is @c OffsetFromUTC, else 0 * @see isOffsetFromUtc() */ int utcOffset() const; /** * Initialises the time specification. * * @param type the time specification type. Note that @c TimeZone * is invalid here. * @param utcOffset number of seconds to add to UTC to get the local * time. Ignored if @p spec is not @c OffsetFromUTC. * @see type(), setType(const KTimeZone&) */ void setType(SpecType type, int utcOffset = 0); /** * Sets the time zone for the time specification. * * To set the time zone to the current local system time zone, * setType(LocalZone) may optionally be used instead. * * @param tz new time zone * @see timeZone(), setType(SpecType) */ void setType(const KTimeZone &tz); /** * Comparison operator. * * @return @c true if the two instances are identical, @c false otherwise * @see equivalentTo() */ bool operator==(const Spec &other) const; bool operator!=(const Spec &other) const { return !operator==(other); } /** * Checks whether this instance is equivalent to another. * The two instances are considered to be equivalent if any of the following * conditions apply: * - both instances are type @c ClockTime. * - both instances are type @c OffsetFromUTC and their offsets from UTC are equal. * - both instances are type @c TimeZone and their time zones are equal. * - both instances are UTC. An instance is considered to be UTC if it is * either type @c UTC, or is type @c OffsetFromUTC with a zero UTC offset. * * @return @c true if the two instances are equivalent, @c false otherwise * @see operator==() */ bool equivalentTo(const Spec &other) const; /** * The UTC time specification. * Provided as a shorthand for KDateTime::Spec(KDateTime::UTC). */ static Spec UTC(); /** * The ClockTime time specification. * Provided as a shorthand for KDateTime::Spec(KDateTime::ClockTime). */ static Spec ClockTime(); /** * Returns a UTC offset time specification. * Provided as a shorthand for KDateTime::Spec(KDateTime::OffsetFromUTC, utcOffset). * * @param utcOffset number of seconds to add to UTC to get the local time * @return UTC offset time specification */ static Spec OffsetFromUTC(int utcOffset); /** * Returns a local time zone time specification. * Provided as a shorthand for KDateTime::Spec(KDateTime::LocalZone). * * @return Local zone time specification */ static Spec LocalZone(); private: KDateTimeSpecPrivate *const d; }; /** Format for strings representing date/time values. */ enum TimeFormat { ISODate, /**< ISO 8601 format, i.e. [±]YYYY-MM-DDThh[:mm[:ss[.sss]]]TZ, * where TZ is the time zone offset (blank for local * time, Z for UTC, or ±hhmm for an offset from UTC). * When parsing a string, the ISO 8601 basic format, * [±]YYYYMMDDThh[mm[ss[.sss]]]TZ, is also accepted. For * date-only values, the formats [±]YYYY-MM-DD and * [±]YYYYMMDD (without time zone specifier) are used. All * formats may contain a day of the year instead of day * and month. * To allow for years past 9999, the year may optionally * contain more than 4 digits. To avoid ambiguity, this is * not allowed in the basic format containing a day * of the year (i.e. when the date part is [±]YYYYDDD). */ RFCDate, /**< RFC 2822 format, * i.e. "[Wdy,] DD Mon YYYY hh:mm[:ss] ±hhmm". This format * also covers RFCs 822, 850, 1036 and 1123. * When parsing a string, it also accepts the format * "Wdy Mon DD HH:MM:SS YYYY" specified by RFCs 850 and * 1036. There is no valid date-only format. */ RFCDateDay, /**< RFC 2822 format including day of the week, * i.e. "Wdy, DD Mon YYYY hh:mm:ss ±hhmm" */ QtTextDate, /**< Same format as Qt::TextDate (i.e. Day Mon DD hh:mm:ss YYYY) * with, if not local time, the UTC offset appended. The * time may be omitted to indicate a date-only value. */ LocalDate, /**< Same format as Qt::LocalDate (i.e. locale dependent) * with, if not local time, the UTC offset appended. The * time may be omitted to indicate a date-only value. */ RFC3339Date /**< RFC 3339 format, * i.e. "YYYY-MM-DDThh:mm:ss[.sss](Z|±hh:mm)". * There is no valid date-only format. */ }; /** * How this KDateTime compares with another. * If any date-only value is involved, comparison of KDateTime values * requires them to be considered as representing time periods. A date-only * instance represents a time period from 00:00:00 to 23:59:59.999 on a given * date, while a date/time instance can be considered to represent a time * period whose start and end times are the same. They may therefore be * earlier or later, or may overlap or be contained one within the other. * * Values may be OR'ed with each other in any combination of 'consecutive' * intervals to represent different types of relationship. * * In the descriptions of the values below, * - s1 = start time of this instance * - e1 = end time of this instance * - s2 = start time of other instance * - e2 = end time of other instance. */ enum Comparison { Before = 0x01, /**< This KDateTime is strictly earlier than the other, * i.e. e1 < s2. */ AtStart = 0x02, /**< This KDateTime starts at the same time as the other, * and ends before the end of the other, * i.e. s1 = s2, e1 < e2. */ Inside = 0x04, /**< This KDateTime starts after the start of the other, * and ends before the end of the other, * i.e. s1 > s2, e1 < e2. */ AtEnd = 0x08, /**< This KDateTime starts after the start of the other, * and ends at the same time as the other, * i.e. s1 > s2, e1 = e2. */ After = 0x10, /**< This KDateTime is strictly later than the other, * i.e. s1 > e2. */ Equal = AtStart | Inside | AtEnd, /**< Simultaneous, i.e. s1 = s2 && e1 = e2. */ Outside = Before | AtStart | Inside | AtEnd | After, /**< This KDateTime starts before the start of the other, * and ends after the end of the other, * i.e. s1 < s2, e1 > e2. */ StartsAt = AtStart | Inside | AtEnd | After, /**< This KDateTime starts at the same time as the other, * and ends after the end of the other, * i.e. s1 = s2, e1 > e2. */ EndsAt = Before | AtStart | Inside | AtEnd /**< This KDateTime starts before the start of the other, * and ends at the same time as the other, * i.e. s1 < s2, e1 = e2. */ }; /** * Constructs an invalid date/time. */ KDateTime(); /** * Constructs a date-only value expressed in a given time specification. The * time is set to 00:00:00. * * The instance is initialised according to the time specification type of * @p spec as follows: * - @c UTC : date is stored as UTC. * - @c OffsetFromUTC : date is a local time at the specified offset * from UTC. * - @c TimeZone : date is a local time in the specified time zone. * - @c LocalZone : date is a local date in the current system time * zone. * - @c ClockTime : time zones are ignored. * * @param date date in the time zone indicated by @p spec * @param spec time specification */ - explicit KDateTime(const QDate &date, const Spec &spec = Spec(LocalZone)); + KDELIBS4SUPPORT_DEPRECATED explicit KDateTime(const QDate &date, const Spec &spec = Spec(LocalZone)); /** * Constructs a date/time expressed as specified by @p spec. * * @p date and @p time are interpreted and stored according to the value of * @p spec as follows: * - @c UTC : @p date and @p time are in UTC. * - @c OffsetFromUTC : date/time is a local time at the specified offset * from UTC. * - @c TimeZone : date/time is a local time in the specified time zone. * - @c LocalZone : @p date and @p time are local times in the current * system time zone. * - @c ClockTime : time zones are ignored. * * @param date date in the time zone indicated by @p spec * @param time time in the time zone indicated by @p spec * @param spec time specification */ KDateTime(const QDate &date, const QTime &time, const Spec &spec = Spec(LocalZone)); /** * Constructs a date/time expressed in a given time specification. * * @p dt is interpreted and stored according to the time specification type * of @p spec as follows: * - @c UTC : @p dt is stored as a UTC value. If * @c dt.timeSpec() is @c Qt::LocalTime, @p dt is first * converted from the current system time zone to UTC * before storage. * - @c OffsetFromUTC : date/time is stored as a local time at the specified * offset from UTC. If @c dt.timeSpec() is @c Qt::UTC, * the time is adjusted by the UTC offset before * storage. If @c dt.timeSpec() is @c Qt::LocalTime, * it is assumed to be a local time at the specified * offset from UTC, and is stored without adjustment. * - @c TimeZone : if @p dt is specified as a UTC time (i.e. @c dt.timeSpec() * is @c Qt::UTC), it is first converted to local time in * specified time zone before being stored. * - @c LocalZone : @p dt is stored as a local time in the current system * time zone. If @c dt.timeSpec() is @c Qt::UTC, @p dt is * first converted to local time before storage. * - @c ClockTime : If @c dt.timeSpec() is @c Qt::UTC, @p dt is first * converted to local time in the current system time zone * before storage. After storage, the time is treated as a * simple clock time, ignoring time zones. * * @param dt date and time * @param spec time specification */ KDateTime(const QDateTime &dt, const Spec &spec); /** * Constructs a date/time from a QDateTime. * The KDateTime is expressed in either UTC or the local system time zone, * according to @p dt.timeSpec(). * * @param dt date and time */ - explicit KDateTime(const QDateTime &dt); + KDELIBS4SUPPORT_DEPRECATED explicit KDateTime(const QDateTime &dt); KDateTime(const KDateTime &other); ~KDateTime(); KDateTime &operator=(const KDateTime &other); /** * Returns whether the date/time is null. * * @return @c true if both date and time are null, else @c false * @see isValid(), QDateTime::isNull() */ bool isNull() const; /** * Returns whether the date/time is valid. * * @return @c true if both date and time are valid, else @c false * @see isNull(), QDateTime::isValid() */ bool isValid() const; /** * Returns whether the instance represents a date/time or a date-only value. * * @return @c true if date-only, @c false if date and time */ bool isDateOnly() const; /** * Returns the date part of the date/time. The value returned should be * interpreted in terms of the instance's time zone or UTC offset. * * @return date value * @see time(), dateTime() */ QDate date() const; /** * Returns the time part of the date/time. The value returned should be * interpreted in terms of the instance's time zone or UTC offset. If * the instance is date-only, the time returned is 00:00:00. * * @return time value * @see date(), dateTime(), isDateOnly() */ QTime time() const; /** * Returns the date/time component of the instance, ignoring the time * zone. The value returned should be interpreted in terms of the * instance's time zone or UTC offset. The returned value's @c timeSpec() * value will be @c Qt::UTC if the instance is a UTC time, else * @c Qt::LocalTime. If the instance is date-only, the time value is set to * 00:00:00. * * @return date/time * @see date(), time() */ QDateTime dateTime() const; /** * Returns the time zone for the date/time. If the date/time is specified * as a UTC time, a UTC time zone is always returned. * * @return time zone, or invalid if a local time at a fixed UTC offset or a * local clock time * @see isUtc(), isLocal() */ KTimeZone timeZone() const; /** * Returns the time specification of the date/time, i.e. whether it is * UTC, what time zone it is, etc. * * @return time specification * @see isLocalZone(), isClockTime(), isUtc(), timeZone() */ Spec timeSpec() const; /** * Returns the time specification type of the date/time, i.e. whether it is * UTC, has a time zone, etc. If the type is the local time zone, * @c TimeZone is returned; use isLocalZone() to check for the local time * zone. * * @return specification type * @see timeSpec(), isLocalZone(), isClockTime(), isUtc(), timeZone() */ SpecType timeType() const; /** * Returns whether the time zone for the date/time is the current local * system time zone. * * @return @c true if local system time zone * @see isUtc(), isOffsetFromUtc(), timeZone() */ bool isLocalZone() const; /** * Returns whether the date/time is a local clock time. * * @return @c true if local clock time * @see isUtc(), timeZone() */ bool isClockTime() const; /** * Returns whether the date/time is a UTC time. * It is considered to be a UTC time if it either has a UTC time * specification (SpecType == UTC), or has a zero offset from UTC * (SpecType == OffsetFromUTC with zero UTC offset). * * @return @c true if UTC * @see isLocal(), isOffsetFromUtc(), timeZone() */ bool isUtc() const; /** * Returns whether the date/time is a local time at a fixed offset from * UTC. * * @return @c true if local time at fixed offset from UTC * @see isLocal(), isUtc(), utcOffset() */ bool isOffsetFromUtc() const; /** * Returns the UTC offset associated with the date/time. The UTC offset is * the number of seconds to add to UTC to get the local time. * * @return UTC offset in seconds, or 0 if local clock time * @see isClockTime() */ int utcOffset() const; /** * Returns whether the date/time is the second occurrence of this time. This * is only applicable to a date/time expressed in terms of a time zone (type * @c TimeZone or @c LocalZone), around the time of change from daylight * savings to standard time. * * When a shift from daylight savings time to standard time occurs, the local * times (typically the previous hour) immediately preceding the shift occur * twice. For example, if a time shift of 1 hour happens at 03:00, the clock * jumps backwards to 02:00, so the local times between 02:00:00 and 02:59:59 * occur once before the shift, and again after the shift. * * For instances which are not of type @c TimeZone, or when the date/time is * not near to a time shift, @c false is returned. * * @return @c true if the time is the second occurrence, @c false otherwise * @see setSecondOccurrence() */ bool isSecondOccurrence() const; /** * Returns the time converted to UTC. The converted time has a UTC offset * of zero. * If the instance is a local clock time, it is first set to the local time * zone, and then converted to UTC. * If the instance is a date-only value, a date-only UTC value is returned, * with the date unchanged. * * @return converted time * @see toOffsetFromUtc(), toLocalZone(), toZone(), toTimeSpec(), toTime_t(), KTimeZone::convert() */ KDateTime toUtc() const; /** * Returns the time expressed as an offset from UTC, using the UTC offset * associated with this instance's date/time. The date and time * components are unchanged. For example, 14:15 on 12 Jan 2001, US Eastern * time zone would return a KDateTime value of 14:15 on 12 Jan 2001 with a * UTC offset of -18000 seconds (i.e. -5 hours). * * If the instance is a local clock time, the offset is set to that of the * local time zone. * If the instance is a date-only value, the offset is set to that at the * start of the day. * * @return converted time * @see toUtc(), toOffsetFromUtc(int), toLocalZone(), toZone(), toTimeSpec(), toTime_t(), KTimeZone::convert() */ KDateTime toOffsetFromUtc() const; /** * Returns the time expressed as a specified offset from UTC. * * If the instance is a local clock time, it is first set to the local time * zone, and then converted to the UTC offset. * If the instance is a date-only value, a date-only clock time value is * returned, with the date unchanged. * * @param utcOffset number of seconds to add to UTC to get the local time. * @return converted time * @see toUtc(), toOffsetFromUtc(), toLocalZone(), toZone(), toTimeSpec(), toTime_t(), KTimeZone::convert() */ KDateTime toOffsetFromUtc(int utcOffset) const; /** * Returns the time converted to the current local system time zone. * If the instance is a date-only value, a date-only local time zone value * is returned, with the date unchanged. * * @return converted time * @see toUtc(), toOffsetFromUtc(), toZone(), toTimeSpec(), KTimeZone::convert() */ KDateTime toLocalZone() const; /** * Returns the time converted to the local clock time. The time is first * converted to the local system time zone before setting its type to * ClockTime, i.e. no associated time zone. * If the instance is a date-only value, a date-only clock time value is * returned, with the date unchanged. * * @return converted time * @see toLocalZone(), toTimeSpec() */ KDateTime toClockTime() const; /** * Returns the time converted to a specified time zone. * If the instance is a local clock time, it is first set to the local time * zone, and then converted to @p zone. * If the instance is a date-only value, a date-only value in @p zone is * returned, with the date unchanged. * * @param zone time zone to convert to * @return converted time * @see toUtc(), toOffsetFromUtc(), toLocalZone(), toTimeSpec(), KTimeZone::convert() */ KDateTime toZone(const KTimeZone &zone) const; /** * Returns the time converted to a new time specification. * If the instance is a local clock time, it is first set to the local time * zone, and then converted to the @p spec time specification. * If the instance is a date-only value, a date-only value is returned, * with the date unchanged. * * @param spec new time specification * @return converted time * @see toLocalZone(), toUtc(), toOffsetFromUtc(), toZone(), KTimeZone::convert() */ KDateTime toTimeSpec(const Spec &spec) const; /** * Returns the time converted to the time specification of another instance. * If this instance is a local clock time, it is first set to the local time * zone, and then converted to the @p spec time specification. * If this instance is a date-only value, a date-only value is returned, * with the date unchanged. * * @param dt instance providing the new time specification * @return converted time * @see toLocalZone(), toUtc(), toOffsetFromUtc(), toZone(), KTimeZone::convert() */ KDateTime toTimeSpec(const KDateTime &dt) const; /** * Converts the time to a UTC time, measured in seconds since 00:00:00 UTC * 1st January 1970 (as returned by time(2)). * * @return converted time, or @c uint(-1) if the date is out of range or invalid * @see setTime_t() */ uint toTime_t() const; /** * Sets the time to a UTC time, specified as seconds since 00:00:00 UTC * 1st January 1970 (as returned by time(2)). * * @param seconds number of seconds since 00:00:00 UTC 1st January 1970 * @see toTime_t() */ void setTime_t(qint64 seconds); /** * Sets the instance either to being a date and time value, or a date-only * value. If its status is changed to date-only, its time is set to * 00:00:00. * * @param dateOnly @c true to set to date-only, @c false to set to date * and time. * @see isDateOnly(), setTime() */ void setDateOnly(bool dateOnly); /** * Sets the date part of the date/time. * * @param date new date value * @see date(), setTime(), setTimeSpec(), setTime_t(), setDateOnly() */ void setDate(const QDate &date); /** * Sets the time part of the date/time. If the instance was date-only, it * is changed to being a date and time value. * * @param time new time value * @see time(), setDate(), setTimeSpec(), setTime_t() */ void setTime(const QTime &time); /** * Sets the date/time part of the instance, leaving the time specification * unaffected. * * If @p dt is a local time (\code dt.timeSpec() == Qt::LocalTime \endcode) * and the instance is UTC, @p dt is first converted from the current * system time zone to UTC before being stored. * * If the instance was date-only, it is changed to being a date and time * value. * * @param dt date and time * @see dateTime(), setDate(), setTime(), setTimeSpec() */ void setDateTime(const QDateTime &dt); /** * Changes the time specification of the instance. * * Any previous time zone is forgotten. The stored date/time component of * the instance is left unchanged (except that its UTC/local time setting * is set to correspond with @p spec). Usually this method will change the * absolute time which this instance represents. * * @param spec new time specification * @see timeSpec(), timeZone() */ void setTimeSpec(const Spec &spec); /** * Sets whether the date/time is the second occurrence of this time. This * is only applicable to a date/time expressed in terms of a time zone (type * @c TimeZone or @c LocalZone), around the time of change from daylight * savings to standard time. * * When a shift from daylight savings time to standard time occurs, the local * times (typically the previous hour) immediately preceding the shift occur * twice. For example, if a time shift of 1 hour happens at 03:00, the clock * jumps backwards to 02:00, so the local times between 02:00:00 and 02:59:59 * occur once before the shift, and again after the shift. * * For instances which are not of type @c TimeZone, or when the date/time is * not near to a time shift, calling this method has no effect. * * Note that most other setting methods clear the second occurrence indicator, * so if you want to retain its setting, you must call setSecondOccurrence() * again after changing the instance's value. * * @param second @c true to set as the second occurrence, @c false to set as * the first occurrence * @see isSecondOccurrence() */ void setSecondOccurrence(bool second); /** * Returns a date/time @p msecs milliseconds later than the stored date/time. * * Except when the instance is a local clock time (type @c ClockTime), the * calculation is done in UTC to ensure that the result takes proper account * of clock changes (e.g. daylight savings) in the time zone. The result is * expressed using the same time specification as the original instance. * * Note that if the instance is a local clock time (type @c ClockTime), any * daylight savings changes or time zone changes during the period will * render the result inaccurate. * * If the instance is date-only, @p msecs is rounded down to a whole number * of days and that value is added to the date to find the result. * * @return resultant date/time * @see addSecs(), addDays(), addMonths(), addYears(), secsTo() */ KDateTime addMSecs(qint64 msecs) const; /** * Returns a date/time @p secs seconds later than the stored date/time. * * Except when the instance is a local clock time (type @c ClockTime), the * calculation is done in UTC to ensure that the result takes proper account * of clock changes (e.g. daylight savings) in the time zone. The result is * expressed using the same time specification as the original instance. * * Note that if the instance is a local clock time (type @c ClockTime), any * daylight savings changes or time zone changes during the period will * render the result inaccurate. * * If the instance is date-only, @p secs is rounded down to a whole number * of days and that value is added to the date to find the result. * * @return resultant date/time * @see addMSecs(), addDays(), addMonths(), addYears(), secsTo() */ KDateTime addSecs(qint64 secs) const; /** * Returns a date/time @p days days later than the stored date/time. * The result is expressed using the same time specification as the * original instance. * * Note that if the instance is a local clock time (type @c ClockTime), any * daylight savings changes or time zone changes during the period may * render the result inaccurate. * * @return resultant date/time * @see addSecs(), addMonths(), addYears(), daysTo() */ KDateTime addDays(qint64 days) const; /** * Returns a date/time @p months months later than the stored date/time. * The result is expressed using the same time specification as the * original instance. * * Note that if the instance is a local clock time (type @c ClockTime), any * daylight savings changes or time zone changes during the period may * render the result inaccurate. * * @return resultant date/time * @see addSecs(), addDays(), addYears(), daysTo() */ KDateTime addMonths(int months) const; /** * Returns a date/time @p years years later than the stored date/time. * The result is expressed using the same time specification as the * original instance. * * Note that if the instance is a local clock time (type @c ClockTime), any * daylight savings changes or time zone changes during the period may * render the result inaccurate. * * @return resultant date/time * @see addSecs(), addDays(), addMonths(), daysTo() */ KDateTime addYears(int years) const; /** * Returns the number of seconds from this date/time to the @p other date/time. * * Before performing the comparison, the two date/times are converted to UTC * to ensure that the result is correct if one of the two date/times has * daylight saving time (DST) and the other doesn't. The exception is when * both instances are local clock time, in which case no conversion to UTC * is done. * * Note that if either instance is a local clock time (type @c ClockTime), * the result cannot be guaranteed to be accurate, since by definition they * contain no information about time zones or daylight savings changes. * * If one instance is date-only and the other is date-time, the date-time * value is first converted to the same time specification as the date-only * value, and the result is the difference in days between the resultant * date and the date-only date. * * If both instances are date-only, the result is the difference in days * between the two dates, ignoring time zones. * * @param other other date/time * @return number of seconds difference * @see addSecs(), daysTo() */ qint64 secsTo(const KDateTime &other) const; /** * @deprecated Since 5.0, use @c secsTo instead * * Returns the number of seconds from this date/time to the @p other date/time. * * Before performing the comparison, the two date/times are converted to UTC * to ensure that the result is correct if one of the two date/times has * daylight saving time (DST) and the other doesn't. The exception is when * both instances are local clock time, in which case no conversion to UTC * is done. * * Note that if either instance is a local clock time (type @c ClockTime), * the result cannot be guaranteed to be accurate, since by definition they * contain no information about time zones or daylight savings changes. * * If one instance is date-only and the other is date-time, the date-time * value is first converted to the same time specification as the date-only * value, and the result is the difference in days between the resultant * date and the date-only date. * * If both instances are date-only, the result is the difference in days * between the two dates, ignoring time zones. * * @param other other date/time * @return number of seconds difference * @see secsTo(), addSecs(), daysTo() */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED inline qint64 secsTo_long(const KDateTime &other) const { return secsTo(other); } #endif /** * Calculates the number of days from this date/time to the @p other date/time. * In calculating the result, @p other is first converted to this instance's * time zone. The number of days difference is then calculated ignoring * the time parts of the two date/times. For example, if this date/time * was 13:00 on 1 January 2000, and @p other was 02:00 on 2 January 2000, * the result would be 1. * * Note that if either instance is a local clock time (type @c ClockTime), * the result cannot be guaranteed to be accurate, since by definition they * contain no information about time zones or daylight savings changes. * * If one instance is date-only and the other is date-time, the date-time * value is first converted to the same time specification as the date-only * value, and the result is the difference in days between the resultant * date and the date-only date. * * If both instances are date-only, the calculation ignores time zones. * * @param other other date/time * @return number of days difference * @see secsTo(), addDays() */ qint64 daysTo(const KDateTime &other) const; /** * Returns the current date and time, as reported by the system clock, * expressed in the local system time zone. * * @return current date/time * @see currentUtcDateTime(), currentDateTime() */ static KDateTime currentLocalDateTime(); /** * Returns the current date and time, as reported by the system clock, * expressed in UTC. * * @return current date/time * @see currentLocalDateTime(), currentDateTime(), currentLocalDate(), currentLocalTime() */ static KDateTime currentUtcDateTime(); /** * Returns the current date and time, as reported by the system clock, * expressed in a given time specification. * * @note To fetch the current date and time expressed in UTC or in the local * system time zone, it is more efficient to use currentUtcDateTime() or * currentLocalDateTime(). * * @param spec time specification * @return current date/time * @see currentUtcDateTime(), currentLocalDateTime() */ static KDateTime currentDateTime(const Spec &spec); /** * Returns the current date in the local time zone, as reported by the * system clock. * * @return current date * @see currentLocalDateTime(), currentLocalTime() * @since 4.3 */ static QDate currentLocalDate(); /** * Returns the current time of day in the local time zone, as reported * by the system clock. * * @return current date * @see currentLocalDateTime(), currentLocalDate() * @since 4.3 */ static QTime currentLocalTime(); /** * Returns the date/time as a string. The @p format parameter determines the * format of the result string. The @p format codes used for the date and time * components follow those used elsewhere in KDE, and are similar but not * identical to those used by strftime(3). Conversion specifiers are * introduced by a '\%' character, and are replaced in @p format as follows: * * \b Date * * - \%y 2-digit year excluding century (00 - 99). Conversion is undefined * if year < 0. * - \%Y full year number * - %:m month number, without leading zero (1 - 12) * - \%m month number, 2 digits (01 - 12) * - \%b abbreviated month name in current locale * - \%B full month name in current locale * - %:b abbreviated month name in English (Jan, Feb, ...) * - %:B full month name in English * - \%e day of the month (1 - 31) * - \%d day of the month, 2 digits (01 - 31) * - \%a abbreviated weekday name in current locale * - \%A full weekday name in current locale * - %:a abbreviated weekday name in English (Mon, Tue, ...) * - %:A full weekday name in English * * \b Time * * - \%H hour in the 24 hour clock, 2 digits (00 - 23) * - \%k hour in the 24 hour clock, without leading zero (0 - 23) * - \%I hour in the 12 hour clock, 2 digits (01 - 12) * - \%l hour in the 12 hour clock, without leading zero (1 - 12) * - \%M minute, 2 digits (00 - 59) * - \%S seconds (00 - 59) * - %:S seconds preceded with ':', but omitted if seconds value is zero * - %:s milliseconds, 3 digits (000 - 999) * - \%P "am" or "pm" in the current locale, or if undefined there, in English * - \%p "AM" or "PM" in the current locale, or if undefined there, in English * - %:P "am" or "pm" * - %:p "AM" or "PM" * * \b Time zone * * - %:u UTC offset of the time zone in hours, e.g. -02. If the offset * is not a whole number of hours, the output is the same as for '\%U'. * - \%z UTC offset of the time zone in hours and minutes, e.g. -0200. * - %:z UTC offset of the time zone in hours and minutes, e.g. +02:00. * - \%Z time zone abbreviation, e.g. UTC, EDT, GMT. This is not guaranteed * to be unique among different time zones. If not applicable (i.e. if * the instance is type OffsetFromUTC), the UTC offset is substituted. * - %:Z time zone name, e.g. Europe/London. This is system dependent. If * not applicable (i.e. if the instance is type OffsetFromUTC), the * UTC offset is substituted. * * \b Other * * - %% literal '\%' character * * Note that if the instance has a time specification of ClockTime, the * time zone or UTC offset in the result will be blank. * * If you want to use the current locale's date format, you should call * KLocale::formatDate() to format the date part of the KDateTime. * * @param format format for the string * @return formatted string * @see fromString(), KLocale::formatDate() */ QString toString(const QString &format) const; /** * Returns the date/time as a string, formatted according to the @p format * parameter, with the UTC offset appended. * * Note that if the instance has a time specification of ClockTime, the UTC * offset in the result will be blank, except for RFC 2822 and RFC 3339 * formats in which it will be the offset for the local system time zone. * * If the instance is date-only, the time will when @p format permits be * omitted from the output string. This applies to @p format = QtTextDate * or LocalDate. It also applies to @p format = ISODate when the instance * has a time specification of ClockTime. For all other cases, a time of * 00:00:00 will be output. * * For RFC 2822 format, set @p format to RFCDateDay to include the day * of the week, or to RFCDate to omit it. * * @param format format for output string * @return formatted string * @see fromString(), QDateTime::toString() */ QString toString(TimeFormat format = ISODate) const; /** * Returns the KDateTime represented by @p string, using the @p format given. * * This method is the inverse of toString(TimeFormat), except that it can * only return a time specification of UTC, OffsetFromUTC or ClockTime. An * actual named time zone cannot be returned since an offset from UTC only * partially specifies a time zone. * * The time specification of the result is determined by the UTC offset * present in the string: * - if the UTC offset is zero the result is type @c UTC. * - if the UTC offset is non-zero, the result is type @c OffsetFromUTC. * - if there is no UTC offset (when @p format permits this), the result is * by default type @c ClockTime. You can use setFromStringDefault() to * change this default. * * If no time is found in @p string, a date-only value is returned, except * when the specified @p format does not permit the time to be omitted, in * which case an error is returned. An error is therefore returned for * ISODate when @p string includes a time zone specification, and for * RFCDate in all cases. * * For RFC format strings (not RFC 3339), you should normally set @p format * to RFCDate. Only set it to RFCDateDay if you want to return an error * when the day of the week is omitted. * * @param string string to convert * @param format format code. LocalDate cannot be used here. * @param negZero if non-null, the value is set to true if a UTC offset of * '-0000' is found or, for RFC 2822 format, an unrecognised * or invalid time zone abbreviation is found, else false. * @return KDateTime value, or an invalid KDateTime if either parameter is invalid * @see setFromStringDefault(), toString(), QString::fromString() */ static KDateTime fromString(const QString &string, TimeFormat format = ISODate, bool *negZero = nullptr); /** * Returns the KDateTime represented by @p string, using the @p format * given, optionally using a time zone collection @p zones as the source of * time zone definitions. The @p format codes are basically the same as * those for toString(), and are similar but not identical to those used by * strftime(3). * * The @p format string consists of the same codes as that for * toString(). However, some codes which are distinct in toString() have * the same function as each other here. * * Numeric values without a stated number of digits permit, but do not * require, leading zeroes. The maximum number of digits consumed by a * numeric code is the minimum needed to cover the possible range of the * number (e.g. for minutes, the range is 0 - 59, so the maximum number of * digits consumed is 2). All non-numeric values are case insensitive. * * \b Date * * - \%y year excluding century (0 - 99). Years 0 - 50 return 2000 - 2050, * while years 51 - 99 return 1951 - 1999. * - \%Y full year number (4 digits with optional sign) * - %:Y full year number (>= 4 digits with optional sign) * - %:m month number (1 - 12) * - \%m month number, 2 digits (01 - 12) * - \%b * - \%B month name in the current locale or, if no match, in English, * abbreviated or in full * - %:b * - %:B month name in English, abbreviated or in full * - \%e day of the month (1 - 31) * - \%d day of the month, 2 digits (01 - 31) * - \%a * - \%A weekday name in the current locale or, if no match, in English, * abbreviated or in full * - %:a * - %:A weekday name in English, abbreviated or in full * * \b Time * * - \%H hour in the 24 hour clock, 2 digits (00 - 23) * - \%k hour in the 24 hour clock (0 - 23) * - \%I hour in the 12 hour clock, 2 digits (01 - 12) * - \%l hour in the 12 hour clock (1 - 12) * - \%M minute, 2 digits (00 - 59) * - %:M minute (0 - 59) * - \%S seconds, 2 digits (00 - 59) * - \%s seconds (0 - 59) * - %:S optional seconds value (0 - 59) preceded with ':'. If no colon is * found in @p string, no input is consumed and the seconds value is * set to zero. * - %:s fractional seconds value, preceded with a decimal point (either '.' * or the locale's decimal point symbol) * - \%P * - \%p "am" or "pm", in the current locale or, if no match, in * English. This format is only useful when used with \%I or \%l. * - %:P * - %:p "am" or "pm" in English. This format is only useful when used with * \%I or \%l. * * \b Time zone * * - %:u * - \%z UTC offset of the time zone in hours and optionally minutes, * e.g. -02, -0200. * - %:z UTC offset of the time zone in hours and minutes, colon separated, * e.g. +02:00. * - \%Z time zone abbreviation, consisting of alphanumeric characters, * e.g. UTC, EDT, GMT. * - %:Z time zone name, e.g. Europe/London. The name may contain any * characters and is delimited by the following character in the * @p format string. It will not work if you follow %:Z with another * escape sequence (except %% or \%t). * * \b Other * * - \%t matches one or more whitespace characters * - %% literal '\%' character * * Any other character must have a matching character in @p string, except * that a space will match zero or more whitespace characters in the input * string. * * If any time zone information is present in the string, the function * attempts to find a matching time zone in the @p zones collection. A time * zone name (format code %:Z) will provide an unambiguous look up in * @p zones. Any other type of time zone information (an abbreviated time * zone code (\%Z) or UTC offset (\%z, %:z, %:u) is searched for in @p zones * and if only one time zone is found to match, the result is set to that * zone. Otherwise: * - If more than one match of a UTC offset is found, the action taken is * determined by @p offsetIfAmbiguous: if @p offsetIfAmbiguous is true, * a local time with an offset from UTC (type @c OffsetFromUTC) will be * returned; if false an invalid KDateTime is returned. * - If more than one match of a time zone abbreviation is found, the UTC * offset for each matching time zone is compared and, if the offsets are * the same, a local time with an offset from UTC (type @c OffsetFromUTC) * will be returned provided that @p offsetIfAmbiguous is true. Otherwise * an invalid KDateTime is returned. * - If a time zone abbreviation does not match any time zone in @p zones, * or the abbreviation does not apply at the parsed date/time, an * invalid KDateTime is returned. * - If a time zone name does not match any time zone in @p zones, an * invalid KDateTime is returned. * - If the time zone UTC offset does not match any time zone in @p zones, * a local time with an offset from UTC (type @c OffsetFromUTC) is * returned. * If @p format contains more than one time zone or UTC offset code, an * error is returned. * * If no time zone information is present in the string, by default a local * clock time (type @c ClockTime) is returned. You can use * setFromStringDefault() to change this default. * * If no time is found in @p string, a date-only value is returned. * * If any inconsistencies are found, i.e. the same item of information * appears more than once but with different values, the weekday name does * not tally with the date, an invalid KDateTime is returned. * * @param string string to convert * @param format format string * @param zones time zone collection, or null for none * @param offsetIfAmbiguous specifies what to do if more than one zone * matches the UTC offset found in the * string. Ignored if @p zones is null. * @return KDateTime value, or an invalid KDateTime if an error occurs, if * time zone information doesn't match any in @p zones, or if the * time zone information is ambiguous and @p offsetIfAmbiguous is * false * @see setFromStringDefault(), toString() */ static KDateTime fromString(const QString &string, const QString &format, const KTimeZones *zones = nullptr, bool offsetIfAmbiguous = true); /** * Sets the default time specification for use by fromString() when no time * zone or UTC offset is found in the string being parsed, or when "-0000" * is found in an RFC 2822 string. * * By default, fromString() returns a local clock time (type @c ClockTime) * when no definite zone or UTC offset is found. You can use this method * to make it return the local time zone, UTC, or whatever you wish. * * @param spec the new default time specification * @see fromString() */ static void setFromStringDefault(const Spec &spec); /** * Always returns false, as dates earlier than -4712 are now supported by * @c KDateTime. * * @return @c false * @see isValid() * @deprecated Since 5.0, we now supports all valid dates. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED inline bool outOfRange() const { return false; } #endif /** * Compare this instance with another to determine whether they are * simultaneous, earlier or later, and in the case of date-only values, * whether they overlap (i.e. partly coincide but are not wholly * simultaneous). * The comparison takes time zones into account: if the two instances have * different time zones, they are first converted to UTC before comparing. * * If both instances are date/time values, this instance is considered to * be either simultaneous, earlier or later, and does not overlap. * * If one instance is date-only and the other is a date/time, this instance * is either strictly earlier, strictly later, or overlaps. * * If both instance are date-only, they are considered simultaneous if both * their start of day and end of day times are simultaneous with each * other. (Both start and end of day times need to be considered in case a * daylight savings change occurs during that day.) Otherwise, this instance * can be strictly earlier, earlier but overlapping, later but overlapping, * or strictly later. * * Note that if either instance is a local clock time (type @c ClockTime), * the result cannot be guaranteed to be correct, since by definition they * contain no information about time zones or daylight savings changes. * * @return @c true if the two instances represent the same time, @c false otherwise * @see operator==(), operator!=(), operator<(), operator<=(), operator>=(), operator>() */ Comparison compare(const KDateTime &other) const; /** * Check whether this date/time is simultaneous with another. * The comparison takes time zones into account: if the two instances have * different time zones, they are first converted to UTC before comparing. * * Note that if either instance is a local clock time (type @c ClockTime), * the result cannot be guaranteed to be correct, since by definition they * contain no information about time zones or daylight savings changes. * * If one instance is date-only and the other is date/time, they are * considered unequal. * * If both instances are date-only, they are considered simultaneous if both * their start of day and end of day times are simultaneous with each * other. (Both start and end of day times need to be considered in case a * daylight saving change occurs during that day.) * * @return @c true if the two instances represent the same time, @c false otherwise * @see compare() */ bool operator==(const KDateTime &other) const; bool operator!=(const KDateTime &other) const { return !(*this == other); } /** * Check whether this date/time is earlier than another. * The comparison takes time zones into account: if the two instances have * different time zones, they are first converted to UTC before comparing. * * Note that if either instance is a local clock time (type @c ClockTime), * the result cannot be guaranteed to be correct, since by definition they * contain no information about time zones or daylight savings changes. * * If one or both instances are date-only, the comparison returns true if * this date/time or day, falls wholly before the other date/time or * day. To achieve this, the time used in the comparison is the end of day * (if this instance is date-only) or the start of day (if the other * instance is date-only). * * @return @c true if this instance represents an earlier time than @p other, * @c false otherwise * @see compare() */ bool operator<(const KDateTime &other) const; bool operator<=(const KDateTime &other) const { return !(other < *this); } bool operator>(const KDateTime &other) const { return other < *this; } bool operator>=(const KDateTime &other) const { return !(*this < other); } /** * Create a separate copy of this instance's data if it is implicitly shared * with another instance. * * You would normally only call this if you want different copies of the * same date/time value to cache conversions to different time zones. Because * only the last conversion to another time zone is cached, and the cached * value is implicitly shared, judicious use of detach() could improve * efficiency when handling several time zones. But take care: if used * inappropriately, it will reduce efficiency! */ void detach(); /** * Set an adjustment to be applied when fetching the current system time. * This is applied by all KDateTime methods which return the system date * and/or time. * * The supplied date/time is used as the current simulated time and the * time adjustment is set to the difference between the real current time * and @p newTime. If @p newTime has a time zone, that time zone is set * to be the simulated local system time zone by calling * KSystemTimeZones::setLocalZone()). * * To cancel time simulation, supply an invalid @p newTime parameter. * * @warning This function is provided only for testing purposes, and should * not be used in released code. If the library is compiled without * debug enabled, setSimulatedSystemTime() has no effect. * To avoid confusion, it is recommended that calls to it should be * conditionally compiled, e.g.: * \code * #ifndef NDEBUG * KDateTime::simulateSystemTime(kdt); * #endif * \endcode * * @param newTime the current simulated time, or invalid to cancel simulation * * @see currentDateTime(), currentLocalDateTime(), currentUtcDateTime(), * currentLocalDate(), currentLocalTime() * @since 4.3 */ static void setSimulatedSystemTime(const KDateTime &newTime); /** * Return the real (not simulated) system time. * * @warning This method is provided only for testing purposes, and should * not be used in released code. If the library is compiled without * debug enabled, currentLocalDateTime() and realCurrentLocalDateTime() * both return the real system time. * To avoid confusion, it is recommended that calls to * realCurrentLocalDateTime() should be conditionally compiled, e.g.: * \code * #ifndef NDEBUG * dt = KDateTime::realCurrentLocalDateTime(); * #endif * \endcode * * @since 4.3 */ static KDateTime realCurrentLocalDateTime(); friend QDataStream KDELIBS4SUPPORT_EXPORT &operator<<(QDataStream &out, const KDateTime &dateTime); friend QDataStream KDELIBS4SUPPORT_EXPORT &operator>>(QDataStream &in, KDateTime &dateTime); private: QSharedDataPointer d; }; Q_DECLARE_METATYPE(KDateTime) Q_DECLARE_METATYPE(KDateTime::Spec) /** Write @p spec to the datastream @p out, in binary format. */ QDataStream KDELIBS4SUPPORT_EXPORT &operator<<(QDataStream &out, const KDateTime::Spec &spec); /** Read a KDateTime::Spec object into @p spec from @p in, in binary format. */ QDataStream KDELIBS4SUPPORT_EXPORT &operator>>(QDataStream &in, KDateTime::Spec &spec); /** Write @p dateTime to the datastream @p out, in binary format. */ QDataStream KDELIBS4SUPPORT_EXPORT &operator<<(QDataStream &out, const KDateTime &dateTime); /** Read a KDateTime object into @p dateTime from @p in, in binary format. */ QDataStream KDELIBS4SUPPORT_EXPORT &operator>>(QDataStream &in, KDateTime &dateTime); #endif diff --git a/src/kdecore/kdatetimeformatter_p.h b/src/kdecore/kdatetimeformatter_p.h index f16de89b..584a5d3d 100644 --- a/src/kdecore/kdatetimeformatter_p.h +++ b/src/kdecore/kdatetimeformatter_p.h @@ -1,97 +1,97 @@ /* Copyright 2010 John Layt 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 KDATETIMEFORMATTER_H #define KDATETIMEFORMATTER_H #include "klocale.h" class QChar; class QString; class QDate; class QTime; class KDateTime; class KCalendarSystem; class KDateTimeFormatter { public: - explicit KDateTimeFormatter(); + KDELIBS4SUPPORT_DEPRECATED explicit KDateTimeFormatter(); virtual ~KDateTimeFormatter(); virtual QString formatDate(const QDate &fromDate, const QString &toFormat, const KCalendarSystem *calendar = KLocale::global()->calendar(), const KLocale *locale = KLocale::global(), KLocale::DigitSet digitSet = KLocale::global()->dateTimeDigitSet(), KLocale::DateTimeFormatStandard standard = KLocale::KdeFormat) const; virtual QString formatTime(const QTime &fromTime, const QString &toFormat, KLocale::TimeFormatOptions timeOptions = nullptr, const KCalendarSystem *calendar = KLocale::global()->calendar(), const KLocale *locale = KLocale::global(), KLocale::DigitSet digitSet = KLocale::global()->dateTimeDigitSet(), KLocale::DateTimeFormatStandard standard = KLocale::KdeFormat) const; virtual QString formatDateTime(const KDateTime &fromDateTime, const QString &toFormat, KLocale::TimeFormatOptions timeOptions = nullptr, const KCalendarSystem *calendar = KLocale::global()->calendar(), const KLocale *locale = KLocale::global(), KLocale::DigitSet digitSet = KLocale::global()->dateTimeDigitSet(), KLocale::DateTimeFormatStandard standard = KLocale::KdeFormat) const; private: virtual QString formatDateTimePosix(const KDateTime &fromDateTime, const QString &toFormat, KLocale::TimeFormatOptions timeOptions, const KCalendarSystem *calendar, const KLocale *locale, KLocale::DigitSet digitSet, KLocale::DateTimeFormatStandard standard) const; virtual void initEnglish(const KCalendarSystem *calendar, const KLocale *locale) const; virtual QString formatDateTimeUnicode(const KDateTime &fromDateTime, const QString &toFormat, KLocale::TimeFormatOptions timeOptions, const KCalendarSystem *calendar, const KLocale *locale, KLocale::DigitSet digitSet) const; virtual QString getUnicodeString(const KDateTime &fromDateTime, const QString &toFormat, KLocale::TimeFormatOptions timeOptions, const KCalendarSystem *calendar, const KLocale *locale, KLocale::DigitSet digitSet) const; virtual QString stringFromInteger(int number, int padWidth, QChar padChar, QChar signChar, KLocale::DigitSet digitSet, const KLocale *locale) const; // Is private class, but if ever made public need to move these into a d-> // Some format modifiers force English names to be returned mutable KLocale *m_englishLocale; mutable KCalendarSystem *m_englishCalendar; }; #endif // KDATETIMEFORMATTER_H diff --git a/src/kdecore/kdatetimeparser_p.h b/src/kdecore/kdatetimeparser_p.h index 81e7ebfa..339b9785 100644 --- a/src/kdecore/kdatetimeparser_p.h +++ b/src/kdecore/kdatetimeparser_p.h @@ -1,79 +1,79 @@ /* Copyright 2010 John Layt 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 KDATETIMEPARSER_H #define KDATETIMEPARSER_H #include "klocale.h" class QChar; class QString; class QDate; class QTime; class KDateTime; class KCalendarSystem; struct DateTimeComponents { int day; int month; int year; bool parsedYear; QString eraName; int yearInEra; int dayInYear; int isoWeekNumber; int dayOfIsoWeek; int inputPosition; int formatPosition; bool error; }; class KDateTimeParser { public: - explicit KDateTimeParser(); + KDELIBS4SUPPORT_DEPRECATED explicit KDateTimeParser(); virtual ~KDateTimeParser(); virtual QDate parseDate(const QString &dateString, const QString &format, const KCalendarSystem *calendar = KLocale::global()->calendar(), const KLocale *locale = KLocale::global(), KLocale::DigitSet digitSet = KLocale::ArabicDigits, KLocale::DateTimeFormatStandard standard = KLocale::KdeFormat) const; private: virtual DateTimeComponents parseDatePosix(const QString &dateString, const QString &format, const KCalendarSystem *calendar, const KLocale *locale, KLocale::DigitSet digitSet, KLocale::DateTimeFormatStandard standard) const; virtual DateTimeComponents parseDateUnicode(const QString &inputString, const QString &format, const KCalendarSystem *calendar, const KLocale *locale, KLocale::DigitSet digitSet) const; virtual int integerFromString(const QString &string, int maxLength, int &readLength) const; }; #endif // KDATETIMEPARSER_H diff --git a/src/kdecore/kdayperiod_p.h b/src/kdecore/kdayperiod_p.h index 8de4916e..d6146734 100644 --- a/src/kdecore/kdayperiod_p.h +++ b/src/kdecore/kdayperiod_p.h @@ -1,175 +1,175 @@ /* Copyright (c) 2010 John Layt 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 KDAYPERIOD_H #define KDAYPERIOD_H #include #include "klocale.h" #include class QDate; class QString; class QTime; class KDayPeriodPrivate; /** * @internal * @since 4.6 * * This class is internal for now but may later be exported if required. * * This is a class to implement the CLDR Day Period Rules. * * Most commonly this will be used to implement support for the 12 hour clock * e.g. 00:00:00 to 11:59:59.999 is AM and 12:00:00 to 23:59:59.999 is PM. * However CLDR Day Period Rules cater for cultures where the day may be divided * into more periods than just AM/PM. * See http://www.unicode.org/reports/tr35/tr35-15.html#DayPeriodRules * * @b license GNU-LGPL v.2 or later * * @see KLocale * * @author John Layt */ class KDayPeriod { public: /** * Constructs a KDayPeriod for a given time period * * @param periodCode the unique code for the period * @param longName the KLocale::LongName of the Day Period * @param shortName the KLocale::ShortName of the Day Period * @param narrowName the KLocale::NarrowName of the Day Period * @param periodStart the inclusive Start Time of the Day Period * @param periodEnd the inclusive End Time of the Day Period * @param offsetFromStart offset of hour in period from the periodStart * @param offsetIfZero if hour is 0, what should it be converted to */ KDayPeriod(const QString &periodCode, const QString &longName, const QString &shortName, const QString &narrowName, const QTime &periodStart, const QTime &periodEnd, int offsetFromStart, int offsetIfZero); /** * Constructs a null KDayPeriod */ - explicit KDayPeriod(); + KDELIBS4SUPPORT_DEPRECATED explicit KDayPeriod(); /** * Copy Constructor * * @param rhs KDayPeriod to copy * */ KDayPeriod(const KDayPeriod &rhs); /** * Destructor. */ virtual ~KDayPeriod(); /** * Assignment operator * * @param rhs KDayPeriod to assign * */ KDayPeriod &operator=(const KDayPeriod &rhs); /** * Return the Period Code * * @return the Period Code */ QString periodCode() const; /** * Return the time the Period starts at * * @return the time the Period starts */ QTime periodStart() const; /** * Return the time the Period ends at * * @return the time the Period ends */ QTime periodEnd() const; /** * Return translated Period Name in the required format * e.g. Ante Meridian, AM or A * * @param format the name format to return * @return the Period Name */ QString periodName(KLocale::DateTimeComponentFormat format = KLocale::ShortName) const; /** * Calculate and return the hour in the Day Period for a given 24h time. * * For example, 17:00 would return 5 in the PM period of the standard 12 hour clock * * @param time the time to return the hour for * @return the Hour in the Day Period */ int hourInPeriod(const QTime &time) const; /** * Calculate and return the 24hr time for a given hms in the Day Period * * For example, 5 in the PM period of the standard 12 hour clock would return 17:00 * * @param hourInPeriod the hour in the day period * @param minute the minute in the hour * @param second the second in the minute * @param millisecond the millisecond in the second * @return the Time in the 24hr clock */ QTime time(int hourInPeriod, int minute, int second, int millisecond = 0) const; /** * Return if the Day Period is valid * * @return if the Day Period is valid */ bool isValid() const; /** * Return if a given time is in the Day Period * * @return if the time is valid in the Day Period */ bool isValid(const QTime &time) const; private: QSharedDataPointer d; }; #endif // KDAYPERIOD_H diff --git a/src/kdecore/kdebug.h b/src/kdecore/kdebug.h index fe0e1d1a..61eeb420 100644 --- a/src/kdecore/kdebug.h +++ b/src/kdecore/kdebug.h @@ -1,468 +1,468 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org) 2000-2002 Stephan Kulow (coolo@kde.org) 2002 Holger Freyther (freyther@kde.org) 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 _KDEBUG_H_ #define _KDEBUG_H_ #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif #include #include /** * \addtogroup kdebug Debug message generators * @{ * KDE debug message streams let you and the user control just how many debug * messages you see. Debug message printing is controlled by (un)defining * QT_NO_DEBUG when compiling your source. If QT_NO_DEBUG is defined then debug * messages are not printed by default but can still be enabled by runtime * configuration, e.g. via kdebugdialog5 or by editing kdebugrc. * * You can also control what you see: see QT_MESSAGE_PATTERN in the QDebug documentation. * This is new in Qt 5.0 and replaces the KDE_DEBUG_* variables from KDE 4.x. */ #if !defined(KDE_NO_DEBUG_OUTPUT) # if defined(QT_NO_DEBUG_OUTPUT) || defined(QT_NO_DEBUG_STREAM) # define KDE_NO_DEBUG_OUTPUT # endif #endif #if !defined(KDE_NO_WARNING_OUTPUT) # if defined(QT_NO_WARNING_OUTPUT) # define KDE_NO_WARNING_OUTPUT # endif #endif #ifdef QT_NO_DEBUG /* The application is compiled in release mode */ # define KDE_DEBUG_ENABLED_BY_DEFAULT false #else # define KDE_DEBUG_ENABLED_BY_DEFAULT true #endif /** * An indicator of where you are in a source file, to be used in * warnings (perhaps debug messages too). * @deprecated kDebug takes care of printing the method name automatically now */ #define k_funcinfo "" /** * An indicator of where you are in a source file, to be used in * warnings (perhaps debug messages too). Gives an accurate * idea of where the message comes from. Not suitable for * user-visible messages. * @deprecated kDebug takes care of printing the method name automatically now */ #define k_lineinfo "[" << __FILE__ << ":" << __LINE__ << "] " /** * @internal * Returns a debug stream that may or may not output anything. */ KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE QDebug kDebugStream(QtMsgType level, int area, const char *file = nullptr, int line = -1, const char *funcinfo = nullptr); /** * @internal * Returns a debug stream that goes the way of the blackhole. */ KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE QDebug kDebugDevNull(); /** * @internal * The actual backtrace. */ KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE QString kRealBacktrace(int); /** * \relates KGlobal * Returns a backtrace. * Note: Hidden symbol visibility may negatively affect the information provided * by kBacktrace - you may want to pass -D__KDE_HAVE_GCC_VISIBILITY=0 to cmake * to turn hidden symbol visibility off. * @param levels the number of levels of the backtrace * @return a backtrace */ #if !defined(KDE_NO_DEBUG_OUTPUT) inline QString kBacktrace(int levels = -1) { return kRealBacktrace(levels); } #else static inline QString kBacktrace(int = -1) { return QString(); } #endif /** * \relates KGlobal * Deletes the kdebugrc cache and therefore forces KDebug to reread the * config file */ KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE void kClearDebugConfig(); #ifndef KDE_DEFAULT_DEBUG_AREA # define KDE_DEFAULT_DEBUG_AREA 0 #endif /*! \macro KDE_DEFAULT_DEBUG_AREA \relates KGlobal Denotes the debug area to use in kDebug/kWarning etc when not - explicitly specified. The default is 0 (zero). + KDELIBS4SUPPORT_DEPRECATED explicitly specified. The default is 0 (zero). Define this macro to the debug area of your application/component before including any KDE headers. Usually, you want to add code like this to your \c CMakeLists.txt: \code ... add_definitions( -DKDE_DEFAULT_DEBUG_AREA=1234 ) ... \endcode This way, you save repeating the debug area all over your source code, in each debug/warning statement. */ #if !defined(KDE_NO_DEBUG_OUTPUT) /** * \relates KGlobal * Returns a debug stream. You can use it to print debug * information. * @param area an id to identify the output, KDE_DEFAULT_DEBUG_AREA for default */ static inline QDebug kDebug(int area = KDE_DEFAULT_DEBUG_AREA) { return kDebugStream(QtDebugMsg, area); } static inline QDebug kDebug(bool cond, int area = KDE_DEFAULT_DEBUG_AREA) { return cond ? kDebug(area) : kDebugDevNull(); } #else // KDE_NO_DEBUG_OUTPUT static inline QDebug kDebug(int = KDE_DEFAULT_DEBUG_AREA) { return kDebugDevNull(); } static inline QDebug kDebug(bool, int = KDE_DEFAULT_DEBUG_AREA) { return kDebugDevNull(); } #endif #if !defined(KDE_NO_WARNING_OUTPUT) /** * \relates KGlobal * Returns a warning stream. You can use it to print warning * information. * @param area an id to identify the output, KDE_DEFAULT_DEBUG_AREA for default */ static inline QDebug kWarning(int area = KDE_DEFAULT_DEBUG_AREA) { return kDebugStream(QtWarningMsg, area); } static inline QDebug kWarning(bool cond, int area = KDE_DEFAULT_DEBUG_AREA) { return cond ? kWarning(area) : kDebugDevNull(); } #else // KDE_NO_WARNING_OUTPUT static inline QDebug kWarning(int = KDE_DEFAULT_DEBUG_AREA) { return kDebugDevNull(); } static inline QDebug kWarning(bool, int = KDE_DEFAULT_DEBUG_AREA) { return kDebugDevNull(); } #endif /** * \relates KGlobal * Returns an error stream. You can use it to print error * information. * @param area an id to identify the output, KDE_DEFAULT_DEBUG_AREA for default */ static inline QDebug kError(int area = KDE_DEFAULT_DEBUG_AREA) { return kDebugStream(QtCriticalMsg, area); } static inline QDebug kError(bool cond, int area = KDE_DEFAULT_DEBUG_AREA) { return cond ? kError(area) : kDebugDevNull(); } /** * \relates KGlobal * Returns a fatal error stream. You can use it to print fatal error * information. * @param area an id to identify the output, KDE_DEFAULT_DEBUG_AREA for default */ static inline QDebug kFatal(int area = KDE_DEFAULT_DEBUG_AREA) { return kDebugStream(QtFatalMsg, area); } static inline QDebug kFatal(bool cond, int area = KDE_DEFAULT_DEBUG_AREA) { return cond ? kFatal(area) : kDebugDevNull(); } struct KDebugTag { }; ///! @internal just a tag class typedef QDebug(*KDebugStreamFunction)(QDebug, KDebugTag); ///< @internal inline QDebug operator<<(QDebug s, KDebugStreamFunction f) { return (*f)(s, KDebugTag()); } /** * \relates KGlobal * Print a message describing the last system error. * @param s the debug stream to write to * @return the debug stream (@p s) * @see perror(3) */ KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE QDebug perror(QDebug, KDebugTag); // operators for KDE types class QUrl; class KDateTime; class QObject; KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE QDebug operator<<(QDebug s, const KDateTime &time); #if 1 || defined(KDE3_SUPPORT) #ifndef KDELIBS4SUPPORT_NO_DEPRECATED class KDELIBS4SUPPORT_DEPRECATED_NOISE kndbgstream { }; typedef QDebug kdbgstream; static inline KDELIBS4SUPPORT_DEPRECATED_NOISE QDebug kdDebug(int area = KDE_DEFAULT_DEBUG_AREA) { return kDebug(area); } static inline KDELIBS4SUPPORT_DEPRECATED_NOISE QDebug kdWarning(int area = KDE_DEFAULT_DEBUG_AREA) { return kWarning(area); } static inline KDELIBS4SUPPORT_DEPRECATED_NOISE QDebug kdError(int area = KDE_DEFAULT_DEBUG_AREA) { return kError(area); } static inline KDELIBS4SUPPORT_DEPRECATED_NOISE QDebug kdFatal(int area = KDE_DEFAULT_DEBUG_AREA) { return kFatal(area); } inline KDELIBS4SUPPORT_DEPRECATED_NOISE QString kdBacktrace(int levels = -1) { return kBacktrace(levels); } static inline KDELIBS4SUPPORT_DEPRECATED_NOISE QDebug kndDebug() { return kDebugDevNull(); } #endif #endif class WrongSyntax {}; /** * @internal * A class for using operator() */ class KDebug //krazy= ? { const char *file; const char *funcinfo; int line; QtMsgType level; public: class Block; - explicit inline KDebug(QtMsgType type, const char *f = nullptr, int l = -1, const char *info = nullptr) + KDELIBS4SUPPORT_DEPRECATED explicit inline KDebug(QtMsgType type, const char *f = nullptr, int l = -1, const char *info = nullptr) : file(f), funcinfo(info), line(l), level(type) { #ifdef KDE4_CMAKE_TOPLEVEL_DIR_LENGTH // set by FindKDE4Internal.cmake file = file + KDE4_CMAKE_TOPLEVEL_DIR_LENGTH + 1; #endif } inline QDebug operator()(int area = KDE_DEFAULT_DEBUG_AREA) { return kDebugStream(level, area, file, line, funcinfo); } inline QDebug operator()(bool cond, int area = KDE_DEFAULT_DEBUG_AREA) { if (cond) { return operator()(area); } return kDebugDevNull(); } /// @internal static KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE bool hasNullOutput(QtMsgType type, bool condition, int area, bool enableByDefault); /// @internal static inline bool hasNullOutputQtDebugMsg(int area = KDE_DEFAULT_DEBUG_AREA) { return hasNullOutput(QtDebugMsg, true, area, KDE_DEBUG_ENABLED_BY_DEFAULT); } /// @internal static inline bool hasNullOutputQtDebugMsg(bool condition, int area = KDE_DEFAULT_DEBUG_AREA) { return hasNullOutput(QtDebugMsg, condition, area, KDE_DEBUG_ENABLED_BY_DEFAULT); } /** * @since 4.4 * Register a debug area dynamically. * @param areaName the name of the area * @param enabled whether debug output should be enabled by default * (users can override this in kdebugdialog5 or with DisableAll=true in kdebugrc) * @return the area code that was allocated for this area * * Typical usage: * If all uses of the debug area are restricted to a single class, add a method like this * (e.g. into the Private class, if there's one) * * static int debugArea() { static int s_area = KDebug::registerArea("areaName"); return s_area; } * * Please do not use a file-static int, it would (indirectly) create KGlobal too early, * create KConfig instances too early (breaking unittests which change QStandardPaths dirs), etc. * By using a function as shown above, you make it all happen on-demand, rather than upfront. * * If all uses of the debug area are restricted to a single .cpp file, do the same * but outside any class, and then use a more specific name for the function. * * If however multiple classes and files need the debug area, then * declare it in one file without static, and use "extern int debugArea();" * in other files (with a better name for the function of course). */ static KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE int registerArea(const QByteArray &areaName, bool enabled = true); private: WrongSyntax operator()(const char *) { return WrongSyntax(); // error! Use kDebug() << "..." or kWarning() << "..." instead. } }; #if !defined(KDE_NO_DEBUG_OUTPUT) /* __VA_ARGS__ should work with any supported GCC version and MSVC > 2005 */ # if defined(Q_CC_GNU) || (defined(Q_CC_MSVC) && _MSC_VER >= 1500) # define kDebug(...) for (bool _k_kDebugDoOutput_ = !KDebug::hasNullOutputQtDebugMsg(__VA_ARGS__); \ Q_UNLIKELY(_k_kDebugDoOutput_); _k_kDebugDoOutput_ = false) \ KDebug(QtDebugMsg, __FILE__, __LINE__, Q_FUNC_INFO)(__VA_ARGS__) # else # define kDebug KDebug(QtDebugMsg, __FILE__, __LINE__, Q_FUNC_INFO) # endif #else # define kDebug while (false) kDebug #endif #if !defined(KDE_NO_WARNING_OUTPUT) # define kWarning KDebug(QtWarningMsg, __FILE__, __LINE__, Q_FUNC_INFO) #else # define kWarning while (false) kWarning #endif #ifndef KDE_NO_DEBUG_OUTPUT /** * @class KDebug::Block * @short Use this to label sections of your code * @since 4.6 * * Usage: * * void function() * { * KDebug::Block myBlock( "section" ); * * debug() << "output1" << endl; * debug() << "output2" << endl; * } * * * Will output: * * app: BEGIN: section * app: [prefix] output1 * app: [prefix] output2 * app: END: section - Took 0.1s * * Alternatively, use the KDEBUG_BLOCK macro, for automatic naming. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDebug::Block { public: Block(const char *label, int area = KDE_DEFAULT_DEBUG_AREA); ~Block(); private: QElapsedTimer m_startTime; int m_area; class Private; Private *d; }; /** * Convenience macro for making a standard KDebug::Block */ #define KDEBUG_BLOCK KDebug::Block _kDebugBlock(Q_FUNC_INFO); #else class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDebug::Block { public: Block(const char *, int = KDE_DEFAULT_DEBUG_AREA) {} ~Block() {} }; #define KDEBUG_BLOCK #endif /** * Convenience macro, use this to remind yourself to finish the implementation of a function * The function name will appear in the output (unless $KDE_DEBUG_NOMETHODNAME is set) * @since 4.6 */ #define KWARNING_NOTIMPLEMENTED kWarning() << "NOT-IMPLEMENTED"; /** * Convenience macro, use this to alert other developers to stop using a function * The function name will appear in the output (unless $KDE_DEBUG_NOMETHODNAME is set) * @since 4.6 */ #define KWARNING_DEPRECATED kWarning() << "DEPRECATED"; /** @} */ #endif diff --git a/src/kdecore/kgenericfactory.h b/src/kdecore/kgenericfactory.h index f2ae2e90..2db69221 100644 --- a/src/kdecore/kgenericfactory.h +++ b/src/kdecore/kgenericfactory.h @@ -1,360 +1,360 @@ /* This file is part of the KDE project * Copyright (C) 2001 Simon Hausmann * * 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 kgenericfactory_h #define kgenericfactory_h #include #include #include #include #include #include #include #include #ifndef KDELIBS4SUPPORT_NO_DEPRECATED /* @internal */ template class KGenericFactoryBase : public KPluginFactory { public: - explicit KGenericFactoryBase(const char *componentName) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactoryBase(const char *componentName) : KPluginFactory() { s_self = this; s_createComponentDataCalled = false; } - explicit KGenericFactoryBase(const KAboutData *data) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactoryBase(const KAboutData *data) : KPluginFactory() { KAboutData::registerPluginData(*data); s_self = this; s_createComponentDataCalled = false; } virtual ~KGenericFactoryBase() { s_self = 0; } #if 0 // not available anymore. Port away from KGenericFactory! static KComponentData componentData() { Q_ASSERT(s_self); if (!s_createComponentDataCalled) { s_createComponentDataCalled = true; KComponentData *kcd = s_self->createComponentData(); Q_ASSERT(kcd); s_self->setComponentData(*kcd); delete kcd; } return static_cast(s_self)->componentData(); } protected: virtual KComponentData *createComponentData() { return new KComponentData(componentData()); } #endif private: static bool s_createComponentDataCalled; static KGenericFactoryBase *s_self; }; /* @internal */ template KGenericFactoryBase *KGenericFactoryBase::s_self = 0; /* @internal */ template bool KGenericFactoryBase::s_createComponentDataCalled = false; /** * This template provides a generic implementation of a KLibFactory , * for use with shared library components. It implements the pure virtual * createObject method of KLibFactory and instantiates objects of the * specified class (template argument) when the class name argument of * createObject matches a class name in the given hierarchy. * * In case you are developing a KParts component, skip this file and * go directly to KParts::GenericFactory . * * Note that the class specified as template argument needs to provide * a certain constructor: *
    *
  • If the class is derived from QObject then it needs to have * a constructor like: * MyClass( QObject *parent, * const QStringList &args ); *
  • If the class is derived from QWidget then it needs to have * a constructor like: * MyWidget( QWidget *parent, * const QStringList &args); *
  • If the class is derived from KParts::Part then it needs to have * a constructor like: * MyPart( QWidget *parentWidget, * QObject *parent, * const QStringList &args ); *
* The args QStringList passed to the constructor is the args string list * that the caller passed to KLibFactory's create method. * * In addition upon instantiation this template provides a central * KComponentData object for your component, accessible through the * static componentData() method. The componentName argument * of the KGenericFactory constructor is passed to the KComponentData object. * * The creation of the KComponentData object can be customized by inheriting * from this template class and re-implementing the virtual createComponentData * method. For example it could look like this: * \code * KComponentData *MyFactory::createComponentData() * { * return new KComponentData( myAboutData ); * } * \endcode * * Example of usage of the whole template: * \code * class MyPlugin : public KParts::Plugin * { * Q_ OBJECT * public: * MyPlugin( QObject *parent, const QStringList &args ); * ... * }; * * K_EXPORT_COMPONENT_FACTORY( libmyplugin, KGenericFactory ) * \endcode * * @deprecated use KPluginFactory */ template class KDELIBS4SUPPORT_DEPRECATED KGenericFactory : public KGenericFactoryBase { public: - explicit KGenericFactory(const char *componentName = nullptr) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactory(const char *componentName = nullptr) : KGenericFactoryBase(componentName) {} - explicit KGenericFactory(const KAboutData *data) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactory(const KAboutData *data) : KGenericFactoryBase(data) {} protected: virtual QObject *createObject(QObject *parent, const char *className, const QStringList &args) { return KDEPrivate::ConcreteFactory ::create(0, parent, className, args); } }; /** * \class KGenericFactory kgenericfactory.h * * This template provides a generic implementation of a KLibFactory , * for use with shared library components. It implements the pure virtual * createObject method of KLibFactory and instantiates objects of the * specified classes in the given typelist template argument when the class * name argument of createObject matches a class names in the given hierarchy * of classes. * * Note that each class in the specified in the typelist template argument * needs to provide a certain constructor: *
    *
  • If the class is derived from QObject then it needs to have * a constructor like: * MyClass( QObject *parent, * const QStringList &args ); *
  • If the class is derived from QWidget then it needs to have * a constructor like: * MyWidget( QWidget *parent, * const QStringList &args); *
  • If the class is derived from KParts::Part then it needs to have * a constructor like: * MyPart( QWidget *parentWidget, * QObject *parent, * const QStringList &args ); *
* The args QStringList passed to the constructor is the args string list * that the caller passed to KLibFactory's create method. * * In addition upon instantiation this template provides a central * KComponentData object for your component, accessible through the * static componentData() method. The componentName argument * of the KGenericFactory constructor is passed to the KComponentData object. * * The creation of the KComponentData object can be customized by inheriting * from this template class and re-implementing the virtual createComponentData * method. For example it could look like this: * \code * KComponentData *MyFactory::createComponentData() * { * return new KComponentData( myAboutData ); * } * \endcode * * Example of usage of the whole template: * \code * class MyPlugin : public KParts::Plugin * { * Q_ OBJECT * public: * MyPlugin( QObject *parent, * const QStringList &args ); * ... * }; * * class MyDialogComponent : public KDialog * { * Q_ OBJECT * public: * MyDialogComponent( QWidget *parentWidget, * const QStringList &args ); * ... * }; * * typedef K_TYPELIST_2( MyPlugin, MyDialogComponent ) Products; * K_EXPORT_COMPONENT_FACTORY( libmyplugin, KGenericFactory ) * \endcode */ template class KGenericFactory< KTypeList, QObject > : public KGenericFactoryBase > { public: - explicit KGenericFactory(const char *componentName = nullptr) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactory(const char *componentName = nullptr) : KGenericFactoryBase >(componentName) {} - explicit KGenericFactory(const KAboutData *data) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactory(const KAboutData *data) : KGenericFactoryBase >(data) {} protected: virtual QObject *createObject(QObject *parent, const char *className, const QStringList &args) { return KDEPrivate::MultiFactory< KTypeList< Product, ProductListTail > > ::create(0, parent, className, args); } }; /** * \class KGenericFactory kgenericfactory.h * * This template provides a generic implementation of a KLibFactory , * for use with shared library components. It implements the pure virtual * createObject method of KLibFactory and instantiates objects of the * specified classes in the given typelist template argument when the class * name argument of createObject matches a class names in the given hierarchy * of classes. * * Note that each class in the specified in the typelist template argument * needs to provide a certain constructor: *
    *
  • If the class is derived from QObject then it needs to have * a constructor like: * MyClass( QObject *parent, * const QStringList &args ); *
  • If the class is derived from QWidget then it needs to have * a constructor like: * MyWidget( QWidget *parent, * const QStringList &args); *
  • If the class is derived from KParts::Part then it needs to have * a constructor like: * MyPart( QWidget *parentWidget, * QObject *parent, * const QStringList &args ); *
* The args QStringList passed to the constructor is the args string list * that the caller passed to KLibFactory's create method. * * In addition upon instantiation this template provides a central * KComponentData object for your component, accessible through the * static componentData() method. The componentName argument * of the KGenericFactory constructor is passed to the KComponentData object. * * The creation of the KComponentData object can be customized by inheriting * from this template class and re-implementing the virtual createComponentData * method. For example it could look like this: * \code * KComponentData *MyFactory::createComponentData() * { * return new KComponentData( myAboutData ); * } * \endcode * * Example of usage of the whole template: * \code * class MyPlugin : public KParts::Plugin * { * Q_ OBJECT * public: * MyPlugin( QObject *parent, * const QStringList &args ); * ... * }; * * class MyDialogComponent : public KDialog * { * Q_ OBJECT * public: * MyDialogComponent( QWidget *parentWidget, * const QStringList &args ); * ... * }; * * typedef K_TYPELIST_2( MyPlugin, MyDialogComponent ) Products; * K_EXPORT_COMPONENT_FACTORY( libmyplugin, KGenericFactory ) * \endcode */ template class KGenericFactory< KTypeList, KTypeList > : public KGenericFactoryBase > { public: - explicit KGenericFactory(const char *componentName = nullptr) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactory(const char *componentName = nullptr) : KGenericFactoryBase >(componentName) {} - explicit KGenericFactory(const KAboutData *data) + KDELIBS4SUPPORT_DEPRECATED explicit KGenericFactory(const KAboutData *data) : KGenericFactoryBase >(data) {} protected: virtual QObject *createObject(QObject *parent, const char *className, const QStringList &args) { return KDEPrivate::MultiFactory< KTypeList< Product, ProductListTail >, KTypeList< ParentType, ParentTypeListTail > > ::create(0, 0, parent, className, args); } }; #endif #endif diff --git a/src/kdecore/kglobal.h b/src/kdecore/kglobal.h index 8c2c93c1..637ae99f 100644 --- a/src/kdecore/kglobal.h +++ b/src/kdecore/kglobal.h @@ -1,565 +1,565 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Sirtaj Singh Kanq Copyright (C) 2007 Matthias Kretz 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 _KGLOBAL_H #define _KGLOBAL_H #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif #include #include #include // To simplify Qt5 porting in KDE code not yet ported to frameworks. #include #include // TODO: Re-add for source compat: #include // // WARNING!! // This code uses undocumented Qt API // Do not copy it to your application! Use only the functions that are here! // Otherwise, it could break when a new version of Qt ships. // class KComponentData; class KCharsets; class KConfig; class KStandardDirs; class KSharedConfig; template class QExplicitlySharedDataPointer; typedef QExplicitlySharedDataPointer KSharedConfigPtr; /// @cond InternalDocs /** * @internal */ typedef void (*KdeCleanUpFunction)(); /** * @internal * * Helper class for K_GLOBAL_STATIC to clean up the object on library unload or application * shutdown. */ class KCleanUpGlobalStatic { public: KdeCleanUpFunction func; inline ~KCleanUpGlobalStatic() { func(); } }; #ifdef Q_CC_MSVC /** * @internal * * MSVC seems to give anonymous structs the same name which fails at link time. So instead we name * the struct and hope that by adding the line number to the name it's unique enough to never clash. */ # define K_GLOBAL_STATIC_STRUCT_NAME(NAME) _k_##NAME##__LINE__ #else /** * @internal * * Make the struct of the K_GLOBAL_STATIC anonymous. */ # define K_GLOBAL_STATIC_STRUCT_NAME(NAME) #endif /// @endcond /** * This macro makes it easy to use non-POD types as global statics. * The object is created on first use and creation is threadsafe. * * The object is destructed on library unload or application exit. * Be careful with calling other objects in the destructor of the class * as you have to be sure that they (or objects they depend on) are not already destructed. * * @param TYPE The type of the global static object. Do not add a *. * @param NAME The name of the function to get a pointer to the global static object. * * If you have code that might be called after the global object has been destroyed you can check * for that using the isDestroyed() function. * * If needed (If the destructor of the global object calls other functions that depend on other * global statics (e.g. KConfig::sync) your destructor has to be called before those global statics * are destroyed. A Qt post routine does that.) you can also install a post routine (qAddPostRoutine) to clean up the object * using the destroy() method. If you registered a post routine and the object is destroyed because * of a lib unload you have to call qRemovePostRoutine! * * Example: * @code * class A { * public: * ~A(); * ... * }; * * K_GLOBAL_STATIC(A, globalA) * // The above creates a new globally static variable named 'globalA' which you * // can use as a pointer to an instance of A. * * void doSomething() * { * // The first time you access globalA a new instance of A will be created automatically. * A *a = globalA; * ... * } * * void doSomethingElse() * { * if (globalA.isDestroyed()) { * return; * } * A *a = globalA; * ... * } * * void installPostRoutine() * { * // A post routine can be used to delete the object when QCoreApplication destructs, * // not adding such a post routine will delete the object normally at program unload * qAddPostRoutine(globalA.destroy); * } * * A::~A() * { * // When you install a post routine you have to remove the post routine from the destructor of * // the class used as global static! * qRemovePostRoutine(globalA.destroy); * } * @endcode * * A common case for the need of deletion on lib unload/app shutdown are Singleton classes. Here's * an example how to do it: * @code * class MySingletonPrivate; * class EXPORT_MACRO MySingleton * { * friend class MySingletonPrivate; * public: * static MySingleton *self(); * QString someFunction(); * * private: * MySingleton(); * ~MySingleton(); * }; * @endcode * in the .cpp file: * @code * // This class will be instantiated and referenced as a singleton in this example * class MySingletonPrivate * { * public: * QString foo; * MySingleton instance; * }; * * K_GLOBAL_STATIC(MySingletonPrivate, mySingletonPrivate) * * MySingleton *MySingleton::self() * { * // returns the singleton; automatically creates a new instance if that has not happened yet. * return &mySingletonPrivate->instance; * } * QString MySingleton::someFunction() * { * // Refencing the singleton directly is possible for your convenience * return mySingletonPrivate->foo; * } * @endcode * * Instead of the above you can use also the following pattern (ignore the name of the namespace): * @code * namespace MySingleton * { * EXPORT_MACRO QString someFunction(); * } * @endcode * in the .cpp file: * @code * class MySingletonPrivate * { * public: * QString foo; * }; * * K_GLOBAL_STATIC(MySingletonPrivate, mySingletonPrivate) * * QString MySingleton::someFunction() * { * return mySingletonPrivate->foo; * } * @endcode * * Now code that wants to call someFunction() doesn't have to do * @code * MySingleton::self()->someFunction(); * @endcode * anymore but instead: * @code * MySingleton::someFunction(); * @endcode * * @ingroup KDEMacros */ #define K_GLOBAL_STATIC(TYPE, NAME) K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ()) /** * @overload * This is the same as K_GLOBAL_STATIC, but can take arguments that are passed * to the object's constructor * * @param TYPE The type of the global static object. Do not add a *. * @param NAME The name of the function to get a pointer to the global static object. * @param ARGS the list of arguments, between brackets * * Example: * @code * class A * { * public: * A(const char *s, int i); * ... * }; * * K_GLOBAL_STATIC_WITH_ARGS(A, globalA, ("foo", 0)) * // The above creates a new globally static variable named 'globalA' which you * // can use as a pointer to an instance of A. * * void doSomething() * { * // The first time you access globalA a new instance of A will be created automatically. * A *a = globalA; * ... * } * @endcode * * @ingroup KDEMacros */ // In Qt5 QBasicAtomicPointer no longer implicit casts to T* // Instead it has load() and store() methods which do not exist in Qt4. // In practice, we should be porting frameworks to the new Q_GLOBAL_STATIC // which isn't in Qt5 yet, so duplicate for now. #define K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \ static QBasicAtomicPointer _k_static_##NAME = Q_BASIC_ATOMIC_INITIALIZER(0); \ static bool _k_static_##NAME##_destroyed; \ static struct K_GLOBAL_STATIC_STRUCT_NAME(NAME) \ { \ inline bool isDestroyed() const \ { \ return _k_static_##NAME##_destroyed; \ } \ inline bool exists() const \ { \ return _k_static_##NAME.load() != 0; \ } \ inline operator TYPE*() \ { \ return operator->(); \ } \ inline TYPE *operator->() \ { \ if (!_k_static_##NAME.load()) { \ if (isDestroyed()) { \ qFatal("Fatal Error: Accessed global static '%s *%s()' after destruction. " \ "Defined at %s:%d", #TYPE, #NAME, __FILE__, __LINE__); \ } \ TYPE *x = new TYPE ARGS; \ if (!_k_static_##NAME.testAndSetOrdered(0, x) \ && _k_static_##NAME.load() != x ) { \ delete x; \ } else { \ static KCleanUpGlobalStatic cleanUpObject = { destroy }; \ } \ } \ return _k_static_##NAME.load(); \ } \ inline TYPE &operator*() \ { \ return *operator->(); \ } \ static void destroy() \ { \ _k_static_##NAME##_destroyed = true; \ TYPE *x = _k_static_##NAME.load(); \ _k_static_##NAME.store(0); \ delete x; \ } \ } NAME; /** * Access to the KDE global objects. * KGlobal provides you with pointers of many central * objects that exist only once in the process. It is also * responsible for managing instances of KStaticDeleterBase. * * @see KStaticDeleterBase * @author Sirtaj Singh Kang (taj@kde.org) */ namespace KGlobal { struct KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE LocaleWrapper : public KLocale { - explicit LocaleWrapper(KLocale *locale) + KDELIBS4SUPPORT_DEPRECATED explicit LocaleWrapper(KLocale *locale) : KLocale(*locale) { } KDELIBS4SUPPORT_DEPRECATED static void insertCatalog(const QString &) { qWarning() << "Your code needs to be ported in KF5. See the Ki18n programmers guide."; } LocaleWrapper *operator->() { return this; } operator KLocale *() { return this; } }; /** * Returns the global component data. There is always at least * one instance of a component in one application (in most * cases the application itself). * @return the global component data * @deprecated since 5.0 use KComponentData::mainComponent() if you really need a KComponentData */ KDELIBS4SUPPORT_DEPRECATED_EXPORT const KComponentData &mainComponent(); //krazy:exclude=constref (don't mess up ref-counting) /** * @internal * Returns whether a main KComponentData is available. * @deprecated since 5.0, use KComponentData::hasMainComponent() if you really need a KComponentData */ KDELIBS4SUPPORT_DEPRECATED_EXPORT bool hasMainComponent(); /** * Returns the application standard dirs object. * @return the global standard dir object */ KDELIBS4SUPPORT_DEPRECATED_EXPORT KStandardDirs *dirs(); /** * Returns the general config object. * @return the global configuration object. * @deprecated since 5.0, use KSharedConfig::openConfig() */ KDELIBS4SUPPORT_DEPRECATED_EXPORT KSharedConfigPtr config(); /** * Returns the global locale object. * @return the global locale object * * Note: in multi-threaded programs, you should call KLocale::global() * in the main thread (e.g. in main(), after creating the QCoreApplication * and setting the main component), to ensure that the initialization is * done in the main thread. However KApplication takes care of this, so this * is only needed when not using KApplication. * * @deprecated since 5.0, use KLocale::global() */ KDELIBS4SUPPORT_DEPRECATED_EXPORT LocaleWrapper locale(); /** * @internal * Returns whether KGlobal has a valid KLocale object * @deprecated since 5.0, port to if (qApp) because KLocale::global() can be called, as soon as a qApp exists. */ KDELIBS4SUPPORT_DEPRECATED_EXPORT bool hasLocale(); /** * The global charset manager. * @return the global charset manager * @deprecated since 5.0, use KCharsets::charsets() */ KDELIBS4SUPPORT_DEPRECATED_EXPORT KCharsets *charsets(); /** * Returns the umask of the process. * @return the umask of the process */ KDELIBS4SUPPORT_DEPRECATED_EXPORT mode_t umask(); /** * Creates a static QString. * * To be used inside functions(!) like: * @code * static const QString &myString = KGlobal::staticQString("myText"); * @endcode * * @attention Do @b NOT use code such as: * @code * static QString myString = KGlobal::staticQString("myText"); * @endcode * This creates a static object (instead of a static reference) * and as you know static objects are EVIL. * @param str the string to create * @return the static string * @deprecated since 5.0, use QLatin1String() or QStringLiteral() */ KDELIBS4SUPPORT_DEPRECATED_EXPORT const QString &staticQString(const char *str); //krazy:exclude=constref (doesn't make sense otherwise) /** * Creates a static QString. * * To be used inside functions(!) like: * @code * static const QString &myString = KGlobal::staticQString(i18n("My Text")); * @endcode * * @attention Do @b NOT use code such as: * @code * static QString myString = KGlobal::staticQString(i18n("myText")); * @endcode * This creates a static object (instead of a static reference) * and as you know static objects are EVIL. * @param str the string to create * @return the static string * @deprecated since 5.0 don't make the string static */ KDELIBS4SUPPORT_DEPRECATED_EXPORT const QString &staticQString(const QString &str); //krazy:exclude=constref (doesn't make sense otherwise) /** * Tells KGlobal about one more operations that should be finished * before the application exits. The standard behavior is to exit on the * "last window closed" event, but some events should outlive the last window closed * (e.g. a file copy for a file manager, or 'compacting folders on exit' for a mail client), * or simply any application with a system tray icon. * * We have some use cases that we want to take care of (the format is "action refcount"): * - open window -> setAllowQuit(true) 1 ; close window 0 => EXIT * - job start 1; job end 0 [don't exit yet]; open window -> setAllowQuit(true) 1 ; close window 0 => EXIT * - job start 1; open window -> setAllowQuit(true) 2; close window 1; job end 0 => EXIT * - job start 1; open window -> setAllowQuit(true) 2; job end 1; close window 0 => EXIT * - open dialog 0; close dialog 0; => DO NOT EXIT * - job start 1; job end 0; create two main objects 2; delete both main objects 0 => EXIT * - open window -> setAllowQuit(true) 1; add systray icon 2; close window 1 => DO NOT EXIT * - open window -> setAllowQuit(true) 1; add systray icon 2; remove systray icon 1; close window 0 => EXIT * - unit test which opens and closes many windows: should call ref() to avoid subevent-loops quitting too early. * * Note that for this to happen you must call qApp->setQuitOnLastWindowClosed(false), * in main() for instance. * * @deprecated since 5.0, use QEventLoopLocker, its constructor does the equivalent of ref */ KDELIBS4SUPPORT_DEPRECATED_EXPORT void ref(); /** * Tells KGlobal that one operation such as those described in ref() just finished. * This call makes the QApplication quit if the counter is back to 0. * * @deprecated since 5.0, use QEventLoopLocker, its destructor does the equivalent of unref */ KDELIBS4SUPPORT_DEPRECATED_EXPORT void deref(); /** * If refcounting reaches 0 (or less), and @p allowQuit is true, the instance of the application * will automatically be exited. Otherwise, the application will not exit automatically. * * This is used by KMainWindow to allow quitting after the first mainwindow is created, * and is used by special applications like kfmclient, to allow quitting even though * no mainwindow was created. * * However, don't try to call setAllowQuit(false) in applications, it doesn't make sense. * If you find that the application quits too early when closing a window, then consider * _what_ is making your application still alive to the user (like a systray icon or a D-Bus object) * and use KGlobal::ref() + KGlobal::deref() in that object. * * @since 4.1.1 * @deprecated since 5.0, not necessary anymore, with QCoreApplication and QEventLoopLocker */ KDELIBS4SUPPORT_DEPRECATED_EXPORT void setAllowQuit(bool allowQuit); /** * The component currently active (useful in a multi-component * application, such as a KParts application). * Don't use this - it's mainly for KAboutDialog and KBugReport. * @internal * @deprecated since 5.0 see KComponentData::activeComponent() about * why you should do without this concept (or let your app remember the active * part/plugin if it cares) */ KDELIBS4SUPPORT_DEPRECATED_EXPORT KComponentData activeComponent(); /** * Set the active component for use by KAboutDialog and KBugReport. * To be used only by a multi-component (KParts) application. * * @see activeComponent() * @deprecated since 5.0 see KComponentData::setActiveComponent about * why you can probably just remove the call. */ KDELIBS4SUPPORT_DEPRECATED_EXPORT void setActiveComponent(const KComponentData &d); /** * Returns a text for the window caption. * * This may be set by * "-caption", otherwise it will be equivalent to the name of the * executable. * @return the text for the window caption * @deprecated since 5.0. Don't use in window titles anymore, Qt takes care of it. * If you really need this, use QGuiApplication::applicationDisplayName(), and if that's empty, QCoreApplication::applicationName(). */ KDELIBS4SUPPORT_DEPRECATED_EXPORT QString caption(); /// @internal KDELIBS4SUPPORT_DEPRECATED_EXPORT QObject *findDirectChild_helper(const QObject *parent, const QMetaObject &mo); /** * Returns the child of the given object that can be cast into type T, or 0 if there is no such object. * Unlike QObject::findChild, the search is NOT performed recursively. * @since 4.4 * @deprecated since Qt 5, use QObject::findChild(FindDirectChildrenOnly) */ template KDELIBS4SUPPORT_DEPRECATED inline T findDirectChild(const QObject *object) { return static_cast(findDirectChild_helper(object, (static_cast(nullptr))->staticMetaObject)); } } struct KCatalogLoader { KDELIBS4SUPPORT_DEPRECATED KCatalogLoader(const QString &) { qWarning() << "Your code needs to be ported in KF5. See the Ki18n programmers guide."; } }; #endif // _KGLOBAL_H diff --git a/src/kdecore/kkernel_mac.cpp b/src/kdecore/kkernel_mac.cpp index e0ecbec3..a9637914 100644 --- a/src/kdecore/kkernel_mac.cpp +++ b/src/kdecore/kkernel_mac.cpp @@ -1,216 +1,216 @@ /* This file is part of the KDE libraries Copyright (C) 2008 Benjamin Reed This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kkernel_mac.h" #ifdef Q_OS_MACX #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int timeout = 3000; // msec bool dbus_initialized = false; /** qAppFileName() is not public in qt4/mac, so we need to redo it here */ QString convert_CFString_to_QString(CFStringRef str) { CFIndex length = CFStringGetLength(str); const UniChar *chars = CFStringGetCharactersPtr(str); if (chars) { return QString(reinterpret_cast(chars), length); } QVarLengthArray buffer(length); CFStringGetCharacters(str, CFRangeMake(0, length), buffer.data()); return QString(reinterpret_cast(buffer.constData()), length); } /** Calling CoreFoundation APIs (which is unavoidable in Qt/Mac) has always had issues - on Mac OS X, but as of 10.5 is explicitly disallowed with an exception. As a + on Mac OS X, but as of 10.5 is KDELIBS4SUPPORT_DEPRECATED explicitly disallowed with an exception. As a result, in the case where we would normally fork and then dlopen code, or continue to run other code, we must now fork-and-exec. See "CoreFoundation and fork()" at http://developer.apple.com/releasenotes/CoreFoundation/CoreFoundation.html */ void mac_fork_and_reexec_self() { int argc = *_NSGetArgc(); char **argv = *_NSGetArgv(); char *newargv[argc + 2]; char progname[PATH_MAX]; uint32_t buflen = PATH_MAX; _NSGetExecutablePath(progname, &buflen); bool found_psn = false; for (int i = 0; i < argc; i++) { newargv[i] = argv[i]; } newargv[argc] = "--nofork"; newargv[argc + 1] = NULL; int x_fork_result = fork(); switch (x_fork_result) { case -1: #ifndef NDEBUG fprintf(stderr, "Mac OS X workaround fork() failed!\n"); #endif ::_exit(255); break; case 0: // Child execvp(progname, newargv); break; default: // Parent _exit(0); break; } } /** Set the D-Bus environment based on session bus socket */ bool mac_set_dbus_address(QString value) { if (!value.isEmpty() && QFile::exists(value) && (QFile::permissions(value) & QFile::WriteUser)) { value = QLatin1String("unix:path=") + value; qputenv("DBUS_SESSION_BUS_ADDRESS", value.toLocal8Bit()); kDebug() << "set session bus address to" << value; return true; } return false; } /** Make sure D-Bus is initialized, by any means necessary. */ void mac_initialize_dbus() { if (dbus_initialized) { return; } QString dbusVar = QString::fromLocal8Bit(qgetenv("DBUS_SESSION_BUS_ADDRESS")); if (!dbusVar.isEmpty()) { dbus_initialized = true; return; } dbusVar = QFile::decodeName(qgetenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET")); if (mac_set_dbus_address(dbusVar)) { dbus_initialized = true; return; } QString externalProc; QStringList path = QFile::decodeName(qgetenv("KDEDIRS")).split(QLatin1Char(':')).replaceInStrings(QRegExp(QLatin1String("$")), QLatin1String("/bin")); path << QFile::decodeName(qgetenv("PATH")).split(QLatin1Char(':')) << QLatin1String("/usr/local/bin"); for (int i = 0; i < path.size(); ++i) { QString testLaunchctl = QString(path.at(i)).append(QLatin1String("/launchctl")); if (QFile(testLaunchctl).exists()) { externalProc = testLaunchctl; break; } } if (!externalProc.isEmpty()) { QProcess qp; qp.setTextModeEnabled(true); qp.start(externalProc, QStringList() << QLatin1String("getenv") << QLatin1String("DBUS_LAUNCHD_SESSION_BUS_SOCKET")); if (!qp.waitForFinished(timeout)) { kDebug() << "error running" << externalProc << qp.errorString(); return; } if (qp.exitCode() != 0) { kDebug() << externalProc << "unsuccessful:" << qp.readAllStandardError(); return; } QString line = QString::fromLatin1(qp.readLine()).trimmed(); // read the first line if (mac_set_dbus_address(line)) { dbus_initialized = true; // hooray } } if (dbus_initialized == false) { kDebug() << "warning: unable to initialize D-Bus environment!"; } } QString mac_app_filename() { static QString appFileName; if (appFileName.isEmpty()) { CFURLRef bundleURL = NULL; CFBundleRef bundle = NULL; CFStringRef bundlePath = NULL; bundle = CFBundleGetMainBundle(); if (bundle) { bundleURL = CFBundleCopyBundleURL(bundle); bundlePath = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle); if (bundleURL) { CFRelease(bundleURL); } if (bundlePath) { appFileName = convert_CFString_to_QString(bundlePath); CFRelease(bundlePath); } } } return appFileName; } #endif diff --git a/src/kdecore/kkernel_win.cpp b/src/kdecore/kkernel_win.cpp index 48171ef5..daadf510 100644 --- a/src/kdecore/kkernel_win.cpp +++ b/src/kdecore/kkernel_win.cpp @@ -1,546 +1,546 @@ /* This file is part of the KDE libraries Copyright (C) 2004 Jarosław Staniek Copyright (C) 2007 Christian Ehrlicher Copyright (C) 2007 Bernhard Loos Copyright (C) 2008-2009 Ralf Habacker This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kkernel_win.h" #include #ifdef Q_OS_WIN #include #include #include #include #include #include #include // console related includes #include #include #include #include #include #ifndef _USE_OLD_IOSTREAMS using namespace std; #endif #if defined(__MINGW32__) # define WIN32_CAST_CHAR (const WCHAR*) #else # define WIN32_CAST_CHAR (LPCWSTR) #endif #ifndef _WIN32_WCE static HINSTANCE kdecoreDllInstance = NULL; #else static HANDLE kdecoreDllInstance = NULL; #endif #ifdef KDELIBS_STATIC_LIBS static bool kde4prefixInitialized = false; #endif static wchar_t kde4prefixUtf16[MAX_PATH + 2] = L""; static QString *kde4Prefix = NULL; void initKde4prefixUtf16() { //the path is C:\some\path\kde4\bin\kdecore.dll #ifndef _WIN32_WCE GetModuleFileNameW(kdecoreDllInstance, kde4prefixUtf16, MAX_PATH + 1); #else GetModuleFileNameW((HMODULE)kdecoreDllInstance, kde4prefixUtf16, MAX_PATH + 1); #endif int bs1 = 0, bs2 = 0; //we convert \ to / and remove \bin\kdecore.dll from the string int pos; for (pos = 0; pos < MAX_PATH + 1 && kde4prefixUtf16[pos] != 0; ++pos) { if (kde4prefixUtf16[pos] == '\\') { bs1 = bs2; bs2 = pos; kde4prefixUtf16[pos] = '/'; } } Q_ASSERT(bs1); Q_ASSERT(pos < MAX_PATH + 1); kde4prefixUtf16[bs1] = '/'; kde4prefixUtf16[bs1 + 1] = 0; } // can't use QCoreApplication::applicationDirPath() because sometimes we // don't have an instantiated QCoreApplication QString getKde4Prefix() { #ifdef _WIN32_WCE if (kde4prefixInitialized) { return QString::fromUtf16((ushort *) kde4prefixUtf16); } QDir kde4prefixDir(QString::fromUtf16((ushort *) STATIC_INSTALL_PATH)); if (kde4prefixDir.exists()) { wcscpy(kde4prefixUtf16, STATIC_INSTALL_PATH); kde4prefixUtf16[wcslen(kde4prefixUtf16)] = 0; kde4prefixInitialized = true; return QString::fromUtf16((ushort *) kde4prefixUtf16); } else { bool ok; QString retval = getWin32RegistryValue(HKEY_LOCAL_MACHINE, "Software\\kde", "KDEDIRS", &ok); if (!ok) { return QString(); } else { retval = QDir::fromNativeSeparators(retval); wcscpy(kde4prefixUtf16, retval.utf16()); kde4prefixUtf16[wcslen(kde4prefixUtf16)] = 0; kde4prefixInitialized = true; return retval; } } #else // we can get called after DLL_PROCESS_DETACH! return kde4Prefix ? *kde4Prefix : QString::fromUtf16((ushort *) kde4prefixUtf16); #endif } #ifndef KDELIBS_STATIC_LIBS /** * The dll entry point - get the instance handle for GetModuleFleNameW * Maybe also some special initialization / cleanup can be done here **/ extern "C" #ifndef _WIN32_WCE BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) #else BOOL WINAPI DllMain(HANDLE hinstDLL, DWORD fdwReason, LPVOID lpReserved) #endif { switch (fdwReason) { case DLL_PROCESS_ATTACH: kdecoreDllInstance = hinstDLL; initKde4prefixUtf16(); kde4Prefix = new QString(QString::fromUtf16((ushort *) kde4prefixUtf16)); break; case DLL_PROCESS_DETACH: /* msdn: When handling DLL_PROCESS_DETACH, a DLL should free resources such as heap memory only if the DLL is being unloaded dynamically (the lpReserved parameter is NULL). If the process is terminating (the lpvReserved parameter is non-NULL), all threads in the process except - the current thread either have exited already or have been explicitly + the current thread either have exited already or have been KDELIBS4SUPPORT_DEPRECATED explicitly terminated by a call to the ExitProcess function, which might leave some process resources such as heaps in an inconsistent state. In this case, it is not safe for the DLL to clean up the resources. Instead, the DLL should allow the operating system to reclaim the memory. */ if (lpReserved == NULL) { delete kde4Prefix; } kde4Prefix = 0; break; default: break; } return true; } #endif /** \return a value from MS Windows native registry. @param key is usually one of HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE constants defined in WinReg.h. @param subKey is a registry subkey defined as a path to a registry folder, eg. "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" ('\' delimiter must be used) @param item is an item inside subKey or "" if default folder's value should be returned @param ok if not null, will be set to true on success and false on failure */ QString getWin32RegistryValue(HKEY key, const QString &subKey, const QString &item, bool *ok) { #define FAILURE \ { if (ok) \ *ok = false; \ return QString(); } if (subKey.isEmpty()) { FAILURE; } HKEY hKey; TCHAR *lszValue; DWORD dwType = REG_SZ; DWORD dwSize; if (ERROR_SUCCESS != RegOpenKeyExW(key, WIN32_CAST_CHAR subKey.utf16(), 0, KEY_READ, &hKey)) { FAILURE; } if (ERROR_SUCCESS != RegQueryValueExW(hKey, WIN32_CAST_CHAR item.utf16(), NULL, NULL, NULL, &dwSize)) { FAILURE; } lszValue = new TCHAR[dwSize]; if (ERROR_SUCCESS != RegQueryValueExW(hKey, WIN32_CAST_CHAR item.utf16(), NULL, &dwType, (LPBYTE) lszValue, &dwSize)) { delete [] lszValue; FAILURE; } RegCloseKey(hKey); QString res = QString::fromUtf16((const ushort *) lszValue); delete [] lszValue; if (ok) { *ok = true; } return res; } bool showWin32FilePropertyDialog(const QString &fileName) { QString path_ = QDir::toNativeSeparators(QFileInfo(fileName).absoluteFilePath()); #ifndef _WIN32_WCE SHELLEXECUTEINFOW execInfo; #else SHELLEXECUTEINFO execInfo; #endif memset(&execInfo, 0, sizeof(execInfo)); execInfo.cbSize = sizeof(execInfo); #ifndef _WIN32_WCE execInfo.fMask = SEE_MASK_INVOKEIDLIST | SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; #else execInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; #endif const QString verb(QLatin1String("properties")); execInfo.lpVerb = WIN32_CAST_CHAR verb.utf16(); execInfo.lpFile = WIN32_CAST_CHAR path_.utf16(); #ifndef _WIN32_WCE return ShellExecuteExW(&execInfo); #else return ShellExecuteEx(&execInfo); //There is no native file property dialog in wince // return false; #endif } // note: QLocale().name().left(2).toLatin1() returns the same QByteArray getWin32LocaleName() { bool ok; QString localeNumber = getWin32RegistryValue(HKEY_CURRENT_USER, QLatin1String("Control Panel\\International"), QLatin1String("Locale"), &ok); if (!ok) { return QByteArray(); } QString localeName = getWin32RegistryValue(HKEY_LOCAL_MACHINE, QLatin1String("SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout\\DosKeybCodes"), localeNumber, &ok); if (!ok) { return QByteArray(); } return localeName.toLatin1(); } /** \return a value from MS Windows native registry for shell folder \a folder. */ QString getWin32ShellFoldersPath(const QString &folder) { return getWin32RegistryValue(HKEY_CURRENT_USER, QLatin1String("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"), folder); } /** kde and qt debug message printer using windows debug message port */ static void kMessageOutputDebugString(QtMsgType type, const char *msg) { int BUFSIZE = 4096; char *buf = new char[BUFSIZE]; switch (type) { case QtDebugMsg: strlcpy(buf, "Debug:", BUFSIZE); strlcat(buf, msg, BUFSIZE); break; case QtWarningMsg: strlcpy(buf, "Warning:", BUFSIZE); strlcat(buf, msg, BUFSIZE); break; case QtCriticalMsg: strlcpy(buf, "Critical:", BUFSIZE); strlcat(buf, msg, BUFSIZE); break; case QtFatalMsg: strlcpy(buf, "Fatal:", BUFSIZE); strlcat(buf, msg, BUFSIZE); //abort(); break; } strlcat(buf, "\n", BUFSIZE); OutputDebugStringW((WCHAR *)QString::fromLatin1(buf).utf16()); delete[] buf; } /** kde and qt debug message printer using FILE pointer based output */ static void kMessageOutputFileIO(QtMsgType type, const char *msg) { switch (type) { case QtDebugMsg: fprintf(stderr, "Debug: %s\n", msg); break; case QtWarningMsg: fprintf(stderr, "Warning: %s\n", msg); break; case QtCriticalMsg: fprintf(stderr, "Critical: %s\n", msg); break; case QtFatalMsg: fprintf(stderr, "Fatal: %s\n", msg); //abort(); } } /** try to attach to the parents console \return true if console has been attached, false otherwise */ typedef BOOL (WINAPI *attachConsolePtr)(DWORD dwProcessId); static attachConsolePtr attachConsole = 0; static bool attachConsoleResolved = false; static bool attachToConsole() { bool out = true; if (!attachConsoleResolved) { attachConsoleResolved = true; attachConsole = (attachConsolePtr)QLibrary::resolve(QLatin1String("kernel32"), "AttachConsole"); } out = attachConsole ? attachConsole(~0U) != 0 : false; if (GetLastError() == ERROR_ACCESS_DENIED) { //we are already atatched to a console out = true; } return out; } /** redirect stdout, stderr and cout, wcout, cin, wcin, wcerr, cerr, wclog and clog to console */ static void redirectToConsole() { //FIXME: for wince we cannot set stdio buffers #ifndef _WIN32_WCE int hCrt; FILE *hf; int i; hCrt = _open_osfhandle((intptr_t) GetStdHandle(STD_INPUT_HANDLE), _O_TEXT); if (hCrt != -1) { hf = _fdopen(hCrt, "r"); *stdin = *hf; i = setvbuf(stdin, NULL, _IONBF, 0); } hCrt = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT); if (hCrt != -1) { hf = _fdopen(hCrt, "w"); *stdout = *hf; i = setvbuf(stdout, NULL, _IONBF, 0); } hCrt = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), _O_TEXT); if (hCrt != -1) { hf = _fdopen(hCrt, "w"); *stderr = *hf; i = setvbuf(stderr, NULL, _IONBF, 0); } // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well ios::sync_with_stdio(); #endif } #include /** ios related debug message printer for win32 */ class debug_streambuf: public std::streambuf { public: debug_streambuf(const char *prefix) { strcpy(buf, prefix); index = rindex = strlen(buf); } protected: virtual int overflow(int c = EOF) { if (c != EOF) { char cc = traits_type::to_char_type(c); // @TODO: buffer size checking buf[index++] = cc; if (cc == '\n') { buf[index] = '\0'; OutputDebugStringW((WCHAR *)QString::fromLatin1(buf).utf16()); index = rindex; } } return traits_type::not_eof(c); } private: char buf[4096]; int index, rindex; }; /** retrieve type of win32 subsystem from the executable header \return type of win32 subsystem - the subsystem types are defined at http://msdn.microsoft.com/en-us/library/ms680339(VS.85).aspx */ static int subSystem() { #ifdef _WIN32_WCE // there is only one subsystem on Windows CE return IMAGE_SUBSYSTEM_WINDOWS_CE_GUI; #else static int subSystem = -1; if (subSystem > -1) { return subSystem; } // get base address of memory mapped executable PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)GetModuleHandle(NULL); PIMAGE_NT_HEADERS ntHeader = (PIMAGE_NT_HEADERS)((char *)dosHeader + dosHeader->e_lfanew); if (ntHeader->Signature != 0x00004550) { subSystem = IMAGE_SUBSYSTEM_UNKNOWN; return subSystem; } subSystem = ntHeader->OptionalHeader.Subsystem; return subSystem; #endif } /** win32 debug and console output handling source type of output 1. kde/qt debug system - kDebug(), kWarning(), kFatal(), kError(), qDebug(), qWarning(), qFatal() 2. ios - cout, wcout, wcerr, cerr, wclog and clog 3. FILE * - stdout,stderr application console ------------------ output ----------------- type available qt/kde-debug ios FILE * cui yes console console console cui no win32debug win32debug no output[1] gui yes win32debug console console gui no win32debug win32debug win32debug win-ce no win32debug win32debug win32debug [1]no redirect solution for FILE * based output yet TODO: report events to the windows event log system http://msdn.microsoft.com/en-us/library/aa363680(VS.85).aspx */ /** setup up debug output */ static class kMessageOutputInstaller { public: kMessageOutputInstaller() : stdoutBuffer("stdout:"), stderrBuffer("stderr:"), oldStdoutBuffer(0), oldStderrBuffer(0) { if (subSystem() == IMAGE_SUBSYSTEM_WINDOWS_CUI) { if (attachToConsole()) { // setup kde and qt level qInstallMsgHandler(kMessageOutputFileIO); // redirect ios and file io to console redirectToConsole(); } else { // setup kde and qt level qInstallMsgHandler(kMessageOutputDebugString); // redirect ios to debug message port oldStdoutBuffer = std::cout.rdbuf(&stdoutBuffer); oldStderrBuffer = std::cerr.rdbuf(&stderrBuffer); } } else if (subSystem() == IMAGE_SUBSYSTEM_WINDOWS_GUI) { // setup kde and qt level qInstallMsgHandler(kMessageOutputDebugString); // try to get a console if (attachToConsole()) { redirectToConsole(); } else { // redirect ios to debug message port oldStdoutBuffer = std::cout.rdbuf(&stdoutBuffer); oldStderrBuffer = std::cerr.rdbuf(&stderrBuffer); // TODO: redirect FILE * level to console, no idea how to do yet } } else if (subSystem() == IMAGE_SUBSYSTEM_WINDOWS_CE_GUI) { // do not try to get a console on WinCE systems qInstallMsgHandler(kMessageOutputDebugString); oldStdoutBuffer = std::cout.rdbuf(&stdoutBuffer); oldStderrBuffer = std::cerr.rdbuf(&stderrBuffer); } else { qWarning("unknown subsystem %d detected, could not setup qt message handler", subSystem()); } } ~kMessageOutputInstaller() { if (oldStdoutBuffer) { std::cout.rdbuf(oldStdoutBuffer); } if (oldStderrBuffer) { std::cerr.rdbuf(oldStderrBuffer); } } private: debug_streambuf stdoutBuffer; debug_streambuf stderrBuffer; std::streambuf *oldStdoutBuffer; std::streambuf *oldStderrBuffer; } kMessageOutputInstallerInstance; bool isExecutable(const QString &file) { return (file.endsWith(QLatin1String(".exe")) || file.endsWith(QLatin1String(".com")) || file.endsWith(QLatin1String(".bat")) || file.endsWith(QLatin1String(".sln")) || file.endsWith(QLatin1String(".lnk"))); } #endif // Q_OS_WIN diff --git a/src/kdecore/klibrary.h b/src/kdecore/klibrary.h index 9c3150b9..a0945ddf 100644 --- a/src/kdecore/klibrary.h +++ b/src/kdecore/klibrary.h @@ -1,81 +1,81 @@ /* This file is part of the KDE libraries Copyright (C) 2007 Bernhard Loos 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 KLIBRARY_H #define KLIBRARY_H #include #include class KLibraryPrivate; class KPluginFactory; /** * \class KLibrary klibrary.h * * KLibrary searches for libraries in the same way that KPluginLoader searches * for plugins. * * @deprecated since 5.0, use QLibrary and KPluginLoader::findPlugin() instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KLibrary : public QLibrary { Q_OBJECT Q_PROPERTY(QString fileName READ fileName WRITE setFileName) public: /** * @deprecated since 5.0, use QFunctionPointer */ typedef void (*void_function_ptr)(); - explicit KLibrary(QObject *parent = nullptr); - explicit KLibrary(const QString &name, QObject *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KLibrary(QObject *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KLibrary(const QString &name, QObject *parent = nullptr); KLibrary(const QString &name, int verNum, QObject *parent = nullptr); virtual ~KLibrary(); /** * @deprecated since 4.0, use KPluginLoader::factory */ KDELIBS4SUPPORT_DEPRECATED KPluginFactory *factory(const char *factoryname = nullptr) { // there is nothing sensible we can do: kdelibs 4 plugins depended on // support from Qt that no longer exists Q_UNUSED(factoryname) return nullptr; } /** * @deprecated since 5.0, use QLibrary::resolve */ KDELIBS4SUPPORT_DEPRECATED void_function_ptr resolveFunction(const char *name) { return resolve(name); } void setFileName(const QString &name); bool unload() { return false; } private: KLibraryPrivate *d_ptr; }; #endif diff --git a/src/kdecore/klocale.h b/src/kdecore/klocale.h index 52aa2cb6..580fc09b 100644 --- a/src/kdecore/klocale.h +++ b/src/kdecore/klocale.h @@ -1,1884 +1,1884 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Stephan Kulow Copyright (C) 1999-2003 Hans Petter Bieker Copyright (c) 2002 Lukas Tinkl 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 KLOCALE_H #define KLOCALE_H #include #include // Include for providing source code compatibility #include #include #include class QStringList; class QTextCodec; class QDate; class QTime; class QDateTime; class KDateTime; class KCalendarSystem; class KCurrencyCode; class KDayPeriod; class KLocalePrivate; /** * \file klocale.h */ /** * KLocale provides support for language and country specific stuff. * * KLocale supports specifying the format * for numbers, currency, time, and date. * * Use KLocale::global() to get pointer to the global KLocale object, * containing the applications current locale settings. * * For example, to format the date May 17, 1995 in the current locale, use: * * \code * QString date = KLocale::global()->formatDate(QDate(1995,5,17)); * \endcode * * @author Stephan Kulow , Preston Brown , * Hans Petter Bieker , Lukas Tinkl * @short class for supporting locale settings */ class KDELIBS4SUPPORT_EXPORT KLocale { public: /** * Constructs a KLocale. * * The constructor looks for entries Language and Country * in the group Locale in the configuration file. * * If no configuration file is specified, it will also look for languages * and country using the environment variables (KDE_LANG, LC_MESSAGES, * LC_ALL, LANG), as well as the global configuration file. * * If you specify a configuration file, it has to be valid until the KLocale * object is destroyed. Note that a setLocale() will be performed on the * config using the current locale language and country, which may cause * a sync() and reparseConfiguration() which will save any changes * you have made and load any changes other shared copies have made. * * @param config a configuration file with a Locale group detailing * locale-related preferences (such as language, country, * and formatting options). */ - explicit KLocale(KSharedConfig::Ptr config = KSharedConfig::Ptr()); + KDELIBS4SUPPORT_DEPRECATED explicit KLocale(KSharedConfig::Ptr config = KSharedConfig::Ptr()); /** * Constructs a KLocale. * * Allows you to override the language and, optionally, the * country of this locale. * * If you specify a configuration file, a setLocale() will be performed on * the config using the current locale language and country, * which may cause a sync() and reparseConfiguration() which * will save any changes you have made. * * @param language the ISO Language Code for the locale, e.g. "en" for English * @param country the ISO Country Code for the locale, e.g. "US" for USA * @param config a configuration file with a Locale group detailing * locale-related preferences (such as language, country, * and formatting options). */ KLocale(const QString &language, const QString &country = QString(), KConfig *config = nullptr); /** * Copy constructor */ KLocale(const KLocale &rhs); /** * Assignment operator */ KLocale &operator= (const KLocale &rhs); /** * Destructor */ virtual ~KLocale(); /** * Changes the current encoding. * * @param mibEnum The mib of the preferred codec * * @return True on success. */ bool setEncoding(int mibEnum); /** * Various positions for where to place the positive or negative * sign when they are related to a monetary value. */ enum SignPosition { /** * Put parantheses around the quantity, e.g. "$ (217)" */ ParensAround = 0, /** * Prefix the quantity with the sign, e.g. "$ -217" */ BeforeQuantityMoney = 1, /** * Suffix the quanitity with the sign, e.g. "$ 217-" */ AfterQuantityMoney = 2, /** * Prefix the currency symbol with the sign, e.g. "-$ 217" */ BeforeMoney = 3, /** * Suffix the currency symbol with the sign, e.g. "$- 217" */ AfterMoney = 4 }; /** * @since 4.3 * * The set of digit characters used to display and enter numbers. */ enum DigitSet { ArabicDigits, /**< 0123456789 (European and some Asian languages and western Arabic dialects) */ ArabicIndicDigits, /**< ٠١٢٣٤٥٦٧٨٩ (eastern Arabic dialects) */ EasternArabicIndicDigits, /**< ۰۱۲۳۴۵۶۷۸۹ (Persian and Urdu) */ DevenagariDigits, /**< ०१२३४५६७८९ (Hindi) */ BengaliDigits, /**< ০১২৩৪৫৬৭৮৯ (Bengali and Assamese) */ GujaratiDigits, /**< ૦૧૨૩૪૫૬૭૮૯ (Gujarati) */ GurmukhiDigits, /**< ੦੧੨੩੪੫੬੭੮੯ (Punjabi) */ KannadaDigits, /**< ೦೧೨೩೪೫೬೭೮೯ (Kannada) */ KhmerDigits, /**< ០១២៣៤៥៦៧៨៩ (Khmer) */ MalayalamDigits, /**< ൦൧൨൩൪൫൬൭൮൯ (Malayalam) */ OriyaDigits, /**< ୦୧୨୩୪୫୬୭୮୯ (Oriya) */ TamilDigits, /**< ௦௧௨௩௪௫௬௭௮ (Tamil) */ TeluguDigits, /**< ౦౧౨౩౪౫౬౭౯ (Telugu) */ ThaiDigits /**< ๐๑๒๓๔๕๖๗๘๙ (Thai) */ // The following Decimal Digit Sets are defined in Unicode but the associated // languages are not yet translated in KDE, so are not yet enabled. // The script names are taken from the Unicode standard, the associated // languages from Wikipedia. // BalineseDigits, /**< ᭐᭑᭒᭓᭔᭕᭖᭗᭘᭙ (Balinese) */ // ChamDigits, /**< ꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙ (Cham) */ // JavaneseDigits, /**< ꧐꧑꧒꧓꧔꧕꧖꧗꧘꧙ (Javanese) */ // KayahLiDigits, /**< ꤀꤁꤂꤃꤄꤅꤆꤇꤈꤉ (Kayah) */ // LaoDigits, /**< ໐໑໒໓໔໕໖໗໘໙ (Lao) */ // LepchaDigits, /**< ᱀᱁᱂᱃᱄᱅᱆᱇᱈᱉ (Lepcha) */ // LimbuDigits, /**< ᥆᥇᥈᥉᥊᥋᥌᥍᥎᥏ (Limbu) */ // MeeteiMayekDigits, /**< ꯰꯱꯲꯳꯴꯵꯶꯷꯸꯹ (Meitei) */ // MongolianDigits, /**< ᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙ (Mongolian) */ // MyanmarDigits, /**< ၀၁၂၃၄၅၆၇၈၉ (Myanmar/Burmese ) */ // MyanmarShanDigits, /**< ႐႑႒႓႔႕႖႗႘႙ (Shan) */ // NewTaiLueDigits, /**< ᧐᧑᧒᧓᧔᧕᧖᧗᧘᧙ (Tai Lü) */ // NKoDigits, /**< ߀߁߂߃߄߅߆߇߈߉ (Mande and N'Ko) */ // OlChikiDigits, /**< ᱐᱑᱒᱓᱔᱕᱖᱗᱘᱙ (Santali) */ // OsmanyaDigits, /**< ҠҡҢңҤҥҦҧҨҩ (Somali) */ // SaurashtraDigits, /**< ꣐꣑꣒꣓꣔꣕꣖꣗꣘꣙ (Saurashtra) */ // SundaneseDigits, /**< ᮰᮱᮲᮳᮴᮵᮶᮷᮸᮹ (Sundanese) */ // TaiThamDigits, /**< ᪐᪑᪒᪓᪔᪕᪖᪗᪘᪙ (Tai Lü) */ // TibetanDigits, /**< ༠༡༢༣༤༥༦༧༨༩ (Tibetan) */ // VaiDigits, /**< ꘠꘡꘢꘣꘤꘥꘦꘧꘨꘩ (Vai) */ }; /** * @since 4.3 * * Convert a digit set identifier to a human readable, localized name. * * @param digitSet the digit set identifier * @param withDigits whether to add the digits themselves to the name * * @return the human readable and localized name of the digit set * * @see DigitSet */ QString digitSetToName(DigitSet digitSet, bool withDigits = false) const; /** * @since 4.3 * * Provides list of all known digit set identifiers. * * @return list of all digit set identifiers * @see DigitSet * @see digitSetToName */ QList allDigitSetsList() const; /** * Returns what a decimal point should look like ("." or "," etc.) * according to the current locale or user settings. * * @return The decimal symbol used by locale. */ QString decimalSymbol() const; /** * Returns what the thousands separator should look * like ("," or "." etc.) * according to the current locale or user settings. * * @return The thousands separator used by locale. */ QString thousandsSeparator() const; /** * @since 4.3 * * Returns the identifier of the digit set used to display numbers. * * @return the digit set identifier * @see DigitSet * @see digitSetToName */ DigitSet digitSet() const; /** * @since 4.4 * * Returns the ISO 4217 Currency Code for the current locale * * @return The default ISO Currency Code used by locale. */ QString currencyCode() const; /** * @since 4.4 * * Returns the Currency Code object for the current locale * * @return The default Currency Code object used by locale. */ KCurrencyCode *currency() const; /** * Returns what the symbol denoting currency in the current locale * as as defined by user settings should look like. * * @return The default currency symbol used by locale. */ QString currencySymbol() const; /** * Returns what a decimal point should look like ("." or "," etc.) * for monetary values, according to the current locale or user * settings. * * @return The monetary decimal symbol used by locale. */ QString monetaryDecimalSymbol() const; /** * Returns what a thousands separator for monetary values should * look like ("," or " " etc.) according to the current locale or * user settings. * * @return The monetary thousands separator used by locale. */ QString monetaryThousandsSeparator() const; /** * Returns what a positive sign should look like ("+", " ", etc.) * according to the current locale or user settings. * * @return The positive sign used by locale. */ QString positiveSign() const; /** * Returns what a negative sign should look like ("-", etc.) * according to the current locale or user settings. * * @return The negative sign used by locale. */ QString negativeSign() const; /** * @deprecated use decimalPlaces() or monetaryDecimalPlaces() * * The number of fractional digits to include in monetary values (usually 2). * * @return Default number of fractional digits used by locale. */ KDELIBS4SUPPORT_DEPRECATED int fracDigits() const; /** * @since 4.4 * * The number of decimal places to include in numeric values (usually 2). * * @return Default number of numeric decimal places used by locale. */ int decimalPlaces() const; /** * @since 4.4 * * The number of decimal places to include in monetary values (usually 2). * * @return Default number of monetary decimal places used by locale. */ int monetaryDecimalPlaces() const; /** * If and only if the currency symbol precedes a positive value, * this will be true. * * @return Where to print the currency symbol for positive numbers. */ bool positivePrefixCurrencySymbol() const; /** * If and only if the currency symbol precedes a negative value, * this will be true. * * @return True if the currency symbol precedes negative numbers. */ bool negativePrefixCurrencySymbol() const; /** * Returns the position of a positive sign in relation to a * monetary value. * * @return Where/how to print the positive sign. * @see SignPosition */ SignPosition positiveMonetarySignPosition() const; /** * Denotes where to place a negative sign in relation to a * monetary value. * * @return Where/how to print the negative sign. * @see SignPosition */ SignPosition negativeMonetarySignPosition() const; /** * @since 4.3 * * Retuns the digit set used to display monetary values. * * @return the digit set identifier * @see DigitSet * @see digitSetToName */ DigitSet monetaryDigitSet() const; /** * Given a double, converts that to a numeric string containing * the localized monetary equivalent. * * e.g. given 123456, return "$ 123,456.00". * * If precision isn't specified or is < 0, then the default monetaryDecimalPlaces() is used. * * @param num The number we want to format * @param currency The currency symbol you want. * @param precision Number of decimal places displayed * * @return The number of money as a localized string * @see monetaryDecimalPlaces() */ QString formatMoney(double num, const QString ¤cy = QString(), int precision = -1) const; /** * Given a double, converts that to a numeric string containing * the localized numeric equivalent. * * e.g. given 123456.78F, return "123,456.78" (for some European country). * * If precision isn't specified or is < 0, then the default decimalPlaces() is used. * * This function is a wrapper that is provided for convenience. * * @param num The number to convert * @param precision Number of decimal places used. * * @return The number as a localized string * @see formatNumber(const QString, bool, int) * @see decimalPlaces() */ QString formatNumber(double num, int precision = -1) const; /** * Given a string representing a number, converts that to a numeric * string containing the localized numeric equivalent. * * e.g. given 123456.78F, return "123,456.78" (for some European country). * * If precision isn't specified or is < 0, then the default decimalPlaces() is used. * * @param numStr The number to format, as a string. * @param round Round fractional digits. (default true) * @param precision Number of fractional digits used for rounding. Unused if round=false. * * @return The number as a localized string */ QString formatNumber(const QString &numStr, bool round = true, int precision = -1) const; /** * Given an integer, converts that to a numeric string containing * the localized numeric equivalent. * * e.g. given 123456L, return "123,456" (for some European country). * * @param num The number to convert * * @return The number as a localized string */ QString formatLong(long num) const; /** * These binary units are used in KDE by the formatByteSize() * functions. * * NOTE: There are several different units standards: * 1) SI (i.e. metric), powers-of-10. * 2) IEC, powers-of-2, with specific units KiB, MiB, etc. * 3) JEDEC, powers-of-2, used for solid state memory sizing which * is why you see flash cards labels as e.g. 4GB. These (ab)use * the metric units. Although JEDEC only defines KB, MB, GB, if * JEDEC is selected all units will be powers-of-2 with metric * prefixes for clarity in the event of sizes larger than 1024 GB. * * Although 3 different dialects are possible this enum only uses * metric names since adding all 3 different names of essentially the same * unit would be pointless. Use BinaryUnitDialect to control the exact * units returned. * * @since 4.4 * @see binaryUnitDialect */ enum BinarySizeUnits { /// Auto-choose a unit such that the result is in the range [0, 1000 or 1024) DefaultBinaryUnits = -1, // The first real unit must be 0 for the current implementation! UnitByte, ///< B 1 byte UnitKiloByte, ///< KiB/KB/kB 1024/1000 bytes. UnitMegaByte, ///< MiB/MB/MB 2^20/10^06 bytes. UnitGigaByte, ///< GiB/GB/GB 2^30/10^09 bytes. UnitTeraByte, ///< TiB/TB/TB 2^40/10^12 bytes. UnitPetaByte, ///< PiB/PB/PB 2^50/10^15 bytes. UnitExaByte, ///< EiB/EB/EB 2^60/10^18 bytes. UnitZettaByte, ///< ZiB/ZB/ZB 2^70/10^21 bytes. UnitYottaByte, ///< YiB/YB/YB 2^80/10^24 bytes. UnitLastUnit = UnitYottaByte }; /** * This enum chooses what dialect is used for binary units. * * Note: Although JEDEC abuses the metric prefixes and can therefore be * confusing, it has been used to describe *memory* sizes for quite some time * and programs should therefore use either Default, JEDEC, or IEC 60027-2 * for memory sizes. * * On the other hand network transmission rates are typically in metric so * Default, Metric, or IEC (which is unambiguous) should be chosen. * * Normally choosing DefaultBinaryDialect is the best option as that uses * the user's selection for units. * * @since 4.4 * @see binaryUnitDialect * @see setBinaryUnitDialect */ enum BinaryUnitDialect { DefaultBinaryDialect = -1, ///< Used if no specific preference IECBinaryDialect, ///< KDE Default, KiB, MiB, etc. 2^(10*n) JEDECBinaryDialect, ///< KDE 3.5 default, KB, MB, etc. 2^(10*n) MetricBinaryDialect, ///< SI Units, kB, MB, etc. 10^(3*n) LastBinaryDialect = MetricBinaryDialect }; /** * Converts @p size from bytes to the string representation using the * user's default binary unit dialect. The default unit dialect is * IEC 60027-2. * * Example: * formatByteSize(1024) returns "1.0 KiB" by default. * * @param size size in bytes * @return converted size as a string - e.g. 123.4 KiB , 12.0 MiB * @see BinaryUnitDialect * @todo KDE 5: Remove in favor of overload added in KDE 4.4. */ QString formatByteSize(double size) const; /** * @since 4.4 * * Converts @p size from bytes to the appropriate string representation * using the binary unit dialect @p dialect and the specific units @p specificUnit. * * Example: * formatByteSize(1000, unit, KLocale::UnitKiloByte) returns: * for KLocale::MetricBinaryDialect, "1.0 kB", * for KLocale::IECBinaryDialect, "0.9 KiB", * for KLocale::JEDECBinaryDialect, "0.9 KB". * * @param size size in bytes * @param precision number of places after the decimal point to use. KDE uses * 1 by default so when in doubt use 1. * @param dialect binary unit standard to use. Use DefaultBinaryDialect to * use the localized user selection unless you need to use a specific * unit type (such as displaying a flash memory size in JEDEC). * @param specificUnit specific unit size to use in result. Use * DefaultBinaryUnits to automatically select a unit that will return * a sanely-sized number. * @return converted size as a translated string including the units. * E.g. "1.23 KiB", "2 GB" (JEDEC), "4.2 kB" (Metric). * @see BinaryUnitDialect */ QString formatByteSize(double size, int precision, BinaryUnitDialect dialect = KLocale::DefaultBinaryDialect, BinarySizeUnits specificUnit = KLocale::DefaultBinaryUnits) const; /** * Returns the user's configured binary unit dialect. * e.g. if MetricBinaryDialect is returned then the values * configured for how much a set of bytes are worth would * be 10^(3*n) and KB (1000 bytes == 1 KB), in this case. * * Will never return DefaultBinaryDialect. * * @since 4.4 * @return User's configured binary unit dialect * @see BinaryUnitDialect */ BinaryUnitDialect binaryUnitDialect() const; /** * Sets @p newDialect to be the default dialect for this locale (and only * this locale). Newly created KLocale objects will continue to default * to the user's choice. * * @param newDialect the new dialect to set as default for this locale object. * @since 4.4 */ void setBinaryUnitDialect(BinaryUnitDialect newDialect); /** * Given a number of milliseconds, converts that to a string containing * the localized equivalent * * e.g. given formatDuration(60000), returns "1.0 minutes" * * @param mSec Time duration in milliseconds * @return converted duration as a string - e.g. "5.5 seconds" "23.0 minutes" */ QString formatDuration(unsigned long mSec) const; /** * Given a number of milliseconds, converts that to a pretty string containing * the localized equivalent. * * e.g. given prettyFormatDuration(60001) returns "1 minute" * given prettyFormatDuration(62005) returns "1 minute and 2 seconds" * given prettyFormatDuration(90060000) returns "1 day and 1 hour" * * @param mSec Time duration in milliseconds * @return converted duration as a string. * Units not interesting to the user, for example seconds or minutes when the first * unit is day, are not returned because they are irrelevant. The same applies for * seconds when the first unit is hour. * @since 4.2 */ QString prettyFormatDuration(unsigned long mSec) const; /** * @deprecated * * Use this to determine whether nouns are declined in * locale's language. This property should remain * read-only (no setter function) * * @return If nouns are declined */ KDELIBS4SUPPORT_DEPRECATED bool nounDeclension() const; /** * @since 4.6 * * Available Calendar Systems * * @see setCalendarSystem() * @see calendarSystem() */ enum CalendarSystem { GregorianCalendar = 1, /**< KDE Default, proleptic Gregorian Calendar as used by QDate */ //BahaiCalendar = 2, /**< Baha'i Calendar */ //BuddhistLunarCalendar = 3, /**< Buddhist Lunar Calendar*/ //ChineseCalendar = 4, /**< Chinese Calendar */ CopticCalendar = 5, /**< Coptic Calendar as used Coptic Church and some parts of Egypt */ EthiopianCalendar = 6, /**< Ethiopian Calendar, aka Ethiopic Calendar */ //EthiopianAmeteAlemCalendar = 7, /**< Ethiopian Amete Alem version, aka Ethiopic Amete Alem */ HebrewCalendar = 9, /**< Hebrew Calendar, aka Jewish Calendar */ //HinduCalendar = 10, /**< Hindu Lunar Calendar */ //IslamicLunarCalendar = 11, /**< Islamic Lunar Calendar */ IslamicCivilCalendar = 12, /**< Islamic Civil Calendar, aka Hijri, not the Lunar Calendar */ //IslamicUmAlQuraCalendar = 13, /**< Islamic Lunar Calendar, Um Al Qura varient used in Saudi Arabia */ IndianNationalCalendar = 14, /**< Indian National Calendar, not the Lunar Calendar */ //Iso8601Calendar = 15, /**< ISO 8601 Standard Calendar */ JalaliCalendar = 16, /**< Jalali Calendar, aka Persian or Iranian, also used in Afghanistan */ //JalaliBirashkCalendar = 17, /**< Jalali Calendar, Birashk Algorythm variant */ //Jalali33YearCalendar = 18, /**< Jalali Calendar, 33 Year cycle variant */ JapaneseCalendar = 19, /**< Japanese Calendar, Gregorian calculation using Japanese Era (Nengô) */ //JucheCalendar = 20, /**< Juche Calendar, used in North Korea */ JulianCalendar = 21, /**< Julian Calendar, as used in Orthodox Churches */ MinguoCalendar = 22, /**< Minguo Calendar, aka ROC, Republic of China or Taiwanese */ ThaiCalendar = 23, /**< Thai Calendar, aka Buddhist or Thai Buddhist */ QDateCalendar = GregorianCalendar /**< @deprecated Alias for GregorianCalendar */ }; /** * @since 4.6 * * System used for Week Numbers * * @see setWeekNumberSystem() * @see weekNumberSystem() */ enum WeekNumberSystem { DefaultWeekNumber = -1, /**< The system locale default */ IsoWeekNumber = 0, /**< ISO Week Number */ FirstFullWeek = 1, /**< Week 1 starts on the first Week Start Day in year ends after 7 days */ FirstPartialWeek = 2, /**< Week 1 starts Jan 1st ends day before first Week Start Day in year */ SimpleWeek = 3 /**< Week 1 starts Jan 1st ends after 7 days */ }; /** * @since 4.4 * * Standard used for Date Time Format String */ enum DateTimeFormatStandard { KdeFormat, /**< KDE Standard */ PosixFormat, /**< POSIX Standard */ UnicodeFormat /**< UNICODE Standard (Qt/Java/OSX/Windows) */ }; /** * @since 4.6 * * Mode to use when parsing a Date Time input string */ enum DateTimeParseMode { LiberalParsing /**< Parse Date/Time liberally. So long as the input string contains at least a reconizable month and day the input will be accepted. */ //ModerateParsing, /**< Parse Date/Time with modeate tolerance. // The date components in the format must all // occur in the input and in the same order, // but the spacing and the componants themselves // may vary from the strict format. */ //StrictParsing /**< Parse Date/Time strictly to the format. */ }; /** * @since 4.6 * * The various Components that make up a Date / Time * In the future the Components may be combined as flags for dynamic * generation of Date Formats. * * @see KCalendarSystem * @see KLocalizedDate * @see DateTimeComponentFormat */ enum DateTimeComponent { Year = 0x1, /**< The Year portion of a date, may be number or name */ YearName = 0x2, /**< The Year Name portion of a date */ Month = 0x4, /**< The Month portion of a date, may be number or name */ MonthName = 0x8, /**< The Month Name portion of a date */ Day = 0x10, /**< The Day portion of a date, may be number or name */ DayName = 0x20, /**< The Day Name portion of a date */ JulianDay = 0x40, /**< The Julian Day of a date */ EraName = 0x80, /**< The Era Name portion of a date */ EraYear = 0x100, /**< The Era and Year portion of a date */ YearInEra = 0x200, /**< The Year In Era portion of a date */ DayOfYear = 0x400, /**< The Day Of Year portion of a date, may be number or name */ DayOfYearName = 0x800, /**< The Day Of Year Name portion of a date */ DayOfWeek = 0x1000, /**< The Day Of Week / Weekday portion of a date, may be number or name */ DayOfWeekName = 0x2000, /**< The Day Of Week Name / Weekday Name portion of a date */ Week = 0x4000, /**< The Week Number portion of a date */ WeekYear = 0x8000, /**< The Week Year portion of a date */ MonthsInYear = 0x10000, /**< The Months In Year portion of a date */ WeeksInYear = 0x20000, /**< The Weeks In Year portion of a date */ DaysInYear = 0x40000, /**< The Days In Year portion of a date */ DaysInMonth = 0x80000, /**< The Days In Month portion of a date */ DaysInWeek = 0x100000, /**< The Days In Week portion of a date */ Hour = 0x200000, /**< The Hours portion of a date */ Minute = 0x400000, /**< The Minutes portion of a date */ Second = 0x800000, /**< The Seconds portion of a date */ Millisecond = 0x1000000, /**< The Milliseconds portion of a date */ DayPeriod = 0x2000000, /**< The Day Period portion of a date, e.g. AM/PM */ DayPeriodHour = 0x4000000, /**< The Day Period Hour portion of a date */ Timezone = 0x8000000, /**< The Time Zone portion of a date, may be offset or name */ TimezoneName = 0x10000000, /**< The Time Zone Name portion of a date */ UnixTime = 0x20000000 /**< The UNIX Time portion of a date */ }; Q_DECLARE_FLAGS(DateTimeComponents, DateTimeComponent) /** * @since 4.6 * * Format used for individual Date/Time Components when converted to/from a string * Largely equivalent to the UNICODE CLDR format width definitions 1..5 * * @see DateTimeComponentFormat */ enum DateTimeComponentFormat { DefaultComponentFormat = -1, /**< The system locale default for the componant */ ShortNumber = 0, /**< Number at its natural width, e.g. 2 for the 2nd*/ LongNumber, /**< Number padded to a required width, e.g. 02 for the 2nd*/ //OrdinalNumber /**< Ordinal number format, e.g. "2nd" for the 2nd */ NarrowName = 3, /**< Narrow text format, may not be unique, e.g. M for Monday */ ShortName, /**< Short text format, e.g. Mon for Monday */ LongName /**< Long text format, e.g. Monday for Monday */ }; /** * Format for date string. */ enum DateFormat { ShortDate, /**< Locale Short date format, e.g. 08-04-2007 */ LongDate, /**< Locale Long date format, e.g. Sunday 08 April 2007 */ FancyShortDate, /**< Same as ShortDate for dates a week or more ago. For more recent dates, it is represented as Today, Yesterday, or the weekday name. */ FancyLongDate, /**< Same as LongDate for dates a week or more ago. For more recent dates, it is represented as Today, Yesterday, or the weekday name. */ IsoDate, /**< ISO-8601 Date format YYYY-MM-DD, e.g. 2009-12-31 */ IsoWeekDate, /**< ISO-8601 Week Date format YYYY-Www-D, e.g. 2009-W01-1 */ IsoOrdinalDate /**< ISO-8601 Ordinal Date format YYYY-DDD, e.g. 2009-001 */ }; /** * Returns a string formatted to the current locale's conventions * regarding dates. * * @param date the date to be formatted * @param format category of date format to use * * @return the date as a string */ QString formatDate(const QDate &date, DateFormat format = LongDate) const; /** * Returns a string formatted to the current locale's conventions * regarding both date and time. * * @param dateTime the date and time to be formatted * @param format category of date format to use * @param includeSecs if @c true, the string will include the seconds part * of the time; otherwise, the seconds will be omitted * * @return the date and time as a string */ QString formatDateTime(const QDateTime &dateTime, DateFormat format = ShortDate, bool includeSecs = false) const; /** * Options for formatting date-time values. */ enum DateTimeFormatOption { TimeZone = 0x01, /**< Include a time zone string */ Seconds = 0x02 /**< Include the seconds value */ }; Q_DECLARE_FLAGS(DateTimeFormatOptions, DateTimeFormatOption) /** * Returns a string formatted to the current locale's conventions * regarding both date and time. * * @param dateTime the date and time to be formatted * @param format category of date format to use * @param options additional output options * * @return The date and time as a string */ QString formatDateTime(const KDateTime &dateTime, DateFormat format = ShortDate, DateTimeFormatOptions options = nullptr) const; /** * Use this to determine whether in dates a possessive form of month * name is preferred ("of January" rather than "January") * * @return If possessive form should be used */ bool dateMonthNamePossessive() const; /** * @deprecated replaced by formatLocaleTime() * * Returns a string formatted to the current locale's conventions * regarding times. * * @param pTime The time to be formatted. * @param includeSecs if true, seconds are included in the output, * otherwise only hours and minutes are formatted. * @param isDuration if true, the given time is a duration, not a clock time. * This means "am/pm" shouldn't be displayed. * * @return The time as a string */ QString formatTime(const QTime &pTime, bool includeSecs = false, bool isDuration = false) const; /** * @since 4.4 * * Format flags for readLocaleTime() and formatLocaleTime() */ enum TimeFormatOption { TimeDefault = 0x0, ///< Default formatting using seconds and the format ///< as specified by the locale. TimeWithoutSeconds = 0x1, ///< Exclude the seconds part of the time from display TimeWithoutAmPm = 0x2, ///< Read/format time string without am/pm suffix but ///< keep the 12/24h format as specified by locale time ///< format, eg. "07.33.05" instead of "07.33.05 pm" for ///< time format "%I.%M.%S %p". TimeDuration = 0x6, ///< Read/format time string as duration. This will strip ///< the am/pm suffix and read/format times with an hour ///< value of 0-23 hours, eg. "19.33.05" instead of ///< "07.33.05 pm" for time format "%I.%M.%S %p". ///< This automatically implies @c TimeWithoutAmPm. TimeFoldHours = 0xE ///< Read/format time string as duration. This will not ///< not output the hours part of the duration but will ///< add the hours (times sixty) to the number of minutes, ///< eg. "70.23" instead of "01.10.23" for time format ///< "%I.%M.%S %p". }; Q_DECLARE_FLAGS(TimeFormatOptions, TimeFormatOption) /** * @since 4.4 * * Returns a string formatted to the current locale's conventions * regarding times. * * @param pTime the time to be formatted * @param options format option to use when formatting the time * @return The time as a string */ QString formatLocaleTime(const QTime &pTime, TimeFormatOptions options = KLocale::TimeDefault) const; /** * @since 4.3 * * Returns the identifier of the digit set used to display dates and time. * * @return the digit set identifier * @see DigitSet * @see digitSetToName */ DigitSet dateTimeDigitSet() const; /** * Use this to determine if the user wants a 12 hour clock. * * @return If the user wants 12h clock * @deprecated. A possible equivalent would be: * @code * static bool use12Clock() * { * const QString str = QLocale().timeFormat(); * // 'A' or 'a' means am/pm is shown (and then 'h' uses 12-hour format) * // but 'H' forces a 24-hour format anyway, even with am/pm shown. * return str.contains(QLatin1Char('a'), Qt::CaseInsensitive) && !str.contains(QLatin1Char('H')); * } * @endcode */ bool use12Clock() const; /** * @since 4.6 * * Returns the Day Period matching the time given * * @param time the time to return the day period for * @param format the format to return teh day period in * @return the Day Period for the given time */ QString dayPeriodText(const QTime &time, DateTimeComponentFormat format = DefaultComponentFormat) const; /** * Use this to determine which day is the first day of the week. * * @return an integer (Monday=1..Sunday=7) */ int weekStartDay() const; /** * Use this to determine which day is the first working day of the week. * * @since 4.2 * @return an integer (Monday=1..Sunday=7) */ int workingWeekStartDay() const; /** * Use this to determine which day is the last working day of the week. * * @since 4.2 * @return an integer (Monday=1..Sunday=7) */ int workingWeekEndDay() const; /** * Use this to determine which day is reserved for religious observance * * @since 4.2 * @return day number (None = 0, Monday = 1, ..., Sunday = 7) */ int weekDayOfPray() const; /** * Returns a pointer to the calendar system object. * * @return the current calendar system instance */ const KCalendarSystem *calendar() const; /** * @deprecated use calendarSystem() instead * * Returns the name of the calendar system that is currently being * used by the system. * * @see calendarSystem() * @return the name of the calendar system */ KDELIBS4SUPPORT_DEPRECATED QString calendarType() const; /** * @since 4.6 * * Returns the type of Calendar System used in this Locale * * @see KLocale::CalendarSystem * @see KCalendarSystem * @return the type of Calendar System */ KLocale::CalendarSystem calendarSystem() const; /** * @deprecated use setCalendarSystem() instead * * Changes the current calendar system to the calendar specified. * If the calendar system specified is not found, gregorian will be used. * * @see setCalendarSystem() * @param calendarType the name of the calendar type */ KDELIBS4SUPPORT_DEPRECATED void setCalendar(const QString &calendarType); /** * @since 4.6 * * Sets the type of Calendar System to use in this Locale * * @see KLocale::CalendarSystem * @see KCalendarSystem * @param calendarSystem the Calendar System to use */ void setCalendarSystem(KLocale::CalendarSystem calendarSystem); /** * @since 4.6 * * Sets the type of Week Number System to use in this Locale * * @see Klocale::WeekNumberSystem * @see weekNumberSystem() * @param weekNumberSystem the Week Number System to use */ void setWeekNumberSystem(KLocale::WeekNumberSystem weekNumberSystem); /** * @since 4.6 * * Returns the type of Week Number System used in this Locale * * @see Klocale::WeekNumberSystem * @see setWeekNumberSystem() * @returns the Week Number System used */ KLocale::WeekNumberSystem weekNumberSystem(); /** * @since 4.7 * * Returns the type of Week Number System used in this Locale * * @see Klocale::WeekNumberSystem * @see setWeekNumberSystem() * @returns the Week Number System used */ KLocale::WeekNumberSystem weekNumberSystem() const; /** * Converts a localized monetary string to a double. * * @param numStr the string we want to convert. * @param ok the boolean that is set to false if it's not a number. * If @p ok is 0, it will be ignored * * @return The string converted to a double */ double readMoney(const QString &numStr, bool *ok = nullptr) const; /** * Converts a localized numeric string to a double. * * @param numStr the string we want to convert. * @param ok the boolean that is set to false if it's not a number. * If @p ok is 0, it will be ignored * * @return The string converted to a double */ double readNumber(const QString &numStr, bool *ok = nullptr) const; /** * Converts a localized date string to a QDate. This method will try all * ReadDateFlag formats in preferred order to read a valid date. * * The bool pointed by ok will be invalid if the date entered was not valid. * * @param str the string we want to convert. * @param ok the boolean that is set to false if it's not a valid date. * If @p ok is 0, it will be ignored * * @return The string converted to a QDate * @see KCalendarSystem::readDate() */ QDate readDate(const QString &str, bool *ok = nullptr) const; /** * Converts a localized date string to a QDate, using the specified format. * You will usually not want to use this method. * @see KCalendarSystem::readDate() */ QDate readDate(const QString &intstr, const QString &fmt, bool *ok = nullptr) const; /** * Flags for readDate() */ enum ReadDateFlags { NormalFormat = 1, /**< Only accept a date string in the locale LongDate format */ ShortFormat = 2, /**< Only accept a date string in the locale ShortDate format */ IsoFormat = 4, /**< Only accept a date string in ISO date format (YYYY-MM-DD) */ IsoWeekFormat = 8, /**< Only accept a date string in ISO Week date format (YYYY-Www-D) */ IsoOrdinalFormat = 16 /**< Only accept a date string in ISO Week date format (YYYY-DDD) */ }; /** * Converts a localized date string to a QDate. * This method is stricter than readDate(str,&ok): it will only accept * a date in a specific format, depending on @p flags. * * @param str the string we want to convert. * @param flags what format the the date string will be in * @param ok the boolean that is set to false if it's not a valid date. * If @p ok is 0, it will be ignored * * @return The string converted to a QDate * @see KCalendarSystem::readDate() */ QDate readDate(const QString &str, ReadDateFlags flags, bool *ok = nullptr) const; /** * Converts a localized time string to a QTime. * This method will try to parse it with seconds, then without seconds. * The bool pointed to by @p ok will be set to false if the time entered was * not valid. * * @param str the string we want to convert. * @param ok the boolean that is set to false if it's not a valid time. * If @p ok is 0, it will be ignored * * @return The string converted to a QTime */ QTime readTime(const QString &str, bool *ok = nullptr) const; /** * Flags for the old version of readTime() * * @deprecated replaced by TimeFormatOptions */ enum ReadTimeFlags { WithSeconds = 0, ///< Only accept a time string with seconds. Default (no flag set) WithoutSeconds = 1 ///< Only accept a time string without seconds. }; // (maybe use this enum as a bitfield, if adding independent features?) /** * @deprecated replaced readLocaleTime() * * Converts a localized time string to a QTime. * This method is stricter than readTime(str,&ok): it will either accept * a time with seconds or a time without seconds. * Use this method when the format is known by the application. * * @param str the string we want to convert. * @param flags whether the time string is expected to contain seconds or not. * @param ok the boolean that is set to false if it's not a valid time. * If @p ok is 0, it will be ignored * * @return The string converted to a QTime */ QTime readTime(const QString &str, ReadTimeFlags flags, bool *ok = nullptr) const; /** * Additional processing options for readLocaleTime(). * * @remarks This is currently used as an enum but declared as a flag * to be extensible */ enum TimeProcessingOption { ProcessStrict = 0x1, ///< Process time in a strict manner, ie. ///< a read time string has to exactly match ///< the defined time format. ProcessNonStrict = 0x2 ///< Process time in a lax manner, ie. ///< allow spaces in the time-format to be ///< left out when entering a time string. }; Q_DECLARE_FLAGS(TimeProcessingOptions, TimeProcessingOption) /** * @since 4.4 * * Converts a localized time string to a QTime. * This method is stricter than readTime(str, &ok) in that it will either * accept a time with seconds or a time without seconds. * * @param str the string we want to convert * @param ok the boolean that is set to false if it's not a valid time. * If @p ok is 0, it will be ignored. * @param options format option to apply when formatting the time * @param processing if set to @c ProcessStrict, checking will be strict * and the read time string has to have the exact time format * specified. If set to @c ProcessNonStrict processing the time * is lax and spaces in the time string can be left out. * * @return The string converted to a QTime */ QTime readLocaleTime(const QString &str, bool *ok = nullptr, TimeFormatOptions options = KLocale::TimeDefault, TimeProcessingOptions processing = ProcessNonStrict) const; /** * Returns the language code used by this object. * * Use languageCodeToName(language) to get human readable, localized * language name. * * @return the currently used language code * * @see languageCodeToName */ QString language() const; /** * Returns the country code of the country where the user lives. * * The returned code complies with the ISO 3166-1 alpha-2 standard, * except by KDE convention it is returned in lowercase whereas the * official standard is uppercase. * See http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 for details. * * defaultCountry() is returned by default, if no other available, * this will always be uppercase 'C'. * * Use countryCodeToName(country) to get human readable, localized * country names. * * @return the country code for the user * * @see countryCodeToName */ QString country() const; /** * @since 4.6 * * Returns the Country Division Code of the Country where the user lives. * When no value is set, then the Country Code will be returned. * * The returned code complies with the ISO 3166-2 standard. * See http://en.wikipedia.org/wiki/ISO_3166-2 for details. * * Note that unlike country() this method will return the correct case, * i.e. normally uppercase.. * * In KDE 4.6 it is the apps responsibility to obtain a translation for the * code, translation and other services will be priovided in KDE 4.7. * * @return the Country Division Code for the user * @see setCountryDivisionCode */ QString countryDivisionCode() const; /** * Returns the language codes selected by user, ordered by decreasing * priority. * * Use languageCodeToName(language) to get human readable, localized * language name. * * @return list of language codes * * @see languageCodeToName */ QStringList languageList() const; /** * @since 4.4 * * Returns the ISO Currency Codes used in the locale, ordered by decreasing * priority. * * Use KCurrency::currencyCodeToName(currencyCode) to get human readable, * localized language name. * * @return list of ISO Currency Codes * * @see currencyCodeToName */ QStringList currencyCodeList() const; /** * Returns the user's preferred encoding. * * @return The name of the preferred encoding * * @see codecForEncoding * @see encodingMib */ const QByteArray encoding() const; /** * Returns the user's preferred encoding. * * @return The Mib of the preferred encoding * * @see encoding * @see codecForEncoding */ int encodingMib() const; /** * Returns the user's preferred encoding. Should never be NULL. * * @return The codec for the preferred encoding * * @see encoding * @see encodingMib */ QTextCodec *codecForEncoding() const; /** * Returns the file encoding. * * @return The Mib of the file encoding * * @see QFile::encodeName * @see QFile::decodeName */ int fileEncodingMib() const; /** * Changes the current date format. * * The format of the date is a string which contains variables that will * be replaced: * @li %Y with the whole year (e.g. "2004" for "2004") * @li %y with the lower 2 digits of the year (e.g. "04" for "2004") * @li %n with the month (January="1", December="12") * @li %m with the month with two digits (January="01", December="12") * @li %e with the day of the month (e.g. "1" on the first of march) * @li %d with the day of the month with two digits (e.g. "01" on the first of march) * @li %b with the short form of the month (e.g. "Jan" for January) * @li %B with the long form of the month (e.g. "January") * @li %a with the short form of the weekday (e.g. "Wed" for Wednesday) * @li %A with the long form of the weekday (e.g. "Wednesday" for Wednesday) * * Everything else in the format string will be taken as is. * For example, March 20th 1989 with the format "%y:%m:%d" results * in "89:03:20". * * @param format The new date format */ void setDateFormat(const QString &format); /** * Changes the current short date format. * * The format of the date is a string which contains variables that will * be replaced: * @li %Y with the whole year (e.g. "1984" for "1984") * @li %y with the lower 2 digits of the year (e.g. "84" for "1984") * @li %n with the month (January="1", December="12") * @li %m with the month with two digits (January="01", December="12") * @li %e with the day of the month (e.g. "1" on the first of march) * @li %d with the day of the month with two digits(e.g. "01" on the first of march) * @li %b with the short form of the month (e.g. "Jan" for January) * @li %B with the long form of the month (e.g. "January") * @li %a with the short form of the weekday (e.g. "Wed" for Wednesday) * @li %A with the long form of the weekday (e.g. "Wednesday" for Wednesday) * * Everything else in the format string will be taken as is. * For example, March 20th 1989 with the format "%y:%m:%d" results * in "89:03:20". * * @param format The new short date format */ void setDateFormatShort(const QString &format); /** * Changes the form of month name used in dates. * * @param possessive True if possessive forms should be used */ void setDateMonthNamePossessive(bool possessive); /** * Changes the current time format. * * The format of the time is string a which contains variables that will * be replaced: * @li %H with the hour in 24h format and 2 digits (e.g. 5pm is "17", 5am is "05") * @li %k with the hour in 24h format and one digits (e.g. 5pm is "17", 5am is "5") * @li %I with the hour in 12h format and 2 digits (e.g. 5pm is "05", 5am is "05") * @li %l with the hour in 12h format and one digits (e.g. 5pm is "5", 5am is "5") * @li %M with the minute with 2 digits (e.g. the minute of 07:02:09 is "02") * @li %S with the seconds with 2 digits (e.g. the minute of 07:02:09 is "09") * @li %p with pm or am (e.g. 17.00 is "pm", 05.00 is "am") * * Everything else in the format string will be taken as is. * For example, 5.23pm with the format "%H:%M" results * in "17:23". * * @param format The new time format */ void setTimeFormat(const QString &format); /** * @since 4.3 * * Set digit characters used to display dates and time. * * @param digitSet the digit set identifier * @see DigitSet */ void setDateTimeDigitSet(DigitSet digitSet); /** * Changes how KLocale defines the first day in week. * * @param day first day of the week (Monday=1..Sunday=7) as integer */ void setWeekStartDay(int day); /** * Changes how KLocale defines the first working day in week. * * @since 4.2 * @param day first working day of the week (Monday=1..Sunday=7) as integer */ void setWorkingWeekStartDay(int day); /** * Changes how KLocale defines the last working day in week. * * @since 4.2 * @param day last working day of the week (Monday=1..Sunday=7) as integer */ void setWorkingWeekEndDay(int day); /** * Changes how KLocale defines the day reserved for religious observance. * * @since 4.2 * @param day day of the week for religious observance (None=0,Monday=1..Sunday=7) as integer */ void setWeekDayOfPray(int day); /** * Returns the currently selected date format. * * @return Current date format. * @see setDateFormat() */ QString dateFormat() const; /** * Returns the currently selected short date format. * * @return Current short date format. * @see setDateFormatShort() */ QString dateFormatShort() const; /** * Returns the currently selected time format. * * @return Current time format. * @see setTimeFormat() */ QString timeFormat() const; /** * Changes the symbol used to identify the decimal pointer. * * @param symbol The new decimal symbol. */ void setDecimalSymbol(const QString &symbol); /** * Changes the separator used to group digits when formating numbers. * * @param separator The new thousands separator. */ void setThousandsSeparator(const QString &separator); /** * Changes the sign used to identify a positive number. Normally this is * left blank. * * @param sign Sign used for positive numbers. */ void setPositiveSign(const QString &sign); /** * Changes the sign used to identify a negative number. * * @param sign Sign used for negative numbers. */ void setNegativeSign(const QString &sign); /** * @since 4.3 * * Changes the set of digit characters used to display numbers. * * @param digitSet the digit set identifier * @see DigitSet */ void setDigitSet(DigitSet digitSet); /** * Changes the sign position used for positive monetary values. * * @param signpos The new sign position */ void setPositiveMonetarySignPosition(SignPosition signpos); /** * Changes the sign position used for negative monetary values. * * @param signpos The new sign position */ void setNegativeMonetarySignPosition(SignPosition signpos); /** * Changes the position where the currency symbol should be printed for * positive monetary values. * * @param prefix True if the currency symbol should be prefixed instead of * postfixed */ void setPositivePrefixCurrencySymbol(bool prefix); /** * Changes the position where the currency symbol should be printed for * negative monetary values. * * @param prefix True if the currency symbol should be prefixed instead of * postfixed */ void setNegativePrefixCurrencySymbol(bool prefix); /** * @deprecated use setDecimalPlaces() or setMonetaryDecimalPlaces() * * Changes the number of digits used when formating numbers. * * @param digits The default number of digits to use. */ KDELIBS4SUPPORT_DEPRECATED void setFracDigits(int digits); /** * @since 4.4 * * Changes the number of decimal places used when formating numbers. * * @param digits The default number of digits to use. */ void setDecimalPlaces(int digits); /** * @since 4.4 * * Changes the number of decimal places used when formating money. * * @param digits The default number of digits to use. */ void setMonetaryDecimalPlaces(int digits); /** * Changes the separator used to group digits when formating monetary values. * * @param separator The new thousands separator. */ void setMonetaryThousandsSeparator(const QString &separator); /** * Changes the symbol used to identify the decimal pointer for monetary * values. * * @param symbol The new decimal symbol. */ void setMonetaryDecimalSymbol(const QString &symbol); /** * @since 4.4 * * Changes the current ISO Currency Code. * * @param newCurrencyCode The new Currency Code */ void setCurrencyCode(const QString &newCurrencyCode); /** * Changes the current currency symbol. * * This symbol should be consistant with the selected Currency Code * * @param symbol The new currency symbol * @see currencyCode, KCurrency::currencySymbols */ void setCurrencySymbol(const QString &symbol); /** * @since 4.3 * * Set digit characters used to display monetary values. * * @param digitSet the digit set identifier * @see DigitSet */ void setMonetaryDigitSet(DigitSet digitSet); /** * Returns the preferred page size for printing. * * @return The preferred page size, cast it to QPrinter::PaperSize */ int pageSize() const; /** * Changes the preferred page size when printing. * * @param paperFormat the new preferred page size in the format QPrinter::PaperSize */ void setPageSize(int paperFormat); /** * The Metric system will give you information in mm, while the * Imperial system will give you information in inches. */ enum MeasureSystem { Metric, ///< Metric system (used e.g. in Europe) Imperial ///< Imperial system (used e.g. in the United States) }; /** * Returns which measuring system we use. * * @return The preferred measuring system */ MeasureSystem measureSystem() const; /** * Changes the preferred measuring system. * * @return value The preferred measuring system */ void setMeasureSystem(MeasureSystem value); /** * Provides list of all known language codes. * * Use languageCodeToName(language) to get human readable, localized * language names. * * @return list of all language codes * * @see languageCodeToName * @see installedLanguages */ QStringList allLanguagesList() const; /** * @since 4.6 * * Provides list of all installed KDE Language Translations. * * Use languageCodeToName(language) to get human readable, localized * language names. * * @return list of all installed language codes * * @see languageCodeToName */ QStringList installedLanguages() const; /** * Convert a known language code to a human readable, localized form. * If an unknown language code is supplied, empty string is returned; * this will never happen if the code has been obtained by one of the * KLocale methods. * * @param language the language code * * @return the human readable and localized form if the code is known, * empty otherwise * * @see language * @see languageList * @see allLanguagesList * @see installedLanguages */ QString languageCodeToName(const QString &language) const; /** * Provides list of all known country codes. * * Use countryCodeToName(country) to get human readable, localized * country names. * * @return a list of all country codes * * @see countryCodeToName */ QStringList allCountriesList() const; /** * Convert a known country code to a human readable, localized form. * * If an unknown country code is supplied, empty string is returned; * this will never happen if the code has been obtained by one of the * KLocale methods. * * @param country the country code * * @return the human readable and localized form of the country name * * @see country * @see allCountriesList */ QString countryCodeToName(const QString &country) const; /** * Parses locale string into distinct parts. * The format of locale is language_COUNTRY@modifier.CHARSET * * @param locale the locale string to split * @param language set to the language part of the locale * @param country set to the country part of the locale * @param modifier set to the modifer part of the locale * @param charset set to the charset part of the locale */ static void splitLocale(const QString &locale, QString &language, QString &country, QString &modifier, QString &charset); /** * Return the global KLocale instance. * This is the one used by default by all i18n calls. * * Note: in multi-threaded programs, you should call KLocale::global() * in the main thread (e.g. in main(), after creating the QCoreApplication * and setting the main component), to ensure that the initialization is * done in the main thread. However KApplication takes care of this, so this * is only needed when not using KApplication. * * @since 5.0 */ static KLocale *global(); /** * Returns the name of the internal language. * * @return Name of the default language */ static QString defaultLanguage(); /** * Returns the code of the default country, i.e. "C" * * This function will not provide a sensible value to use in your app, * please use country() instead. * * @see country * * @return Name of the default country */ static QString defaultCountry(); /** * @since 4.4 * * Returns the ISO Code of the default currency. * * @return ISO Currency Code of the default currency */ static QString defaultCurrencyCode(); /** * Changes the current country. The current country will be left * unchanged if failed. It will force a reload of the country specific * configuration. * * An empty country value will set the country to the system default. * * If you specify a configuration file, a setLocale() will be performed on * the config using the current locale language, which may cause a sync() * and reparseConfiguration() which will save any changes you have made. * * @param country the ISO 3166 country code * @param config a configuration file with a Locale group detailing * locale-related preferences (such as language, contry, * and formatting options). * * @return @c true on success, @c false on failure */ bool setCountry(const QString &country, KConfig *config); /** * @since 4.6 * * Sets the Country Division Code of the Country where the user lives. * * The code must comply with the ISO 3166-2 standard. * See http://en.wikipedia.org/wiki/ISO_3166-2 for details. * * In KDE 4.6 it is the apps responsibility to validate the input, * full validation and other services will be provided in KDE 4.7. * * @param countryDivision the Country Division Code for the user * @return @c true on success, @c false on failure * @see countryDivisionCode */ bool setCountryDivisionCode(const QString &countryDivision); /** * Changes the current language. The current language will be left * unchanged if failed. It will force a reload of the country specific * configuration as well. * * If you specify a configuration file, a setLocale() will be performed on * the config using the current locale language, which may cause a sync() * and reparseConfiguration() which will save any changes you have made. * * @param language the language code * @param config a configuration file with a Locale group detailing * locale-related preferences (such as language, country, * and formatting options). * * @return true on success */ bool setLanguage(const QString &language, KConfig *config); /** * Changes the list of preferred languages for the locale. The first valid * language in the list will be used, or the default language (en_US) * if none of the specified languages were available. * * @param languages the list of language codes * * @return true if one of the specified languages were used */ bool setLanguage(const QStringList &languages); /** * @since 4.3 * * Convert all digits in the string to the given digit set. * * Conversion is normally not performed if the given digit set * is not appropriate in the current locale and language context. * Unconditional conversion may be requested by setting * @p ignoreContext to @c true. * * @param str the string to convert * @param digitSet the digit set identifier * @param ignoreContext unconditional conversion if @c true * * @return string with converted digits * * @see DigitSet */ QString convertDigits(const QString &str, DigitSet digitSet, bool ignoreContext = false) const; /** * @since 4.8 * * Reparse locale configuration files for the current selected * language. */ void reparseConfiguration(); private: friend class KLocalePrivate; friend class KLocaleTest; friend class KDateTimeFormatter; KLocalePrivate *const d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KLocale::DateTimeFormatOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KLocale::DateTimeComponents) Q_DECLARE_OPERATORS_FOR_FLAGS(KLocale::TimeFormatOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KLocale::TimeProcessingOptions) #endif diff --git a/src/kdecore/klocale_p.h b/src/kdecore/klocale_p.h index 42bc9605..3da4e43e 100644 --- a/src/kdecore/klocale_p.h +++ b/src/kdecore/klocale_p.h @@ -1,1117 +1,1117 @@ /* This file is part of the KDE libraries * Copyright 2009 David Faure * Copyright 2010 John Layt * * 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 KLOCALE_P_H #define KLOCALE_P_H #include "klocale.h" #include "klocalizedstring.h" class KCatalog; class KDayPeriod; class KDELIBS4SUPPORT_EXPORT KLocalePrivate { public: /** * Constructors * * This class should not be instantited directly, it is intended as a base class for each * platform to provide a common KDE fallback implementation. Instead use the relevant * derived system class for Unix, Win, or Mac which will prefer the local platform settings * where possible. */ KLocalePrivate(KLocale *q_ptr); /** * Copy constructor */ KLocalePrivate(const KLocalePrivate &rhs); /** * Assignment operator */ KLocalePrivate &operator=(const KLocalePrivate &rhs); /** * Destructor */ virtual ~KLocalePrivate(); /************************** ** Initialization ** **************************/ /** * Reads the format configuration from disk. */ virtual void initFormat(); protected: /** * @internal Returns config object */ KSharedConfigPtr config(); /** * @internal Copies object members */ virtual void copy(const KLocalePrivate &rhs); /** * @internal Main init function, needs to be called by appropriate child constructor. */ virtual void init(const QString &language, const QString &country, KSharedConfig::Ptr persistantconfig, KConfig *tempConfig); /** * @internal Init config. */ virtual void initConfig(KConfig *config); /************************** ** Country settings ** **************************/ protected: /** - * @internal Initializes the country if not already explicitly set when calling the constructor + * @internal Initializes the country if not already KDELIBS4SUPPORT_DEPRECATED explicitly set when calling the constructor * Will default to any value set in the config, otherwise will attempt to use the host system * country, or finally fall back to the default C. */ virtual void initCountry(const QString &country, const QString &configCountry); /** * @internal Returns the host system country ISO code * If country could not be determined then may return an empty string or "C" */ virtual QString systemCountry() const; public: /** * @internal Sets the Locale Country * The worker of the same-name KLocale API function. */ virtual bool setCountry(const QString &country, KConfig *config); /** * @internal Returns the Locale ISO Country Code * The worker of the same-name KLocale API function. */ virtual QString country() const; /** * @internal Returns the name of the default country. * The worker of the same-name KLocale API function. */ static QString defaultCountry(); /** * @internal Returns a list of all known country codes. * The worker of the same-name KLocale API function. */ virtual QStringList allCountriesList() const; /** * @internal Convert a known country code to a human readable, localized form. * The worker of the same-name KLocale API function. */ virtual QString countryCodeToName(const QString &country) const; /** * @internal Sets the Country Division Code * The worker of the same-name KLocale API function. */ bool setCountryDivisionCode(const QString &countryDivision); /** * @internal Returns the Country Division Code * The worker of the same-name KLocale API function. */ QString countryDivisionCode() const; /************************** ** Language settings ** **************************/ protected: /** * @internal Converts a language variable in a list of languages */ static void getLanguagesFromVariable(QStringList &list, const char *variable, bool isLanguageList = false); /** * @internal Returns the list of host system languages */ virtual QStringList systemLanguageList() const; /** * @internal Initializes the list of valid languages from the user's point of view. This is the * list of languages that the user picks in kcontrol. The config object should be valid and * contain the global entries. * * @param language The defualt language to use * @param configLanguages The "Language" setting from the current config * @param useEnv Whether to use the envvars */ virtual void initLanguageList(const QString &language, const QString &configLanguages, bool useEnv); /** * @internal function used to determine if we are using the en_US translation */ virtual bool useDefaultLanguage() const; public: /** * @internal Sets the Locale Language * The worker of the same-name KLocale API function. */ virtual bool setLanguage(const QString &language, KConfig *config); /** * @internal Sets the list of preferred languages for the locale. * The worker of the same-name KLocale API function. */ virtual bool setLanguage(const QStringList &languages); /** * @internal Returns the Locale Language * The worker of the same-name KLocale API function. */ virtual QString language() const; /** * @internal Returns the language codes selected by user * The worker of the same-name KLocale API function. */ virtual QStringList languageList() const; /** * @internal Returns a list of all known language codes. * The worker of the same-name KLocale API function. */ virtual QStringList allLanguagesList(); /** * @internal Returns a list of all installed KDE languages. * The worker of the same-name KLocale API function. */ virtual QStringList installedLanguages(); /** * @internal Returns the name of the internal language. * The worker of the same-name KLocale API function. */ static QString defaultLanguage(); /** * @internal Convert a known language code to a human readable, localized form. * The worker of the same-name KLocale API function. */ virtual QString languageCodeToName(const QString &language); /** * @deprecated * @internal Returns if nouns are declined in the locale language. * The worker of the same-name KLocale API function. */ virtual bool nounDeclension() const; /*************************** ** Calendar settings ** ***************************/ protected: /** * @internal Converts a CalendarType into a CalendarSystem */ virtual KLocale::CalendarSystem calendarTypeToCalendarSystem(const QString &calendarType) const; /** * @internal Converts a CalendarSystem into a CalendarType */ virtual QString calendarSystemToCalendarType(KLocale::CalendarSystem) const; public: /** * @internal Sets the current calendar system to the calendar specified. * The worker of the same-name KLocale API function. */ virtual void setCalendar(const QString &calendarType); /** * @internal Sets the current calendar system to the calendar specified. * The worker of the same-name KLocale API function. */ virtual void setCalendarSystem(KLocale::CalendarSystem); /** * @internal Returns the name of the calendar system that is currently being used by the system. * The worker of the same-name KLocale API function. */ virtual QString calendarType() const; /** * @internal Returns the type of the calendar system that is currently being used by the system. * The worker of the same-name KLocale API function. */ KLocale::CalendarSystem calendarSystem() const; /** * @internal Returns a pointer to the calendar system object. * The worker of the same-name KLocale API function. */ virtual const KCalendarSystem *calendar(); /** * @internal Sets the Week Number System to use * The worker of the same-name KLocale API function. */ void setWeekNumberSystem(KLocale::WeekNumberSystem weekNumberSystem); /** * @internal Returns the Week Number System used * The worker of the same-name KLocale API function. */ KLocale::WeekNumberSystem weekNumberSystem(); /** * @internal Changes how KLocale defines the first day in week. * The worker of the same-name KLocale API function. */ virtual void setWeekStartDay(int day); /** * @internal Returns which day is the first day of the week. * The worker of the same-name KLocale API function. */ virtual int weekStartDay() const; /** * @internal Changes how KLocale defines the first working day in week. * The worker of the same-name KLocale API function. */ virtual void setWorkingWeekStartDay(int day); /** * @internal Returns which day is the first working day of the week. * The worker of the same-name KLocale API function. */ virtual int workingWeekStartDay() const; /** * @internal Changes how KLocale defines the last working day in week. * The worker of the same-name KLocale API function. */ virtual void setWorkingWeekEndDay(int day); /** * @internal Returns which day is the last working day of the week. * The worker of the same-name KLocale API function. */ virtual int workingWeekEndDay() const; /** * @internal Changes how KLocale defines the day reserved for religious observance. * The worker of the same-name KLocale API function. */ virtual void setWeekDayOfPray(int day); /** * @internal Returns which day is reserved for religious observance * The worker of the same-name KLocale API function. */ virtual int weekDayOfPray() const; /*************************** ** Date/Time settings ** ***************************/ protected: /** * @internal initialises the Day Periods */ virtual void initDayPeriods(const KConfigGroup &cg); public: /** * @internal Sets the current date format. * The worker of the same-name KLocale API function. */ virtual void setDateFormat(const QString &format); /** * @internal Returns the currently selected date format. * The worker of the same-name KLocale API function. */ virtual QString dateFormat() const; /** * @internal Sets the current short date format. * The worker of the same-name KLocale API function. */ virtual void setDateFormatShort(const QString &format); /** * @internal Returns the currently selected short date format. * The worker of the same-name KLocale API function. */ virtual QString dateFormatShort() const; /** * @internal Changes the current time format. * The worker of the same-name KLocale API function. */ virtual void setTimeFormat(const QString &format); /** * @internal Returns the currently selected time format. * The worker of the same-name KLocale API function. */ virtual QString timeFormat() const; /** * @internal Set digit characters used to display dates and time. * The worker of the same-name KLocale API function. */ virtual void setDateTimeDigitSet(KLocale::DigitSet digitSet); /** * @internal Returns the identifier of the digit set used to display dates and time. * The worker of the same-name KLocale API function. */ virtual KLocale::DigitSet dateTimeDigitSet() const; /** * @internal Sets of the possessive form of month name should be used in dates. * The worker of the same-name KLocale API function. */ virtual void setDateMonthNamePossessive(bool possessive); /** * @internal Returns if possessive form of month name should be used * The worker of the same-name KLocale API function. */ virtual bool dateMonthNamePossessive() const; /** * @internal Returns if the user wants 12h clock * The worker of the same-name KLocale API function. */ virtual bool use12Clock() const; /** * @internal * The worker of the same-name KLocale API function. */ virtual void setDayPeriods(const QList &dayPeriods); /** * @internal * The worker of the same-name KLocale API function. */ virtual QList dayPeriods() const; /** * @internal * The worker of the same-name KLocale API function. */ virtual KDayPeriod dayPeriodForTime(const QTime &time) const; /** * @internal Returns a string formatted to the current locale's conventions * The worker of the same-name KLocale API function. */ virtual QString formatDate(const QDate &date, KLocale::DateFormat format = KLocale::LongDate); /** * @internal Converts a localized date string to a QDate. * The worker of the same-name KLocale API function. */ virtual QDate readDate(const QString &str, bool *ok = nullptr); /** * @internal Converts a localized date string to a QDate, using the specified format. * The worker of the same-name KLocale API function. */ virtual QDate readDate(const QString &intstr, const QString &fmt, bool *ok = nullptr); /** * @internal Converts a localized date string to a QDate. * The worker of the same-name KLocale API function. */ virtual QDate readDate(const QString &str, KLocale::ReadDateFlags flags, bool *ok = nullptr); /** * @deprecated replaced by formatLocaleTime() * @internal Returns a string formatted to the current locale's conventions regarding times. * The worker of the same-name KLocale API function. */ virtual QString formatTime(const QTime &pTime, bool includeSecs = false, bool isDuration = false) const; /** * @internal Returns a string formatted to the current locale's conventions regarding times. * The worker of the same-name KLocale API function. */ virtual QString formatLocaleTime(const QTime &pTime, KLocale::TimeFormatOptions options = KLocale::TimeDefault) const; /** * @internal Converts a localized time string to a QTime. * The worker of the same-name KLocale API function. */ virtual QTime readTime(const QString &str, bool *ok = nullptr) const; /** * @deprecated replaced by readLocaleTime() * @internal Converts a localized time string to a QTime. * The worker of the same-name KLocale API function. */ virtual QTime readTime(const QString &str, KLocale::ReadTimeFlags flags, bool *ok = nullptr) const; /** * @internal Converts a localized time string to a QTime. * The worker of the same-name KLocale API function. */ virtual QTime readLocaleTime(const QString &str, bool *ok = nullptr, KLocale::TimeFormatOptions options = KLocale::TimeDefault, KLocale::TimeProcessingOptions processing = KLocale::ProcessNonStrict) const; /** * @internal Formats a date/time according to specified format. * The worker of the same-name KLocale API function. */ static QString formatDateTime(const KLocale *locale, const QDateTime &dateTime, KLocale::DateFormat, bool includeSeconds, int daysToNow, int secsToNow); /** * @internal Return the date and time as a string * The worker of the same-name KLocale API function. */ virtual QString formatDateTime(const QDateTime &dateTime, KLocale::DateFormat format = KLocale::ShortDate, bool includeSecs = false) const; /** * @internal Return the date and time as a string * The worker of the same-name KLocale API function. */ virtual QString formatDateTime(const KDateTime &dateTime, KLocale::DateFormat format = KLocale::ShortDate, KLocale::DateTimeFormatOptions options = nullptr); /** * @internal Returns converted duration as a string * The worker of the same-name KLocale API function. */ virtual QString formatDuration(unsigned long mSec) const; /** * @internal Returns converted duration as a string. * The worker of the same-name KLocale API function. */ virtual QString prettyFormatDuration(unsigned long mSec) const; /*************************** ** Digit Set settings ** ***************************/ protected: /** * @internal Converts a number string in any digit set into Arabic digits */ static QString toArabicDigits(const QString &str); /** * @internal Returns the digits for a digit set as a string, e.g. "0123456789" */ static QString digitSetString(KLocale::DigitSet digitSet); public: /** * @internal Provides list of all known digit set identifiers. * The worker of the same-name KLocale API function. */ virtual QList allDigitSetsList() const; /** * @internal Convert a digit set identifier to a human readable, localized name. * The worker of the same-name KLocale API function. */ virtual QString digitSetToName(KLocale::DigitSet digitSet, bool withDigits = false) const; /** * @internal Convert all digits in the string to the given digit set. * The worker of the same-name KLocale API function. */ virtual QString convertDigits(const QString &str, KLocale::DigitSet digitSet, bool ignoreContext = false) const; /*************************** ** Number settings ** ***************************/ public: /** * @internal Sets the number of decimal places used when formating numbers. * The worker of the same-name KLocale API function. */ virtual void setDecimalPlaces(int digits); /** * @internal Returns the number of numeric decimal places used by locale. * The worker of the same-name KLocale API function. */ virtual int decimalPlaces() const; /** * @internal Sets the symbol used to identify the decimal pointer. * The worker of the same-name KLocale API function. */ virtual void setDecimalSymbol(const QString &symbol); /** * @internal Returns the decimal symbol used by locale. * The worker of the same-name KLocale API function. */ virtual QString decimalSymbol() const; /** * @internal Sets the separator used to group digits when formating numbers. * The worker of the same-name KLocale API function. * KDE5 Rename to setNumericDigitGroupSeparator() */ virtual void setThousandsSeparator(const QString &separator); /** * @internal Returns the digit group separator used by locale. * The worker of the same-name KLocale API function. * KDE5 Rename to numericDigitGroupSeparator() */ virtual QString thousandsSeparator() const; /** * @internal Sets the digit grouping to apply to numbers * For now internal only api designed for processing efficiency, if needed publicly then may * need to review if this is the best way. */ virtual void setNumericDigitGrouping(QList groupList); /** * @internal Returns the digit grouping to apply to numbers * For now internal only api designed for processing efficiency, if needed publicly then may * need to review if this is the best way. */ virtual QList numericDigitGrouping() const; /** * @internal Sets the sign used to identify a positive number. * The worker of the same-name KLocale API function. */ virtual void setPositiveSign(const QString &sign); /** * @internal Returns the positive sign used by locale. * The worker of the same-name KLocale API function. */ virtual QString positiveSign() const; /** * @internal Sets the sign used to identify a negative number. * The worker of the same-name KLocale API function. */ virtual void setNegativeSign(const QString &sign); /** * @internal Returns the negative sign used by locale. * The worker of the same-name KLocale API function. */ virtual QString negativeSign() const; /** * @internal Sets the set of digit characters used to display numbers. * The worker of the same-name KLocale API function. */ virtual void setDigitSet(KLocale::DigitSet digitSet); /** * @internal Returns the identifier of the digit set used to display numbers. * The worker of the same-name KLocale API function. */ virtual KLocale::DigitSet digitSet() const; /** * @internal Returns a number as a localized string * The worker of the same-name KLocale API function. */ virtual QString formatNumber(double num, int precision = -1) const; /** * @internal Returns a number as a localized string * The worker of the same-name KLocale API function. */ virtual QString formatNumber(const QString &numStr, bool round = true, int precision = -1) const; /** * @internal Returns a number as a localized string * The worker of the same-name KLocale API function. */ virtual QString formatLong(long num) const; /** * @internal Converts a localized numeric string to a double. * The worker of the same-name KLocale API function. */ virtual double readNumber(const QString &numStr, bool *ok = nullptr) const; /************************** ** Currency settings ** **************************/ protected: /** * @internal Initialises the Currency */ virtual void initCurrency(); public: /** * @internal Sets the Locale Currency Code * The worker of the same-name KLocale API function. */ virtual void setCurrencyCode(const QString &newCurrencyCode); /** * @internal Returns the Locale ISO Currency Code * The worker of the same-name KLocale API function. */ virtual QString currencyCode() const; /** * @internal Returns the Locale Currency object * The worker of the same-name KLocale API function. */ virtual KCurrencyCode *currency(); /** * @internal Returns the ISO Code of the default currency. * The worker of the same-name KLocale API function. */ static QString defaultCurrencyCode(); /** * @internal Returns the ISO Currency Codes used in the locale * The worker of the same-name KLocale API function. */ virtual QStringList currencyCodeList() const; /*************************** ** Money settings ** ***************************/ public: /** * @internal Sets the current currency symbol. * The worker of the same-name KLocale API function. */ virtual void setCurrencySymbol(const QString &symbol); /** * @internal Returns the default currency symbol used by locale. * The worker of the same-name KLocale API function. */ virtual QString currencySymbol() const; /** * @internal Sets the symbol used to identify the decimal pointer for monetary values. * The worker of the same-name KLocale API function. */ virtual void setMonetaryDecimalSymbol(const QString &symbol); /** * @internal Returns the monetary decimal symbol used by locale. * The worker of the same-name KLocale API function. */ virtual QString monetaryDecimalSymbol() const; /** * @internal Sets the separator used to group digits when formating monetary values. * The worker of the same-name KLocale API function. * KDE5 Rename to setMonetaryDigitGroupSeparator() */ virtual void setMonetaryThousandsSeparator(const QString &separator); /** * @internal Returns the monetary thousands separator used by locale. * The worker of the same-name KLocale API function. * KDE5 Rename to monetaryDigitGroupSeparator() */ virtual QString monetaryThousandsSeparator() const; /** * @internal Sets the digit grouping to apply to numbers * For now internal only api designed for processing efficiency, if needed publicly then may * need to review if this is the best way. */ virtual void setMonetaryDigitGrouping(QList groupList); /** * @internal Returns the digit grouping to apply to numbers * For now internal only api designed for processing efficiency, if needed publicly then may * need to review if this is the best way. */ virtual QList monetaryDigitGrouping() const; /** * @internal Sets the number of decimal places used when formating money. * The worker of the same-name KLocale API function. */ virtual void setMonetaryDecimalPlaces(int digits); /** * @internal Returns the number of monetary decimal places used by locale. * The worker of the same-name KLocale API function. */ virtual int monetaryDecimalPlaces() const; /** * @internal Sets the position where the currency symbol should be printed for * positive monetary values. * The worker of the same-name KLocale API function. */ virtual void setPositivePrefixCurrencySymbol(bool prefix); /** * @internal Returns where to print the currency symbol for positive numbers. * The worker of the same-name KLocale API function. */ virtual bool positivePrefixCurrencySymbol() const; /** * @internal Sets the position where the currency symbol should be printed for * negative monetary values. * The worker of the same-name KLocale API function. */ virtual void setNegativePrefixCurrencySymbol(bool prefix); /** * @internal Returns if the currency symbol precedes negative numbers. * The worker of the same-name KLocale API function. */ virtual bool negativePrefixCurrencySymbol() const; /** * @internal Sets the sign position used for positive monetary values. * The worker of the same-name KLocale API function. */ virtual void setPositiveMonetarySignPosition(KLocale::SignPosition signpos); /** * @internal Returns where/how to print the positive sign. * The worker of the same-name KLocale API function. */ virtual KLocale::SignPosition positiveMonetarySignPosition() const; /** * @internal Sets the sign position used for negative monetary values. * The worker of the same-name KLocale API function. */ virtual void setNegativeMonetarySignPosition(KLocale::SignPosition signpos); /** * @internal Returns where/how to print the negative sign. * The worker of the same-name KLocale API function. */ virtual KLocale::SignPosition negativeMonetarySignPosition() const; /** * @internal Set digit characters used to display monetary values. * The worker of the same-name KLocale API function. */ virtual void setMonetaryDigitSet(KLocale::DigitSet digitSet); /** * @internal Retuns the digit set used to display monetary values. * The worker of the same-name KLocale API function. */ virtual KLocale::DigitSet monetaryDigitSet() const; /** * @internal Returns an amount of money as a localized string * The worker of the same-name KLocale API function. */ virtual QString formatMoney(double num, const QString ¤cy = QString(), int precision = -1) const; /** * @internal Converts a localized monetary string to a double. * The worker of the same-name KLocale API function. */ virtual double readMoney(const QString &numStr, bool *ok = nullptr) const; /*************************** ** Units settings ** ***************************/ protected: /** * @internal * @return list of translated binary unit for @p dialect. */ QList dialectUnitsList(KLocale::BinaryUnitDialect dialect); enum DurationType { DaysDurationType = 0, HoursDurationType, MinutesDurationType, SecondsDurationType }; /** * @internal Formats a duration according to the given type and number */ static QString formatSingleDuration(KLocalePrivate::DurationType durationType, int n); public: /** * @internal Returns the user's default binary unit dialect. * The worker of the same-name KLocale API function. */ virtual KLocale::BinaryUnitDialect binaryUnitDialect() const; /** * @internal Sets the default dialect for this locale * The worker of the same-name KLocale API function. */ virtual void setBinaryUnitDialect(KLocale::BinaryUnitDialect newDialect); /** * @internal Returns converted size as a string * The worker of the same-name KLocale API function. */ virtual QString formatByteSize(double size); /** * @internal Returns converted size as a translated string including the units. * The worker of the same-name KLocale API function. */ virtual QString formatByteSize(double size, int precision, KLocale::BinaryUnitDialect dialect = KLocale::DefaultBinaryDialect, KLocale:: BinarySizeUnits specificUnit = KLocale::DefaultBinaryUnits); /** * @internal Sets the preferred page size when printing. * The worker of the same-name KLocale API function. */ virtual void setPageSize(int paperFormat); /** * @internal Returns the preferred page size for printing. * The worker of the same-name KLocale API function. */ virtual int pageSize() const; /** * @internal Sets the preferred measuring system. * The worker of the same-name KLocale API function. */ virtual void setMeasureSystem(KLocale::MeasureSystem value); /** * @internal Returns which measuring system we use. * The worker of the same-name KLocale API function. */ virtual KLocale::MeasureSystem measureSystem() const; /*************************** ** Encoding settings ** ***************************/ protected: /** * @internal Figures out which encoding the user prefers. */ virtual void initEncoding(); /** * @internal Returns the system codeset. */ virtual QByteArray systemCodeset() const; /** * @internal A QFile filename encoding function (QFile::encodeFn). */ static QByteArray encodeFileNameUTF8(const QString &fileName); /** * @internal QFile filename decoding function (QFile::decodeFn). */ static QString decodeFileNameUTF8(const QByteArray &localFileName); public: /** * @internal Sets the current encoding * The worker of the same-name KLocale API function. */ virtual bool setEncoding(int mibEnum); /** * @internal Returns the user's preferred encoding. * The worker of the same-name KLocale API function. */ virtual const QByteArray encoding(); /** * @internal Returns the user's preferred encoding. * The worker of the same-name KLocale API function. */ virtual int encodingMib() const; /** * @internal Returns the file encoding. * The worker of the same-name KLocale API function. */ virtual int fileEncodingMib() const; /** * @internal Returns the user's preferred encoding. * The worker of the same-name KLocale API function. */ virtual QTextCodec *codecForEncoding() const; /*************************** ** Utilities ** ***************************/ public: /** * @internal Parses locale string into distinct parts. * The worker of the same-name KLocale API function. */ static void splitLocale(const QString &locale, QString &language, QString &country, QString &modifier, QString &charset); private: /** * @internal COnvert digit group format string to digit group list */ QList digitGroupFormatToList(const QString &digitGroupFormat) const; /** * @internal Insert digit group separator */ QString formatDigitGroup(const QString &number, const QString &groupSeparator, const QString &decimalSeperator, QList groupList) const; /** * @internal Remove digit group separator, return ok if valid format */ QString parseDigitGroup(const QString &number, const QString &groupSeparator, const QString &decimalSeperator, QList groupList, bool *ok) const; public: // Parent KLocale, public needed for copy ctor KLocale *q; private: // Config file containing locale config KSharedConfig::Ptr m_config; // Country settings QString m_country; QString m_countryDivisionCode; // Language settings QString m_language; KConfig *m_languages; QStringList m_languageList; bool m_languageSensitiveDigits; // FIXME: Temporary until full language-sensitivity implemented. bool m_nounDeclension; // Calendar settings KLocale::CalendarSystem m_calendarSystem; KCalendarSystem *m_calendar; KLocale::WeekNumberSystem m_weekNumberSystem; int m_weekStartDay; int m_workingWeekStartDay; int m_workingWeekEndDay; int m_weekDayOfPray; // Date/Time settings QString m_dateFormat; QString m_dateFormatShort; QString m_timeFormat; KLocale::DigitSet m_dateTimeDigitSet; bool m_dateMonthNamePossessive; mutable QList m_dayPeriods; // Number settings int m_decimalPlaces; QString m_decimalSymbol; QString m_thousandsSeparator; QList m_numericDigitGrouping; QString m_positiveSign; QString m_negativeSign; KLocale::DigitSet m_digitSet; // Currency settings QString m_currencyCode; KCurrencyCode *m_currency; QStringList m_currencyCodeList; // Money settings QString m_currencySymbol; QString m_monetaryDecimalSymbol; QString m_monetaryThousandsSeparator; QList m_monetaryDigitGrouping; int m_monetaryDecimalPlaces; KLocale::SignPosition m_positiveMonetarySignPosition; KLocale::SignPosition m_negativeMonetarySignPosition; bool m_positivePrefixCurrencySymbol; bool m_negativePrefixCurrencySymbol; KLocale::DigitSet m_monetaryDigitSet; // Units settings KLocale::BinaryUnitDialect m_binaryUnitDialect; QList m_byteSizeFmt; int m_pageSize; KLocale::MeasureSystem m_measureSystem; // Encoding settings QString m_encoding; QTextCodec *m_codecForEncoding; bool m_utf8FileEncoding; }; #endif /* KLOCALE_P_H */ diff --git a/src/kdecore/klocalizeddate.cpp b/src/kdecore/klocalizeddate.cpp index 86151a82..35f75820 100644 --- a/src/kdecore/klocalizeddate.cpp +++ b/src/kdecore/klocalizeddate.cpp @@ -1,618 +1,618 @@ /* Copyright 2010 John Layt 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. */ #include "klocalizeddate.h" #include "kcalendarsystem.h" #include #include /***************************************************************************** * * Private Section * *****************************************************************************/ class KLocalizedDatePrivate : public QSharedData { public: - explicit KLocalizedDatePrivate(const QDate &date, const KCalendarSystem *calendar, bool manageCalendar); + KDELIBS4SUPPORT_DEPRECATED explicit KLocalizedDatePrivate(const QDate &date, const KCalendarSystem *calendar, bool manageCalendar); KLocalizedDatePrivate(const KLocalizedDatePrivate &rhs); KLocalizedDatePrivate &operator=(const KLocalizedDatePrivate &rhs); virtual ~KLocalizedDatePrivate(); QDate m_date; const KCalendarSystem *m_calendar; bool m_manageCalendar; }; KLocalizedDatePrivate::KLocalizedDatePrivate(const QDate &date, const KCalendarSystem *calendar, bool manageCalendar) : QSharedData(), m_date(date), m_calendar(calendar), m_manageCalendar(manageCalendar) { } KLocalizedDatePrivate::KLocalizedDatePrivate(const KLocalizedDatePrivate &rhs) : QSharedData(rhs), m_date(rhs.m_date), m_calendar(rhs.m_calendar), m_manageCalendar(rhs.m_manageCalendar) { // If we're managing the calendar object, then take a copy, // i.e. user called setCalendarSystem() rather than passing a custom one into the constructor if (m_manageCalendar) { m_calendar = KCalendarSystem::create(m_calendar->calendarSystem(), new KLocale(*m_calendar->locale())); } } KLocalizedDatePrivate &KLocalizedDatePrivate::operator=(const KLocalizedDatePrivate &rhs) { m_date = rhs.m_date; m_calendar = rhs.m_calendar; m_manageCalendar = rhs.m_manageCalendar; // If we're managing the calendar object, then take a copy, // i.e. user called setCalendarSystem() rather than passing a custom one into the constructor if (rhs.m_manageCalendar) { m_calendar = KCalendarSystem::create(m_calendar->calendarSystem(), new KLocale(*m_calendar->locale())); } return *this; } KLocalizedDatePrivate::~KLocalizedDatePrivate() { // If we're managing the calendar object, then delete it, // i.e. user called setCalendarSystem() rather than passing a custom one into the constructor if (m_manageCalendar) { delete m_calendar; } } /***************************************************************************** * * Date Creation Section * *****************************************************************************/ KLocalizedDate::KLocalizedDate(const QDate &date, const KCalendarSystem *calendarSystem) : d(new KLocalizedDatePrivate(date, calendarSystem, false)) { } KLocalizedDate::KLocalizedDate(int year, int month, int day, const KCalendarSystem *calendarSystem) : d(new KLocalizedDatePrivate(QDate(), calendarSystem, false)) { setDate(year, month, day); } KLocalizedDate::KLocalizedDate(const KLocalizedDate &rhs) : d(new KLocalizedDatePrivate(*rhs.d)) { } KLocalizedDate &KLocalizedDate::operator=(const KLocalizedDate &rhs) { *d = *rhs.d; return *this; } KLocalizedDate &KLocalizedDate::operator=(const QDate &rhs) { d->m_date = rhs; return *this; } KLocalizedDate::~KLocalizedDate() { } /***************************************************************************** * * Calendar System Section * *****************************************************************************/ void KLocalizedDate::setCalendarSystem(KLocale::CalendarSystem calendarSystem) { if (calendarSystem == calendar()->calendarSystem()) { return; } KCalendarSystem *newCalendar = KCalendarSystem::create(calendarSystem, new KLocale(*calendar()->locale())); if (d->m_manageCalendar) { delete d->m_calendar; } d->m_calendar = newCalendar; } KLocale::CalendarSystem KLocalizedDate::calendarSystem() { return calendar()->calendarSystem(); } const KCalendarSystem *KLocalizedDate::calendar() const { if (d->m_calendar) { return d->m_calendar; } return KLocale::global()->calendar(); } /***************************************************************************** * * Date Status Section * *****************************************************************************/ bool KLocalizedDate::isNull() const { return date().isNull(); } bool KLocalizedDate::isValid() const { return calendar()->isValid(date()); } /***************************************************************************** * * Date Setting Section * *****************************************************************************/ bool KLocalizedDate::setDate(const QDate &date) { d->m_date = date; return isValid(); } bool KLocalizedDate::setDate(int year, int month, int day) { calendar()->setDate(d->m_date, year, month, day); return isValid(); } bool KLocalizedDate::setDate(int year, int dayOfYear) { calendar()->setDate(d->m_date, year, dayOfYear); return isValid(); } bool KLocalizedDate::setDate(QString eraName, int yearInEra, int month, int day) { calendar()->setDate(d->m_date, eraName, yearInEra, month, day); return isValid(); } bool KLocalizedDate::setDate(KLocale::WeekNumberSystem weekNumberSystem, int year, int isoWeekNumber, int dayOfIsoWeek) { Q_UNUSED(weekNumberSystem); // Only support ISO Week at the moment calendar()->setDateIsoWeek(d->m_date, year, isoWeekNumber, dayOfIsoWeek); return isValid(); } bool KLocalizedDate::setCurrentDate() { d->m_date = QDate::currentDate(); return isValid(); } /***************************************************************************** * * Static Date Creation Section * *****************************************************************************/ KLocalizedDate KLocalizedDate::currentDate() { return KLocalizedDate(QDate::currentDate()); } KLocalizedDate KLocalizedDate::fromDate(const QDate &date) { return KLocalizedDate(date); } KLocalizedDate KLocalizedDate::fromJulianDay(int jd) { return KLocalizedDate(QDate::fromJulianDay(jd)); } /***************************************************************************** * * Date Componant Section * *****************************************************************************/ int KLocalizedDate::toJulianDay() const { return d->m_date.toJulianDay(); } QDate KLocalizedDate::date() const { return d->m_date; } void KLocalizedDate::getDate(int *year, int *month, int *day) const { calendar()->getDate(date(), year, month, day); } int KLocalizedDate::year() const { return calendar()->year(date()); } int KLocalizedDate::month() const { return calendar()->month(date()); } int KLocalizedDate::day() const { return calendar()->day(date()); } QString KLocalizedDate::eraName() const { return formatDate(KLocale::EraName); } QString KLocalizedDate::eraYear() const { return formatDate(KLocale::EraYear); } int KLocalizedDate::yearInEra() const { return calendar()->yearInEra(date()); } int KLocalizedDate::dayOfYear() const { return calendar()->dayOfYear(date()); } int KLocalizedDate::dayOfWeek() const { return calendar()->dayOfWeek(date()); } int KLocalizedDate::week(int *yearNum) const { return calendar()->week(date(), yearNum); } int KLocalizedDate::week(KLocale::WeekNumberSystem weekNumberSystem, int *yearNum) const { return calendar()->week(date(), weekNumberSystem, yearNum); } int KLocalizedDate::monthsInYear() const { return calendar()->monthsInYear(date()); } int KLocalizedDate::weeksInYear() const { return calendar()->weeksInYear(date()); } int KLocalizedDate::weeksInYear(KLocale::WeekNumberSystem weekNumberSystem) const { return calendar()->weeksInYear(date(), weekNumberSystem); } int KLocalizedDate::daysInYear() const { return calendar()->daysInYear(date()); } int KLocalizedDate::daysInMonth() const { return calendar()->daysInMonth(date()); } int KLocalizedDate::daysInWeek() const { return calendar()->daysInWeek(date()); } bool KLocalizedDate::isLeapYear() const { return calendar()->isLeapYear(date()); } /***************************************************************************** * * Date Formatting Section * *****************************************************************************/ QString KLocalizedDate::formatDate(KLocale::DateFormat toFormat) const { return calendar()->formatDate(date(), toFormat); } QString KLocalizedDate::formatDate(const QString &toFormat, KLocale::DateTimeFormatStandard formatStandard) const { return calendar()->formatDate(date(), toFormat, formatStandard); } QString KLocalizedDate::formatDate(KLocale::DateTimeComponent component, KLocale::DateTimeComponentFormat format, KLocale::WeekNumberSystem weekNumberSystem) const { return calendar()->formatDate(date(), component, format, weekNumberSystem); } /***************************************************************************** * * Date Parsing Section * *****************************************************************************/ KLocalizedDate KLocalizedDate::readDate(const QString &dateString, KLocale::DateTimeParseMode parseMode, const KCalendarSystem *calendar) { Q_UNUSED(parseMode); if (!calendar) { calendar = KLocale::global()->calendar(); } return KLocalizedDate(calendar->readDate(dateString)); } KLocalizedDate KLocalizedDate::readDate(const QString &dateString, KLocale::ReadDateFlags formatFlags, KLocale::DateTimeParseMode parseMode, const KCalendarSystem *calendar) { Q_UNUSED(parseMode); if (!calendar) { calendar = KLocale::global()->calendar(); } return KLocalizedDate(calendar->readDate(dateString, formatFlags)); } KLocalizedDate KLocalizedDate::readDate(const QString &dateString, const QString &dateFormat, KLocale::DateTimeParseMode parseMode, KLocale::DateTimeFormatStandard formatStandard, const KCalendarSystem *calendar) { Q_UNUSED(parseMode); if (!calendar) { calendar = KLocale::global()->calendar(); } return KLocalizedDate(calendar->readDate(dateString, dateFormat, nullptr, formatStandard)); } /***************************************************************************** * * Date Maths Section * *****************************************************************************/ KLocalizedDate KLocalizedDate::addYears(int years) const { KLocalizedDate newDate; newDate = *this; newDate.setDate(calendar()->addYears(date(), years)); return newDate; } bool KLocalizedDate::addYearsTo(int years) { d->m_date = calendar()->addYears(date(), years); return isValid(); } KLocalizedDate KLocalizedDate::addMonths(int months) const { KLocalizedDate newDate(*this); newDate.setDate(calendar()->addMonths(date(), months)); return newDate; } bool KLocalizedDate::addMonthsTo(int months) { d->m_date = calendar()->addMonths(date(), months); return isValid(); } KLocalizedDate KLocalizedDate::addDays(int days) const { KLocalizedDate newDate(*this); newDate.setDate(calendar()->addDays(date(), days)); return newDate; } bool KLocalizedDate::addDaysTo(int days) { d->m_date = calendar()->addDays(date(), days); return isValid(); } void KLocalizedDate::dateDifference(const KLocalizedDate &toDate, int *yearsDiff, int *monthsDiff, int *daysDiff, int *direction) const { dateDifference(toDate.date(), yearsDiff, monthsDiff, daysDiff, direction); } void KLocalizedDate::dateDifference(const QDate &toDate, int *yearsDiff, int *monthsDiff, int *daysDiff, int *direction) const { calendar()->dateDifference(date(), toDate, yearsDiff, monthsDiff, daysDiff, direction); } int KLocalizedDate::yearsDifference(const KLocalizedDate &toDate) const { return yearsDifference(toDate.date()); } int KLocalizedDate::yearsDifference(const QDate &toDate) const { return calendar()->yearsDifference(date(), toDate); } int KLocalizedDate::monthsDifference(const KLocalizedDate &toDate) const { return monthsDifference(toDate.date()); } int KLocalizedDate::monthsDifference(const QDate &toDate) const { return calendar()->monthsDifference(date(), toDate); } int KLocalizedDate::daysDifference(const KLocalizedDate &toDate) const { return daysDifference(toDate.date()); } int KLocalizedDate::daysDifference(const QDate &toDate) const { return calendar()->daysDifference(date(), toDate); } KLocalizedDate KLocalizedDate::firstDayOfYear() const { KLocalizedDate newDate(*this); newDate.setDate(calendar()->firstDayOfYear(date())); return newDate; } KLocalizedDate KLocalizedDate::lastDayOfYear() const { KLocalizedDate newDate(*this); newDate.setDate(calendar()->lastDayOfYear(date())); return newDate; } KLocalizedDate KLocalizedDate::firstDayOfMonth() const { KLocalizedDate newDate(*this); newDate.setDate(calendar()->firstDayOfMonth(date())); return newDate; } KLocalizedDate KLocalizedDate::lastDayOfMonth() const { KLocalizedDate newDate(*this); newDate.setDate(calendar()->lastDayOfMonth(date())); return newDate; } /***************************************************************************** * * Date Operators Section * *****************************************************************************/ bool KLocalizedDate::operator==(const KLocalizedDate &rhs) const { return (date() == rhs.date()); } bool KLocalizedDate::operator==(const QDate &rhs) const { return (date() == rhs); } bool KLocalizedDate::operator!=(const KLocalizedDate &rhs) const { return (date() != rhs.date()); } bool KLocalizedDate::operator!=(const QDate &rhs) const { return (date() != rhs); } bool KLocalizedDate::operator<(const KLocalizedDate &rhs) const { return (date() < rhs.date()); } bool KLocalizedDate::operator<(const QDate &rhs) const { return (date() < rhs); } bool KLocalizedDate::operator<=(const KLocalizedDate &rhs) const { return (d->m_date <= rhs.date()); } bool KLocalizedDate::operator<=(const QDate &rhs) const { return (date() <= rhs); } bool KLocalizedDate::operator>(const KLocalizedDate &rhs) const { return (date() > rhs.date()); } bool KLocalizedDate::operator>(const QDate &rhs) const { return (date() > rhs); } bool KLocalizedDate::operator>=(const KLocalizedDate &rhs) const { return (date() >= rhs.date()); } bool KLocalizedDate::operator>=(const QDate &rhs) const { return (date() >= rhs); } QDataStream &operator<<(QDataStream &out, const KLocalizedDate &date) { return out << (quint32)(date.toJulianDay()) << date.calendar()->calendarSystem(); } QDataStream &operator>>(QDataStream &in, KLocalizedDate &date) { quint32 jd; int calendarSystem; in >> jd >> calendarSystem; date.setDate(QDate::fromJulianDay(jd)); date.setCalendarSystem((KLocale::CalendarSystem)calendarSystem); return in; } QDebug operator<<(QDebug dbg, const KLocalizedDate &date) { if (date.calendar()->calendarSystem() == KLocale::QDateCalendar) { dbg.nospace() << "KLocalizedDate(" << date.formatDate(KLocale::IsoDate) << ", " << date.calendar()->calendarLabel() << ')'; } else { dbg.nospace() << "KLocalizedDate(" << date.formatDate(KLocale::IsoDate) << ", " << date.calendar()->calendarLabel() << ')' << " = QDate(" << date.date().toString(Qt::ISODate) << ')'; } return dbg.space(); } diff --git a/src/kdecore/klocalizeddate.h b/src/kdecore/klocalizeddate.h index bc2332d6..a60f8125 100644 --- a/src/kdecore/klocalizeddate.h +++ b/src/kdecore/klocalizeddate.h @@ -1,1188 +1,1188 @@ /* Copyright 2010 John Layt 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 KLOCALIZEDDATE_H #define KLOCALIZEDDATE_H #include #include #include #include "klocale.h" class KLocalizedDatePrivate; /** * @short A class representing a date localized using the local calendar system, language and formats * * Topics: * - @ref intro * - @ref calsys * - @ref custom * - @ref formatting * - @ref maths * * @section intro Introduction * * This class provides a simple and convenient way to localize dates * * @section calsys Calendar System * * KDE supports the use of different calendar systems. * * @section custom Default and Custom Locale and Calendar System * * In most cases you will want to use the default Global Locale and Calendar * System, in which case you need only create a default KLocalizedDate. If * however you specifically need a different Calendar System or Locale settings * then you need to take some extra steps. * * The simplest method is just changing the Calendar System while keeping the * current Locale settings. This is easily done using setCalendarSystem() * which will copy the current Locale being used and apply this to the new * Calendar System. Note this means any changes to the old locale settings, * either the Global Locale or a custom Locale (see below) will not apply * to that date instance. * * You may however wish to use a custom Locale with the Calendar System. * For example, if you want your app to normally show dates using the Global * Locale and Calendar System, but wish to show an info box with the Islamic * date in Arabic language and format, then you need a custom Locale to do * this. * * \code * KLocale *myLocale = new KLocale("myapp", "ar", "eg"); * KCalendarSystem *myCalendar = KCalendarSystem::create(KLocale::IslamicCivilCalendar, myLocale); * KLocalizedDate myDate(QDate(2010,1,1), myCalendar); * \endcode * * In this case you are responsible for the memory management of the KLocale * and KCalendarSystem. This allows you to reuse this calendar across multiple * date instances without it being deleted under you. It also allows you to * change any setting in the Locale and have it apply across all those date * instances. @warning Don't try changing the Calendar System via your Locale * instance, your KCalendarSystem instance will be deleted and all the dates * will be invalid! * * @see * * @section formatting Date Formatting * * When you display dates or date components to users in a GUI, they will * expect them to be displayed in their language and digit set following their * local date formatting conventions. Directly displaying values returned by * the normal date component methods such as day() will not conform to these * expectations, so you need to use different methods to obtain the localized * string form of the date or component. * * You can either format the entire date, or just a single component of the * date such as the month or day. * * When formatting a full date, it is preferred to use one of the standard date * formats defined in the Locale, although you can provide your own format in * either the KDE, POSIX, or UNICODE standards. * * @see formatDate() formatDate() * * @section parsing Date Parsing * * Basic concepts on date parsing, then full details on KLocale::ReadDateFlags * formats, definging your own date format strings, and setting how strictly * the format is appplied. * * You can choose how strictly a date format is applied in parsing. Currently * only liberal Parsing is supported. * * The KLocale::LiberalParsing mode applies the following rules: * * 1) You must supply a format and string containing at least one of the following combinations to * create a valid date: * @li a month and day of month * @li a day of year * @li a ISO week number and day of week * * 2) If a year number is not supplied then the current year will be assumed. * * 3) All date components must be separated by a non-numeric character. * * 4) The format is not applied strictly to the input string: * @li extra whitespace is ignored * @li leading 0's on numbers are ignored * @li capitalisation of literals is ignored * * @see readDate() * * @section maths Date Maths * * A full set of date maths functions are provided which operate in a consistent * manner, i.e. you can safely round-trip. * */ class KDELIBS4SUPPORT_EXPORT KLocalizedDate { public: /** * Constructs a localized date with the given date. * * By default, uses the global Calendar System and Locale. * * If you pass in a custom Calendar System then you retain ownership of it * and are responsible for deleting it. This allows you to reuse the same * custom Calendar System for many localized date instances. * * See @ref custom for more details on using custom Calendar Systems. * * @param date the QDate to set the KLocalizedDate to, defaults to invalid date * @param calendar the calendar system to use, defaults to the global */ - explicit KLocalizedDate(const QDate &date = QDate(), const KCalendarSystem *calendar = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KLocalizedDate(const QDate &date = QDate(), const KCalendarSystem *calendar = nullptr); /** * Constructs a localized date with the given year, month and day. * * By default, uses the global Calendar System and Locale. * * If you pass in a custom Calendar System then you retain ownership of it * and are responsible for deleting it. This allows you to reuse the same * custom Calendar System for many localized date instances. * * See @ref custom for more details on using custom Calendar Systems. * * @param year the year to set the KLocalizedDate to * @param month the month to set the KLocalizedDate to * @param day the day to set the KLocalizedDate to * @param calendar the calendar system to use, defaults to the global */ KLocalizedDate(int year, int month, int day, const KCalendarSystem *calendar = nullptr); /** * Copy constructor * * @param rhs the date to copy */ KLocalizedDate(const KLocalizedDate &rhs); /** * Assignment operator * * @param rhs the date to assign */ KLocalizedDate &operator=(const KLocalizedDate &rhs); /** * Assignment operator * * @param rhs the date to assign */ KLocalizedDate &operator=(const QDate &rhs); /** * Destructor. */ ~KLocalizedDate(); /** * Set the Calendar System used for this date instance only. * * This method is mostly useful for when you quickly want to see what the * currently set date would look like in a different Calendar System but * using the same Locale. * * When the Calendar System is changed, a copy will be taken of the Locale * previously used and this copy will be applied to the new Calendar System. * Any changes to the old Locale settings, either the Global or a Custom * Locale, will not be applied to this date instance. * * See @ref custom for more details on using custom Calendar Systems. * * @see KLocale::CalendarSystem * @see calendarSystem() * @param calendarSystem the Calendar System to use */ void setCalendarSystem(KLocale::CalendarSystem calendarSystem); /** * Returns the Calendar System used by this localized date instance * * @see KLocale::CalendarSystem * @see setCalendarSystem() * @return the Calendar System currently used */ KLocale::CalendarSystem calendarSystem(); /** * Returns a pointer to the Calendar System object used by this date instance. * * Usually this will be the Global Calendar System, but this may have been * changed. * * Normally you will not need to access this object unless the KLocalizedDate * API does not provide the methods you require. * * @see KCalendarSystem * @see calendarSystem * @see setCalendarSystem * @return the current calendar system instance */ const KCalendarSystem *calendar() const; /** * Returns whether the date is null, i.e. invalid in any Calendar System. * * @see isValid * @return @c true if the date is null, @c false otherwise */ bool isNull() const; /** * Returns whether the date is valid in the current Calendar System. * * @see isNull * @return @c true if the date is valid, @c false otherwise */ bool isValid() const; /** * Set the date using a QDate. * * @param date the QDate to set to * @return @c true if the date is valid, @c false otherwise */ bool setDate(const QDate &date); /** * Set the date's year, month and day. * * The range of the year, month and day, and the validity of the date as a * whole depends on which Calendar System is being used. * * @see getDate() * @param year year number * @param month month of year number * @param day day of month * @return @c true if the date is valid, @c false otherwise */ bool setDate(int year, int month, int day); /** * Set the date using the year number and day of year number only. * * @see dayOfYear() * @param year year * @param dayOfYear day of year * @return @c true if the date is valid, @c false otherwise */ bool setDate(int year, int dayOfYear); /** * Set the date using the era, year in era number, month and day * * @see eraName() * @see yearInEra() * @param eraName Era string * @param yearInEra Year In Era number * @param month Month number * @param day Day Of Month number * @return @c true if the date is valid, @c false otherwise */ bool setDate(QString eraName, int yearInEra, int month, int day); /** * Set the date using the year, week and day of week. * * Currently only the ISO Week Number System is supported. * * @see week() * @see dayOfWeek() * @param weekNumberSystem the week number system to use * @param year year * @param weekOfYear week of year * @param dayOfWeek day of week Mon..Sun (1..7) * @return @c true if the date is valid, @c false otherwise */ bool setDate(KLocale::WeekNumberSystem weekNumberSystem, int year, int weekOfYear, int dayOfWeek); /** * Set the date to today's date * * @see currentDate() * @return @c true if the date is valid, @c false otherwise */ bool setCurrentDate(); /** * Returns a KLocalizedDate set to today's date in the Global Locale and * Calendar System. * * @see setCurrentDate() * @return today's localized date */ static KLocalizedDate currentDate(); /** * Returns a KLocalizedDate set the required date in the Global Locale and * Calendar System. * * @param date the date to set to * @return a localized date */ static KLocalizedDate fromDate(const QDate &date); /** * Returns a KLocalizedDate set the required Julian Day number in the Global * Locale and Calendar System. * * @see toJulianDay() * @param jd the Julian Day number to set to * @return a localized date */ static KLocalizedDate fromJulianDay(int jd); /** * Returns the currently set date as a Julian Day number * * @see fromJulianDay() * @return the currently set date as a Julian Day number */ int toJulianDay() const; /** * Returns the currently set date as a QDate * * @return the currently set date as a QDate */ QDate date() const; /** * Returns the year, month and day portion of the date in the current * Calendar System. * * See @ref formatting for why you should never display this value. * * @see setDate() * @see formatDate() * @param year year number returned in this variable * @param month month number returned in this variable * @param day day of month returned in this variable */ void getDate(int *year, int *month, int *day) const; /** * Returns the year portion of the date in the current calendar system * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return the localized year number */ int year() const; /** * Returns the month portion of the date in the current calendar system * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return the localized month number, 0 if date is invalid */ int month() const; /** * Returns the day portion of the date in the current calendar system * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return the localized day number, 0 if date is invalid */ int day() const; /** * Returns the Era Name portion of the date in the current calendar system, * for example "AD" or "Anno Domini" for the Gregorian calendar and Christian Era. * * See @ref formatting for more details on Date Formatting. * * @see formatDate() * @return the localized era name, empty string if date is invalid */ QString eraName() const; /** * Returns the Era Year portion of the date in the current * calendar system, for example "2000 AD" or "Heisei 22". * * See @ref formatting for more details on Date Formatting. * * @see formatDate() * @return the localized era year string, empty string if date is invalid */ QString eraYear() const; /** * Returns the Year In Era portion of the date in the current calendar * system, for example 1 for "1 BC". * * See @ref formatting for why you should never display this value. * * @see formatDate() * @see formatYearInEra() * @return the localized Year In Era number, -1 if date is invalid */ int yearInEra() const; /** * Returns the day number of year for the date * * The days are numbered 1..daysInYear() * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return day of year number, -1 if date not valid */ int dayOfYear() const; /** * Returns the weekday number for the date * * The weekdays are numbered 1..7 for Monday..Sunday. * * This value is @em not affected by the value of KLocale::weekStartDay() * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return day of week number, -1 if date not valid */ int dayOfWeek() const; /** * Returns the localized Week Number for the date. * * See @ref formatting for why you should never display this value. * * This may be ISO, US, or any other supported week numbering scheme. If * you specifically require the ISO Week or any other scheme, you should use * the week(KLocale::WeekNumberSystem) form. * * If the date falls in the last week of the previous year or the first * week of the following year, then the yearNum returned will be set to the * appropriate year. * * @see weeksInYear() * @see formatDate() * @param yearNum returns the year the date belongs to * @return localized week number, -1 if input date invalid */ int week(int *yearNum = nullptr) const; /** * Returns the Week Number for the date in the required Week Number System. * * See @ref formatting for why you should never display this value. * * Unless you want a specific Week Number System (e.g. ISO Week), you should * use the localized Week Number form of week(). * * If the date falls in the last week of the previous year or the first * week of the following year, then the yearNum returned will be set to the * appropriate year. * * Technically, the ISO Week Number only applies to the ISO/Gregorian Calendar * System, but the same rules will be applied to the current Calendar System. * * @see weeksInYear() * @see formatDate() * @param weekNumberSystem the Week Number System to use * @param yearNum returns the year the date belongs to * @return week number, -1 if input date invalid */ int week(KLocale::WeekNumberSystem weekNumberSystem, int *yearNum = nullptr) const; /** * Returns number of months in the year * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return number of months in the year, -1 if date invalid */ int monthsInYear() const; /** * Returns the number of localized weeks in the currently set year. * * See @ref formatting for why you should never display this value. * * If you specifically require the number of ISO Weeks, you should use * weeksInYear(KLocale::IsoWeekNumber) * * @see week() * @see formatDate() * @return number of weeks in the year, -1 if date invalid */ int weeksInYear() const; /** * Returns the number of Weeks in the currently set year using the required * Week Number System. * * See @ref formatting for why you should never display this value. * * Unless you specifically want a particular Week Number System (e.g. ISO Weeks) * you should use the localized number of weeks provided by weeksInYear(). * * @see week() * @see formatDate() * @param weekNumberSystem the week number system to use * @return number of weeks in the year, -1 if date invalid */ int weeksInYear(KLocale::WeekNumberSystem weekNumberSystem) const; /** * Returns the number of days in the year. * * For example, in the Gregorian calendar most years have 365 days but Leap * Years have 366 years. Other Calendar Systems have different length years. * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return number of days in year, -1 if date invalid */ int daysInYear() const; /** * Returns the number of days in the month. * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return number of days in month, -1 if date invalid */ int daysInMonth() const; /** * Returns the number of days in the week. * * See @ref formatting for why you should never display this value. * * @see formatDate() * @return number of days in week, -1 if date invalid */ int daysInWeek() const; /** * Returns whether the currently set date falls in a Leap Year in the * current Calendar System. * * @return true if the date falls in a leap year */ bool isLeapYear() const; /** * Returns the Date as a localized string in the requested standard Locale * format. * * See @ref formatting for more details on Date Formatting and valid Locale * formats. * * @see formatDate() * @param dateFormat the standard date format to use * @return The date as a localized string */ QString formatDate(KLocale::DateFormat dateFormat = KLocale::LongDate) const; /** * Returns the Date as a localized string in the requested format. * * See @ref formatting for more details on Date Formatting and valid format * codes. * * Please use with care and only in situations where the standard Locale * formats or the component format methods do not provide what you * need. You should almost always translate your @p formatString as * documented above. Using the standard DateFormat options instead would * take care of the translation for you. * * The toFormat parameter is a good candidate to be made translatable, * so that translators can adapt it to their language's convention. * There should also be a context using the "kdedt-format" keyword (for * automatic validation of translations) and stating the format's purpose: * \code * QDate reportDate; * KLocale::global()->calendar()->setDate(reportDate, reportYear, reportMonth, 1); * dateFormat = i18nc("(kdedt-format) Report month and year in report header", "%B %Y")); * dateString = KLocale::global()->calendar()->formatDate(reportDate, dateFormat); * \endcode * * The date format string can be defined using either the KDE, POSIX or the Qt * subset of the UNICODE standards. * * The KDE standard closely follows the POSIX standard but with some exceptions. * Always use the KDE standard within KDE, but where interaction is required with * external POSIX compliant systems (e.g. Gnome, glibc, etc) the POSIX standard * should be used. The UNICODE standard is provided for comaptability with QDate * and so is not yet the full standard, only what Qt currently supports. * * Date format strings are made up of date components and string literals. * Date components are prefixed by a % escape character and are made up of * optional padding and case modifier flags, an optional width value, and a * compulsary code for the actual date component: * %[Flags][Width][Componant] * e.g. %_^5Y * No spaces are allowed. * * The Flags can modify the padding character and/or case of the Date Componant. * The Flags are optional and may be combined and/or repeated in any order, * in which case the last Padding Flag and last Case Flag will be the * ones used. The Flags must be immediately after the % and before any Width. * * The Width can modify how wide the date Componant is padded to. The Width * is an optional interger value and must be after any Flags but before the * Componant. If the Width is less than the minimum defined for a Componant * then the default minimum will be used instead. * * By default most numeric Date Componants are right-aligned with leading 0's. * * By default all string name fields are capital case and unpadded. * * The following Flags may be specified: * @li - (hyphen) no padding (e.g. 1 Jan and "%-j" = "1") * @li _ (underscore) pad with spaces (e.g. 1 Jan and "%-j" = " 1") * @li 0 (zero) pad with 0's (e.g. 1 Jan and "%0j" = "001") * @li ^ (caret) make uppercase (e.g. 1 Jan and "%^B" = "JANUARY") * @li # (hash) invert case (e.g. 1 Jan and "%#B" = "???") * * The following Date Componants can be specified: * @li %Y the year to 4 digits (e.g. "1984" for 1984, "0584" for 584, "0084" for 84) * @li %C the 'century' portion of the year to 2 digits (e.g. "19" for 1984, "05" for 584, "00" for 84) * @li %y the lower 2 digits of the year to 2 digits (e.g. "84" for 1984, "05" for 2005) * @li %EY the full local era year (e.g. "2000 AD") * @li %EC the era name short form (e.g. "AD") * @li %Ey the year in era to 1 digit (e.g. 1 or 2000) * @li %m the month number to 2 digits (January="01", December="12") * @li %n the month number to 1 digit (January="1", December="12"), see notes! * @li %d the day number of the month to 2 digits (e.g. "01" on the first of March) * @li %e the day number of the month to 1 digit (e.g. "1" on the first of March) * @li %B the month name long form (e.g. "January") * @li %b the month name short form (e.g. "Jan" for January) * @li %h the month name short form (e.g. "Jan" for January) * @li %A the weekday name long form (e.g. "Wednesday" for Wednesday) * @li %a the weekday name short form (e.g. "Wed" for Wednesday) * @li %j the day of the year number to 3 digits (e.g. "001" for 1 Jan) * @li %V the ISO week of the year number to 2 digits (e.g. "01" for ISO Week 1) * @li %G the year number in long form of the ISO week of the year to 4 digits (e.g. "2004" for 1 Jan 2005) * @li %g the year number in short form of the ISO week of the year to 2 digits (e.g. "04" for 1 Jan 2005) * @li %u the day of the week number to 1 digit (e.g. "1" for Monday) * @li %D the US short date format (e.g. "%m/%d/%y") * @li %F the ISO short date format (e.g. "%Y-%m-%d") * @li %x the KDE locale short date format * @li %% the literal "%" * @li %t a tab character * * Everything else in the format string will be taken as literal text. * * Examples: * "%Y-%m-%d" = "2009-01-01" * "%Y-%-m-%_4d" = "2009-1- 1" * * The following format codes behave differently in the KDE and POSIX standards * @li %e in GNU/POSIX is space padded to 2 digits, in KDE is not padded * @li %n in GNU/POSIX is newline, in KDE is short month number * * The following POSIX format codes are currently not supported: * @li %U US week number * @li %w US day of week * @li %W US week number * @li %O locale's alternative numeric symbols, in KDE is not supported * * %0 is not supported as the returned result is always in the locale's chosen numeric symbol digit set. * * @see formatDate() * @param formatString the date format to use * @param formatStandard the standard the @p dateFormat uses, defaults to KDE Standard * @return The date as a localized string */ QString formatDate(const QString &formatString, KLocale::DateTimeFormatStandard formatStandard = KLocale::KdeFormat) const; /** * Returns a Date Component as a localized string in the requested format. * * See @ref formatting for more details on Date Formatting. * * Each format size may vary depending on Locale and Calendar System but will * generally match the format description. Some formats may not be directly * valid but a sensible value will always be returned. * * For example for 2010-01-01 the KLocale::Month with en_US Locale and Gregorian calendar may return: * KLocale::ShortNumber = "1" * KLocale::LongNumber = "01" * KLocale::NarrowName = "J" * KLocale::ShortName = "Jan" * KLocale::LongName = "January" * * @see formatDate() * @param component The date component to return * @param format The format to return the @p component in * @param weekNumberSystem To override the default Week Number System to use * @return The string form of the date component */ QString formatDate(KLocale::DateTimeComponent component, KLocale::DateTimeComponentFormat format = KLocale::DefaultComponentFormat, KLocale::WeekNumberSystem weekNumberSystem = KLocale::DefaultWeekNumber) const; /** * Converts a localized date string to a KLocalizedDate using either the * Global Calendar System and Locale, or the provided Calendar System. * * See @ref parsing for more details on Date Parsing from strings. * * This method is more liberal and will return a valid date if the * @p dateString matches any of the KLocale::ReadDateFlags formats * for the Locale. * * If you require a certain KLocale::ReadDateFlags format or a customized * format string, use one of the other readDate() methods. * * @param dateString the string to parse * @param parseMode how strictly to apply the locale formats to the @p dateString * @param calendar the Calendar System to use when parsing the date * @return the localized date parsed from the string */ static KLocalizedDate readDate(const QString &dateString, KLocale::DateTimeParseMode parseMode = KLocale::LiberalParsing, const KCalendarSystem *calendar = nullptr); /** * Converts a localized date string to a KLocalizedDate using either the * Global Calendar System and Locale, or the provided Calendar System. * * See @ref parsing for more details on Date Parsing from strings. * * This method is stricter and will return a valid date only if the * @p dateString matches one of the @p dateFlags formats requested. * * If you require any KLocale::ReadDateFlags format or a customized format * string, use one of the other readDate() methods. * * @param dateString the string to parse * @param formatFlags the locale format(s) to try parse the string with * @param parseMode how strictly to apply the @p formatFlags to the @p dateString * @param calendar the Calendar System to use when parsing the date * @return the localized date parsed from the string */ static KLocalizedDate readDate(const QString &dateString, KLocale::ReadDateFlags formatFlags, KLocale::DateTimeParseMode parseMode = KLocale::LiberalParsing, const KCalendarSystem *calendar = nullptr); /** * Converts a localized date string to a KLocalizedDate using either the * Global Calendar System and Locale, or the provided Calendar System. * * See @ref parsing for more details on Date Parsing from strings. * * This method allows you to define your own date format to parse the date * string with. * * If you require one of the standard any KLocale::ReadDateFlags formats * then use one of the other readDate() methods. * * @param dateString the string to parse * @param dateFormat the date format to try parse the string with * @param parseMode how strictly to apply the @p dateFormat to the @p dateString * @param formatStandard the standard the @p dateFormat format uses * @param calendar the Calendar System to use when parsing the date * @return the localized date parsed from the string */ static KLocalizedDate readDate(const QString &dateString, const QString &dateFormat, KLocale::DateTimeParseMode parseMode = KLocale::LiberalParsing, KLocale::DateTimeFormatStandard formatStandard = KLocale::KdeFormat, const KCalendarSystem *calendar = nullptr); /** * Returns a KLocalizedDate containing a date @p years years later. * * @see addYearsTo() * @see addMonths() addDays() * @see dateDifference() yearsDifference() * @param years The number of years to add * @return The new date, null date if any errors */ KLocalizedDate addYears(int years) const; /** * Add years onto this date instance. * * If the result of the addition is invalid in the current Calendar System * then the date will become invalid. * * @see addYears() * @see addMonthsTo() addDaysTo() * @see dateDifference() yearsDifference() * @param years The number of years to add * @return if the resulting date is valid */ bool addYearsTo(int years); /** * Returns a KLocalizedDate containing a date @p months months later. * * @see addMonthsTo() * @see addYears() addDays() * @see dateDifference() yearsDifference() * @param months number of months to add * @return The new date, null date if any errors */ KLocalizedDate addMonths(int months) const; /** * Add months onto this date instance. * * If the result of the addition is invalid in the current Calendar System * then the date will become invalid. * * @see addMonths() * @see addYearsTo() addDaysTo() * @see dateDifference() yearsDifference() * @param months The number of months to add * @return if the resulting date is valid */ bool addMonthsTo(int months); /** * Returns a KLocalizedDate containing a date @p days days later. * * @see addDaysTo() * @see addYears() addMonths() * @see dateDifference() yearsDifference() * @param days number of days to add * @return The new date, null date if any errors */ KLocalizedDate addDays(int days) const; /** * Add days onto this date instance. * * If the result of the addition is invalid in the current Calendar System * then the date will become invalid. * * @see addDays() * @see addYearsTo(), addMonthsTo() * @see dateDifference() yearsDifference() * @param days The number of days to add * @return if the resulting date is valid */ bool addDaysTo(int days); /** * Returns the difference between this and another date in years, months and days * in the current Calendar System. * * The difference is always calculated from the earlier date to the later * date in year, month and day order, with the @p direction parameter * indicating which direction the difference is applied from this date. * In other words, this difference can be added onto the earlier date in * year, month, day order to reach the later date. * * For example, the difference between 2010-06-10 and 2012-09-5 is 2 years, * 2 months and 26 days. Note that the difference between two last days of * the month is always 1 month, e.g. 2010-01-31 to 2010-02-28 is 1 month * not 28 days. * * @see addYears() addMonths() addDays() * @see yearsDifference() monthsDifference() daysDifference() * @param toDate The date to end at * @param yearsDiff Returns number of years difference * @param monthsDiff Returns number of months difference * @param daysDiff Returns number of days difference * @param direction Returns direction of difference, 1 if this Date <= toDate, -1 otherwise */ void dateDifference(const KLocalizedDate &toDate, int *yearsDiff, int *monthsDiff, int *daysDiff, int *direction) const; /** * Returns the difference between this and another date in years, months and days * in the current Calendar System. * * The difference is always calculated from the earlier date to the later * date in year, month and day order, with the @p direction parameter * indicating which direction the difference is applied from this date. * In other words, this difference can be added onto the earlier date in * year, month, day order to reach the later date. * * For example, the difference between 2010-06-10 and 2012-09-5 is 2 years, * 2 months and 26 days. Note that the difference between two last days of * the month is always 1 month, e.g. 2010-01-31 to 2010-02-28 is 1 month * not 28 days. * * @see addYears() addMonths() addDays() * @see yearsDifference() monthsDifference() daysDifference() * @param toDate The date to end at * @param yearsDiff Returns number of years difference * @param monthsDiff Returns number of months difference * @param daysDiff Returns number of days difference * @param direction Returns direction of difference, 1 if this Date <= toDate, -1 otherwise */ void dateDifference(const QDate &toDate, int *yearsDiff, int *monthsDiff, int *daysDiff, int *direction) const; /** * Returns the difference between this and another date in completed calendar years * in the current Calendar System. * * The returned value will be negative if @p toDate < this date. * * For example, the difference between 2010-06-10 and 2012-09-5 is 2 years. * * @see addYears() * @see dateDifference() monthsDifference() daysDifference() * @param toDate The date to end at * @return The number of years difference */ int yearsDifference(const KLocalizedDate &toDate) const; /** * Returns the difference between this and another date in completed calendar years * in the current Calendar System. * * The returned value will be negative if @p toDate < this date. * * For example, the difference between 2010-06-10 and 2012-09-5 is 2 years. * * @see addYears() * @see dateDifference() monthsDifference() daysDifference() * @param toDate The date to end at * @return The number of years difference */ int yearsDifference(const QDate &toDate) const; /** * Returns the difference between this and another date in completed calendar months * in the current Calendar System. * * The returned value will be negative if @p toDate < this date. * * For example, the difference between 2010-06-10 and 2012-09-5 is 26 months. * Note that the difference between two last days of the month is always 1 * month, e.g. 2010-01-31 to 2010-02-28 is 1 month not 28 days. * * @see addMonths() * @see dateDifference() yearsDifference() daysDifference() * @param toDate The date to end at * @return The number of months difference */ int monthsDifference(const KLocalizedDate &toDate) const; /** * Returns the difference between this and another date in completed calendar months * in the current Calendar System. * * The returned value will be negative if @p toDate < this date. * * For example, the difference between 2010-06-10 and 2012-09-5 is 26 months. * Note that the difference between two last days of the month is always 1 * month, e.g. 2010-01-31 to 2010-02-28 is 1 month not 28 days. * * @see addMonths() * @see dateDifference() yearsDifference() daysDifference() * @param toDate The date to end at * @return The number of months difference */ int monthsDifference(const QDate &toDate) const; /** * Returns the difference between this and another date in days * The returned value will be negative if @p toDate < this date. * * @see addDays() * @see dateDifference() yearsDifference() monthsDifference() * @param toDate The date to end at * @return The number of days difference */ int daysDifference(const KLocalizedDate &toDate) const; /** * Returns the difference between this and another date in days * The returned value will be negative if @p toDate < this date. * * @see addDays() * @see dateDifference() yearsDifference() monthsDifference() * @param toDate The date to end at * @return The number of days difference */ int daysDifference(const QDate &toDate) const; /** * Returns a KLocalizedDate containing the first day of the currently set year * * @see lastDayOfYear() * @return The first day of the year */ KLocalizedDate firstDayOfYear() const; /** * Returns a KLocalizedDate containing the last day of the currently set year * * @see firstDayOfYear() * @return The last day of the year */ KLocalizedDate lastDayOfYear() const; /** * Returns a KLocalizedDate containing the first day of the currently set month * * @see lastDayOfMonth() * @return The first day of the month */ KLocalizedDate firstDayOfMonth() const; /** * Returns a KLocalizedDate containing the last day of the currently set month * * @see firstDayOfMonth() * @return The last day of the month */ KLocalizedDate lastDayOfMonth() const; /** * KLocalizedDate equality operator * * @param other the date to compare */ bool operator==(const KLocalizedDate &other) const; /** * QDate equality operator * * @param other the date to compare */ bool operator==(const QDate &other) const; /** * KLocalizedDate inequality operator * * @param other the date to compare */ bool operator!=(const KLocalizedDate &other) const; /** * QDate inequality operator * * @param other the date to compare */ bool operator!=(const QDate &other) const; /** * KLocalizedDate less than operator * * @param other the date to compare */ bool operator<(const KLocalizedDate &other) const; /** * QDate less than operator * * @param other the date to compare */ bool operator<(const QDate &other) const; /** * KLocalizedDate less than or equal to operator * * @param other the date to compare */ bool operator<=(const KLocalizedDate &other) const; /** * QDate less than or equal to operator * * @param other the date to compare */ bool operator<=(const QDate &other) const; /** * KLocalizedDate greater than operator * * @param other the date to compare */ bool operator>(const KLocalizedDate &other) const; /** * QDate greater than operator * * @param other the date to compare */ bool operator>(const QDate &other) const; /** * KLocalizedDate greater than or equal to operator * * @param other the date to compare */ bool operator>=(const KLocalizedDate &other) const; /** * QDate greater than or equal to operator * * @param other the date to compare */ bool operator>=(const QDate &other) const; private: friend QDataStream KDELIBS4SUPPORT_EXPORT &operator<<(QDataStream &out, const KLocalizedDate &date); friend QDataStream KDELIBS4SUPPORT_EXPORT &operator>>(QDataStream &in, KLocalizedDate &date); friend QDebug KDELIBS4SUPPORT_EXPORT operator<<(QDebug, const KLocalizedDate &); QSharedDataPointer d; }; Q_DECLARE_METATYPE(KLocalizedDate) /** * Data stream output operator * * @param out the datastream to write to * @param date the date to write to the stream */ QDataStream KDELIBS4SUPPORT_EXPORT &operator<<(QDataStream &out, const KLocalizedDate &date); /** * Data stream input operator * * @param in the datastream to read from * @param date the date to read from the stream */ QDataStream KDELIBS4SUPPORT_EXPORT &operator>>(QDataStream &in, KLocalizedDate &date); /** * Debug stream output operator * * @param debug the debug datastream to write to * @param date the date to write to the stream */ QDebug KDELIBS4SUPPORT_EXPORT operator<<(QDebug debug, const KLocalizedDate &date); #endif // KLOCALIZEDDATE_H diff --git a/src/kdecore/klockfile.h b/src/kdecore/klockfile.h index 83ccb15b..001916e1 100644 --- a/src/kdecore/klockfile.h +++ b/src/kdecore/klockfile.h @@ -1,145 +1,145 @@ /* This file is part of the KDE libraries Copyright (c) 2004 Waldo Bastian 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 KLOCKFILE_H #define KLOCKFILE_H #include #include #include class QString; /** * \class KLockFile klockfile.h * * The KLockFile class provides NFS safe lockfiles. * * @author Waldo Bastian * @deprecated since 5.0, please use QLockFile instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KLockFile { public: /** * Constructor * @deprecated since 5.0, use QLockFile(file), drop the component name. */ - explicit KLockFile(const QString &file, const QString &componentName = QString()); + KDELIBS4SUPPORT_DEPRECATED explicit KLockFile(const QString &file, const QString &componentName = QString()); /** * Destroys the object, releasing the lock if held */ ~KLockFile(); /** * Possible return values of the lock function. */ enum LockResult { /** * Lock was acquired successfully */ LockOK = 0, /** * The lock could not be acquired because it is held by another process */ LockFail, /** * The lock could not be acquired due to an error */ LockError, /** * A stale lock has been detected */ LockStale }; enum LockFlag { /** * Return immediately, do not wait for the lock to become available */ NoBlockFlag = 1, /** * Automatically remove a lock when a lock is detected that is stale * for more than staleTime() seconds, or if the process that created it * is not running anymore. */ ForceFlag = 2 }; Q_DECLARE_FLAGS(LockFlags, LockFlag) /** * Attempt to acquire the lock * * @param flags A set of @ref LockFlag values OR'ed together. * @deprecated since 5.0 * KLockFile::lock() --> QLockFile::lock(). Possibly after setStaleLockTime(0), but * only for the case of protecting a resource for a very long time. * KLockFile::lock(NoBlockFlag) --> QLockFile::tryLock(). Possibly after setStaleLockTime(0), but * only for the case of protecting a resource for a very long time. * KLockFile::lock(ForceFlag) --> QLockFile::lock(). * KLockFile::lock(NoBlockFlag|ForceFlag) --> QLockFile::tryLock(). * Note that the return value is now simply a bool (success/failure). */ LockResult lock(LockFlags flags = LockFlags()); /** * Returns whether the lock is held or not */ bool isLocked() const; /** * Release the lock */ void unlock(); /** * Return the time in seconds after which a lock is considered stale * The default is 30. * @deprecated since 5.0. WARNING: QLockFile::staleLockTime() is in ms, so divide the result by 1000. */ int staleTime() const; /** * Set the time in seconds after which a lock is considered stale * @deprecated since 5.0. WARNING: QLockFile::setStaleLockTime() is in ms, so multiply the argument by 1000. */ void setStaleTime(int _staleTime); /** * Returns the pid, hostname and appname of the process holding * the lock after the lock functon has returned with LockStale. * @returns false if the pid and hostname could not be determined * @deprecated since 5.0. Use QLockFile::getLockInfo(qint64 *pid, QString *hostname, QString *appname) */ bool getLockInfo(int &pid, QString &hostname, QString &appname); private: class Private; Private *const d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KLockFile::LockFlags) #endif diff --git a/src/kdecore/kmd5.h b/src/kdecore/kmd5.h index e048e2e2..b72ac48c 100644 --- a/src/kdecore/kmd5.h +++ b/src/kdecore/kmd5.h @@ -1,263 +1,263 @@ /* Copyright (C) 2000-2001 Dawit Alemayehu Copyright (C) 2001 Rik Hemsley (rikkus) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. RFC 1321 "MD5 Message-Digest Algorithm" Copyright (C) 1991-1992. // krazy:exclude=copyright RSA Data Security, Inc. Created 1991. All rights reserved. The KMD5 class is based on a C++ implementation of "RSA Data Security, Inc. MD5 Message-Digest Algorithm" by Mordechai T. Abzug, Copyright (c) 1995. This implementation // krazy:exclude=copyright passes the test-suite as defined in RFC 1321. The encoding and decoding utilities in KCodecs with the exception of quoted-printable are based on the java implementation in HTTPClient package by Ronald Tschalär Copyright (C) 1996-1999. // krazy:exclude=copyright The quoted-printable codec as described in RFC 2045, section 6.7. is by Rik Hemsley (C) 2001. */ #ifndef KMD5_H #define KMD5_H #include #include class QByteArray; class QIODevice; class KMD5Private; /** * @short An adapted C++ implementation of RSA Data Securities MD5 algorithm. * * DEPRECATED. please use QCryptographicHash instead * * The default constructor is designed to provide much the same * functionality as the most commonly used C-implementation, while * the other three constructors are meant to further simplify the * process of obtaining a digest by calculating the result in a * single step. * * KMD5 is state-based, that means you can add new contents with * update() as long as you didn't request the digest value yet. * After the digest value was requested, the object is "finalized" * and you have to call reset() to be able to do another calculation * with it. The reason for this behavior is that upon requesting * the message digest KMD5 has to pad the received contents up to a * 64 byte boundary to calculate its value. After this operation it * is not possible to resume consuming data. * * \b Usage: * * A common usage of this class: * * \code * const char* test1; * KMD5::Digest rawResult; * * test1 = "This is a simple test."; * KMD5 context (test1); * cout << "Hex Digest output: " << context.hexDigest().data() << endl; * \endcode * * To cut down on the unnecessary overhead of creating multiple KMD5 * objects, you can simply invoke reset() to reuse the same object * in making another calculation: * * \code * context.reset (); * context.update ("TWO"); * context.update ("THREE"); * cout << "Hex Digest output: " << context.hexDigest().data() << endl; * \endcode * * @author Dirk Mueller , Dawit Alemayehu * * @deprecated * @see QCryptographicHash */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KMD5 { public: typedef unsigned char Digest[16]; KMD5(); ~KMD5(); /** * Constructor that updates the digest for the given string. * * @param in C string or binary data * @param len if negative, calculates the length by using * strlen on the first parameter, otherwise * it trusts the given length (does not stop on NUL byte). */ - explicit KMD5(const char *in, int len = -1); + KDELIBS4SUPPORT_DEPRECATED explicit KMD5(const char *in, int len = -1); /** * @overload * * Same as above except it accepts a QByteArray as its argument. */ - explicit KMD5(const QByteArray &a); + KDELIBS4SUPPORT_DEPRECATED explicit KMD5(const QByteArray &a); /** * Updates the message to be digested. Be sure to add all data * before you read the digest. After reading the digest, you * can not add more data! * * @param in message to be added to digest * @param len the length of the given message. * * @deprecated please use QCryptographicHash::addData instead */ void update(const char *in, int len = -1); /** * @overload * * please use QCryptographicHash::addData instead */ void update(const unsigned char *in, int len = -1); /** * @overload * * @param in message to be added to the digest (QByteArray). * * @deprecated please use QCryptographicHash::addData instead */ void update(const QByteArray &in); /** * @overload * * reads the data from an I/O device, i.e. from a file (QFile). * * NOTE that the file must be open for reading. * * @param file a pointer to FILE as returned by calls like f{d,re}open * * @returns false if an error occurred during reading. * * @deprecated please use QCryptographicHash::addData instead */ bool update(QIODevice &file); /** * Calling this function will reset the calculated message digest. * Use this method to perform another message digest calculation * without recreating the KMD5 object. * * @deprecated please use QCryptographicHash::reset() instead */ void reset(); /** * @return the raw representation of the digest * @deprecated please use QCryptographicHash::result instead */ const Digest &rawDigest(); //krazy:exclude=constref (simple array) /** * Fills the given array with the binary representation of the * message digest. * * Use this method if you do not want to worry about making * copy of the digest once you obtain it. * * @param bin an array of 16 characters ( char[16] ) */ void rawDigest(KMD5::Digest &bin); /** * Returns the value of the calculated message digest in * a hexadecimal representation. * @deprecated please use QCryptographicHash::result().toHex() instead */ QByteArray hexDigest(); /** * @overload */ void hexDigest(QByteArray &); /** * Returns the value of the calculated message digest in * a base64-encoded representation. * @deprecated please use QCryptographicHash::result().toBase64() instead */ QByteArray base64Digest(); /** * returns true if the calculated digest for the given * message matches the given one. */ bool verify(const KMD5::Digest &digest); /** * @overload */ bool verify(const QByteArray &); protected: /** * Performs the real update work. Note * that length is implied to be 64. */ void transform(const unsigned char buffer[64]); /** * finalizes the digest */ void finalize(); private: KMD5(const KMD5 &u); KMD5 &operator=(const KMD5 &md); void init(); void encode(unsigned char *output, quint32 *in, quint32 len); void decode(quint32 *output, const unsigned char *in, quint32 len); quint32 rotate_left(quint32 x, quint32 n); quint32 F(quint32 x, quint32 y, quint32 z); quint32 G(quint32 x, quint32 y, quint32 z); quint32 H(quint32 x, quint32 y, quint32 z); quint32 I(quint32 x, quint32 y, quint32 z); void FF(quint32 &a, quint32 b, quint32 c, quint32 d, quint32 x, quint32 s, quint32 ac); void GG(quint32 &a, quint32 b, quint32 c, quint32 d, quint32 x, quint32 s, quint32 ac); void HH(quint32 &a, quint32 b, quint32 c, quint32 d, quint32 x, quint32 s, quint32 ac); void II(quint32 &a, quint32 b, quint32 c, quint32 d, quint32 x, quint32 s, quint32 ac); private: quint32 m_state[4]; quint32 m_count[2]; quint8 m_buffer[64]; Digest m_digest; bool m_finalized; KMD5Private *d; }; #endif // KCODECS_H diff --git a/src/kdecore/ksavefile.h b/src/kdecore/ksavefile.h index 7aaf91ce..4ee48e6a 100644 --- a/src/kdecore/ksavefile.h +++ b/src/kdecore/ksavefile.h @@ -1,220 +1,220 @@ /* This file is part of the KDE libraries Copyright 1999 Waldo Bastian Copyright 2006 Jaison Lee 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 KSAVEFILE_H #define KSAVEFILE_H #include #include "kbackup.h" #include #include /** * \class KSaveFile ksavefile.h * * @brief Class to allow for atomic file I/O, as well as utility functions. * * The KSaveFile class has been made to write out changes to an existing * file atomically. This means that either ALL changes will be written * to the file, or NO changes have been written, and the original file * (if any) has been unchanged. This is useful if you have lots of * time-consuming processing to perform during which an interruption could * occur, or if any error in the file structure will cause the entire file * to be corrupt. * * When you create a KSaveFile for a given file, a temporary file is instead * created and all your I/O occurs in the save file. Once you call finalize() * the temporary file is renamed to the target file, so that all your changes * happen at once. If abort() is called then the temporary file is removed and * the target file is untouched. KSaveFile derives from QFile so you can use * it just as you would a normal QFile. * * This class also includes several static utility functions available that * can help ensure data integrity. See the individual functions for details. * * Here is a quick example of how to use KSaveFile: * * First we create the KSaveFile and open it. * * @code * KSaveFile saveFile; * saveFile.setFileName("/lib/foo/bar.dat"); * if ( !saveFile.open() ) { * //Handle error * } * @endcode * * At this point the file "/lib/foo/bar.dat" has not been altered in any way. * Now, let's write out some data to the file. * * @code * QTextStream stream ( &saveFile ); * stream << "Add some data."; * // Perform long processing * stream << "Add some more data."; * stream.flush(); * @endcode * * Even after writing this data, the target file "/lib/foo/bar.dat" still has * not been altered in any way. Now that we are done writing our data, we can * write out all the changes that we have made by calling finalize(). * * @code * if ( !saveFile.finalize() ) { * //Handle error * } * @endcode * * If a user interruption or error occurred while we were writing out our * changes, we would instead call abort() to cancel all the I/O without * affecting the target file. * * @see QFile * * @author Jaison Lee * @author Waldo Bastian * * @deprecated since 5.0, port to QSaveFile. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KSaveFile : public QFile { public: /** * Default constructor. */ KSaveFile(); /** * Creates a new KSaveFile and sets the target file to @p filename. * * @param filename the path of the file */ - explicit KSaveFile(const QString &filename); + KDELIBS4SUPPORT_DEPRECATED explicit KSaveFile(const QString &filename); /** * Destructor. * @note If the file has been opened but not yet finalized, the * destructor will call finalize(). If you do not want the target file * to be affected you need to call abort() before destroying the object. **/ virtual ~KSaveFile(); /** * @brief Set the target filename for the save file. * You must use this to set the filename of the target file if you do * not use the contructor that does so. * @param filename Name of the target file. */ void setFileName(const QString &filename); /** * @brief Returns the name of the target file. * This function returns the name of the target file, or an empty * QString if it has not yet been set. * @returns The name of the target file. */ QString fileName() const Q_DECL_OVERRIDE; /** * @brief Returns the last error that occurred. * Use this function to check for errors. * @returns The last error that occurred, or QFile::NoError. */ QFile::FileError error() const; /** * @brief Returns a human-readable description of the last error. * Use this function to get a human-readable description of the * last error that occurred. * @return A string describing the last error that occurred. */ QString errorString() const; /** * @brief Open the save file. * This function will open the save file by creating a temporary file to write * to. It will also check to ensure that there are sufficient permissions to * write to the target file. * * @param flags Sets the QIODevice::OpenMode. It should contain the write flag, otherwise you * have a save file you cannot save to. * * @return true if successful, or false if an error has occurred. */ bool open(OpenMode flags = QIODevice::ReadWrite) Q_DECL_OVERRIDE; /** * @brief Discard changes without affecting the target file. * This will discard all changes that have been made to this file. * The target file will not be altered in any way. **/ void abort(); /** * @brief Finalize changes to the file. * This will commit all the changes that have been made to the file. * @return true if successful, or false if an error has occurred. **/ bool finalize(); /** * Allows writing over the existing file if necessary. * * QSaveFile creates a temporary file in the same directory as the final * file and atomically renames it. However this is not possible if the * directory permissions do not allow creating new files. * In order to preserve atomicity guarantees, open() fails when it * cannot create the temporary file. * * In order to allow users to edit files with write permissions in a * directory with restricted permissions, call setDirectWriteFallback() with * \a enabled set to true, and the following calls to open() will fallback to * opening the existing file directly and writing into it, without the use of * a temporary file. * This does not have atomicity guarantees, i.e. an application crash or * for instance a power failure could lead to a partially-written file on disk. * It also means cancelWriting() has no effect, in such a case. * * Typically, to save documents edited by the user, call setDirectWriteFallback(true), * and to save application internal files (configuration files, data files, ...), keep * the default setting which ensures atomicity. * * @since 4.10.3 */ void setDirectWriteFallback(bool enabled); /** * Returns true if the fallback solution for saving files in read-only * directories is enabled. * * @since 4.10.3 */ bool directWriteFallback() const; private: Q_DISABLE_COPY(KSaveFile) class Private; Private *const d; }; #endif diff --git a/src/kdecore/ksharedptr.h b/src/kdecore/ksharedptr.h index 7ffb0e4b..77f6f552 100644 --- a/src/kdecore/ksharedptr.h +++ b/src/kdecore/ksharedptr.h @@ -1,311 +1,311 @@ /* * This file is part of the KDE libraries. * * Copyright 2005 Frerich Raabe * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef KSHAREDPTR_H #define KSHAREDPTR_H #include #include /** * @deprecated * Use QSharedData instead. */ typedef KDELIBS4SUPPORT_DEPRECATED QSharedData KShared; /** * \class KSharedPtr ksharedptr.h * * Can be used to control the lifetime of an object that has derived * QSharedData. As long a someone holds * a KSharedPtr on some QSharedData object it won't become deleted but * is deleted once its reference count is 0. * This struct emulates C++ pointers virtually perfectly. * So just use it like a simple C++ pointer. * * The difference with QSharedPointer is that QSharedPointer does the refcounting * in the pointer, while KSharedPtr does the refcounting in the object. * This allows to convert to a raw pointer temporarily and back to a KSharedPtr * without deleting the object, if another reference exists. But it imposes a * requirement on the object, which must inherit QSharedData. * * The difference with using QSharedDataPointer is that QSharedDataPointer is * a building block for implementing a value class with implicit sharing (like QString), * whereas KSharedPtr provides refcounting to code that uses pointers. * * @author Waldo Bastian * * @deprecated use QExplicitlySharedDataPointer instead * */ template< class T > class KDELIBS4SUPPORT_DEPRECATED KSharedPtr { public: /** * Creates a null pointer. */ inline KSharedPtr() : d(nullptr) { } /** * Creates a new pointer. * @param p the pointer */ - inline explicit KSharedPtr(T *p) + inline KDELIBS4SUPPORT_DEPRECATED explicit KSharedPtr(T *p) : d(p) { if (d) { d->ref.ref(); } } /** * Copies a pointer. * @param o the pointer to copy */ inline KSharedPtr(const KSharedPtr &o) : d(o.d) { if (d) { d->ref.ref(); } } /** * Unreferences the object that this pointer points to. If it was * the last reference, the object will be deleted. */ inline ~KSharedPtr() { if (d && !d->ref.deref()) { delete d; } } inline KSharedPtr &operator= (const KSharedPtr &o) { attach(o.d); return *this; } inline bool operator== (const KSharedPtr &o) const { return (d == o.d); } inline bool operator!= (const KSharedPtr &o) const { return (d != o.d); } inline bool operator< (const KSharedPtr &o) const { return (d < o.d); } inline KSharedPtr &operator= (T *p) { attach(p); return *this; } inline bool operator== (const T *p) const { return (d == p); } inline bool operator!= (const T *p) const { return (d != p); } /** * Test if the shared pointer is NOT null. * @return true if the shared pointer is NOT null, false otherwise. * @see isNull */ inline operator bool() const { return (d != nullptr); } /** * @return the pointer */ inline T *data() { return d; } /** * @return the pointer */ inline const T *data() const { return d; } /** * @return a const pointer to the shared object. */ inline const T *constData() const { return d; } inline const T &operator*() const { Q_ASSERT(d); return *d; } inline T &operator*() { Q_ASSERT(d); return *d; } inline const T *operator->() const { Q_ASSERT(d); return d; } inline T *operator->() { Q_ASSERT(d); return d; } /** * Attach the given pointer to the current KSharedPtr. * If the previous shared pointer is not owned by any KSharedPtr, * it is deleted. */ void attach(T *p); /** * Clear the pointer, i.e. make it a null pointer. */ void clear(); /** * Returns the number of references. * @return the number of references */ inline int count() const { return d ? d->ref.load() : 0; } // for debugging purposes /** * Test if the shared pointer is null. * @return true if the pointer is null, false otherwise. * @see opertor (bool) */ inline bool isNull() const { return (d == 0); } /** * @return Whether this is the only shared pointer pointing to * to the pointee, or whether it's shared among multiple * shared pointers. */ inline bool isUnique() const { return count() == 1; } template friend class KSharedPtr; /** * Convert KSharedPtr to KSharedPtr, using a static_cast. * This will compile whenever T* and U* are compatible, i.e. * T is a subclass of U or vice-versa. * Example syntax: * * KSharedPtr tPtr; * KSharedPtr uPtr = KSharedPtr::staticCast( tPtr ); * */ template static KSharedPtr staticCast(const KSharedPtr &o) { return KSharedPtr(static_cast(o.d)); } /** * Convert KSharedPtr to KSharedPtr, using a dynamic_cast. * This will compile whenever T* and U* are compatible, i.e. * T is a subclass of U or vice-versa. * Example syntax: * * KSharedPtr tPtr; * KSharedPtr uPtr = KSharedPtr::dynamicCast( tPtr ); * * Since a dynamic_cast is used, if U derives from T, and tPtr isn't an instance of U, uPtr will be 0. */ template static KSharedPtr dynamicCast(const KSharedPtr &o) { return KSharedPtr(dynamic_cast(o.d)); } protected: T *d; }; template Q_INLINE_TEMPLATE bool operator== (const T *p, const KSharedPtr &o) { return (o == p); } template Q_INLINE_TEMPLATE bool operator!= (const T *p, const KSharedPtr &o) { return (o != p); } template Q_INLINE_TEMPLATE void KSharedPtr::attach(T *p) { if (d != p) { if (p) { p->ref.ref(); } if (d && !d->ref.deref()) { delete d; } d = p; } } template Q_INLINE_TEMPLATE void KSharedPtr::clear() { attach(static_cast(0)); } #endif diff --git a/src/kdecore/ktempdir.h b/src/kdecore/ktempdir.h index 379154f2..8a30554b 100644 --- a/src/kdecore/ktempdir.h +++ b/src/kdecore/ktempdir.h @@ -1,173 +1,173 @@ /* This file is part of the KDE libraries Copyright (c) 2003 Joseph Wenninger 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 KTEMPDIR_H #define KTEMPDIR_H #include #include /** * \class KTempDir ktempdir.h * * @deprecated use QTemporaryDir * * @brief Create a unique directory for temporary use. * * The KTempDir class creates a unique directory for temporary use. * * Porting to QTemporaryDir goes as follows: * - Replace KTempDir with QTemporaryDir * - Replace name() with path(), but keep in mind that name ended with a '/', while path does not. * - Replace status() with isValid() * * A typical usage of KTempDir was * KTempDir(KStandardDirs::locateLocal("tmp", prefix)); * This should be ported to * QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + prefix); * * Note: KTempDir does not create any missing directories, but * KStandardDirs::locateLocal() does. * * @see QTemporaryDir */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KTempDir { public: /** * Creates a temporary directory with the name: * \p \\ * * The default \p directoryPrefix is "/tmp/appname" * * @param directoryPrefix the prefix of the file name, or * QString() for the default value * @param mode the file permissions, * almost always in octal. The first digit selects permissions for * the user who owns the file: read (4), write (2), and execute * (1); the second selects permissions for other users in the * file's group, with the same values; and the third for other * users not in the file's group, with the same values. * * @deprecated Use QTemporaryDir() or QTemporaryDir(directoryPrefix). * If a specific mode was set, you'll need to use QFile::setPermissions on the temporary dir path. */ - explicit KTempDir(const QString &directoryPrefix = QString(), + KDELIBS4SUPPORT_DEPRECATED explicit KTempDir(const QString &directoryPrefix = QString(), int mode = 0700); /** * The destructor deletes the directory and its contents if autoRemove * is set to true. * @see setAutoRemove. **/ ~KTempDir(); /** * Turn automatic deletion of the directory on or off. * Automatic deletion is on by default. * @param autoRemove toggle automatic deletion on or off **/ void setAutoRemove(bool autoRemove); /** * @return whether auto remove is active * @see setAutoRemove **/ bool autoRemove() const; /** * Returns the status of the directory creation based on errno. * (see errno.h) * * @note You should check the status after object creation to check * whether the directory could be created. * * @return the errno status, 0 means ok * * @deprecated use QTemporaryDir::isValid() */ int status() const; /** * Returns the full path and name of the directory, including a * trailing '/'. * @return The name of the directory, or QString() if creating the * directory has failed or the directory has been unlinked * * @deprecated use QTemporaryDir::path() */ QString name() const; /** * Deletes the directory recursively * * @deprecated use QTemporaryDir::remove() */ void unlink(); /** * Returns true if a temporary directory has successfully been created * and has not been unlinked yet. * * @deprecated use QTemporaryDir::isValid() + QDir::exists(path) if there's really * a doubt that it might have been deleted meanwhile. */ bool exists() const; /** * @brief Remove a directory and all its contents * * Remove recursively a directory, even if it is not empty * or contains other directories. * * However the function works too when the @p path given * is a non-directory file. In that case it simply remove that file. * * The function stops on the first error. * * @note This function is more meant for removing a directory * not created by the user. For user-created directories, * using KIO::del() is recommended instead, * especially as it has user feedback for long operations. * * @param path Path of the directory to delete * @return true if successful, otherwise false * (Use errno for more details about the error.) * * @deprecated use QDir(path)::removeRecursively in Qt 5. */ static bool removeDir(const QString &path); protected: /** * Creates a "random" directory with specified mode * @param directoryPrefix to use when creating temp directory * (the rest is generated randomly) * @param mode directory permissions * @return true upon success */ bool create(const QString &directoryPrefix, int mode); private: class Private; Private *const d; }; #endif diff --git a/src/kdecore/ktemporaryfile.h b/src/kdecore/ktemporaryfile.h index 617b90ef..2c007aff 100644 --- a/src/kdecore/ktemporaryfile.h +++ b/src/kdecore/ktemporaryfile.h @@ -1,99 +1,99 @@ /* This file is part of the KDE libraries * Copyright 2006 Jaison Lee * * 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 ktemporaryfile_h #define ktemporaryfile_h #include #include "kglobal.h" #include class KTemporaryFilePrivate; /** * \class KTemporaryFile ktemporaryfile.h * * @deprecated use QTemporaryFile * * By default the filename will start with your application's name, * followed by six random characters. You can call QTemporaryFile::setFileTemplate() * to change that. * * Porting to QTemporaryFile is simple: in apps, you can probably just use the default constructor. * * In parts and plugins, you were probably passing a component data to KTemporaryFile, so instead use: * QTemporaryFile(QDir::tempPath() + QLatin1Char('/') + componentData.name() + QLatin1String("XXXXXX")) * * For setPrefix, change the QDir::tempPath() from the above line. * For setSuffix, append it after the XXXXXX. * * In the simplest case where the application was only calling setSuffix(".txt"), this becomes * QTemporaryFile(QDir::tempPath() + QLatin1String("/myapp_XXXXXX.txt")) * * @see QTemporaryFile */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KTemporaryFile : public QTemporaryFile { public: /** * Construct a new KTemporaryFile. The file will be stored in the temporary * directory configured in KDE. The default prefix is the value of the * default KDE temporary directory, plus your application's instance name. * The default suffix is ".tmp". * * \param componentData The KComponentData to use for the name of the file and * to look up the directory. */ - explicit KTemporaryFile(const KComponentData &componentData = KGlobal::mainComponent()); + KDELIBS4SUPPORT_DEPRECATED explicit KTemporaryFile(const KComponentData &componentData = KGlobal::mainComponent()); /** * Destructor. */ virtual ~KTemporaryFile(); /** * @brief Sets a prefix to use when creating the file. * * This function sets a prefix to use when creating the file. The random * part of the filename will come after this prefix. The prefix can also * change or modify the target directory. If @p prefix is an absolute * path it will override the default temporary directory. If @p prefix is * a relative directory it will be relative to the default temporary * location. To set a relative directory for the current working directory * you should use QTemporaryFile::setFileTemplate() directly. * @param prefix The prefix to use when creating the file. Remember to * end the prefix with a '/' if you are designating a directory. */ void setPrefix(const QString &prefix); /** * @brief Sets a suffix to use when creating the file. * * Sets a suffix to use when creating the file. The random part of the * filename will come before this suffix. * @param suffix The suffix to use when creating the file. */ void setSuffix(const QString &suffix); private: KTemporaryFilePrivate *const d; }; #endif diff --git a/src/kdecore/ktimezone.cpp b/src/kdecore/ktimezone.cpp index 83650a81..719c09e2 100644 --- a/src/kdecore/ktimezone.cpp +++ b/src/kdecore/ktimezone.cpp @@ -1,1396 +1,1396 @@ /* This file is part of the KDE libraries Copyright (c) 2005-2008,2011 David Jarvie Copyright (c) 2005 S.R.Haque . 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. */ #include "ktimezone.h" #include // SIZEOF_TIME_T #if HAVE_SYS_TIME_H #include #endif #if HAVE_TIME_H #include #endif #include #include #include #include #include #include int gmtoff(time_t t); // defined in ksystemtimezone.cpp /******************************************************************************/ class KTimeZonesPrivate { public: KTimeZonesPrivate() {} KTimeZones::ZoneMap zones; }; KTimeZones::KTimeZones() : d(new KTimeZonesPrivate) { } KTimeZones::~KTimeZones() { delete d; } const KTimeZones::ZoneMap KTimeZones::zones() const { return d->zones; } bool KTimeZones::add(const KTimeZone &zone) { if (!zone.isValid()) { return false; } if (d->zones.find(zone.name()) != d->zones.end()) { return false; // name already exists } d->zones.insert(zone.name(), zone); return true; } KTimeZone KTimeZones::remove(const KTimeZone &zone) { if (zone.isValid()) { for (ZoneMap::Iterator it = d->zones.begin(), end = d->zones.end(); it != end; ++it) { if (it.value() == zone) { d->zones.erase(it); return zone; } } } return KTimeZone(); } KTimeZone KTimeZones::remove(const QString &name) { if (!name.isEmpty()) { ZoneMap::Iterator it = d->zones.find(name); if (it != d->zones.end()) { KTimeZone zone = it.value(); d->zones.erase(it); return zone; } } return KTimeZone(); } void KTimeZones::clear() { d->zones.clear(); } KTimeZone KTimeZones::zone(const QString &name) const { if (!name.isEmpty()) { ZoneMap::ConstIterator it = d->zones.constFind(name); if (it != d->zones.constEnd()) { return it.value(); } if (name == KTimeZone::utc().name()) { return KTimeZone::utc(); } } return KTimeZone(); // error } /******************************************************************************/ class KTimeZonePhasePrivate : public QSharedData { public: QByteArray abbreviations; // time zone abbreviations (zero-delimited) QString comment; // optional comment int utcOffset; // seconds to add to UTC bool dst; // true if daylight savings time - explicit KTimeZonePhasePrivate(int offset = 0, bool ds = false) + KDELIBS4SUPPORT_DEPRECATED explicit KTimeZonePhasePrivate(int offset = 0, bool ds = false) : QSharedData(), utcOffset(offset), dst(ds) {} KTimeZonePhasePrivate(const KTimeZonePhasePrivate &rhs) : QSharedData(rhs), abbreviations(rhs.abbreviations), comment(rhs.comment), utcOffset(rhs.utcOffset), dst(rhs.dst) {} bool operator==(const KTimeZonePhasePrivate &rhs) const { return abbreviations == rhs.abbreviations && comment == rhs.comment && utcOffset == rhs.utcOffset && dst == rhs.dst; } }; KTimeZone::Phase::Phase() : d(new KTimeZonePhasePrivate) { } KTimeZone::Phase::Phase(int utcOffset, const QByteArray &abbrevs, bool dst, const QString &cmt) : d(new KTimeZonePhasePrivate(utcOffset, dst)) { d->abbreviations = abbrevs; d->comment = cmt; } KTimeZone::Phase::Phase(int utcOffset, const QList &abbrevs, bool dst, const QString &cmt) : d(new KTimeZonePhasePrivate(utcOffset, dst)) { for (int i = 0, end = abbrevs.count(); i < end; ++i) { if (i > 0) { d->abbreviations += '\0'; } d->abbreviations += abbrevs[i]; } d->comment = cmt; } KTimeZone::Phase::Phase(const KTimeZone::Phase &rhs) : d(rhs.d) { } KTimeZone::Phase::~Phase() { } KTimeZone::Phase &KTimeZone::Phase::operator=(const KTimeZone::Phase &rhs) { d = rhs.d; return *this; } bool KTimeZone::Phase::operator==(const KTimeZone::Phase &rhs) const { return d == rhs.d || *d == *rhs.d; } int KTimeZone::Phase::utcOffset() const { return d->utcOffset; } QList KTimeZone::Phase::abbreviations() const { return d->abbreviations.split('\0'); } bool KTimeZone::Phase::isDst() const { return d->dst; } QString KTimeZone::Phase::comment() const { return d->comment; } /******************************************************************************/ class KTimeZoneTransitionPrivate { public: QDateTime time; KTimeZone::Phase phase; }; KTimeZone::Transition::Transition() : d(new KTimeZoneTransitionPrivate) { } KTimeZone::Transition::Transition(const QDateTime &t, const KTimeZone::Phase &p) : d(new KTimeZoneTransitionPrivate) { d->time = t; d->phase = p; } KTimeZone::Transition::Transition(const KTimeZone::Transition &t) : d(new KTimeZoneTransitionPrivate) { d->time = t.d->time; d->phase = t.d->phase; } KTimeZone::Transition::~Transition() { delete d; } KTimeZone::Transition &KTimeZone::Transition::operator=(const KTimeZone::Transition &t) { d->time = t.d->time; d->phase = t.d->phase; return *this; } bool KTimeZone::Transition::operator<(const KTimeZone::Transition &rhs) const { return d->time < rhs.d->time; } QDateTime KTimeZone::Transition::time() const { return d->time; } KTimeZone::Phase KTimeZone::Transition::phase() const { return d->phase; } /******************************************************************************/ class KTimeZoneDataPrivate { public: QList phases; QList transitions; QList leapChanges; QList utcOffsets; QList abbreviations; KTimeZone::Phase prePhase; // phase to use before the first transition KTimeZoneDataPrivate() {} // Find the last transition before a specified UTC or local date/time. int transitionIndex(const QDateTime &dt) const; bool transitionIndexes(const QDateTime &start, const QDateTime &end, int &ixstart, int &ixend) const; bool isSecondOccurrence(const QDateTime &utcLocalTime, int transitionIndex) const; }; /******************************************************************************/ class KTimeZonePrivate : public QSharedData { public: KTimeZonePrivate() : source(nullptr), data(nullptr), refCount(1), cachedTransitionIndex(-1) {} KTimeZonePrivate(KTimeZoneSource *src, const QString &nam, const QString &country, float lat, float lon, const QString &cmnt); KTimeZonePrivate(const KTimeZonePrivate &); ~KTimeZonePrivate() { delete data; } KTimeZonePrivate &operator=(const KTimeZonePrivate &); static KTimeZoneSource *utcSource(); static void cleanup(); KTimeZoneSource *source; QString name; QString countryCode; QString comment; float latitude; float longitude; mutable KTimeZoneData *data; int refCount; // holds the number of KTimeZoneBackend instances using the KTimeZonePrivate instance as a d-pointer. int cachedTransitionIndex; QDateTime cachedTransitionStartZoneTime; QDateTime cachedTransitionEndZoneTime; bool cachedTransitionTimesValid; private: static KTimeZoneSource *mUtcSource; }; KTimeZoneSource *KTimeZonePrivate::mUtcSource = nullptr; KTimeZonePrivate::KTimeZonePrivate(KTimeZoneSource *src, const QString &nam, const QString &country, float lat, float lon, const QString &cmnt) : source(src), name(nam), countryCode(country.toUpper()), comment(cmnt), latitude(lat), longitude(lon), data(nullptr), refCount(1), cachedTransitionIndex(-1) { // Detect duff values. if (latitude > 90 || latitude < -90) { latitude = KTimeZone::UNKNOWN; } if (longitude > 180 || longitude < -180) { longitude = KTimeZone::UNKNOWN; } } KTimeZonePrivate::KTimeZonePrivate(const KTimeZonePrivate &rhs) : QSharedData(rhs), source(rhs.source), name(rhs.name), countryCode(rhs.countryCode), comment(rhs.comment), latitude(rhs.latitude), longitude(rhs.longitude), refCount(1), cachedTransitionIndex(rhs.cachedTransitionIndex), cachedTransitionStartZoneTime(rhs.cachedTransitionStartZoneTime), cachedTransitionEndZoneTime(rhs.cachedTransitionEndZoneTime), cachedTransitionTimesValid(rhs.cachedTransitionTimesValid) { if (rhs.data) { data = rhs.data->clone(); } else { data = nullptr; } } KTimeZonePrivate &KTimeZonePrivate::operator=(const KTimeZonePrivate &rhs) { // Changing the contents of a KTimeZonePrivate instance by means of operator=() doesn't affect how // many references to it are held. source = rhs.source; name = rhs.name; countryCode = rhs.countryCode; comment = rhs.comment; latitude = rhs.latitude; longitude = rhs.longitude; cachedTransitionIndex = rhs.cachedTransitionIndex; cachedTransitionStartZoneTime = rhs.cachedTransitionStartZoneTime; cachedTransitionEndZoneTime = rhs.cachedTransitionEndZoneTime; cachedTransitionTimesValid = rhs.cachedTransitionTimesValid; delete data; if (rhs.data) { data = rhs.data->clone(); } else { data = nullptr; } // refCount is unchanged return *this; } KTimeZoneSource *KTimeZonePrivate::utcSource() { if (!mUtcSource) { mUtcSource = new KTimeZoneSource; qAddPostRoutine(KTimeZonePrivate::cleanup); } return mUtcSource; } void KTimeZonePrivate::cleanup() { delete mUtcSource; } /******************************************************************************/ Q_GLOBAL_STATIC(KTimeZonePrivate, s_emptyTimeZonePrivate) KTimeZoneBackend::KTimeZoneBackend() : d(s_emptyTimeZonePrivate()) { ++d->refCount; } KTimeZoneBackend::KTimeZoneBackend(const QString &name) : d(new KTimeZonePrivate(KTimeZonePrivate::utcSource(), name, QString(), KTimeZone::UNKNOWN, KTimeZone::UNKNOWN, QString())) {} KTimeZoneBackend::KTimeZoneBackend(KTimeZoneSource *source, const QString &name, const QString &countryCode, float latitude, float longitude, const QString &comment) : d(new KTimeZonePrivate(source, name, countryCode, latitude, longitude, comment)) {} KTimeZoneBackend::KTimeZoneBackend(const KTimeZoneBackend &other) : d(other.d) { ++d->refCount; } KTimeZoneBackend::~KTimeZoneBackend() { if (d && --d->refCount == 0) { delete d; } d = nullptr; } KTimeZoneBackend &KTimeZoneBackend::operator=(const KTimeZoneBackend &other) { if (d != other.d) { if (--d->refCount == 0) { delete d; } d = other.d; ++d->refCount; } return *this; } QByteArray KTimeZoneBackend::type() const { return "KTimeZone"; } KTimeZoneBackend *KTimeZoneBackend::clone() const { return new KTimeZoneBackend(*this); } int KTimeZoneBackend::offsetAtZoneTime(const KTimeZone *caller, const QDateTime &zoneDateTime, int *secondOffset) const { if (!zoneDateTime.isValid() || zoneDateTime.timeSpec() != Qt::LocalTime) { // check for invalid time if (secondOffset) { *secondOffset = KTimeZone::InvalidOffset; } return KTimeZone::InvalidOffset; } const QList transitions = caller->transitions(); int index = d->cachedTransitionIndex; if (index >= 0 && index < transitions.count()) { // There is a cached transition - check whether zoneDateTime uses it. // Caching is used because this method has been found to consume // significant CPU in real life applications. if (!d->cachedTransitionTimesValid) { const int offset = transitions[index].phase().utcOffset(); const int preoffset = (index > 0) ? transitions[index - 1].phase().utcOffset() : d->data ? d->data->previousUtcOffset() : KTimeZone::InvalidOffset; d->cachedTransitionStartZoneTime = transitions[index].time().addSecs(qMax(offset, preoffset)); if (index + 1 < transitions.count()) { const int postoffset = transitions[index + 1].phase().utcOffset(); d->cachedTransitionEndZoneTime = transitions[index + 1].time().addSecs(qMin(offset, postoffset)); } d->cachedTransitionTimesValid = true; } QDateTime dtutc = zoneDateTime; dtutc.setTimeSpec(Qt::UTC); if (dtutc >= d->cachedTransitionStartZoneTime && (index + 1 >= transitions.count() || dtutc < d->cachedTransitionEndZoneTime)) { // The time falls within the cached transition limits, so return its UTC offset const int offset = transitions[index].phase().utcOffset(); if (secondOffset) { *secondOffset = offset; } #ifdef COMPILING_TESTS // qDebug() << "-> Using cache"; // enable the debug area to see this in the tests #endif return offset; } } // The time doesn't fall within the cached transition, or there isn't a cached transition #ifdef COMPILING_TESTS // qDebug() << "-> No cache"; // enable the debug area to see this in the tests #endif bool validTime; int secondIndex = -1; index = caller->transitionIndex(zoneDateTime, (secondOffset ? &secondIndex : nullptr), &validTime); const KTimeZone::Transition *tr = (index >= 0) ? &transitions[index] : nullptr; const int offset = tr ? tr->phase().utcOffset() : validTime ? (d->data ? d->data->previousUtcOffset() : KTimeZone::InvalidOffset) : KTimeZone::InvalidOffset; if (secondOffset) { *secondOffset = (secondIndex >= 0) ? transitions.at(secondIndex).phase().utcOffset() : offset; } // Cache transition data for subsequent date/time values which occur after the same transition. d->cachedTransitionIndex = index; d->cachedTransitionTimesValid = false; return offset; } int KTimeZoneBackend::offsetAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const { if (!utcDateTime.isValid() || utcDateTime.timeSpec() != Qt::UTC) { // check for invalid time return 0; } const QList transitions = caller->transitions(); int index = d->cachedTransitionIndex; if (index >= 0 && index < transitions.count()) { // There is a cached transition - check whether utcDateTime uses it. if (utcDateTime >= transitions[index].time() && (index + 1 >= transitions.count() || utcDateTime < transitions[index + 1].time())) { // The time falls within the cached transition, so return its UTC offset #ifdef COMPILING_TESTS // qDebug() << "Using cache"; // enable the debug area to see this in the tests #endif return transitions[index].phase().utcOffset(); } } // The time doesn't fall within the cached transition, or there isn't a cached transition #ifdef COMPILING_TESTS // qDebug() << "No cache"; // enable the debug area to see this in the tests #endif index = caller->transitionIndex(utcDateTime); d->cachedTransitionIndex = index; // cache transition data d->cachedTransitionTimesValid = false; const KTimeZone::Transition *tr = (index >= 0) ? &transitions.at(index) : nullptr; return tr ? tr->phase().utcOffset() : (d->data ? d->data->previousUtcOffset() : KTimeZone::InvalidOffset); } int KTimeZoneBackend::offset(const KTimeZone *caller, time_t t) const { return offsetAtUtc(caller, KTimeZone::fromTime_t(t)); } bool KTimeZoneBackend::isDstAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const { if (!utcDateTime.isValid() || utcDateTime.timeSpec() != Qt::UTC) { // check for invalid time return false; } const KTimeZone::Transition *tr = caller->transition(utcDateTime); if (!tr) { return false; } return tr->phase().isDst(); } bool KTimeZoneBackend::isDst(const KTimeZone *caller, time_t t) const { return isDstAtUtc(caller, KTimeZone::fromTime_t(t)); } bool KTimeZoneBackend::hasTransitions(const KTimeZone *caller) const { Q_UNUSED(caller); return false; } /******************************************************************************/ #if SIZEOF_TIME_T == 8 const time_t KTimeZone::InvalidTime_t = 0x800000000000000LL; #else const time_t KTimeZone::InvalidTime_t = 0x80000000; #endif const int KTimeZone::InvalidOffset = 0x80000000; const float KTimeZone::UNKNOWN = 1000.0; KTimeZone::KTimeZone() : d(new KTimeZoneBackend()) {} KTimeZone::KTimeZone(const QString &name) : d(new KTimeZoneBackend(name)) {} KTimeZone::KTimeZone(const KTimeZone &tz) : d(tz.d->clone()) {} KTimeZone::~KTimeZone() { delete d; } KTimeZone::KTimeZone(KTimeZoneBackend *impl) : d(impl) { // 'impl' should be a newly constructed object, with refCount = 1 Q_ASSERT(d->d->refCount == 1 || d->d == s_emptyTimeZonePrivate()); } KTimeZone &KTimeZone::operator=(const KTimeZone &tz) { if (d != tz.d) { delete d; d = tz.d->clone(); } return *this; } bool KTimeZone::operator==(const KTimeZone &rhs) const { return d->d == rhs.d->d; } QByteArray KTimeZone::type() const { return d->type(); } bool KTimeZone::isValid() const { return !d->d->name.isEmpty(); } QString KTimeZone::countryCode() const { return d->d->countryCode; } float KTimeZone::latitude() const { return d->d->latitude; } float KTimeZone::longitude() const { return d->d->longitude; } QString KTimeZone::comment() const { return d->d->comment; } QString KTimeZone::name() const { return d->d->name; } QList KTimeZone::abbreviations() const { if (!data(true)) { return QList(); } return d->d->data->abbreviations(); } QByteArray KTimeZone::abbreviation(const QDateTime &utcDateTime) const { if (utcDateTime.timeSpec() != Qt::UTC || !data(true)) { return QByteArray(); } return d->d->data->abbreviation(utcDateTime); } QList KTimeZone::utcOffsets() const { if (!data(true)) { return QList(); } return d->d->data->utcOffsets(); } QList KTimeZone::phases() const { if (!data(true)) { return QList(); } return d->d->data->phases(); } bool KTimeZone::hasTransitions() const { return d->hasTransitions(this); } QList KTimeZone::transitions(const QDateTime &start, const QDateTime &end) const { if (!data(true)) { return QList(); } return d->d->data->transitions(start, end); } const KTimeZone::Transition *KTimeZone::transition(const QDateTime &dt, const Transition **secondTransition, bool *validTime) const { if (!data(true)) { if (validTime) { *validTime = false; } return nullptr; } return d->d->data->transition(dt, secondTransition, validTime); } int KTimeZone::transitionIndex(const QDateTime &dt, int *secondIndex, bool *validTime) const { if (!data(true)) { if (validTime) { *validTime = false; } return -1; } return d->d->data->transitionIndex(dt, secondIndex, validTime); } QList KTimeZone::transitionTimes(const Phase &phase, const QDateTime &start, const QDateTime &end) const { if (!data(true)) { return QList(); } return d->d->data->transitionTimes(phase, start, end); } QList KTimeZone::leapSecondChanges() const { if (!data(true)) { return QList(); } return d->d->data->leapSecondChanges(); } KTimeZoneSource *KTimeZone::source() const { return d->d->source; } const KTimeZoneData *KTimeZone::data(bool create) const { if (!isValid()) { return nullptr; } if (create && !d->d->data && d->d->source->useZoneParse()) { d->d->data = d->d->source->parse(*this); } return d->d->data; } void KTimeZone::setData(KTimeZoneData *data, KTimeZoneSource *source) { if (!isValid()) { return; } delete d->d->data; d->d->data = data; if (source) { d->d->source = source; } } bool KTimeZone::updateBase(const KTimeZone &other) { if (d->d->name.isEmpty() || d->d->name != other.d->d->name) { return false; } d->d->countryCode = other.d->d->countryCode; d->d->comment = other.d->d->comment; d->d->latitude = other.d->d->latitude; d->d->longitude = other.d->d->longitude; return true; } bool KTimeZone::parse() const { if (!isValid()) { return false; } if (d->d->source->useZoneParse()) { delete d->d->data; d->d->data = d->d->source->parse(*this); } return d->d->data; } QDateTime KTimeZone::toUtc(const QDateTime &zoneDateTime) const { if (!zoneDateTime.isValid() || zoneDateTime.timeSpec() != Qt::LocalTime) { return QDateTime(); } const int secs = offsetAtZoneTime(zoneDateTime); if (secs == InvalidOffset) { return QDateTime(); } QDateTime dt = zoneDateTime; dt.setTimeSpec(Qt::UTC); return dt.addSecs(-secs); } QDateTime KTimeZone::toZoneTime(const QDateTime &utcDateTime, bool *secondOccurrence) const { if (secondOccurrence) { *secondOccurrence = false; } if (!utcDateTime.isValid() || utcDateTime.timeSpec() != Qt::UTC) { // check for invalid time return QDateTime(); } // Convert UTC to local time if (hasTransitions()) { if (!data(true)) { // No data - default to UTC QDateTime dt = utcDateTime; dt.setTimeSpec(Qt::LocalTime); return dt; } const KTimeZoneData *data = d->d->data; const int index = data->transitionIndex(utcDateTime); const int secs = (index >= 0) ? data->transitions().at(index).phase().utcOffset() : data->previousUtcOffset(); QDateTime dt = utcDateTime.addSecs(secs); if (secondOccurrence) { // Check whether the local time occurs twice around a daylight savings time // shift, and if so, whether it's the first or second occurrence. *secondOccurrence = data->d->isSecondOccurrence(dt, index); } dt.setTimeSpec(Qt::LocalTime); return dt; } else { const int secs = offsetAtUtc(utcDateTime); QDateTime dt = utcDateTime.addSecs(secs); dt.setTimeSpec(Qt::LocalTime); if (secondOccurrence) { // Check whether the local time occurs twice around a daylight savings time // shift, and if so, whether it's the first or second occurrence. *secondOccurrence = (secs != offsetAtZoneTime(dt)); } return dt; } } QDateTime KTimeZone::convert(const KTimeZone &newZone, const QDateTime &zoneDateTime) const { if (newZone == *this) { if (zoneDateTime.timeSpec() != Qt::LocalTime) { return QDateTime(); } return zoneDateTime; } return newZone.toZoneTime(toUtc(zoneDateTime)); } int KTimeZone::offsetAtZoneTime(const QDateTime &zoneDateTime, int *secondOffset) const { return d->offsetAtZoneTime(this, zoneDateTime, secondOffset); } int KTimeZone::offsetAtUtc(const QDateTime &utcDateTime) const { return d->offsetAtUtc(this, utcDateTime); } int KTimeZone::offset(time_t t) const { return d->offset(this, t); } int KTimeZone::currentOffset(Qt::TimeSpec basis) const { // Get current offset of this time zone to UTC const time_t now = time(nullptr); const int secs = offset(now); switch (basis) { case Qt::LocalTime: // Return the current offset of this time zone to the local system time return secs - gmtoff(now); case Qt::UTC: // Return the current offset of this time zone to UTC return secs; default: break; } return 0; } bool KTimeZone::isDstAtUtc(const QDateTime &utcDateTime) const { return d->isDstAtUtc(this, utcDateTime); } bool KTimeZone::isDst(time_t t) const { return d->isDst(this, t); } KTimeZone KTimeZone::utc() { static KTimeZone utcZone(QLatin1String("UTC")); return utcZone; } QDateTime KTimeZone::fromTime_t(time_t t) { static const int secondsADay = 86400; static const QDate epochDate(1970, 1, 1); static const QTime epochTime(0, 0, 0); int days = t / secondsADay; int secs; if (t >= 0) { secs = t % secondsADay; } else { secs = secondsADay - (-t % secondsADay); --days; } return QDateTime(epochDate.addDays(days), epochTime.addSecs(secs), Qt::UTC); } time_t KTimeZone::toTime_t(const QDateTime &utcDateTime) { static const QDate epochDate(1970, 1, 1); static const QTime epochTime(0, 0, 0); if (utcDateTime.timeSpec() != Qt::UTC) { return InvalidTime_t; } const qint64 days = epochDate.daysTo(utcDateTime.date()); const qint64 secs = epochTime.secsTo(utcDateTime.time()); const qint64 t64 = days * 86400 + secs; const time_t t = static_cast(t64); if (static_cast(t) != t64) { return InvalidTime_t; } return t; } /******************************************************************************/ class KTimeZoneSourcePrivate { public: bool mUseZoneParse; }; KTimeZoneSource::KTimeZoneSource() : d(new KTimeZoneSourcePrivate) { d->mUseZoneParse = true; } KTimeZoneSource::KTimeZoneSource(bool useZoneParse) : d(new KTimeZoneSourcePrivate) { d->mUseZoneParse = useZoneParse; } KTimeZoneSource::~KTimeZoneSource() { delete d; } KTimeZoneData *KTimeZoneSource::parse(const KTimeZone &) const { Q_ASSERT(d->mUseZoneParse); // method should never be called if it isn't usable return new KTimeZoneData; } bool KTimeZoneSource::useZoneParse() const { return d->mUseZoneParse; } /******************************************************************************/ class KTimeZoneLeapSecondsPrivate { public: QDateTime dt; // UTC time when this change occurred QString comment; // optional comment int seconds; // number of leap seconds }; KTimeZone::LeapSeconds::LeapSeconds() : d(new KTimeZoneLeapSecondsPrivate) { } KTimeZone::LeapSeconds::LeapSeconds(const QDateTime &utc, int leap, const QString &cmt) : d(new KTimeZoneLeapSecondsPrivate) { if (utc.timeSpec() == Qt::UTC) { // invalid if start time is not UTC d->dt = utc; d->comment = cmt; d->seconds = leap; } } KTimeZone::LeapSeconds::LeapSeconds(const KTimeZone::LeapSeconds &c) : d(new KTimeZoneLeapSecondsPrivate) { d->dt = c.d->dt; d->comment = c.d->comment; d->seconds = c.d->seconds; } KTimeZone::LeapSeconds::~LeapSeconds() { delete d; } KTimeZone::LeapSeconds &KTimeZone::LeapSeconds::operator=(const KTimeZone::LeapSeconds &c) { d->dt = c.d->dt; d->comment = c.d->comment; d->seconds = c.d->seconds; return *this; } bool KTimeZone::LeapSeconds::operator<(const KTimeZone::LeapSeconds &c) const { return d->dt < c.d->dt; } QDateTime KTimeZone::LeapSeconds::dateTime() const { return d->dt; } bool KTimeZone::LeapSeconds::isValid() const { return d->dt.isValid(); } int KTimeZone::LeapSeconds::leapSeconds() const { return d->seconds; } QString KTimeZone::LeapSeconds::comment() const { return d->comment; } /******************************************************************************/ int KTimeZoneDataPrivate::transitionIndex(const QDateTime &dt) const { // Do a binary search to find the last transition before this date/time int start = -1; int end = transitions.count(); if (dt.timeSpec() == Qt::UTC) { while (end - start > 1) { int i = (start + end) / 2; if (dt < transitions[i].time()) { end = i; } else { start = i; } } } else { QDateTime dtutc = dt; dtutc.setTimeSpec(Qt::UTC); while (end - start > 1) { const int i = (start + end) / 2; if (dtutc.addSecs(-transitions[i].phase().utcOffset()) < transitions[i].time()) { end = i; } else { start = i; } } } return end ? start : -1; } // Find the indexes to the transitions at or after start, and before or at end. // start and end must be UTC. // Reply = false if none. bool KTimeZoneDataPrivate::transitionIndexes(const QDateTime &start, const QDateTime &end, int &ixstart, int &ixend) const { ixstart = 0; if (start.isValid() && start.timeSpec() == Qt::UTC) { ixstart = transitionIndex(start); if (ixstart < 0) { ixstart = 0; } else if (transitions[ixstart].time() < start) { if (++ixstart >= transitions.count()) { return false; // there are no transitions at/after 'start' } } } ixend = -1; if (end.isValid() && end.timeSpec() == Qt::UTC) { ixend = transitionIndex(end); if (ixend < 0) { return false; // there are no transitions at/before 'end' } } return true; } /* Check if it's a local time which occurs both before and after the specified * transition (for which it has to span a daylight saving to standard time change). * @param utcLocalTime local time set to Qt::UTC */ bool KTimeZoneDataPrivate::isSecondOccurrence(const QDateTime &utcLocalTime, int transitionIndex) const { if (transitionIndex < 0) { return false; } const int offset = transitions[transitionIndex].phase().utcOffset(); const int prevoffset = (transitionIndex > 0) ? transitions[transitionIndex - 1].phase().utcOffset() : prePhase.utcOffset(); const int phaseDiff = prevoffset - offset; if (phaseDiff <= 0) { return false; } // Find how long after the start of the latest phase 'dt' is const qint64 afterStart = transitions[transitionIndex].time().msecsTo(utcLocalTime)/1000 - offset; return (afterStart < phaseDiff); } KTimeZoneData::KTimeZoneData() : d(new KTimeZoneDataPrivate) { } KTimeZoneData::KTimeZoneData(const KTimeZoneData &c) : d(new KTimeZoneDataPrivate) { d->phases = c.d->phases; d->transitions = c.d->transitions; d->leapChanges = c.d->leapChanges; d->utcOffsets = c.d->utcOffsets; d->abbreviations = c.d->abbreviations; d->prePhase = c.d->prePhase; } KTimeZoneData::~KTimeZoneData() { delete d; } KTimeZoneData &KTimeZoneData::operator=(const KTimeZoneData &c) { d->phases = c.d->phases; d->transitions = c.d->transitions; d->leapChanges = c.d->leapChanges; d->utcOffsets = c.d->utcOffsets; d->abbreviations = c.d->abbreviations; d->prePhase = c.d->prePhase; return *this; } KTimeZoneData *KTimeZoneData::clone() const { return new KTimeZoneData(*this); } QList KTimeZoneData::abbreviations() const { if (d->abbreviations.isEmpty()) { for (int i = 0, end = d->phases.count(); i < end; ++i) { const QList abbrevs = d->phases[i].abbreviations(); for (int j = 0, jend = abbrevs.count(); j < jend; ++j) if (!d->abbreviations.contains(abbrevs[j])) { d->abbreviations.append(abbrevs[j]); } } if (d->abbreviations.isEmpty()) { d->abbreviations += "UTC"; } } return d->abbreviations; } QByteArray KTimeZoneData::abbreviation(const QDateTime &utcDateTime) const { if (d->phases.isEmpty()) { return "UTC"; } const KTimeZone::Transition *tr = transition(utcDateTime); const QList abbrevs = tr ? tr->phase().abbreviations() : d->prePhase.abbreviations(); if (abbrevs.isEmpty()) { return QByteArray(); } return abbrevs[0]; } QList KTimeZoneData::utcOffsets() const { if (d->utcOffsets.isEmpty()) { for (int i = 0, end = d->phases.count(); i < end; ++i) { const int offset = d->phases[i].utcOffset(); if (!d->utcOffsets.contains(offset)) { d->utcOffsets.append(offset); } } if (d->utcOffsets.isEmpty()) { d->utcOffsets += 0; } else { qSort(d->utcOffsets); } } return d->utcOffsets; } QList KTimeZoneData::phases() const { return d->phases; } void KTimeZoneData::setPhases(const QList &phases, const KTimeZone::Phase &previousPhase) { d->phases = phases; d->prePhase = previousPhase; } void KTimeZoneData::setPhases(const QList &phases, int previousUtcOffset) { d->phases = phases; d->prePhase = KTimeZone::Phase(previousUtcOffset, QByteArray(), false); } bool KTimeZoneData::hasTransitions() const { return false; } QList KTimeZoneData::transitions(const QDateTime &start, const QDateTime &end) const { int ixstart, ixend; if (!d->transitionIndexes(start, end, ixstart, ixend)) { return QList(); // there are no transitions within the time period } if (ixend >= 0) { return d->transitions.mid(ixstart, ixend - ixstart + 1); } if (ixstart > 0) { return d->transitions.mid(ixstart); } return d->transitions; } void KTimeZoneData::setTransitions(const QList &transitions) { d->transitions = transitions; } int KTimeZoneData::previousUtcOffset() const { return d->prePhase.utcOffset(); } const KTimeZone::Transition *KTimeZoneData::transition(const QDateTime &dt, const KTimeZone::Transition **secondTransition, bool *validTime) const { int secondIndex; const int index = transitionIndex(dt, (secondTransition ? &secondIndex : nullptr), validTime); if (secondTransition) { *secondTransition = (secondIndex >= 0) ? &d->transitions[secondIndex] : nullptr; } return (index >= 0) ? &d->transitions[index] : nullptr; } int KTimeZoneData::transitionIndex(const QDateTime &dt, int *secondIndex, bool *validTime) const { if (validTime) { *validTime = true; } // Find the last transition before this date/time int index = d->transitionIndex(dt); if (dt.timeSpec() == Qt::UTC) { if (secondIndex) { *secondIndex = index; } return index; } else { /* Check whether the specified local time actually occurs. * Find the start of the next phase, and check if it falls in the gap * between the two phases. */ QDateTime dtutc = dt; dtutc.setTimeSpec(Qt::UTC); const int count = d->transitions.count(); const int next = (index >= 0) ? index + 1 : 0; if (next < count) { KTimeZone::Phase nextPhase = d->transitions.at(next).phase(); const int offset = (index >= 0) ? d->transitions.at(index).phase().utcOffset() : d->prePhase.utcOffset(); const int phaseDiff = nextPhase.utcOffset() - offset; if (phaseDiff > 0) { // Get UTC equivalent as if 'dt' was in the next phase if (dtutc.msecsTo(d->transitions.at(next).time())/1000 + nextPhase.utcOffset() <= phaseDiff) { // The time falls in the gap between the two phases, // so return an invalid value. if (validTime) { *validTime = false; } if (secondIndex) { *secondIndex = -1; } return -1; } } } if (index < 0) { // The specified time is before the first phase if (secondIndex) { *secondIndex = -1; } return -1; } /* Check if it's a local time which occurs both before and after the 'latest' * phase start time (for which it has to span a daylight saving to standard * time change). */ bool duplicate = true; if (d->isSecondOccurrence(dtutc, index)) { // 'dt' occurs twice if (secondIndex) { *secondIndex = index; duplicate = false; } // Get the transition containing the first occurrence of 'dt' if (index <= 0) { return -1; // first occurrence of 'dt' is just before the first transition } --index; } if (secondIndex && duplicate) { *secondIndex = index; } return index; } } QList KTimeZoneData::transitionTimes(const KTimeZone::Phase &phase, const QDateTime &start, const QDateTime &end) const { QList times; int ixstart, ixend; if (d->transitionIndexes(start, end, ixstart, ixend)) { if (ixend < 0) { ixend = d->transitions.count() - 1; } while (ixstart <= ixend) { if (d->transitions[ixstart].phase() == phase) { times += d->transitions[ixstart].time(); } } } return times; } QList KTimeZoneData::leapSecondChanges() const { return d->leapChanges; } void KTimeZoneData::setLeapSecondChanges(const QList &adjusts) { d->leapChanges = adjusts; } KTimeZone::LeapSeconds KTimeZoneData::leapSecondChange(const QDateTime &utc) const { if (utc.timeSpec() != Qt::UTC) { qCritical() << "KTimeZoneData::leapSecondChange(): non-UTC time specified" << endl; } else { for (int i = d->leapChanges.count(); --i >= 0;) { if (d->leapChanges[i].dateTime() < utc) { return d->leapChanges[i]; } } } return KTimeZone::LeapSeconds(); } diff --git a/src/kdecore/ktimezone.h b/src/kdecore/ktimezone.h index 76ab4db9..0d4438df 100644 --- a/src/kdecore/ktimezone.h +++ b/src/kdecore/ktimezone.h @@ -1,1532 +1,1532 @@ /* This file is part of the KDE libraries Copyright (c) 2005-2007 David Jarvie Copyright (c) 2005 S.R.Haque . 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. */ /** @file * Time zone functions * @author David Jarvie . * @author S.R.Haque . */ #ifndef _KTIMEZONES_H #define _KTIMEZONES_H #include #include #include #include #include #include #include #include #include class KTimeZone; class KTimeZoneBackend; class KTimeZoneData; class KTimeZoneSource; class KTimeZonesPrivate; class KTimeZonePrivate; class KTimeZoneSourcePrivate; class KTimeZoneDataPrivate; class KTimeZoneTransitionPrivate; class KTimeZoneLeapSecondsPrivate; /** @defgroup timezones Time zone classes * * The time zone classes provide a framework for accessing time zone data, and * converting times and dates between different time zones. They provide access * to the system time zone database, and also allow developers to derive classes * to access custom sources of time zone information such as calendar files. * * A time zone is represented by the KTimeZone class. This provides access to * the time zone's detailed definition and contains methods to convert times to * and from that zone. In order to save processing, KTimeZone obtains its time * zone details only when they are actually required. Each KTimeZone class has * a corresponding KTimeZoneBackend backend class which implements reference * counting of the time zone's data. * * A collection of time zones is represented by the KTimeZones class, which acts * as a container of KTimeZone objects. Within any KTimeZones object, each * KTimeZone instance is uniquely identified by its name. Typically, each * individual source of time zone information would be represented by a different * KTimeZones object. This scheme allows conflicting time zone definitions * between the different sources to be handled, since KTimeZone names need only * be unique within a single KTimeZones object. Note that KTimeZone instances do * not have to belong to any KTimeZones container. * * Time zone source data can come in all sorts of different forms: TZFILE format * for a UNIX system time zone database, definitions within calendar files, calls * to libraries (e.g. libc), etc. The KTimeZoneSource class provides reading and * parsing functions to access such data, handing off the parsed data for a * specific time zone in a KTimeZoneData object. Both of these are base classes * from which should be derived other classes which know about the particular * access method and data format (KTimeZoneSource) and which details are actually * provided (KTimeZoneData). When a KTimeZone instance needs its time zone's * definition, it calls KTimeZoneSource::parse() and receives the data back in a * KTimeZoneData object which it keeps for reference. * * KTimeZoneData holds the definitions of the different daylight saving time and * standard time phases in KTimeZone::Phase objects, and the timed sequence of * daylight saving time changes in KTimeZone::Transition objects. Leap seconds * adjustments are held in KTimeZone::LeapSeconds objects. You can access this * data directly via KTimeZone and KTimeZoneData methods if required. * * The mapping of the different classes to external data is as follows: * * - Each different source data format or access method is represented by a * different KTimeZoneSource class. * * - Each different set of data provided from source data is represented by a * different KTimeZoneData class. For example, some time zone sources provide * only the absolute basic information about time zones, i.e. name, transition * times and offsets from UTC. Others provide information on leap second * adjustments, while still others might contain information on which countries * use the time zone. To allow for this variation, KTimeZoneData is made * available for inheritance. When the necessary information is not available, * the KTimeZone::Phase, KTimeZone::Transition and KTimeZone::LeapSeconds data * will be empty. * * - Each KTimeZoneData class will have a corresponding KTimeZone class, and * related KTimeZoneBackend class, which can interpret its data. * * - Each different source database will typically be represented by a different * KTimeZones instance, to avoid possible conflicts between time zone definitions. * If it is known that two source databases are definitely compatible, they can * be grouped together into the same KTimeZones instance. * * * \section sys System time zones * * Access to system time zones is provided by the KSystemTimeZones class, which * reads the zone.tab file to obtain the list of system time zones, and creates a * KSystemTimeZone instance for each one. KSystemTimeZone has a * KSystemTimeZoneBackend backend class, and uses the KSystemTimeZoneSource * and KSystemTimeZoneData classes to obtain time zone data via libc library * functions. * * Normally, KSystemTimeZoneSource and KSystemTimeZoneData operate in the * background and you will not need to use them directly. * * @warning The KSystemTimeZone class uses the standard system libraries to * access time zone data, and its functionality is limited to what these libraries * provide. On many systems, dates earlier than 1902 are not handled, and on * non-GNU systems there is no guarantee that the time zone abbreviation returned * for a given date will be correct if the abbreviations applicable then were * not those currently in use. The KSystemTimeZones::readZone() method overcomes * these restrictions by reading the time zone definition directly from the * system time zone database files. * * \section tzfile Tzfile access * * The KTzfileTimeZone class provides access to tzfile(5) time zone definition * files, which are used to form the time zone database on UNIX systems. Usually, * for current information, it is easier to use the KSystemTimeZones class to * access system tzfile data. However, for dealing with past data the * KTzfileTimeZone class provides better guarantees of accurary, although it * cannot handle dates earlier than 1902. It also provides more detailed * information, and allows you to read non-system tzfile files. Alternatively, * the KSystemTimeZones::readZone() method uses the KTzfileTimeZone class to * read system time zone definition files. * * KTzfileTimeZone has a KTzfileTimeZoneBackend backend class, and uses the * KTzfileTimeZoneSource and KTzfileTimeZoneData classes to obtain time zone * data from tzfile files. * * * \section deriving Handling time zone data from other sources * * To implement time zone classes to access a new time zone data source, you need * as a minimum to derive a new class from KTimeZoneSource, and implement one or * more parse() methods. If you can know in advance what KTimeZone instances to create * without having to parse the source data, you should reimplement the virtual method * KTimeZoneSource::parse(const KTimeZone&). Otherwise, you need to define your * own parse() methods with appropriate signatures, to both read and parse the new * data, and create new KTimeZone instances. * * If the data for each time zone which is available from the new source happens * to be the same as for another source for which KTimeZone classes already exist, * you could simply use the existing KTimeZone, KTimeZoneBackend and KTimeZoneData * derived classes to receive the parsed data from your new KTimeZoneSource class: * * \code * class NewTimeZoneSource : public KTimeZoneSource * { * public: * NewTimeZoneSource(...); // parameters might include location of data source ... * ~NewTimeZoneSource(); * * // Option 1: reimplement KTimeZoneSource::parse() if you can * // pre-create the KTimeZone instances. * KTimeZoneData *parse(const KTimeZone &zone) const; * * // Option 2: implement new parse() methods if you don't know * // in advance what KTimeZone instances to create. * void parse(..., KTimeZones *zones) const; * NewTimeZone *parse(...) const; * }; * * // Option 1: * KTimeZoneData *NewTimeZoneSource::parse(const KTimeZone &zone) const * { * QString zoneName = zone.name(); * ExistingTimeZoneData* data = new ExistingTimeZoneData(); * * // Read the data for 'zoneName' from the new data source. * * // Parse what we have read, and write it into 'data'. * // Compile the sequence of daylight savings changes and leap * // seconds adjustments (if available) and write into 'data'. * * return data; * } * \endcode * * If the data from the new source is different from what any existing * KTimeZoneData class contains, you will need to implement new KTimeZone, * KTimeZoneBackend and KTimeZoneData classes in addition to the KTimeZoneSource * class illustrated above: * * \code * class NewTimeZone : public KTimeZone * { * public: * NewTimeZone(NewTimeZoneSource *source, const QString &name, ...); * ~NewTimeZone(); * * // Methods implementing KTimeZone virtual methods are implemented * // in NewTimeZoneBackend, not here. * * // Anything else which you need * private: * // No d-pointer ! * }; * * class NewTimeZoneBackend : public KTimeZoneBackend * { * public: * NewTimeZoneBackend(NewTimeZoneSource *source, const QString &name, ...); * ~NewTimeZoneBackend(); * * KTimeZoneBackend *clone() const; * * // Virtual methods which need to be reimplemented * int offsetAtZoneTime(const KTimeZone *caller, const QDateTime &zoneDateTime, int *secondOffset = 0) const; * int offsetAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const; * int offset(const KTimeZone *caller, time_t t) const; * int isDstAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const; * bool isDst(const KTimeZone *caller, time_t t) const; * * // Anything else which you need * private: * NewTimeZonePrivate *d; // non-const ! * }; * * class NewTimeZoneData : public KTimeZoneData * { * friend class NewTimeZoneSource; * * public: * NewTimeZoneData(); * ~NewTimeZoneData(); * * // Virtual methods which need to be reimplemented * KTimeZoneData *clone() const; * QList abbreviations() const; * QByteArray abbreviation(const QDateTime &utcDateTime) const; * * // Data members containing whatever is read by NewTimeZoneSource * }; * \endcode * * Here is a guide to implementing the offset() and offsetAtUtc() methods, in * the case where the source data does not use time_t for its time measurement: * * \code * int NewTimeZoneBackend::offsetAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const * { * // Access this time zone's data. If we haven't already read it, * // force a read from source now. * NewTimeZoneData *zdata = caller->data(true); * * // Use 'zdata' contents to work out the UTC offset * * return offset; * } * * int NewTimeZoneBackend::offset(const KTimeZone *caller, time_t t) const * { * return offsetAtUtc(KTimeZone::fromTime_t(t)); * } * \endcode * * The other NewTimeZoneBackend methods would work in an analogous way to * NewTimeZoneBackend::offsetAtUtc() and NewTimeZoneBackend::offset(). */ /** * The KTimeZones class represents a time zone database which consists of a * collection of individual time zone definitions. * * Each individual time zone is defined in a KTimeZone instance, which provides * generic support for private or system time zones. The time zones in the * collection are indexed by name, which must be unique within the collection. * * Different time zone sources could define the same time zone differently. (For * example, a calendar file originating from another system might hold its own * time zone definitions, which may not necessarily be identical to your own * system's definitions.) In order to keep conflicting definitions separate, * it will often be necessary when dealing with multiple time zone sources to * create a separate KTimeZones instance for each source collection. * * If you want to access system time zones, use the KSystemTimeZones class. * * @short Represents a time zone database or collection * @ingroup timezones * @author David Jarvie . * @author S.R.Haque . */ class KDELIBS4SUPPORT_EXPORT KTimeZones { public: KTimeZones(); ~KTimeZones(); /** * Returns the time zone with the given name. * * @param name name of time zone * @return time zone, or 0 if not found */ KTimeZone zone(const QString &name) const; /** Map of KTimeZone instances, indexed by time zone name. */ typedef QMap ZoneMap; /** * Returns all the time zones defined in this collection. * * @return time zone collection, indexed by time zone name */ const ZoneMap zones() const; /** * Adds a time zone to the collection. * The time zone's name must be unique within the collection. * * @param zone time zone to add * @return @c true if successful, @c false if zone's name duplicates one already in the collection * @see remove() */ bool add(const KTimeZone &zone); /** * Removes a time zone from the collection. * * @param zone time zone to remove * @return the time zone which was removed, or invalid if not found * @see clear(), add() */ KTimeZone remove(const KTimeZone &zone); /** * Removes a time zone from the collection. * * @param name name of time zone to remove * @return the time zone which was removed, or invalid if not found * @see clear(), add() */ KTimeZone remove(const QString &name); /** * Clears the collection. * * @see remove() */ void clear(); private: KTimeZones(const KTimeZones &); // prohibit copying KTimeZones &operator=(const KTimeZones &); // prohibit copying KTimeZonesPrivate *const d; }; /** * Base class representing a time zone. * * The KTimeZone base class contains general descriptive data about the time zone, and * provides an interface for methods to read and parse time zone definitions, and to * translate between UTC and local time. Derived classes must implement these methods, * and may also hold the actual details of the dates and times of daylight savings * changes, offsets from UTC, etc. They should be tailored to deal with the type and * format of data held by a particular type of time zone database. * * If this base class is instantiated as a valid instance, it always represents the * UTC time zone. * * KTimeZone is designed to work in partnership with KTimeZoneSource. KTimeZone * provides access to individual time zones, while classes derived from * KTimeZoneSource read and parse a particular format of time zone definition. * Because time zone sources can differ in what information they provide about time zones, * the parsed data retured by KTimeZoneSource can vary between different sources, * resulting in the need to create different KTimeZone classes to handle the data. * * KTimeZone instances are often grouped into KTimeZones collections. * - * Copying KTimeZone instances is very efficient since the class data is explicitly + * Copying KTimeZone instances is very efficient since the class data is KDELIBS4SUPPORT_DEPRECATED explicitly * shared, meaning that only a pointer to the data is actually copied. To achieve * this, each class inherited from KTimeZone must have a corresponding backend * class derived from KTimeZoneBackend. * * @note Classes derived from KTimeZone should not have their own d-pointer. The * d-pointer is instead contained in their backend class (derived from * KTimeZoneBackend). This allows KTimeZone's reference-counting of private data to * take care of the derived class's data as well, ensuring that instance data is * not deleted while any references to the class instance remains. All virtual * methods which override KTimeZone virtual methods must be defined in the * backend class instead. * * @short Base class representing a time zone * @see KTimeZoneBackend, KTimeZoneSource, KTimeZoneData * @ingroup timezones * @author David Jarvie . * @author S.R.Haque . */ class KDELIBS4SUPPORT_EXPORT KTimeZone //krazy:exclude=dpointer (has non-const d-pointer to Backend class) { public: /* * Time zone phase. * * A phase can be daylight savings time or standard time. It holds the * UTC offset and time zone abbreviation (e.g. EST, GMT). * * @short Time zone phase * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT Phase { public: /** * Default constructor. * Creates a standard-time time zone phase with UTC offset 0. */ Phase(); /** * Constructor. * * @param utcOffset number of seconds to add to UTC to get local time in this phase * @param abbreviations time zone abbreviation for this phase. If translations exist, * concatenate all abbreviations as null-terminated strings. * @param dst true if daylight savings time, false if standard time * @param comment optional comment */ Phase(int utcOffset, const QByteArray &abbreviations, bool dst, const QString &comment = QString()); /** * Constructor. * * @param utcOffset number of seconds to add to UTC to get local time in this phase * @param abbreviations time zone abbreviation for this phase, plus any translations * @param dst true if daylight savings time, false if standard time * @param comment optional comment */ Phase(int utcOffset, const QList &abbreviations, bool dst, const QString &comment = QString()); Phase(const Phase &rhs); ~Phase(); Phase &operator=(const Phase &rhs); bool operator==(const Phase &rhs) const; bool operator!=(const Phase &rhs) const { return !operator==(rhs); } /** * Return the UTC offset in seconds during this phase. * The UTC offset is the number of seconds which you must add to UTC * to get local time. * * @return offset in seconds to add to UTC */ int utcOffset() const; /** * Return the time zone abbreviations which apply to this phase. * * More than one abbreviation may be returned, to allow for possible translations. * * @return time zone abbreviations */ QList abbreviations() const; /** * Return whether daylight savings time applies during this phase. * * @return true if daylight savings are in operation, false otherwise */ bool isDst() const; /** * Return the comment (if any) applying to this phase. * * @return comment */ QString comment() const; private: QSharedDataPointer d; }; /* * Time zone daylight saving time transition. * * A Transition instance holds details of a transition to daylight saving time or * standard time, including the UTC time of the change. * * @short Time zone transition * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT Transition { public: Transition(); Transition(const QDateTime &dt, const Phase &phase); Transition(const KTimeZone::Transition &t); ~Transition(); Transition &operator=(const KTimeZone::Transition &t); /** * Return the UTC time of the transition. * * @return UTC time */ QDateTime time() const; /** * Return the time zone phase which takes effect after the transition. * * @return time zone phase */ Phase phase() const; /** * Compare the date/time values of two transitions. * * @param rhs other instance * @return @c true if this Transition is earlier than @p rhs */ bool operator<(const Transition &rhs) const; private: KTimeZoneTransitionPrivate *const d; }; /* * Leap seconds adjustment for a time zone. * * This class defines a leap seconds adjustment for a time zone by its UTC time of * occurrence and the cumulative number of leap seconds to be added at that time. * * @short Leap seconds adjustment for a time zone * @see KTimeZone, KTimeZoneData * @ingroup timezones * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT LeapSeconds { public: LeapSeconds(); LeapSeconds(const QDateTime &utcTime, int leapSeconds, const QString &comment = QString()); LeapSeconds(const LeapSeconds &c); ~LeapSeconds(); LeapSeconds &operator=(const LeapSeconds &c); bool operator<(const LeapSeconds &c) const; // needed by qSort() /** * Return whether this instance holds valid data. * * @return true if valid, false if invalid */ bool isValid() const; /** * Return the UTC date/time when this change occurred. * * @return date/time */ QDateTime dateTime() const; /** * Return the cumulative number of leap seconds to be added after this * change occurs. * * @return number of leap seconds */ int leapSeconds() const; /** * Return the comment (if any) applying to this change. * * @return comment */ QString comment() const; private: KTimeZoneLeapSecondsPrivate *const d; }; /** * Constructs a null time zone. A null time zone is invalid. * * @see isValid() */ KTimeZone(); /** * Constructs a UTC time zone. * * @param name name of the UTC time zone */ - explicit KTimeZone(const QString &name); + KDELIBS4SUPPORT_DEPRECATED explicit KTimeZone(const QString &name); KTimeZone(const KTimeZone &tz); KTimeZone &operator=(const KTimeZone &tz); virtual ~KTimeZone(); /** * Checks whether this is the same instance as another one. * Note that only the pointers to the time zone data are compared, not the * contents. So it will only return equality if one instance was copied * from the other. * * @param rhs other instance * @return true if the same instance, else false */ bool operator==(const KTimeZone &rhs) const; bool operator!=(const KTimeZone &rhs) const { return !operator==(rhs); } /** * Returns the class name of the data represented by this instance. * If a derived class object has been assigned to this instance, this * method will return the name of that class. * * @return "KTimeZone" or the class name of a derived class */ QByteArray type() const; /** * Checks whether the instance is valid. * * @return true if valid, false if invalid */ bool isValid() const; /** * Returns the name of the time zone. * If it is held in a KTimeZones container, the name is the time zone's unique * identifier within that KTimeZones instance. * * @return name in system-dependent format */ QString name() const; /** * Returns the two-letter country code of the time zone. * * @return upper case ISO 3166 2-character country code, empty if unknown */ QString countryCode() const; /** * Returns the latitude of the time zone. * * @return latitude in degrees, UNKNOWN if not known */ float latitude() const; /** * Returns the latitude of the time zone. * * @return latitude in degrees, UNKNOWN if not known */ float longitude() const; /** * Returns any comment for the time zone. * * @return comment, may be empty */ QString comment() const; /** * Returns the list of time zone abbreviations used by the time zone. * This may include historical ones which are no longer in use or have * been superseded. * * @return list of abbreviations * @see abbreviation() */ QList abbreviations() const; /** * Returns the time zone abbreviation current at a specified time. * * @param utcDateTime UTC date/time. An error occurs if * @p utcDateTime.timeSpec() is not Qt::UTC. * @return time zone abbreviation, or empty string if error * @see abbreviations() */ QByteArray abbreviation(const QDateTime &utcDateTime) const; /** * Returns the complete list of UTC offsets used by the time zone. This may * include historical ones which are no longer in use or have been * superseded. * * A UTC offset is the number of seconds which you must add to UTC to get * local time in this time zone. * * If due to the nature of the source data for the time zone, compiling a * complete list would require significant processing, an empty list is * returned instead. * * @return sorted list of UTC offsets, or empty list if not readily available. */ QList utcOffsets() const; /** * Converts a date/time, which is interpreted as being local time in this * time zone, into local time in another time zone. * * @param newZone other time zone which the time is to be converted into * @param zoneDateTime local date/time. An error occurs if * @p zoneDateTime.timeSpec() is not Qt::LocalTime. * @return converted date/time, or invalid date/time if error * @see toUtc(), toZoneTime() */ QDateTime convert(const KTimeZone &newZone, const QDateTime &zoneDateTime) const; /** * Converts a date/time, which is interpreted as local time in this time * zone, into UTC. * * Because of daylight savings time shifts, the date/time may occur twice. In * such cases, this method returns the UTC time for the first occurrence. * If you need the UTC time of the second occurrence, use offsetAtZoneTime(). * * @param zoneDateTime local date/time. An error occurs if * @p zoneDateTime.timeSpec() is not Qt::LocalTime. * @return UTC date/time, or invalid date/time if error * @see toZoneTime(), convert() */ QDateTime toUtc(const QDateTime &zoneDateTime) const; /** * Converts a UTC date/time into local time in this time zone. * * Because of daylight savings time shifts, some local date/time values occur * twice. The @p secondOccurrence parameter may be used to determine whether * the time returned is the first or second occurrence of that time. * * @param utcDateTime UTC date/time. An error occurs if * @p utcDateTime.timeSpec() is not Qt::UTC. * @param secondOccurrence if non-null, returns @p true if the return value * is the second occurrence of that time, else @p false * @return local date/time, or invalid date/time if error * @see toUtc(), convert() */ QDateTime toZoneTime(const QDateTime &utcDateTime, bool *secondOccurrence = nullptr) const; /** * Returns the current offset of this time zone to UTC or the local * system time zone. The offset is the number of seconds which you must * add to UTC or the local system time to get local time in this time zone. * * Take care if you cache the results of this routine; that would * break if the result were stored across a daylight savings change. * * @param basis Qt::UTC to return the offset to UTC, Qt::LocalTime * to return the offset to local system time * @return offset in seconds * @see offsetAtZoneTime(), offsetAtUtc() */ int currentOffset(Qt::TimeSpec basis = Qt::UTC) const; /** * Returns the offset of this time zone to UTC at the given local date/time. * Because of daylight savings time shifts, the date/time may occur twice. Optionally, * the offsets at both occurrences of @p dateTime are calculated. * * The offset is the number of seconds which you must add to UTC to get * local time in this time zone. * * @param zoneDateTime the date/time at which the offset is to be calculated. This * is interpreted as a local time in this time zone. An error * occurs if @p zoneDateTime.timeSpec() is not Qt::LocalTime. * @param secondOffset if non-null, and the @p zoneDateTime occurs twice, receives the * UTC offset for the second occurrence. Otherwise, it is set * the same as the return value. * @return offset in seconds. If @p zoneDateTime occurs twice, it is the offset at the * first occurrence which is returned. If @p zoneDateTime does not exist because * of daylight savings time shifts, InvalidOffset is returned. If any other error * occurs, 0 is returned. * @see offsetAtUtc(), currentOffset() */ virtual int offsetAtZoneTime(const QDateTime &zoneDateTime, int *secondOffset = nullptr) const; /** * Returns the offset of this time zone to UTC at the given UTC date/time. * * The offset is the number of seconds which you must add to UTC to get * local time in this time zone. * * If a derived class needs to work in terms of time_t (as when accessing the * system time functions, for example), it should override both this method and * offset() so as to implement its offset calculations in offset(), and * reimplement this method simply as * \code * offset(toTime_t(utcDateTime)); * \endcode * * @param utcDateTime the UTC date/time at which the offset is to be calculated. * An error occurs if @p utcDateTime.timeSpec() is not Qt::UTC. * @return offset in seconds, or 0 if error * @see offset(), offsetAtZoneTime(), currentOffset() */ virtual int offsetAtUtc(const QDateTime &utcDateTime) const; /** * Returns the offset of this time zone to UTC at a specified UTC time. * * The offset is the number of seconds which you must add to UTC to get * local time in this time zone. * * Note that time_t has a more limited range than QDateTime, so consider using * offsetAtUtc() instead. * * @param t the UTC time at which the offset is to be calculated, measured in seconds * since 00:00:00 UTC 1st January 1970 (as returned by time(2)) * @return offset in seconds, or 0 if error * @see offsetAtUtc() */ virtual int offset(time_t t) const; /** * Returns whether daylight savings time is in operation at the given UTC date/time. * * If a derived class needs to work in terms of time_t (as when accessing the * system time functions, for example), it should override both this method and * isDst() so as to implement its offset calculations in isDst(), and reimplement * this method simply as * \code * isDst(toTime_t(utcDateTime)); * \endcode * * @param utcDateTime the UTC date/time. An error occurs if * @p utcDateTime.timeSpec() is not Qt::UTC. * @return @c true if daylight savings time is in operation, @c false otherwise * @see isDst() */ virtual bool isDstAtUtc(const QDateTime &utcDateTime) const; /** * Returns whether daylight savings time is in operation at a specified UTC time. * * Note that time_t has a more limited range than QDateTime, so consider using * isDstAtUtc() instead. * * @param t the UTC time, measured in seconds since 00:00:00 UTC 1st January 1970 * (as returned by time(2)) * @return @c true if daylight savings time is in operation, @c false otherwise * @see isDstAtUtc() */ virtual bool isDst(time_t t) const; /** * Return all daylight savings time phases for the time zone. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not allow a list of daylight savings time * changes to be compiled easily. In such cases, this method will return an * empty list. * * @return list of phases */ QList phases() const; /** * Return whether daylight saving transitions are available for the time zone. * * The base class returns @c false. * * @return @c true if transitions are available, @c false if not * @see transitions(), transition() */ virtual bool hasTransitions() const; /** * Return all daylight saving transitions, in time order. If desired, the * transitions returned may be restricted to a specified time range. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not allow a list of daylight saving time * changes to be compiled easily. In such cases, this method will return an * empty list. * * @param start start UTC date/time, or invalid date/time to return all transitions * up to @p end. @p start.timeSpec() must be Qt::UTC, else * @p start will be considered invalid. * @param end end UTC date/time, or invalid date/time for no end. @p end.timeSpec() * must be Qt::UTC, else @p end will be considered invalid. * @return list of transitions, in time order * @see hasTransitions(), transition(), transitionTimes() */ QList transitions(const QDateTime &start = QDateTime(), const QDateTime &end = QDateTime()) const; /** * Find the last daylight savings time transition at or before a given * UTC or local time. * * Because of daylight savings time shifts, a local time may occur twice or * may not occur at all. In the former case, the transitions at or before * both occurrences of @p dt may optionally be calculated and returned in * @p secondTransition. The latter case may optionally be detected by use of * @p validTime. * * @param dt date/time. @p dt.timeSpec() may be set to Qt::UTC or Qt::LocalTime. * @param secondTransition if non-null, and the @p dt occurs twice, receives the * transition for the second occurrence. Otherwise, it is set * the same as the return value. * @param validTime if non-null, is set to false if @p dt does not occur, or * to true otherwise * @return time zone transition, or null either if @p dt is either outside the * defined range of the transition data or if @p dt does not occur * @see transitionIndex(), hasTransitions(), transitions() */ const KTimeZone::Transition *transition(const QDateTime &dt, const Transition **secondTransition = nullptr, bool *validTime = nullptr) const; /** * Find the index to the last daylight savings time transition at or before * a given UTC or local time. The return value is the index into the transition * list returned by transitions(). * * Because of daylight savings time shifts, a local time may occur twice or * may not occur at all. In the former case, the transitions at or before * both occurrences of @p dt may optionally be calculated and returned in * @p secondIndex. The latter case may optionally be detected by use of * @p validTime. * * @param dt date/time. @p dt.timeSpec() may be set to Qt::UTC or Qt::LocalTime. * @param secondIndex if non-null, and the @p dt occurs twice, receives the * index to the transition for the second occurrence. Otherwise, * it is set the same as the return value. * @param validTime if non-null, is set to false if @p dt does not occur, or * to true otherwise * @return index into the time zone transition list, or -1 either if @p dt is * either outside the defined range of the transition data or if @p dt * does not occur * @see transition(), transitions(), hasTransitions() */ int transitionIndex(const QDateTime &dt, int *secondIndex = nullptr, bool *validTime = nullptr) const; /** * Return the times of all daylight saving transitions to a given time zone * phase, in time order. If desired, the times returned may be restricted to * a specified time range. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not allow a list of daylight saving time * changes to be compiled easily. In such cases, this method will return an * empty list. * * @param phase time zone phase * @param start start UTC date/time, or invalid date/time to return all transitions * up to @p end. @p start.timeSpec() must be Qt::UTC, else * @p start will be considered invalid. * @param end end UTC date/time, or invalid date/time for no end. @p end.timeSpec() * must be Qt::UTC, else @p end will be considered invalid. * @return ordered list of transition times * @see hasTransitions(), transition(), transitions() */ QList transitionTimes(const Phase &phase, const QDateTime &start = QDateTime(), const QDateTime &end = QDateTime()) const; /** * Return all leap second adjustments, in time order. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not provide information on leap second * adjustments. In such cases, this method will return an empty list. * * @return list of adjustments */ QList leapSecondChanges() const; /** * Returns the source reader/parser for the time zone's source database. * * @return reader/parser */ KTimeZoneSource *source() const; /** * Extracts time zone detail information for this time zone from the source database. * * @return @c false if the parse encountered errors, @c true otherwise */ bool parse() const; /** * Returns the detailed parsed data for the time zone. * This will return null unless either parse() has been called beforehand, or * @p create is true. * * @param create true to parse the zone's data first if not already parsed * @return pointer to data, or null if data has not been parsed */ const KTimeZoneData *data(bool create = false) const; /** * Update the definition of the time zone to be identical to another * KTimeZone instance. A prerequisite is that the two instances must * have the same name. * * The main purpose of this method is to allow updates of the time zone * definition by derived classes without invalidating pointers to the * instance (particularly pointers held by KDateTime objects). Note * that the KTimeZoneData object and KTimeZoneSource pointer are not * updated: the caller class should do this itself by calling setData(). * * @param other time zone whose definition is to be used * @return true if definition was updated (i.e. names are the same) * * @see setData() */ bool updateBase(const KTimeZone &other); /** * Converts a UTC time, measured in seconds since 00:00:00 UTC 1st January 1970 * (as returned by time(2)), to a UTC QDateTime value. * QDateTime::setTime_t() is limited to handling @p t >= 0, since its parameter * is unsigned. This method takes a parameter of time_t which is signed. * * @return converted time * @see toTime_t() */ static QDateTime fromTime_t(time_t t); /** * Converts a UTC QDateTime to a UTC time, measured in seconds since 00:00:00 UTC * 1st January 1970 (as returned by time(2)). * QDateTime::toTime_t() returns an unsigned value. This method returns a time_t * value, which is signed. * * @param utcDateTime date/time. An error occurs if @p utcDateTime.timeSpec() is * not Qt::UTC. * @return converted time, or -1 if the date is out of range for time_t or * @p utcDateTime.timeSpec() is not Qt::UTC * @see fromTime_t() */ static time_t toTime_t(const QDateTime &utcDateTime); /** * Returns a standard UTC time zone, with name "UTC". * * @note The KTimeZone returned by this method does not belong to any * KTimeZones collection. Any KTimeZones instance may contain its own UTC * KTimeZone defined by its time zone source data, but that will be a * different instance than this KTimeZone. * * @return UTC time zone */ static KTimeZone utc(); /** Indicates an invalid UTC offset. This is returned by offsetAtZoneTime() when * the local time does not occur due to a shift to daylight savings time. */ static const int InvalidOffset; /** Indicates an invalid time_t value. */ static const time_t InvalidTime_t; /** * A representation for unknown locations; this is a float * that does not represent a real latitude or longitude. */ static const float UNKNOWN; protected: KTimeZone(KTimeZoneBackend *impl); /** * Sets the detailed parsed data for the time zone, and optionally * a new time zone source object. * * @param data parsed data * @param source if non-null, the new source object for the time zone * * @see data() */ void setData(KTimeZoneData *data, KTimeZoneSource *source = nullptr); private: KTimeZoneBackend *d; }; /** * Base backend class for KTimeZone classes. * * KTimeZone and each class inherited from it must have a corresponding * backend class to implement its constructors and its virtual methods, * and to provide a virtual clone() method. This allows KTimeZone virtual methods * to work together with reference counting of private data. * * @note Classes derived from KTimeZoneBackend should not normally implement their * own copy constructor or assignment operator, and must have a non-const d-pointer. * * @short Base backend class for KTimeZone classes * @see KTimeZone * @ingroup timezones * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT KTimeZoneBackend //krazy:exclude=dpointer (non-const d-pointer for KTimeZoneBackend-derived classes) { public: /** Implements KTimeZone::KTimeZone(). */ KTimeZoneBackend(); /** Implements KTimeZone::KTimeZone(const QString&). */ - explicit KTimeZoneBackend(const QString &name); + KDELIBS4SUPPORT_DEPRECATED explicit KTimeZoneBackend(const QString &name); KTimeZoneBackend(const KTimeZoneBackend &other); KTimeZoneBackend &operator=(const KTimeZoneBackend &other); virtual ~KTimeZoneBackend(); /** * Creates a copy of this instance. * * @note Every inherited class must reimplement clone(). * * @return new copy */ virtual KTimeZoneBackend *clone() const; /** * Returns the class name of the data represented by this instance. * * @note Every inherited class must reimplement type(). * * This base class returns "KTimeZone". * * @return the class name */ virtual QByteArray type() const; /** * Implements KTimeZone::offsetAtZoneTime(). * * @param caller calling KTimeZone object */ virtual int offsetAtZoneTime(const KTimeZone *caller, const QDateTime &zoneDateTime, int *secondOffset) const; /** * Implements KTimeZone::offsetAtUtc(). * * @param caller calling KTimeZone object */ virtual int offsetAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const; /** * Implements KTimeZone::offset(). * * @param caller calling KTimeZone object */ virtual int offset(const KTimeZone *caller, time_t t) const; /** * Implements KTimeZone::isDstAtUtc(). * * @param caller calling KTimeZone object */ virtual bool isDstAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const; /** * Implements KTimeZone::isDst(). * * @param caller calling KTimeZone object */ virtual bool isDst(const KTimeZone *caller, time_t t) const; /** * Implements KTimeZone::hasTransitions(). * * @param caller calling KTimeZone object */ virtual bool hasTransitions(const KTimeZone *caller) const; protected: /** * Constructs a time zone. * * @param source reader/parser for the database containing this time zone. This will * be an instance of a class derived from KTimeZoneSource. * @param name in system-dependent format. The name must be unique within any * KTimeZones instance which contains this KTimeZone. * @param countryCode ISO 3166 2-character country code, empty if unknown * @param latitude in degrees (between -90 and +90), UNKNOWN if not known * @param longitude in degrees (between -180 and +180), UNKNOWN if not known * @param comment description of the time zone, if any */ KTimeZoneBackend(KTimeZoneSource *source, const QString &name, const QString &countryCode = QString(), float latitude = KTimeZone::UNKNOWN, float longitude = KTimeZone::UNKNOWN, const QString &comment = QString()); private: KTimeZonePrivate *d; // non-const friend class KTimeZone; }; /** * Base class representing a source of time zone information. * * Derive subclasses from KTimeZoneSource to read and parse time zone details * from a time zone database or other source of time zone information. If can know * in advance what KTimeZone instances to create without having to parse the source * data, you should reimplement the virtual method parse(const KTimeZone&). Otherwise, * you need to define your own parse() methods with appropriate signatures, to both * read and parse the new data, and create new KTimeZone instances. * * KTimeZoneSource itself may be used as a dummy source which returns empty * time zone details. * * @short Base class representing a source of time zone information * @see KTimeZone, KTimeZoneData * @ingroup timezones * @author David Jarvie . * @author S.R.Haque . */ class KDELIBS4SUPPORT_EXPORT KTimeZoneSource { public: KTimeZoneSource(); virtual ~KTimeZoneSource(); /** * Extracts detail information for one time zone from the source database. * * In this base class, the method always succeeds and returns an empty data * instance. Derived classes should reimplement this method to return an * appropriate data class derived from KTimeZoneData. Some source databases * may not be compatible with this method of parsing. In these cases, they * should use the constructor KTimeZoneSource(false) and calling this method * will produce a fatal error. * * @param zone the time zone for which data is to be extracted. * @return an instance of a class derived from KTimeZoneData containing * the parsed data. The caller is responsible for deleting the * KTimeZoneData instance. * Null is returned on error. */ virtual KTimeZoneData *parse(const KTimeZone &zone) const; /** * Return whether the source database supports the ad hoc extraction of data for * individual time zones using parse(const KTimeZone&). * * @return true if parse(const KTimeZone&) works, false if parsing must be * performed by other methods */ bool useZoneParse() const; protected: /** * Constructor for use by derived classes, which specifies whether the * source database supports the ad hoc extraction of data for individual * time zones using parse(const KTimeZone&). * * If parse(const KTimeZone&) cannot be used, KTimeZone derived classes * which use this KTimeZoneSource derived class must create a * KTimeZoneData object at construction time so that KTimeZone::data() * will always return a data object. * * Note the default constructor is equivalent to KTimeZoneSource(true), i.e. * it is only necessary to use this constructor if parse(const KTimeZone&) * does not work. * * @param useZoneParse true if parse(const KTimeZone&) works, false if * parsing must be performed by other methods */ - explicit KTimeZoneSource(bool useZoneParse); + KDELIBS4SUPPORT_DEPRECATED explicit KTimeZoneSource(bool useZoneParse); private: KTimeZoneSourcePrivate *const d; }; /** * Base class for the parsed data returned by a KTimeZoneSource class. * * It contains all the data available from the KTimeZoneSource class, * including, when available, a complete list of daylight savings time * changes and leap seconds adjustments. * * This base class can be instantiated, but contains no data. * * @short Base class for parsed time zone data * @see KTimeZone, KTimeZoneSource * @ingroup timezones * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT KTimeZoneData { friend class KTimeZone; public: KTimeZoneData(); KTimeZoneData(const KTimeZoneData &c); virtual ~KTimeZoneData(); KTimeZoneData &operator=(const KTimeZoneData &c); /** * Creates a new copy of this object. * The caller is responsible for deleting the copy. * Derived classes must reimplement this method to return a copy of the * calling instance. * * @return copy of this instance */ virtual KTimeZoneData *clone() const; /** * Returns the complete list of time zone abbreviations. This may include * translations. * * @return the list of abbreviations. * In this base class, it consists of the single string "UTC". * @see abbreviation() */ virtual QList abbreviations() const; /** * Returns the time zone abbreviation current at a specified time. * * @param utcDateTime UTC date/time. An error occurs if * @p utcDateTime.timeSpec() is not Qt::UTC. * @return time zone abbreviation, or empty string if error * @see abbreviations() */ virtual QByteArray abbreviation(const QDateTime &utcDateTime) const; /** * Returns the complete list of UTC offsets for the time zone, if the time * zone's source makes such information readily available. If compiling a * complete list would require significant processing, an empty list is * returned instead. * * @return sorted list of UTC offsets, or empty list if not readily available. * In this base class, it consists of the single value 0. */ virtual QList utcOffsets() const; /** * Returns the UTC offset to use before the start of data for the time zone. * * @return UTC offset */ int previousUtcOffset() const; /** * Return all daylight savings time phases. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not allow a list of daylight savings time * changes to be compiled easily. In such cases, this method will return an * empty list. * * @return list of phases */ QList phases() const; /** * Return whether daylight saving transitions are available for the time zone. * * The base class returns @c false. * * @return @c true if transitions are available, @c false if not * @see transitions(), transition() */ virtual bool hasTransitions() const; /** * Return all daylight saving transitions, in time order. If desired, the * transitions returned may be restricted to a specified time range. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not allow a list of daylight saving time * changes to be compiled easily. In such cases, this method will return an * empty list. * * @param start start date/time, or invalid date/time to return all transitions up * to @p end. @p start.timeSpec() must be Qt::UTC, else * @p start will be considered invalid. * @param end end date/time, or invalid date/time for no end. @p end.timeSpec() * must be Qt::UTC, else @p end will be considered invalid. * @return list of transitions, in time order * @see hasTransitions(), transition(), transitionTimes() */ QList transitions(const QDateTime &start = QDateTime(), const QDateTime &end = QDateTime()) const; /** * Find the last daylight savings time transition at or before a given * UTC or local time. * * Because of daylight savings time shifts, a local time may occur twice or * may not occur at all. In the former case, the transitions at or before * both occurrences of @p dt may optionally be calculated and returned in * @p secondTransition. The latter case may optionally be detected by use of * @p validTime. * * @param dt date/time. @p dt.timeSpec() may be set to Qt::UTC or Qt::LocalTime. * @param secondTransition if non-null, and the @p dt occurs twice, receives the * transition for the second occurrence. Otherwise, it is set * the same as the return value. * @param validTime if non-null, is set to false if @p dt does not occur, or * to true otherwise * @return time zone transition, or null either if @p dt is either outside the * defined range of the transition data or if @p dt does not occur * @see transitionIndex(), hasTransitions(), transitions() */ const KTimeZone::Transition *transition(const QDateTime &dt, const KTimeZone::Transition **secondTransition = nullptr, bool *validTime = nullptr) const; /** * Find the index to the last daylight savings time transition at or before * a given UTC or local time. The return value is the index into the transition * list returned by transitions(). * * Because of daylight savings time shifts, a local time may occur twice or * may not occur at all. In the former case, the transitions at or before * both occurrences of @p dt may optionally be calculated and returned in * @p secondIndex. The latter case may optionally be detected by use of * @p validTime. * * @param dt date/time. @p dt.timeSpec() may be set to Qt::UTC or Qt::LocalTime. * @param secondIndex if non-null, and the @p dt occurs twice, receives the * index to the transition for the second occurrence. Otherwise, * it is set the same as the return value. * @param validTime if non-null, is set to false if @p dt does not occur, or * to true otherwise * @return index into the time zone transition list, or -1 either if @p dt is * either outside the defined range of the transition data or if @p dt * does not occur * @see transition(), transitions(), hasTransitions() */ int transitionIndex(const QDateTime &dt, int *secondIndex = nullptr, bool *validTime = nullptr) const; /** * Return the times of all daylight saving transitions to a given time zone * phase, in time order. If desired, the times returned may be restricted to * a specified time range. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not allow a list of daylight saving time * changes to be compiled easily. In such cases, this method will return an * empty list. * * @param phase time zone phase * @param start start UTC date/time, or invalid date/time to return all transitions * up to @p end. @p start.timeSpec() must be Qt::UTC, else * @p start will be considered invalid. * @param end end UTC date/time, or invalid date/time for no end. @p end.timeSpec() * must be Qt::UTC, else @p end will be considered invalid. * @return ordered list of transition times * @see hasTransitions(), transition(), transitions() */ QList transitionTimes(const KTimeZone::Phase &phase, const QDateTime &start = QDateTime(), const QDateTime &end = QDateTime()) const; /** * Return all leap second adjustments, in time order. * * Note that some time zone data sources (such as system time zones accessed * via the system libraries) may not provide information on leap second * adjustments. In such cases, this method will return an empty list. * * @return list of adjustments */ QList leapSecondChanges() const; /** * Find the leap second adjustment which is applicable at a given UTC time. * * @param utc UTC date/time. An error occurs if @p utc.timeSpec() is not Qt::UTC. * @return leap second adjustment, or invalid if @p utc is earlier than the * first leap second adjustment or @p utc is a local time */ KTimeZone::LeapSeconds leapSecondChange(const QDateTime &utc) const; protected: /** * Initialise the daylight savings time phase list. * * @param phases list of phases * @param previousPhase phase to use before the first daylight savings time * transition * @see phases() * @since 4.8.3 */ void setPhases(const QList &phases, const KTimeZone::Phase &previousPhase); /** * Initialise the daylight savings time phase list. * This setPhases() variant should be used when the time zone abbreviation * used before the start of the first phase is not known. * * @param phases list of phases * @param previousUtcOffset UTC offset to use before the start of the first * phase * @see phases() */ void setPhases(const QList &phases, int previousUtcOffset); /** * Initialise the daylight savings time transition list. * * @param transitions list of transitions * @see transitions() */ void setTransitions(const QList &transitions); /** * Initialise the leap seconds adjustment list. * * @param adjusts list of adjustments * @see leapSecondChanges() */ void setLeapSecondChanges(const QList &adjusts); private: KTimeZoneDataPrivate *const d; }; #endif diff --git a/src/kdecore/ktimezone_win.cpp b/src/kdecore/ktimezone_win.cpp index 84dcf2e7..ad656141 100644 --- a/src/kdecore/ktimezone_win.cpp +++ b/src/kdecore/ktimezone_win.cpp @@ -1,736 +1,736 @@ /* This file is part of the KDE libraries Copyright (c) 2008 Marc Mutz , Till Adam 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. */ #include "ktimezone_win.h" #include #include #include "kdebug.h" #include #include #include #include struct ZoneKey { QString zoneOlson; QString zoneWin; }; static const ZoneKey ZoneTbl[] = { {QLatin1String("Australia/Darwin"), QLatin1String("AUS Central Standard Time")}, {QLatin1String("Australia/Sydney"), QLatin1String("AUS Eastern Standard Time")}, {QLatin1String("Asia/Kabul"), QLatin1String("Afghanistan Standard Time")}, {QLatin1String("America/Anchorage"), QLatin1String("Alaskan Standard Time")}, {QLatin1String("Asia/Riyadh"), QLatin1String("Arab Standard Time")}, {QLatin1String("Asia/Dubai"), QLatin1String("Arabian Standard Time")}, {QLatin1String("Asia/Baghdad"), QLatin1String("Arabic Standard Time")}, {QLatin1String("America/Buenos_Aires"), QLatin1String("Argentina Standard Time")}, {QLatin1String("Asia/Yerevan"), QLatin1String("Armenian Standard Time")}, {QLatin1String("America/Halifax"), QLatin1String("Atlantic Standard Time")}, {QLatin1String("Asia/Baku"), QLatin1String("Azerbaijan Standard Time")}, {QLatin1String("Atlantic/Azores"), QLatin1String("Azores Standard Time")}, {QLatin1String("America/Regina"), QLatin1String("Canada Central Standard Time")}, {QLatin1String("Atlantic/Cape_Verde"), QLatin1String("Cape Verde Standard Time")}, {QLatin1String("Asia/Yerevan"), QLatin1String("Caucasus Standard Time")}, {QLatin1String("Australia/Adelaide"), QLatin1String("Cen. Australia Standard Time")}, {QLatin1String("America/Guatemala"), QLatin1String("Central America Standard Time")}, {QLatin1String("Asia/Dhaka"), QLatin1String("Central Asia Standard Time")}, {QLatin1String("America/Manaus"), QLatin1String("Central Brazilian Standard Time")}, {QLatin1String("Europe/Budapest"), QLatin1String("Central Europe Standard Time")}, {QLatin1String("Europe/Warsaw"), QLatin1String("Central European Standard Time")}, {QLatin1String("Pacific/Guadalcanal"), QLatin1String("Central Pacific Standard Time")}, {QLatin1String("America/Chicago"), QLatin1String("Central Standard Time")}, {QLatin1String("America/Mexico_City"), QLatin1String("Central Standard Time (Mexico)")}, {QLatin1String("Asia/Shanghai"), QLatin1String("China Standard Time")}, {QLatin1String("Etc/GMT+12"), QLatin1String("Dateline Standard Time")}, {QLatin1String("Africa/Nairobi"), QLatin1String("E. Africa Standard Time")}, {QLatin1String("Australia/Brisbane"), QLatin1String("E. Australia Standard Time")}, {QLatin1String("Europe/Minsk"), QLatin1String("E. Europe Standard Time")}, {QLatin1String("America/Sao_Paulo"), QLatin1String("E. South America Standard Time")}, {QLatin1String("America/New_York"), QLatin1String("Eastern Standard Time")}, {QLatin1String("Africa/Cairo"), QLatin1String("Egypt Standard Time")}, {QLatin1String("Asia/Yekaterinburg"), QLatin1String("Ekaterinburg Standard Time")}, {QLatin1String("Europe/Kiev"), QLatin1String("FLE Standard Time")}, {QLatin1String("Pacific/Fiji"), QLatin1String("Fiji Standard Time")}, {QLatin1String("Europe/London"), QLatin1String("GMT Standard Time")}, {QLatin1String("Europe/Istanbul"), QLatin1String("GTB Standard Time")}, {QLatin1String("Etc/GMT-3"), QLatin1String("Georgian Standard Time")}, {QLatin1String("America/Godthab"), QLatin1String("Greenland Standard Time")}, {QLatin1String("Atlantic/Reykjavik"), QLatin1String("Greenwich Standard Time")}, {QLatin1String("Pacific/Honolulu"), QLatin1String("Hawaiian Standard Time")}, {QLatin1String("Asia/Calcutta"), QLatin1String("India Standard Time")}, {QLatin1String("Asia/Tehran"), QLatin1String("Iran Standard Time")}, {QLatin1String("Asia/Jerusalem"), QLatin1String("Israel Standard Time")}, {QLatin1String("Asia/Amman"), QLatin1String("Jordan Standard Time")}, {QLatin1String("Asia/Seoul"), QLatin1String("Korea Standard Time")}, {QLatin1String("Indian/Mauritius"), QLatin1String("Mauritius Standard Time")}, {QLatin1String("America/Mexico_City"), QLatin1String("Mexico Standard Time")}, {QLatin1String("America/Chihuahua"), QLatin1String("Mexico Standard Time 2")}, {QLatin1String("Atlantic/South_Georgia"), QLatin1String("Mid-Atlantic Standard Time")}, {QLatin1String("Asia/Beirut"), QLatin1String("Middle East Standard Time")}, {QLatin1String("America/Montevideo"), QLatin1String("Montevideo Standard Time")}, {QLatin1String("Africa/Casablanca"), QLatin1String("Morocco Standard Time")}, {QLatin1String("America/Denver"), QLatin1String("Mountain Standard Time")}, {QLatin1String("America/Chihuahua"), QLatin1String("Mountain Standard Time (Mexico)")}, {QLatin1String("Asia/Rangoon"), QLatin1String("Myanmar Standard Time")}, {QLatin1String("Asia/Novosibirsk"), QLatin1String("N. Central Asia Standard Time")}, {QLatin1String("Africa/Windhoek"), QLatin1String("Namibia Standard Time")}, {QLatin1String("Asia/Katmandu"), QLatin1String("Nepal Standard Time")}, {QLatin1String("Pacific/Auckland"), QLatin1String("New Zealand Standard Time")}, {QLatin1String("America/St_Johns"), QLatin1String("Newfoundland Standard Time")}, {QLatin1String("Asia/Irkutsk"), QLatin1String("North Asia East Standard Time")}, {QLatin1String("Asia/Krasnoyarsk"), QLatin1String("North Asia Standard Time")}, {QLatin1String("America/Santiago"), QLatin1String("Pacific SA Standard Time")}, {QLatin1String("America/Los_Angeles"), QLatin1String("Pacific Standard Time")}, {QLatin1String("America/Tijuana"), QLatin1String("Pacific Standard Time (Mexico)")}, {QLatin1String("Asia/Karachi"), QLatin1String("Pakistan Standard Time")}, {QLatin1String("Europe/Paris"), QLatin1String("Romance Standard Time")}, {QLatin1String("Europe/Moscow"), QLatin1String("Russian Standard Time")}, {QLatin1String("Etc/GMT+3"), QLatin1String("SA Eastern Standard Time")}, {QLatin1String("America/Bogota"), QLatin1String("SA Pacific Standard Time")}, {QLatin1String("America/La_Paz"), QLatin1String("SA Western Standard Time")}, {QLatin1String("Asia/Bangkok"), QLatin1String("SE Asia Standard Time")}, {QLatin1String("Pacific/Apia"), QLatin1String("Samoa Standard Time")}, {QLatin1String("Asia/Singapore"), QLatin1String("Singapore Standard Time")}, {QLatin1String("Africa/Johannesburg"), QLatin1String("South Africa Standard Time")}, {QLatin1String("Asia/Colombo"), QLatin1String("Sri Lanka Standard Time")}, {QLatin1String("Asia/Taipei"), QLatin1String("Taipei Standard Time")}, {QLatin1String("Australia/Hobart"), QLatin1String("Tasmania Standard Time")}, {QLatin1String("Asia/Tokyo"), QLatin1String("Tokyo Standard Time")}, {QLatin1String("Pacific/Tongatapu"), QLatin1String("Tonga Standard Time")}, {QLatin1String("Etc/GMT+5"), QLatin1String("US Eastern Standard Time")}, {QLatin1String("America/Phoenix"), QLatin1String("US Mountain Standard Time")}, {QLatin1String("America/Caracas"), QLatin1String("Venezuela Standard Time")}, {QLatin1String("Asia/Vladivostok"), QLatin1String("Vladivostok Standard Time")}, {QLatin1String("Australia/Perth"), QLatin1String("W. Australia Standard Time")}, {QLatin1String("Africa/Lagos"), QLatin1String("W. Central Africa Standard Time")}, {QLatin1String("Europe/Berlin"), QLatin1String("W. Europe Standard Time")}, {QLatin1String("Asia/Tashkent"), QLatin1String("West Asia Standard Time")}, {QLatin1String("Pacific/Port_Moresby"), QLatin1String("West Pacific Standard Time")}, {QLatin1String("Asia/Yakutsk"), QLatin1String("Yakutsk Standard Time")} }; static QString getWinZoneName(const QString &name) { for (int i = 0; i < sizeof(ZoneTbl) / sizeof(ZoneTbl[0]); ++i) { if (ZoneTbl[i].zoneOlson == name) { return ZoneTbl[i].zoneWin; } } return name; } typedef BOOL (WINAPI *PtrTzSpecificLocalTimeToSystemTime)(LPTIME_ZONE_INFORMATION lpTimeZoneInformation, LPSYSTEMTIME lpLocalTime, LPSYSTEMTIME lpUniversalTime ); static PtrTzSpecificLocalTimeToSystemTime pTzSpecificLocalTimeToSystemTime = 0; namespace { class HKeyCloser { const HKEY hkey; Q_DISABLE_COPY(HKeyCloser) public: - explicit HKeyCloser(HKEY hk) : hkey(hk) {} + KDELIBS4SUPPORT_DEPRECATED explicit HKeyCloser(HKEY hk) : hkey(hk) {} ~HKeyCloser() { RegCloseKey(hkey); } }; struct TZI { LONG Bias; LONG StandardBias; LONG DaylightBias; SYSTEMTIME StandardDate; SYSTEMTIME DaylightDate; }; } // TCHAR can be either uchar, or wchar_t: #ifdef UNICODE static inline QString tchar_to_qstring(const TCHAR *str) { return QString::fromUtf16(reinterpret_cast(str)); } static inline const TCHAR *qstring_to_tchar(const QString &str) { return reinterpret_cast(str.utf16()); } static inline std::basic_string qstring_to_tcharstring(const QString &str) { return std::basic_string(qstring_to_tchar(str)); } #else static inline QString tchar_to_qstring(const TCHAR *str) { return QString::fromLocal8Bit(str); } static inline const TCHAR *qstring_to_tchar(const QString &str) { return str.toLocal8Bit().constData(); } static inline std::basic_string qstring_to_tcharstring(const QString &str) { return std::basic_string(qstring_to_tchar(str)); } #endif static const TCHAR timeZonesKey[] = TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones"); static inline QDateTime systemtime_to_qdatetime(const SYSTEMTIME &st) { return QDateTime(QDate(st.wYear, st.wMonth, st.wDay), QTime(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds)); } static SYSTEMTIME qdatetime_to_systemtime(const QDateTime &dt) { const QDate d = dt.date(); const QTime t = dt.time(); const SYSTEMTIME st = { d.year(), d.month(), d.dayOfWeek() % 7, // 1..7 (Mon..Sun)->0..6(Sun..Sat) d.day(), t.hour(), t.minute(), t.second(), t.msec(), }; return st; } static bool TzSpecificLocalTimeToSystemTime_Portable(TIME_ZONE_INFORMATION *tz, SYSTEMTIME *i_stLocal, SYSTEMTIME *o_stUniversal) { // the method below was introduced in XP. If it's there, use it, otherwise // fall back to doing things manually if (!pTzSpecificLocalTimeToSystemTime) { QLibrary kernelLib(QLatin1String("kernel32")); pTzSpecificLocalTimeToSystemTime = (PtrTzSpecificLocalTimeToSystemTime)kernelLib.resolve("TzSpecificLocalTimeToSystemTime"); } if (pTzSpecificLocalTimeToSystemTime) { return pTzSpecificLocalTimeToSystemTime(tz, i_stLocal, o_stUniversal) != 0; } // the algorithm is: // - switch to the desired timezone temporarily // - convert system time to (local) file time in that timezone // - convert local file time to utc file time // - convert utc file time to system time // - reset timezone FILETIME ft, ft_utc; int result = 1; TIME_ZONE_INFORMATION currentTimeZone; result = GetTimeZoneInformation(¤tTimeZone); if (result == TIME_ZONE_ID_INVALID) { kWarning(161) << "Getting time zone information failed"; return false; } result = SetTimeZoneInformation(tz); if (result == 0) { kWarning(161) << "Setting temporary time zone failed"; return false; } result = SystemTimeToFileTime(i_stLocal, &ft); if (result == 0) { kWarning(161) << "SysteTimeToFileTime failed"; return false; } result = LocalFileTimeToFileTime(&ft, &ft_utc); if (result == 0) { kWarning(161) << "LocalFileTimeToFileTime failed"; return false; } result = FileTimeToSystemTime(&ft_utc, o_stUniversal); if (result == 0) { kWarning(161) << "FileTimeToSystemTime failed"; return false; } result = SetTimeZoneInformation(¤tTimeZone); if (result == 0) { kWarning(161) << "Re-setting time zone information failed"; return false; } return true; } static bool get_binary_value(HKEY key, const TCHAR *value, void *data, DWORD numData, DWORD *outNumData = 0) { DWORD size = numData; DWORD type = REG_BINARY; if (RegQueryValueEx(key, value, 0, &type, (LPBYTE)data, &size) != ERROR_SUCCESS) { return false; } assert(type == REG_BINARY); if (type != REG_BINARY) { return false; } if (outNumData) { *outNumData = size; } return true; } static bool get_string_value(HKEY key, const TCHAR *value, TCHAR *dest, DWORD destSizeInBytes) { DWORD size = destSizeInBytes; DWORD type = REG_SZ; dest[0] = '\0'; if (RegQueryValueEx(key, value, 0, &type, (LPBYTE)dest, &size) != ERROR_SUCCESS) { return false; } //dest[ qMin( size, destSizeInBytes - sizeof( WCHAR ) ) / sizeof( WCHAR ) ] = 0; assert(type == REG_SZ); if (type != REG_SZ) { return false; } return true; } // // // Backend interface impl: // // static bool check_prereq(const KTimeZone *caller, const QDateTime &dt, Qt::TimeSpec spec) { return caller && caller->isValid() && dt.isValid() && dt.timeSpec() == spec; } static inline bool check_local(const KTimeZone *caller, const QDateTime &dt) { return check_prereq(caller, dt, Qt::LocalTime); } static inline bool check_utc(const KTimeZone *caller, const QDateTime &dt) { return check_prereq(caller, dt, Qt::UTC); } static bool has_transition(const TIME_ZONE_INFORMATION &tz) { return tz.StandardDate.wMonth != 0 && tz.DaylightDate.wMonth != 0; } static int win_dayofweek_to_qt_dayofweek(int wdow) { // Sun(0)..Sat(6) -> Mon(1)...Sun(7) return wdow ? wdow : 7; } static int qt_dayofweek_to_win_dayofweek(int qdow) { // Mon(1)...Sun(7) -> Sub(0)...Sat(6) return qdow % 7; } static QDate find_nth_weekday_in_month_of_year(int nth, int dayOfWeek, int month, int year) { assert(nth >= 1); assert(nth <= 5); const QDate first(year, month, 1); const int actualDayOfWeek = first.dayOfWeek(); QDate candidate = first.addDays((nth - 1) * 7 + dayOfWeek - actualDayOfWeek); assert(candidate.dayOfWeek() == dayOfWeek); if (nth == 5) if (candidate.month() != month) { candidate = candidate.addDays(-7); } assert(candidate.month() == month); return candidate; } static QDateTime transition(const SYSTEMTIME &st, int year) { assert(st.wYear == 0); assert(st.wMonth != 0); return QDateTime(find_nth_weekday_in_month_of_year(st.wDay, win_dayofweek_to_qt_dayofweek(st.wDayOfWeek), st.wMonth, year), QTime(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds)); } struct Transitions { QDateTime stdStart, dstStart; }; Transitions transitions(const TIME_ZONE_INFORMATION &tz, int year) { const Transitions t = { transition(tz.StandardDate, year), transition(tz.DaylightDate, year) }; return t; } static const int MAX_KEY_LENGTH = 255; static QStringList list_key(HKEY key) { DWORD numSubKeys = 0; QStringList result; if (RegQueryInfoKey(key, 0, 0, 0, &numSubKeys, 0, 0, 0, 0, 0, 0, 0) == ERROR_SUCCESS) for (DWORD i = 0; i < numSubKeys; ++i) { TCHAR name[MAX_KEY_LENGTH + 1]; DWORD nameLen = MAX_KEY_LENGTH; if (RegEnumKeyEx(key, i, name, &nameLen, 0, 0, 0, 0) == ERROR_SUCCESS) { result.push_back(tchar_to_qstring(name)); } } return result; } static QStringList list_standard_names() { QStringList standardNames; HKEY timeZones; QStringList keys; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, timeZonesKey, 0, KEY_READ, &timeZones) == ERROR_SUCCESS) { keys = list_key(timeZones); } std::basic_string path(timeZonesKey); path += TEXT("\\"); const HKeyCloser closer(timeZones); Q_FOREACH (const QString &keyname, keys) { std::basic_string keypath(path); keypath += qstring_to_tcharstring(keyname); HKEY key; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keypath.c_str(), 0, KEY_READ, &key) != ERROR_SUCCESS) { return standardNames; // FIXME what's the right error handling here? } const HKeyCloser closer(key); TIME_ZONE_INFORMATION tz; get_string_value(key, L"Std", tz.StandardName, sizeof(tz.StandardName)); standardNames << tchar_to_qstring(tz.StandardName); } for (int i = 0; i < sizeof(ZoneTbl) / sizeof(ZoneTbl[0]); ++i) { standardNames << ZoneTbl[i].zoneOlson; } return standardNames; } static std::basic_string pathFromZoneName(const KTimeZone &zone) { std::basic_string path(timeZonesKey); path += TEXT("\\"); QString name = zone.name(); name = getWinZoneName(name); HKEY timeZones; QStringList keys; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, timeZonesKey, 0, KEY_READ, &timeZones) == ERROR_SUCCESS) { keys = list_key(timeZones); } const HKeyCloser closer(timeZones); Q_FOREACH (const QString &keyname, keys) { std::basic_string keypath(path); keypath += qstring_to_tcharstring(keyname); HKEY key; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keypath.c_str(), 0, KEY_READ, &key) != ERROR_SUCCESS) { return 0; // FIXME what's the right error handling here? } const HKeyCloser closer(key); TIME_ZONE_INFORMATION tz; get_string_value(key, L"Std", tz.StandardName, sizeof(tz.StandardName)); if (tchar_to_qstring(tz.StandardName) == name) { return keypath; } } Q_ASSERT(false); return path; } /******************************************************************************/ class KSystemTimeZoneSourceWindowsPrivate { public: KSystemTimeZoneSourceWindowsPrivate() {} ~KSystemTimeZoneSourceWindowsPrivate() {} }; class KSystemTimeZoneBackendWindows : public KTimeZoneBackend { public: KSystemTimeZoneBackendWindows(KTimeZoneSource *source, const QString &name) : KTimeZoneBackend(source, name) {} ~KSystemTimeZoneBackendWindows() {} KSystemTimeZoneBackendWindows *clone() const; QByteArray type() const; int offsetAtZoneTime(const KTimeZone *caller, const QDateTime &zoneDateTime, int *secondOffset) const; int offsetAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const; int offset(const KTimeZone *caller, time_t t) const; bool isDstAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const; bool isDst(const KTimeZone *caller, time_t t) const; }; class KSystemTimeZoneDataWindows : public KTimeZoneData { public: KSystemTimeZoneDataWindows() : KTimeZoneData() { } TIME_ZONE_INFORMATION _tzi; QString displayName; const TIME_ZONE_INFORMATION &tzi(int year = 0) const { Q_UNUSED(year); return _tzi; } }; KSystemTimeZoneSourceWindows::KSystemTimeZoneSourceWindows() : d(new KSystemTimeZoneSourceWindowsPrivate) { } KTimeZoneData *KSystemTimeZoneSourceWindows::parse(const KTimeZone &zone) const { KSystemTimeZoneDataWindows *data = new KSystemTimeZoneDataWindows(); std::basic_string path = pathFromZoneName(zone); HKEY key; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, path.c_str(), 0, KEY_READ, &key) != ERROR_SUCCESS) { delete data; return 0; // FIXME what's the right error handling here? } const HKeyCloser closer(key); TZI tzi = { 0 }; if (!get_binary_value(key, TEXT("TZI"), &tzi, sizeof(TZI))) { delete data; return 0; // ? } get_string_value(key, L"Std", data->_tzi.StandardName, sizeof(data->_tzi.StandardName)); get_string_value(key, L"Dlt", data->_tzi.DaylightName, sizeof(data->_tzi.DaylightName)); TCHAR display[512]; get_string_value(key, L"Display", display, sizeof(display)); data->displayName = tchar_to_qstring(display); #define COPY( name ) data->_tzi.name = tzi.name COPY(Bias); COPY(StandardBias); COPY(StandardDate); COPY(DaylightBias); COPY(DaylightDate); #undef COPY return data; } Transitions transitions(const KTimeZone *caller, int year) { return transitions(static_cast(caller->data(true))->tzi(year), year); } static bool is_dst(const TIME_ZONE_INFORMATION &tzi, const QDateTime &utc, int year) { if (!has_transition(tzi)) { return false; } const Transitions trans = transitions(tzi, year); if (trans.stdStart < trans.dstStart) { return trans.dstStart <= utc || utc < trans.stdStart; } else { return trans.dstStart <= utc && utc < trans.stdStart; } } static bool is_dst(const KTimeZone *caller, const QDateTime &utc) { assert(caller); assert(caller->isValid()); const int year = utc.date().year(); const TIME_ZONE_INFORMATION &tzi = static_cast(caller->data(true))->tzi(year); return is_dst(tzi, utc, year); } static int effective_offset(const TIME_ZONE_INFORMATION &tz, bool isDst) { int bias = tz.Bias; if (has_transition(tz)) if (isDst) { bias += tz.DaylightBias; } else { bias += tz.StandardBias; } return bias * -60; // min -> secs } static int offset_at_utc(const KTimeZone *caller, const QDateTime &utc) { assert(caller); assert(caller->isValid()); const int year = utc.date().year(); const TIME_ZONE_INFORMATION &tz = static_cast(caller->data(true))->tzi(year); return effective_offset(tz, is_dst(tz, utc, year)); } static const int OneHour = 3600; //sec static int difference(const SYSTEMTIME &st1, const SYSTEMTIME &st2) { return systemtime_to_qdatetime(st1).secsTo(systemtime_to_qdatetime(st2)); } static int offset_at_zone_time(const KTimeZone *caller, const SYSTEMTIME &zone, int *secondOffset) { assert(caller); assert(caller->isValid()); assert(caller->data(true)); const KSystemTimeZoneDataWindows *const data = static_cast(caller->data(true)); const TIME_ZONE_INFORMATION &tz = data->tzi(zone.wYear); SYSTEMTIME utc; if (!TzSpecificLocalTimeToSystemTime_Portable(const_cast(&tz), const_cast(&zone), &utc)) { return 0; } const bool isDst = is_dst(tz, systemtime_to_qdatetime(utc), utc.wYear); int result = effective_offset(tz, isDst); //FIXME: SystemTimeToTzSpecificLocalTime does not exsit on wince #ifndef _WIN32_WCE if (secondOffset) { const SYSTEMTIME utcplus1 = qdatetime_to_systemtime(systemtime_to_qdatetime(utc).addSecs(OneHour)); const SYSTEMTIME utcminus1 = qdatetime_to_systemtime(systemtime_to_qdatetime(utc).addSecs(-OneHour)); SYSTEMTIME zoneplus1, zoneminus1; if (!SystemTimeToTzSpecificLocalTime(const_cast(&tz), const_cast(&utcplus1), &zoneplus1) || !SystemTimeToTzSpecificLocalTime(const_cast(&tz), const_cast(&utcminus1), &zoneminus1)) { return result; } if (difference(zoneminus1, zone) != OneHour || difference(zone, zoneplus1) != OneHour) { *secondOffset = effective_offset(tz, !isDst); if (result < *secondOffset) { qSwap(result, *secondOffset); } } } #endif return result; } KSystemTimeZoneBackendWindows *KSystemTimeZoneBackendWindows::clone() const { return new KSystemTimeZoneBackendWindows(*this); } QByteArray KSystemTimeZoneBackendWindows::type() const { return "KSystemTimeZoneWindows"; } int KSystemTimeZoneBackendWindows::offsetAtZoneTime(const KTimeZone *caller, const QDateTime &zoneDateTime, int *secondOffset) const { if (!caller->isValid() || !zoneDateTime.isValid() || zoneDateTime.timeSpec() != Qt::LocalTime) { return 0; } if (!check_local(caller, zoneDateTime)) { return 0; } return offset_at_zone_time(caller, qdatetime_to_systemtime(zoneDateTime), secondOffset); } int KSystemTimeZoneBackendWindows::offsetAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const { if (!caller->isValid() || !utcDateTime.isValid()) { return 0; } if (!check_utc(caller, utcDateTime)) { return 0; } return offset_at_utc(caller, utcDateTime); } int KSystemTimeZoneBackendWindows::offset(const KTimeZone *caller, time_t t) const { if (!caller->isValid() || t == KTimeZone::InvalidTime_t) { return 0; } return offsetAtUtc(caller, KTimeZone::fromTime_t(t)); } bool KSystemTimeZoneBackendWindows::isDstAtUtc(const KTimeZone *caller, const QDateTime &utcDateTime) const { return check_utc(caller, utcDateTime) && is_dst(caller, utcDateTime); } bool KSystemTimeZoneBackendWindows::isDst(const KTimeZone *caller, time_t t) const { return isDstAtUtc(caller, KTimeZone::fromTime_t(t)); } KSystemTimeZoneWindows::KSystemTimeZoneWindows(KTimeZoneSource *source, const QString &name) : KTimeZone(new KSystemTimeZoneBackendWindows(source, name)) {} QStringList KSystemTimeZoneWindows::listTimeZones() { return list_standard_names(); } diff --git a/src/kdecore/ktzfiletimezone.h b/src/kdecore/ktzfiletimezone.h index 867b9451..985c6087 100644 --- a/src/kdecore/ktzfiletimezone.h +++ b/src/kdecore/ktzfiletimezone.h @@ -1,215 +1,215 @@ /* This file is part of the KDE libraries Copyright (c) 2005-2008 David Jarvie 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. */ /** @file * TZFILE time zone functions * @author David Jarvie . */ #ifndef _KTZFILETIMEZONE_H #define _KTZFILETIMEZONE_H #include #include #include class KTzfileTimeZoneSource; class KTzfileTimeZonePrivate; class KTzfileTimeZoneDataPrivate; class KTzfileTimeZoneSourcePrivate; /** * The KTzfileTimeZone class represents a time zone defined in tzfile(5) format. * * It works in partnership with the KTzfileTimeZoneSource class which reads and parses the * time zone definition files. * * @short Represents a time zone defined in tzfile(5) format * @see KTzfileTimeZoneBackend, KTzfileTimeZoneSource, KTzfileTimeZoneData * @ingroup timezones * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT KTzfileTimeZone : public KTimeZone //krazy:exclude=dpointer (no d-pointer for KTimeZone derived classes) { public: /** * Creates a time zone. * * @param source tzfile reader and parser * @param name time zone's unique name, which must be the tzfile path relative * to the location specified for @p source * @param countryCode ISO 3166 2-character country code, empty if unknown * @param latitude in degrees (between -90 and +90), UNKNOWN if not known * @param longitude in degrees (between -180 and +180), UNKNOWN if not known * @param comment description of the time zone, if any */ KTzfileTimeZone(KTzfileTimeZoneSource *source, const QString &name, const QString &countryCode = QString(), float latitude = UNKNOWN, float longitude = UNKNOWN, const QString &comment = QString()); ~KTzfileTimeZone(); private: // d-pointer is in KTzfileTimeZoneBackend. // This is a requirement for classes inherited from KTimeZone. }; /** * Backend class for KTzfileTimeZone class. * * This class implements KTzfileTimeZone's constructors and virtual methods. A * backend class is required for all classes inherited from KTimeZone to * allow KTimeZone virtual methods to work together with reference counting of * private data. * * @short Backend class for KTzfileTimeZone class * @see KTimeZoneBackend, KTzfileTimeZone, KTimeZone * @ingroup timezones * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT KTzfileTimeZoneBackend : public KTimeZoneBackend //krazy:exclude=dpointer (non-const d-pointer for KTimeZoneBackend-derived classes) { public: /** Implements KTzfileTimeZone::KTzfileTimeZone(). */ KTzfileTimeZoneBackend(KTzfileTimeZoneSource *source, const QString &name, const QString &countryCode, float latitude, float longitude, const QString &comment); ~KTzfileTimeZoneBackend(); /** * Creates a copy of this instance. * * @return new copy */ KTimeZoneBackend *clone() const Q_DECL_OVERRIDE; /** * Returns the class name of the data represented by this instance. * * @return "KTzfileTimeZone" */ QByteArray type() const Q_DECL_OVERRIDE; /** * Implements KTzfileTimeZone::hasTransitions(). * * Returns whether daylight saving transitions are available for the time zone. * * @param caller calling KTzfileTimeZone object * @return @c true */ bool hasTransitions(const KTimeZone *caller) const Q_DECL_OVERRIDE; private: KTzfileTimeZonePrivate *d; // non-const }; /** * A class to read and parse tzfile time zone definition files. * * tzfile is the format used by zoneinfo files in the system time zone database. * The format is documented in the tzfile(5) manpage. * * @short Reads and parses tzfile(5) time zone definition files * @see KTzfileTimeZone, KTzfileTimeZoneData * @ingroup timezones * @author David Jarvie . */ class KDELIBS4SUPPORT_EXPORT KTzfileTimeZoneSource : public KTimeZoneSource { public: /** * Constructs a time zone source. * * The directory containing the time zone definition files is given by the * @p location parameter, which will usually be the zoneinfo directory. For * tzfile files in other locations, bear in mind that the name generated * for each KTzfileTimeZone is its file path relative to @p location. * * @param location the local directory containing the time zone definition files */ - explicit KTzfileTimeZoneSource(const QString &location); + KDELIBS4SUPPORT_DEPRECATED explicit KTzfileTimeZoneSource(const QString &location); virtual ~KTzfileTimeZoneSource(); /** * Returns the local directory containing the time zone definition files. * * @return path to time zone definition files */ QString location() const; /** * Parses a tzfile file to extract detailed information for one time zone. * * @param zone the time zone for which data is to be extracted * @return a KTzfileTimeZoneData instance containing the parsed data. * The caller is responsible for deleting the KTimeZoneData instance. * Null is returned on error. */ KTimeZoneData *parse(const KTimeZone &zone) const Q_DECL_OVERRIDE; private: KTzfileTimeZoneSourcePrivate *const d; }; /** * @internal * The parsed data returned by KTzfileTimeZoneSource. * * @short Parsed data from tzfile(5) time zone definition files * @see KTzfileTimeZoneSource, KTzfileTimeZone * @ingroup timezones * @author David Jarvie . */ class KTzfileTimeZoneData : public KTimeZoneData { friend class KTzfileTimeZoneSource; public: KTzfileTimeZoneData(); KTzfileTimeZoneData(const KTzfileTimeZoneData &); virtual ~KTzfileTimeZoneData(); KTzfileTimeZoneData &operator=(const KTzfileTimeZoneData &); /** * Creates a new copy of this object. * The caller is responsible for deleting the copy. * Derived classes must reimplement this method to return a copy of the * calling instance * * @return copy of this instance. This is a KTzfileTimeZoneData pointer. */ KTimeZoneData *clone() const Q_DECL_OVERRIDE; /** * Return whether daylight saving transitions are available for the time zone. * * @return @c true */ bool hasTransitions() const Q_DECL_OVERRIDE; private: // Enable this if you add KDELIBS4SUPPORT_EXPORT to this class //KTzfileTimeZoneDataPrivate * const d; }; #endif diff --git a/src/kdecore/kurl.h b/src/kdecore/kurl.h index 2b763417..1dcd77cc 100644 --- a/src/kdecore/kurl.h +++ b/src/kdecore/kurl.h @@ -1,1195 +1,1195 @@ /* This file is part of the KDE libraries * Copyright (C) 1999 Torben Weis * Copyright (C) 2005-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 kurl_h #define kurl_h #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif #include #include #include class QStringList; class QMimeData; class KUrlPrivate; /** * \class KUrl kurl.h * * Represents and parses a URL. * * A prototypical URL looks like: * \code * protocol://user:password\@hostname:port/path/to/file.ext#reference * \endcode * * KUrl handles escaping of URLs. This means that the specification * of a full URL will differ from the corresponding string that would specify a * local file or directory in file-operations like fopen. This is because an URL * doesn't allow certain characters and escapes them. (e.g. '#'->"%23", space->"%20") * (In a URL the hash-character '#' is used to specify a "reference", i.e. the position * within a document). * * The constructor KUrl(const QString&) expects a string properly escaped, * or at least non-ambiguous. * If you have the absolute path you should use KUrl::fromPath(const QString&). * \code * KUrl kurl = KUrl::fromPath("/bar/#foo#"); * QString url = kurl.url(); // -> "file:///bar/%23foo%23" * \endcode * * If you have the URL of a local file or directory and need the absolute path, * you would use toLocalFile(). * \code * KUrl url( "file:///bar/%23foo%23" ); * ... * if ( url.isLocalFile() ) * QString path = url.toLocalFile(); // -> "/bar/#foo#" * \endcode * * This must also be considered when you have separated directory and file * strings and need to put them together. * While you can simply concatenate normal path strings, you must take care if * the directory-part is already an escaped URL. * (This might be needed if the user specifies a relative path, and your * program supplies the rest from elsewhere.) * * Wrong: * \code * QString dirUrl = "file:///bar/"; * QString fileName = "#foo#"; * QString invalidURL = dirUrl + fileName; // -> "file:///bar/#foo#" won't behave like you would expect. * \endcode * Instead you should use addPath(): * Right: * \code * KUrl url( "file:///bar/" ); * QString fileName = "#foo#"; * url.addPath( fileName ); * QString validURL = url.url(); // -> "file:///bar/%23foo%23" * \endcode * * Also consider that some URLs contain the password, but this shouldn't be * visible. Your program should use prettyUrl() every time it displays a * URL, whether in the GUI or in debug output or... * * \code * KUrl url( "ftp://name:password@ftp.faraway.org/bar/%23foo%23"); * QString visibleURL = url.prettyUrl(); // -> "ftp://name@ftp.faraway.org/bar/%23foo%23" * \endcode * Note that prettyUrl() doesn't change the character escapes (like "%23"). * Otherwise the URL would be invalid and the user wouldn't be able to use it in another * context. * * @deprecated since 5.0; use QUrl directly */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE KUrl : public QUrl // krazy:exclude=dpointer,qclasses (krazy can't deal with embedded classes) { public: typedef QMap MetaDataMap; enum MimeDataFlags { DefaultMimeDataFlags = 0, NoTextExport = 1 }; /** * Options to be used in adjustPath */ enum AdjustPathOption { /** * strips a trailing '/', except when the path is already just "/". */ RemoveTrailingSlash, /** * Do not change the path. */ LeaveTrailingSlash, /** * adds a trailing '/' if there is none yet */ AddTrailingSlash }; /** * \class List kurl.h * * KUrl::List is a QList that contains KUrls with a few * convenience methods. * @see KUrl * @see QList */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE List : public QList //krazy:exclude=dpointer (just some convenience methods) { public: /** * Creates an empty List. */ List() { } /** * Creates a list that contains the given URL as only * item. * @param url the url to add. */ List(const KUrl &url); /** * Creates a list that contains the URLs from the given * list of strings. * @param list the list containing the URLs as strings */ List(const QStringList &list); /** * Creates a list that contains the URLs from the given QList. * @param list the list containing the URLs */ List(const QList &list); /** * Creates a list that contains the URLs from the given QList. * @param list the list containing the URLs * @since 4.7 */ List(const QList &list); /** * Converts the URLs of this list to a list of strings. * @return the list of strings */ QStringList toStringList() const; /** * Converts the URLs of this list to a list of strings. * * @param trailing use to add or remove a trailing slash to/from the path. * * @return the list of strings * * @since 4.6 */ QStringList toStringList(KUrl::AdjustPathOption trailing) const; /** * Converts this KUrl::List to a QVariant, this allows to use KUrl::List * in QVariant() constructor */ operator QVariant() const; /** * Converts this KUrl::List into a list of QUrl instances. * @since 4.7 */ operator QList() const; /** * Adds URLs data into the given QMimeData. * * By default, populateMimeData also exports the URLs as plain text, for e.g. dropping * onto a text editor. * But in some cases this might not be wanted, e.g. if adding other mime data * which provides better plain text data. * * WARNING: do not call this method multiple times on the same mimedata object, * you can add urls only once. But you can add other things, e.g. images, XML... * * @param mimeData the QMimeData instance used to drag or copy this URL * @param metaData KIO metadata shipped in the mime data, which is used for instance to * set a correct HTTP referrer (some websites require it for downloading e.g. an image) * @param flags set NoTextExport to prevent setting plain/text data into @p mimeData * * @deprecated since 5.0, use QMimeData::setUrls, followed by KUrlMimeData::setMetaData if you have metadata. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void populateMimeData(QMimeData *mimeData, const KUrl::MetaDataMap &metaData = MetaDataMap(), MimeDataFlags flags = DefaultMimeDataFlags) const; #endif /** * Adds URLs into the given QMimeData. * * This should add both the KDE-style URLs (eg: desktop:/foo) and * the "most local" version of the URLs (eg: * file:///home/jbloggs/Desktop/foo) to the mimedata. * * This method should be called on the KDE-style URLs. * * @code * QMimeData* mimeData = new QMimeData(); * * KUrl::List kdeUrls; * kdeUrls << "desktop:/foo"; * kdeUrls << "desktop:/bar"; * * KUrl::List normalUrls; * normalUrls << "file:///home/jbloggs/Desktop/foo"; * normalUrls << "file:///home/jbloggs/Desktop/bar"; * * kdeUrls.populateMimeData(normalUrls, mimeData); * @endcode * * @param mostLocalUrls the "most local" urls * @param mimeData the mime data object to populate * @param metaData KIO metadata shipped in the mime data, which is * used for instance to set a correct HTTP referrer * (some websites require it for downloading e.g. an * image) * @param flags set NoTextExport to prevent setting plain/text * data into @p mimeData. * @since 4.2 * @deprecated since 5.0, use KUrlMimeData::setUrls, followed by KUrlMimeData::setMetaData if you have metadata. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void populateMimeData(const KUrl::List &mostLocalUrls, QMimeData *mimeData, const KUrl::MetaDataMap &metaData = MetaDataMap(), MimeDataFlags flags = DefaultMimeDataFlags) const; #endif /** * Return true if @p mimeData contains URI data * @deprecated since 5.0, use QMimeData::hasUrls */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED static bool canDecode(const QMimeData *mimeData); #endif /** * Return the list of mimeTypes that can be decoded by fromMimeData * @deprecated since 5.0, use KUrlMimeData::mimeDataTypes */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED static QStringList mimeDataTypes(); #endif /** * Flags to be used in fromMimeData. * @since 4.2.3 * @deprecated since 5.0, use KUrlMimeData */ enum DecodeOptions { /** * When the mimedata contains both KDE-style URLs (eg: desktop:/foo) and * the "most local" version of the URLs (eg: file:///home/dfaure/Desktop/foo), * decode it as local urls. Useful in paste/drop operations that end up calling KIO, * so that urls from other users work as well. */ PreferLocalUrls, /** * When the mimedata contains both KDE-style URLs (eg: desktop:/foo) and * the "most local" version of the URLs (eg: file:///home/dfaure/Desktop/foo), * decode it as the KDE-style URL. Useful in DnD code e.g. when moving icons, * and the kde-style url is used as identifier for the icons. */ PreferKdeUrls }; /** * Extract a list of KUrls from the contents of @p mimeData. * Decoding will fail if @p mimeData does not contain any URLs, or if at * least one extracted URL is not valid. * @param mimeData the mime data to extract from; cannot be 0 * @param decodeOptions options for decoding * @param metaData optional pointer to a map holding the metadata * @return the list of urls * @since 4.2.3 * @deprecated since 5.0, use KUrlMimeData::urlsFromMimeData */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED static KUrl::List fromMimeData(const QMimeData *mimeData, DecodeOptions decodeOptions = PreferKdeUrls, KUrl::MetaDataMap *metaData = nullptr); #endif }; /** * Constructs an empty URL. */ KUrl(); /** * Destructs the KUrl object. */ ~KUrl(); /** * Usual constructor, to construct from a string. * @param urlOrPath An encoded URL or a path. * * @deprecated since 5.0, use QUrl(str) if it's a URL, QUrl::fromLocalFile(str) if it's a local path, * and QUrl::fromUserInput() if it could be either. */ KUrl(const QString &urlOrPath); /** * Constructor taking a char * @p urlOrPath, which is an _encoded_ representation * of the URL, exactly like the usual constructor. This is useful when * the URL, in its encoded form, is strictly ascii. * @param urlOrPath An encoded URL, or a path. * * @deprecated since 5.0, use QUrl(str) if it's a URL, QUrl::fromLocalFile(str) if it's a local path, * and QUrl::fromUserInput() if it could be either. */ - explicit KUrl(const char *urlOrPath); + KDELIBS4SUPPORT_DEPRECATED explicit KUrl(const char *urlOrPath); /** * Constructor taking a QByteArray @p urlOrPath, which is an _encoded_ representation * of the URL, exactly like the usual constructor. This is useful when * the URL, in its encoded form, is strictly ascii. * @param urlOrPath An encoded URL, or a path. * * @deprecated since 5.0, use QUrl(str) if it's a URL, QUrl::fromLocalFile(str) if it's a local path, * and QUrl::fromUserInput() if it could be either. */ - explicit KUrl(const QByteArray &urlOrPath); + KDELIBS4SUPPORT_DEPRECATED explicit KUrl(const QByteArray &urlOrPath); /** * Copy constructor. * @param u the KUrl to copy */ KUrl(const KUrl &u); /** * Converts from a QUrl. * @param u the QUrl */ KUrl(const QUrl &u); //krazy:exclude=qclasses /** * Constructor allowing relative URLs. * * @param _baseurl The base url. * @param _rel_url A relative or absolute URL. * If this is an absolute URL then @p _baseurl will be ignored. * If this is a relative URL it will be combined with @p _baseurl. * Note that _rel_url should be encoded too, in any case. * So do NOT pass a path here (use setPath or addPath instead). * * @deprecated since 5.0, use QUrl(_baseurl).resolved(QUrl(_rel_url)) */ KUrl(const KUrl &_baseurl, const QString &_rel_url); /** * Returns the protocol for the URL (i.e., file, http, etc.), lowercased. * @deprecated since 5.0, use QUrl::scheme() instead */ QString protocol() const; /** * @deprecated since 5.0, use QUrl::setScheme() instead */ void setProtocol(const QString &proto); /** * @deprecated since 5.0, use QUrl::userName() instead */ QString user() const; /** * @deprecated since 5.0, use QUrl::setUserName() instead */ void setUser(const QString &user); /** * @deprecated since 5.0, use QUrl::userName() and QString::isEmpty() instead */ bool hasUser() const; /** * @deprecated since 5.0, use QUrl::password() instead **/ QString pass() const; /** * @deprecated since 5.0, use QUrl::setPassword() instead **/ void setPass(const QString &pass); /** * @deprecated since 5.0, use QUrl::password() and QString::isEmpty() instead **/ bool hasPass() const; /** * @deprecated since 5.0, use QUrl::host() and QString::isEmpty() instead **/ bool hasHost() const; /** * @param trailing use to add or remove a trailing slash to/from the path. see adjustPath * @return The current decoded path. This does not include the query. Can * be QString() if no path is set. * * @deprecated since 5.0, use QUrl::path(). If RemoveTrailingSlash was used, use * url.adjusted(QUrl::StripTrailingSlash).path() */ QString path(AdjustPathOption trailing = LeaveTrailingSlash) const; /** * @param trailing use to add or remove a trailing slash to/from the local path. see adjustPath * * @return The current local path. Can * be QString() if no path is set. * * @deprecated since 5.0, use QUrl::toLocalFile() instead; if * RemoveTrailingSlash was used, use * url.adjusted(QUrl::StripTrailingSlash).toLocalFile() */ QString toLocalFile(AdjustPathOption trailing = LeaveTrailingSlash) const; /** * KUrl's setPath on an empty url implies the "file" protocol. * @deprecated since 5.0, use QUrl::fromLocalFile instead, for the case of local paths. * Do not port to QUrl u; u.setPath(...); since that would lead to a URL without a scheme! */ KDELIBS4SUPPORT_DEPRECATED void setPath(const QString &path); /** * @deprecated since 5.0, use QUrl::path() and QString::isEmpty() **/ bool hasPath() const; /** * Options to be used in cleanPath */ enum CleanPathOption { /** * if set, occurrences of consecutive directory separators * (e.g. /foo//bar) are cleaned up as well. (set by default) */ SimplifyDirSeparators = 0x00, /** * The opposite of SimplifyDirSeparators. */ KeepDirSeparators = 0x01 }; Q_DECLARE_FLAGS(CleanPathOptions, CleanPathOption) /** * Resolves "." and ".." components in path. * Some servers seem not to like the removal of extra '/' * even though it is against the specification in RFC 2396. * * @param options use KeepDirSeparators if you don't want to remove consecutive * occurrences of directory separator * @deprecated since 5.0, use url.setPath(QDir::cleanPath(url.path())) in file-management code. * No replacement available yet for the old HTTP issue mentionned above. */ void cleanPath(const CleanPathOption &options = SimplifyDirSeparators); /** * Add or remove a trailing slash to/from the path. * * If the URL has no path, then no '/' is added * anyway. And on the other side: If the path is "/", then this * character won't be stripped. Reason: "ftp://weis\@host" means something * completely different than "ftp://weis\@host/". So adding or stripping * the '/' would really alter the URL, while "ftp://host/path" and * "ftp://host/path/" mean the same directory. * * @param trailing RemoveTrailingSlash strips any trailing '/' and * AddTrailingSlash adds a trailing '/' if there is none yet * @deprecated For RemoveTrailingSlash, use url = url.adjusted(QUrl::StripTrailingSlash) (remember * to add the assignment!). For AppendTrailingSlash, use: * if (!url.path().endsWith('/')) url.setPath(url.path() + '/'). */ void adjustPath(AdjustPathOption trailing); /** * This is useful for HTTP. It looks first for '?' and decodes then. * The encoded path is the concatenation of the current path and the query. * @param _txt the new path and query. * * @deprecated since 5.0, use QUrl::setPath() and * QUrl::fromPercentEncoding() to set the encoded path; use QUrl::setQuery() * with an appropriate QUrl::ParsingMode value to set the query. */ void setEncodedPathAndQuery(const QString &_txt); /** * Option to be used in encodedPathAndQuery **/ enum EncodedPathAndQueryOption { /** * Permit empty path (default) */ PermitEmptyPath = 0x00, /** * If set to true then an empty path is substituted by "/" * (this is the opposite of PermitEmptyPath) */ AvoidEmptyPath = 0x01 }; Q_DECLARE_FLAGS(EncodedPathAndQueryOptions, EncodedPathAndQueryOption) /** * Returns the encoded path and the query. * * @param trailing add or remove a trailing '/', see adjustPath * @param options a set of flags from EncodedPathAndQueryOption * @return The concatenation of the encoded path , '?' and the encoded query. * * @deprecated since 5.0, use QUrl::path() and QUrl::query(); * QUrl::adjusted() can be used to remove a trailing slash if necessary. */ QString encodedPathAndQuery(AdjustPathOption trailing = LeaveTrailingSlash, const EncodedPathAndQueryOptions &options = PermitEmptyPath) const; /** * @param query This is considered to be encoded. This has a good reason: * The query may contain the 0 character. * * The query should start with a '?'. If it doesn't '?' is prepended. * * @deprecated since 5.0, use QUrl::setQuery(QString), but note that it * doesn't start with '?' (it uses null vs empty, instead). */ void setQuery(const QString &query); /** * Returns the query of the URL. * The query may contain the 0 character. * If a query is present it always starts with a '?'. * A single '?' means an empty query. * An empty string means no query. * @return The encoded query, or QString() if there is none. * * @deprecated since 5.0, use QByteArray QUrl::query(), but note that it * doesn't start with '?' (QUrl::hasQuery() can be used to distinguish * between no query and an empty query). */ QString query() const; /** * Returns the @em encoded reference (or "fragment") of the URL (everything after '#'). * @return the encoded reference, or QString("") if the reference part is empty, * or QString() if the URL has no reference. * @deprecated since 5.0, use QUrl::fragment(QUrl::FullyEncoded) */ QString ref() const; /** * Sets the reference/fragment part (everything after '#'). * If you have an encoded fragment already (as a QByteArray), you can call setFragment directly. * @param fragment the @em encoded reference (or QString() to remove it). * @deprecated since 5.0, use QUrl::setFragment() */ void setRef(const QString &fragment); /** * Checks whether the URL has a reference/fragment part. * @return true if the URL has a reference part. In a URL like * http://www.kde.org/kdebase.tar#tar:/README it would * return true, too. * @deprecated since 5.0, use QUrl::hasFragment() */ bool hasRef() const; /** * Returns the @em unencoded reference (or "fragment") of the URL (everything after '#'). * @return the unencoded reference, or QString("") if the reference part is empty, * or QString() if the URL has no reference. * @see split * @see hasSubUrl * @see encodedHtmlRef * @deprecated since 5.0, use QUrl::fragment(QUrl::FullyDecoded) */ QString htmlRef() const; /** * Returns the @em encoded reference (or "fragment") of the URL (everything after '#'). * @return the encoded reference, or QString("") if the reference part is empty, * or QString() if the URL has no reference. * @see ref * @deprecated since 5.0, use QUrl::fragment(QUrl::FullyEncoded) */ QString encodedHtmlRef() const; /** * Sets the HTML-style reference. * * @param ref The new reference. This is considered to be @em not encoded in * contrast to setRef(). Use QString() to remove it. * @see htmlRef() * @deprecated since 5.0, use QUrl::setFragment(ref, QUrl::DecodedMode) */ void setHTMLRef(const QString &ref); /** * Checks whether there is a HTML reference. * @return true if the URL has an HTML-style reference. * @see htmlRef() * @deprecated since 5.0, use QUrl::hasFragment() */ bool hasHTMLRef() const; /** * Checks whether the file is local. * @return true if the file is a plain local file (i.e. uses the file protocol * and no hostname, or the local hostname). * When isLocalFile returns true, you can use toLocalFile to read the file contents. * Otherwise you need to use KIO (e.g. KIO::get). */ bool isLocalFile() const; /** * Adds encoding information to url by adding a "charset" parameter. If there * is already a charset parameter, it will be replaced. * @param encoding the encoding to add or QString() to remove the * encoding. */ void setFileEncoding(const QString &encoding); /** * Returns encoding information from url, the content of the "charset" * parameter. * @return An encoding suitable for QTextCodec::codecForName() * or QString() if not encoding was specified. */ QString fileEncoding() const; /** * Checks whether the URL has any sub URLs. See split() * for examples for sub URLs. * @return true if the file has at least one sub URL. * @see split */ bool hasSubUrl() const; /** * Adds to the current path. * Assumes that the current path is a directory. @p txt is appended to the * current path. The function adds '/' if needed while concatenating. * This means it does not matter whether the current path has a trailing * '/' or not. If there is none, it becomes appended. If @p txt * has a leading '/' then this one is stripped. * * @param txt The text to add. It is considered to be decoded. * @deprecated since 5.0, use u.setPath(u.path() + '/' + txt). * If the path might already have a trailing slash, use u = u.adjusted(QUrl::StripTrailingSlash) first. */ void addPath(const QString &txt); /** * Options for queryItems. Currently, only one option is * defined: * * @param CaseInsensitiveKeys normalize query keys to lowercase. **/ enum QueryItemsOption { CaseInsensitiveKeys = 1 }; Q_DECLARE_FLAGS(QueryItemsOptions, QueryItemsOption) /** * Returns the list of query items as a map mapping keys to values. * * This does the same as QUrl::queryItems(), except that it * decodes "+" into " " in the value, supports CaseInsensitiveKeys, * and returns a different data type. * * @param options any of QueryItemsOption ored together. * * @return the map of query items or the empty map if the url has no * query items. * @deprecated since 5.0, use QUrlQuery(url).queryItems() */ QMap< QString, QString > queryItems(const QueryItemsOptions &options = nullptr) const; /** * Returns the value of a certain query item. * * This does the same as QUrl::queryItemValue(), except that it * decodes "+" into " " in the value. * * @param item Item whose value we want * * @return the value of the given query item name or QString() if the * specified item does not exist. * @deprecated since 5.0, use QUrlQuery(url).queryItemValue(item) */ QString queryItem(const QString &item) const; /** * Add an additional query item. * To replace an existing query item, the item should first be * removed with removeQueryItem() * * @param _item Name of item to add * @param _value Value of item to add * @deprecated since 5.0, use QUrlQuery(url), then addQueryItem(), then QUrl::setQuery() */ void addQueryItem(const QString &_item, const QString &_value); /** * Sets the filename of the path. * In comparison to addPath() this function does not assume that the current * path is a directory. This is only assumed if the current path ends with '/'. * * Any reference is reset. * * @param _txt The filename to be set. It is considered to be decoded. If the * current path ends with '/' then @p _txt int just appended, otherwise * all text behind the last '/' in the current path is erased and * @p _txt is appended then. It does not matter whether @p _txt starts * with '/' or not. * @deprecated since 5.0, use u = u.adjusted(QUrl::RemoveFilename); followed by * u.setPath(u.path() + txt); */ void setFileName(const QString &_txt); /** * option to be used in fileName and directory */ enum DirectoryOption { /** * This tells whether a trailing '/' should be ignored. * * If the flag is not set, for both file:///hallo/torben/ and file:///hallo/torben * the fileName is "torben" and the path is "hallo" * * If the flag is set, then everything behind the last '/'is considered to be the filename. * So "hallo/torben" will be the path and the filename will be empty. */ ObeyTrailingSlash = 0x02, /** * tells whether the returned result should end with '/' or not. * If the flag is set, '/' is added to the end of the path * * If the path is empty or just "/" then this flag has no effect. * * This option should only be used in directory(), it has no effect in fileName() */ AppendTrailingSlash = 0x04, /** * Opposite of ObeyTrailingSlash (default) * fileName("file:/foo/") and fileName("file:/foo") is "foo" in both cases. */ IgnoreTrailingSlash = 0x01 }; Q_DECLARE_FLAGS(DirectoryOptions, DirectoryOption) /** * Returns the filename of the path. * @param options a set of DirectoryOption flags. (StripTrailingSlashFromResult has no effect) * @return The filename of the current path. The returned string is decoded. Null * if there is no file (and thus no path). * @deprecated since 5.0, use url.fileName(), which behaves like ObeyTrailingSlash though. * To get rid of the trailing slash if there could be one, use adjusted(QUrl::StripTrailingSlash) first. */ QString fileName(const DirectoryOptions &options = IgnoreTrailingSlash) const; /** * Returns the directory of the path. * @param options a set of DirectoryOption flags * @return The directory part of the current path. Everything between the last and the second last '/' * is returned. For example file:///hallo/torben/ would return "/hallo/torben/" while * file:///hallo/torben would return "hallo/". The returned string is decoded. * QString() is returned when there is no path. * @deprecated since 5.0, use url.adjusted(QUrl::RemoveFilename).path(), which behaves like ObeyTrailingSlash though. * To get rid of the trailing slash if there could be one, use adjusted(QUrl::StripTrailingSlash) first. * Do not combine the two calls! You want to remove the trailing slash first, and then remove the filename. */ QString directory(const DirectoryOptions &options = IgnoreTrailingSlash) const; /** * Set the directory to @p dir, leaving the filename empty. */ void setDirectory(const QString &dir); /** * Changes the directory by descending into the given directory. * It is assumed the current URL represents a directory. * If @p dir starts with a "/" the * current URL will be "protocol://host/dir" otherwise @p _dir will * be appended to the path. @p _dir can be ".." * This function won't strip protocols. That means that when you are in * file:///dir/dir2/my.tgz#tar:/ and you do cd("..") you will * still be in file:///dir/dir2/my.tgz#tar:/ * * @param _dir the directory to change to * @return true if successful */ bool cd(const QString &_dir); /** * Returns the URL as string, with all escape sequences intact, * encoded in a given charset. * This is used in particular for encoding URLs in UTF-8 before using them * in a drag and drop operation. * Please note that the string returned by url() will include * the password of the URL. If you want to show the URL to the * user, use prettyUrl(). * * @param trailing use to add or remove a trailing slash to/from the path. See adjustPath * @return The complete URL, with all escape sequences intact, encoded * in a given charset. * @see prettyUrl() * * @deprecated since 5.0, use QUrl::toString() instead. * In case of RemoveTrailingSlash, call adjusted(QUrl::StripTrailingSlash) first. * AddTrailingSlash is not available directly, test if path ends with '/', and if not setPath(path() + '/'). */ QString url(AdjustPathOption trailing = LeaveTrailingSlash) const; /** * Returns the URL as string in human-friendly format. * Example: * \code * http://localhost:8080/test.cgi?test=hello world&name=fred * \endcode * @param trailing use to add or remove a trailing slash to/from the path. see adjustPath. * * @return A human readable URL, with no non-necessary encodings/escaped * characters. Password will not be shown. * @see url() * * @deprecated since 5.0, use QUrl::toDisplayString() instead. */ QString prettyUrl(AdjustPathOption trailing = LeaveTrailingSlash) const; /** * Return the URL as a string, which will be either the URL (as prettyUrl * would return) or, when the URL is a local file without query or ref, * the path. * Use this method, to display URLs to the user. * You can give the result of pathOrUrl back to the KUrl constructor, it accepts * both paths and urls. * * @return the new KUrl * @param trailing use to add or remove a trailing slash to/from the path. see adjustPath. * @since 4.2 * @deprecated since 5.0, use QUrl::toDisplayString(QUrl::PreferLocalFile | ...) instead. */ QString pathOrUrl(AdjustPathOption trailing = LeaveTrailingSlash) const; /** * Returns the URL as a string, using the standard conventions for mime data * (drag-n-drop or copy-n-paste). * Internally used by KUrl::List::fromMimeData, which is probably what you want to use instead. * @deprecated since 5.0, use QMimeData::setUrls directly, or KUrlMimeData::setUrls */ QString toMimeDataString() const; /** * This function is useful to implement the "Up" button in a file manager for example. * cd() never strips a sub-protocol. That means that if you are in * file:///home/x.tgz#gzip:/#tar:/ and hit the up button you expect to see * file:///home. The algorithm tries to go up on the right-most URL. If that is not * possible it strips the right most URL. It continues stripping URLs. * @return a URL that is a level higher * @deprecated since 5.0, use KIO::upUrl() instead, from kio/global.h */ KUrl upUrl() const; KUrl &operator=(const KUrl &_u); - // Define those, since the constructors are explicit + // Define those, since the constructors are KDELIBS4SUPPORT_DEPRECATED explicit KUrl &operator=(const char *_url) { *this = KUrl(_url); return *this; } KUrl &operator=(const QByteArray &_url) { *this = KUrl(_url); return *this; } KUrl &operator=(const QString &_url) { *this = KUrl(_url); return *this; } bool operator==(const KUrl &_u) const; bool operator==(const QString &_u) const; bool operator!=(const KUrl &_u) const { return !(*this == _u); } bool operator!=(const QString &_u) const { return !(*this == _u); } /** * Converts this KUrl to a QVariant, this allows to use KUrl * in QVariant() constructor */ operator QVariant() const; /** * The same as equals(), just with a less obvious name. * Compares this url with @p u. * @param u the URL to compare this one with. * @param ignore_trailing set to true to ignore trailing '/' characters. * @return True if both urls are the same. If at least one of the urls is invalid, * false is returned. * @see operator==. This function should be used if you want to * ignore trailing '/' characters. * @deprecated since 4.0, use equals() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool cmp(const KUrl &u, bool ignore_trailing = false) const; #endif /** * Flags to be used in URL comparison functions like equals, or urlcmp */ enum EqualsOption { /** * ignore trailing '/' characters. The paths "dir" and "dir/" are treated the same. * Note however, that by default, the paths "" and "/" are not the same * (For instance ftp://user@host redirects to ftp://user@host/home/user (on a linux server), * while ftp://user@host/ is the root dir). * This is also why path(RemoveTrailingSlash) for "/" returns "/" and not "". * * When dealing with web pages however, you should also set AllowEmptyPath so that * no path and "/" are considered equal. */ CompareWithoutTrailingSlash = 0x01, /** * disables comparison of HTML-style references. */ CompareWithoutFragment = 0x02, /** * Treat a URL with no path as equal to a URL with a path of "/", * when CompareWithoutTrailingSlash is set. * Example: * KUrl::urlcmp("http://www.kde.org", "http://www.kde.org/", KUrl::CompareWithoutTrailingSlash | KUrl::AllowEmptyPath) * returns true. * This option is ignored if CompareWithoutTrailingSlash isn't set. * @since 4.5 */ AllowEmptyPath = 0x04 }; Q_DECLARE_FLAGS(EqualsOptions, EqualsOption) /** * Compares this url with @p u. * @param u the URL to compare this one with. * @param options a set of EqualsOption flags * @return True if both urls are the same. If at least one of the urls is invalid, * false is returned. * @see operator==. This function should be used if you want to * set additional options, like ignoring trailing '/' characters. * @deprecated since 5.0, use matches(u, formattingOptions) * equals(u, KUrl::CompareWithoutTrailingSlash) becomes matches(u, QUrl::StripTrailingSlash) * equals(u, KUrl::CompareWithoutFragment) becomes matches(u, QUrl::RemoveFragment) * equals(u, KUrl::CompareWithoutTrailingSlash|KUrl::AllowEmptyPath) needs manual handling * (it was mostly unused). */ bool equals(const KUrl &u, const EqualsOptions &options = nullptr) const; /** * Checks whether the given URL is parent of this URL. * For instance, ftp://host/dir/ is a parent of ftp://host/dir/subdir/subsubdir/. * @return true if this url is a parent of @p u (or the same URL as @p u) * @deprecated since 5.0. url.isParentOf(child) is now * url.isParentOf(child) || url.matches(child, QUrl::StripTrailingSlash); */ bool isParentOf(const KUrl &child) const; /** * Splits nested URLs like file:///home/weis/kde.tgz#gzip:/#tar:/kdebase * A URL like http://www.kde.org#tar:/kde/README.hml#ref1 will be split in * http://www.kde.org and tar:/kde/README.html#ref1. * That means in turn that "#ref1" is an HTML-style reference and not a new sub URL. * Since HTML-style references mark * a certain position in a document this reference is appended to every URL. * The idea behind this is that browsers, for example, only look at the first URL while * the rest is not of interest to them. * * * @param _url The URL that has to be split. * @return An empty list on error or the list of split URLs. * @see hasSubUrl */ static List split(const QString &_url); /** * Splits nested URLs like file:///home/weis/kde.tgz#gzip:/#tar:/kdebase * A URL like http://www.kde.org#tar:/kde/README.hml#ref1 will be split in * http://www.kde.org and tar:/kde/README.html#ref1. * That means in turn that "#ref1" is an HTML-style reference and not a new sub URL. * Since HTML-style references mark * a certain position in a document this reference is appended to every URL. * The idea behind this is that browsers, for example, only look at the first URL while * the rest is not of interest to them. * * @return An empty list on error or the list of split URLs. * * @param _url The URL that has to be split. * @see hasSubUrl */ static List split(const KUrl &_url); /** * Reverses split(). Only the first URL may have a reference. This reference * is considered to be HTML-like and is appended at the end of the resulting * joined URL. * @param _list the list to join * @return the joined URL */ static KUrl join(const List &_list); /** * Creates a KUrl object from a QString representing an absolute local path. - * KUrl url( somePath ) is almost the same, but this method is more explicit, + * KUrl url( somePath ) is almost the same, but this method is more KDELIBS4SUPPORT_DEPRECATED explicit, * avoids the path-or-url detection in the KUrl constructor, and parses * "abc:def" as a filename, not as URL. * * @param text the local path * @return the new KUrl * * @deprecated since 5.0, use QUrl::fromLocalFile */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED static KDELIBS4SUPPORT_DEPRECATED KUrl fromPath(const QString &text) { return fromLocalFile(text); } #endif /** * @deprecated since 4.0, use QUrl() instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED static KDELIBS4SUPPORT_DEPRECATED KUrl fromPathOrUrl(const QString &text); #endif /** * Adds URL data into the given QMimeData. * * By default, populateMimeData also exports the URL as plain text, for e.g. dropping * onto a text editor. * But in some cases this might not be wanted, e.g. if adding other mime data * which provides better plain text data. * * WARNING: do not call this method multiple times, use KUrl::List::populateMimeData instead. * * @param mimeData the QMimeData instance used to drag or copy this URL * @param metaData KIO metadata shipped in the mime data, which is used for instance to * set a correct HTTP referrer (some websites require it for downloading e.g. an image) * @param flags set NoTextExport to prevent setting plain/text data into @p mimeData * * @deprecated since 5.0, use QMimeData::setUrls(QList() << url), * followed by KUrlMimeData::setMetaData if you have metadata. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void populateMimeData(QMimeData *mimeData, const MetaDataMap &metaData = MetaDataMap(), MimeDataFlags flags = DefaultMimeDataFlags) const; #endif /** * Convenience function. * * Returns whether '_url' is likely to be a "relative" URL instead of * an "absolute" URL. * * This is mostly meant for KUrl(url, relativeUrl). * * If you are looking for the notion of "relative path" (foo) vs "absolute path" (/foo), * use QUrl::isRelative() instead. * Indeed, isRelativeUrl() returns true for the string "/foo" since it doesn't contain a protocol, * while KUrl("/foo").isRelative() is false since the KUrl constructor turns it into file:///foo. * The two methods basically test the same thing, but this one takes a string (which is faster) * while the class method requires a QUrl/KUrl which gives a more expected result, given * the "magic" in the KUrl constructor. * * @param _url URL to examine * @return true when the URL is likely to be "relative", false otherwise. * @deprecated since 5.0, use QUrl(_url)::isRelative instead */ static bool isRelativeUrl(const QString &_url); /** * Convenience function * * Returns a "relative URL" based on @p base_url that points to @p url. * * If no "relative URL" can be created, e.g. because the protocol * and/or hostname differ between @p base_url and @p url an absolute * URL is returned. * Note that if @p base_url represents a directory, it should contain * a trailing slash. * @param base_url the URL to derive from * @param url new URL * @see adjustPath() * @deprecated since 5.0, check that the URLs have the same scheme+host+port+user+pass, * then make the path relative with QDir(base_url.path()).relativeFilePath(url.path()) */ static QString relativeUrl(const KUrl &base_url, const KUrl &url); /** * Convenience function * * Returns a relative path based on @p base_dir that points to @p path. * @param base_dir the base directory to derive from * @param path the new target directory * @param isParent A pointer to a boolean which, if provided, will be set to reflect * whether @p path has @p base_dir is a parent dir. * @deprecated since 5.0, use QDir(base_dir).relativeFilePath(path). isParent can be * replaced with a call to startsWith("..") on the result value. */ static QString relativePath(const QString &base_dir, const QString &path, bool *isParent = nullptr); private: void _setQuery(const QString &query); void _setEncodedUrl(const QByteArray &url); operator QString() const; // forbidden, use url(), prettyUrl(), or pathOrUrl() instead. }; Q_DECLARE_OPERATORS_FOR_FLAGS(KUrl::EncodedPathAndQueryOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KUrl::CleanPathOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KUrl::QueryItemsOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KUrl::EqualsOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KUrl::DirectoryOptions) Q_DECLARE_METATYPE(KUrl) Q_DECLARE_METATYPE(KUrl::List) /** * \relates KUrl * Compares URLs. They are parsed, split and compared. * Two malformed URLs with the same string representation * are nevertheless considered to be unequal. * That means no malformed URL equals anything else. * @deprecated since 4.5, use QUrl(_url1) == QUrl(_url2) instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED_EXPORT bool urlcmp(const QString &_url1, const QString &_url2); // KDE5: remove, KUrl::equals is better API #endif /** * \relates KUrl * Compares URLs. They are parsed, split and compared. * Two malformed URLs with the same string representation * are nevertheless considered to be unequal. * That means no malformed URL equals anything else. * * @param _url1 A reference URL * @param _url2 A URL that will be compared with the reference URL * @param options a set of KUrl::EqualsOption flags * @deprecated since 4.5, use QUrl(_url1).adjusted(options) == QUrl(_url2).adjusted(options) instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED_EXPORT bool urlcmp(const QString &_url1, const QString &_url2, const KUrl::EqualsOptions &options); // KDE5: remove, KUrl::equals is better API #endif #endif diff --git a/src/kdeui/k4style.h b/src/kdeui/k4style.h index 17a922c2..b339f2da 100644 --- a/src/kdeui/k4style.h +++ b/src/kdeui/k4style.h @@ -1,1604 +1,1604 @@ /** * KStyle for KDE4 * Copyright (C) 2004-2005 Maksim Orlovich * Copyright (C) 2005,2006 Sandro Giessl * * Based in part on the following software: * KStyle for KDE3 * Copyright (C) 2001-2002 Karol Szwed * Portions (C) 1998-2000 TrollTech AS * Keramik for KDE3, * Copyright (C) 2002 Malte Starostik * (C) 2002-2003 Maksim Orlovich * Portions (C) 2001-2002 Karol Szwed * (C) 2001-2002 Fredrik Höglund * (C) 2000 Daniel M. Duley * (C) 2000 Dirk Mueller * (C) 2001 Martijn Klingens * (C) 2003 Sandro Giessl * 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 KDE_K4STYLE_H #define KDE_K4STYLE_H #include #include #include #include #include class QStyleOptionProgressBar; class QStyleOptionTab; class K4StylePrivate; /** * Makes style coding more convenient. * * @todo and allows to style KDE specific widgets. * * K4Style strives to ease style development by implementing various QStyle * methods. These implementations are based on * -# the concept of Layout Properties. These properties can be set using * setWidgetLayoutProp(). K4Style uses this information to respect various * metrics (like space between primitives or margins around widget contents) * or turn specific features on or off. * -# the concept of K4Style Primitives. These can be implemented by overriding * drawKStylePrimitive() and providing drawing methods for specific * primitives. Often, the drawing of more complex widgets consists of * several primitives. * * In the following modules, information about related members is collected: * - \ref OptionGroup * - \ref WidgetGroup * * @author Maksim Orlovich (maksim\@kde.org) * @author Sandro Giessl (giessl\@kde.org) * * @see KStyleFactory for how to implement the style plugin interface. */ // TODO: From 'Qt4 Themes' discussion on kde-devel // - Remi Villatel: extend QStyle enums for KColorButton, KColorCombo, KKeyButton, split PE_HeaderSection into KPopupTitle, PopupMenuTitle, TaskContainer) // - RV: KLineEdit "plays with its colors" - related to K4Style? // - RV: KMulitTabBarTab ... does it need support from K4Style (instead of manual button rotation etc.)? Or is it dumped already? // - RV: KTabCtl draws itself mimicking QDrawShadeThingies // - RV: fixed colors (e.g. Konqueror, KToolbarButton label text ->KPE_ToolbarButton?): To prevent hacks like "preventing any PaletteChange()"... mor related to KDE4 color schemes... I guess // - LM: User interface guidelines... related to K4Style? // - e.g. drawFancyPE() in kdeui for KDE widgets: check "qobject_cast(style())", or fallback drawing... // TODO: implement standardIcon().. and what about standardPalette()? // TODO: maybe the arrow in CE_PushButtonLabel should be painted in CE_PushButtonBevel like QCommonStyle class KDELIBS4SUPPORT_DEPRECATED_EXPORT K4Style: public QCommonStyle { Q_OBJECT public: K4Style(); ~K4Style(); /** * Returns the default widget style. */ static QString defaultStyle(); /** * Runtime element extension * This is just convenience and does /not/ require the using widgets style to inherit K4Style * (i.e. calling this while using cleanlooks won't segfault or so but just return 0) * Returns a unique id for an element string (e.g. "CE_CapacityBar") * * For simplicity, only StyleHints, ControlElements and their SubElements are supported * If you don't need extended SubElement functionality, just drop it * * @param element The style element, represented as string. * Naming convention: "appname.(2-char-element-type)_element" * where the 2-char-element-type is of {SH, CE, SE} * (widgets in kdelibs don't have to pass the appname) * examples: "CE_CapacityBar", "amarok.CE_Analyzer" * @param widget Your widget ("this") passing this is mandatory, passing NULL will just return 0 * @returns a unique id for the @p element string or 0, if the element is not supported by the * widgets current style * * Important notes: * 1) If your string lacks the matching "SH_", "CE_" or "SE_" token the element * request will be ignored (return is 0) * 2) Try to avoid custom elements and use default ones (if possible) to get better style support * and keep UI coherency * 3) If you cache this value (good idea, this requires a map lookup) don't (!) forget to catch * style changes in QWidget::changeEvent() */ static StyleHint customStyleHint(const QString &element, const QWidget *widget); static ControlElement customControlElement(const QString &element, const QWidget *widget); static SubElement customSubElement(const QString &element, const QWidget *widget); protected: /** * Runtime element extension, allows inheriting styles to add support custom elements * merges supporting inherit chains * Supposed to be called e.g. in your constructor. * * NOTICE: in order to have this work, your style must provide * an "X-KDE-CustomElements" classinfo, i.e. * class MyStyle : public K4Style * { * Q_OBJECT * Q_CLASSINFO ("X-KDE-CustomElements", "true") * * public: * ..... * } * * @param element The style element, represented as string. * Suggested naming convention: appname.(2-char-element-type)_element * where the 2-char-element-type is of {SH, CE, SE} * widgets in kdelibs don't have to pass the appname * examples: "CE_CapacityBar", "amarok.CE_Analyzer" * * Important notes: * 1) If your string lacks the matching "SH_", "CE_" or "SE_" token the element * request will be ignored (return is 0) * 2) To keep UI coherency, don't support any nonsense in your style, but convince app developers * to use standard elements - if available */ StyleHint newStyleHint(const QString &element); ControlElement newControlElement(const QString &element); SubElement newSubElement(const QString &element); /** @name Helper Methods * These are methods helping with QRect handling, for example. */ //@{ /** Draws inside the rectangle using a thinkness 0 pen. This is what drawRect in Qt3 used to do. */ void drawInsideRect(QPainter *p, const QRect &r) const; /** Returns a w x h QRect center inside the 'in' rectangle */ QRect centerRect(const QRect &in, int w, int h) const; /** Return a size-dimension QRect centered inside the 'in' rectangle */ QRect centerRect(const QRect &in, const QSize &size) const; //@} /** * \defgroup OptionGroup K4Style option representation * Things related to the representation of options passed when drawing things. */ //@{ /** * @brief A representation for colors for use as a widget layout property. * * This marshals to and from integers. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT ColorMode //krazy:exclude=dpointer (lightweight helper) { public: /** K4Style understands two kinds of colors: * -# Palette entries. This means the item must be painted with a specific * color role from the palette. * -# Auto-selected black or white, dependent on the brightness of a certain * color role from the palette. */ enum Mode { PaletteEntryMode, BWAutoContrastMode = 0x8000000 }; private: Mode mode; QPalette::ColorRole role; public: /// Constructor, using a the given palette role @p _role /// and a default mode. ColorMode(QPalette::ColorRole _role); - /// Constructor with explicit color mode and palette roles. + /// Constructor with KDELIBS4SUPPORT_DEPRECATED explicit color mode and palette roles. ColorMode(Mode _mode, QPalette::ColorRole _role); /// Represent as an int to store as a property operator int() const; /// Decode from an int. ColorMode(int encoded); /// Return the color corresponding to our role from the palette, /// automatically compensating for the contrast mode. QColor color(const QPalette &palette); }; /** Base for our own option classes. The idea here is that Option is the main base, and all the public bases inherit off it indirectly using OptionBase, which helps implement the default handling When implementing the actual types, just implement the default ctor, filling in defaults, and you're set. */ struct KDELIBS4SUPPORT_DEPRECATED_EXPORT Option { virtual ~Option() {} //So dynamic_cast works, and g++ shuts up }; /** Intermediatary base that helps implement subtypes of Option that properly handle defaults EventualSubtype --- the type of option which will be implemented by inheritting of this class BaseType --- the type of option from which this should inherit */ template struct KDELIBS4SUPPORT_DEPRECATED_EXPORT OptionBase: public BaseType { /** Default value for this option. Uses the default constructor of EventualSubtype to create the option. */ static EventualSubtype *defaultOption() { static EventualSubtype *theDefault = nullptr; //### function static, not very nice, - //but avoids need for explicit instantiation. + //but avoids need for KDELIBS4SUPPORT_DEPRECATED explicit instantiation. if (!theDefault) { theDefault = new EventualSubtype; } return theDefault; } }; /** The extractOption method casts the passed in option object, and returns it, if available, or the defaults for the given type. When implementing drawing of things with associated options, just use this to extract the parameter. */ template static T extractOption(Option *option); /** Option representing the color of the thing to draw. Used for arrows, and for text (the latter actually uses TextOption) */ struct KDELIBS4SUPPORT_DEPRECATED_EXPORT ColorOption: public OptionBase { /** Color to use for the drawing. Public, modifiable. */ ColorMode color; ColorOption(): color(QPalette::ButtonText) {} }; /** Option for drawing icons: represents whether the icon should be active or not. The implementation is responsible for all other flags */ struct KDELIBS4SUPPORT_DEPRECATED_EXPORT IconOption: public OptionBase { bool active; ///< Is the icon active? QIcon icon; ///< Icon drawn by this option QSize size; IconOption(): active(false) {} }; /** * Option for drawing double scrollbar buttons, indicating whether * a button should be drawn active or not. * @sa ScrollBar::Primitive */ struct KDELIBS4SUPPORT_DEPRECATED_EXPORT DoubleButtonOption: public OptionBase { /** * List of active button possibilities. */ enum ActiveButton { None, ///< No button is active Top, ///< Vertical scrollbar: The upper button is active Left, ///< Horizontal scrollbar: The left button is active Right, ///< Horizontal scrollbar: The right button is active Bottom ///< Vertical scrollbar: The lower button is active }; /** Whether any of the two buttons is active; and if yes, which one. */ ActiveButton activeButton; DoubleButtonOption(): activeButton(None) {} /** * Convenience constructor. * * @param ab initializes the active button property */ DoubleButtonOption(ActiveButton ab): activeButton(ab) {} }; /** * Option for drawing WT_Window titlebar buttons, indicating whether * the button is pressed, and containing the window icon * @sa Window */ struct KDELIBS4SUPPORT_DEPRECATED_EXPORT TitleButtonOption: public OptionBase { bool active; ///< whether the button is pressed QIcon icon; ///< window Icon // /// whether the button is hovered, this doesn't work at the moment (not even in any Qt style)... // bool hover; TitleButtonOption(): active(false)/*, hover(false)*/ {} /** * Convenience constructor. * * @param act initializes the active button property */ TitleButtonOption(bool act): active(act) {} }; ///Option representing text drawing info. For Generic::Text. struct KDELIBS4SUPPORT_DEPRECATED_EXPORT TextOption: public OptionBase { Qt::Alignment hAlign; ///< The horizontal alignment, default is Qt::AlignLeft QString text; ///< The text to draw TextOption(); /** * Convenience constructor. * * @param _text initializes the text string property */ TextOption(const QString &_text); /** * Called by the constructor to set the default value of @c hAlign */ void init(); }; //@} /** * \defgroup WidgetGroup K4Style widget representation * Things related to the representation of widgets. */ //@{ /** This enum is used to represent K4Style's concept of a widget, and to associate drawing requests and metrics with it. The generic value is used for primitives and metrics that are common between many widgets */ enum WidgetType { WT_Generic, ///< @sa Generic WT_PushButton, ///< @sa PushButton WT_Splitter, ///< @sa Splitter WT_CheckBox, ///< @sa CheckBox WT_RadioButton, ///< @sa RadioButton WT_DockWidget, ///< @sa DockWidget WT_ProgressBar, ///< @sa ProgressBar WT_MenuBar, ///< @sa MenuBar WT_MenuBarItem, ///< @sa MenuBarItem WT_Menu, ///< @sa Menu WT_MenuItem, ///< @sa MenuItem WT_ScrollBar, ///< @sa ScrollBar WT_TabBar, ///< @sa TabBar WT_TabWidget, ///< @sa TabWidget WT_Slider, ///< @sa Slider WT_Tree, ///< @sa Tree WT_SpinBox, ///< @sa SpinBox WT_ComboBox, ///< @sa ComboBox WT_Header, ///< @sa Header WT_LineEdit, ///< @sa LineEdit WT_GroupBox, ///< @sa GroupBox WT_StatusBar, ///< @sa StatusBar WT_ToolBar, ///< @sa ToolBar WT_ToolButton, ///< @sa ToolButton WT_ToolBoxTab, ///< @sa ToolBoxTab WT_Window, ///< @sa Window WT_Limit = 0xFFFF ///< For enum extensibility }; /** These constants describe how to access various fields of a margin property. For example, to set an additional top margin of 2 pixels, use * \code * setWidgetLayoutProp(WT_SomeWidget, SomeWidget::Margin + Top, 2); * \endcode */ enum MarginOffsets { MainMargin, /**< The main margin is applied equally on each side. * In the example above, 'SomeWidget::Margin+MainMargin' is * the same as 'SomeWidget::Margin'. */ Top, ///< Apply an additional top margin. Bot, ///< Apply an additional bottom margin. Left, ///< Apply an additional left margin. Right, ///< Apply an additional right margin. MarginInc /**< Used to reserve space in an enum for the Top, Bot, * Left, Right margins. */ }; /** * Basic primitive drawing operations. Are intended to be used in every * WidgetType combination. */ struct Generic { /** * Layout properties. These can be set with setWidgetLayoutProp() * Generic LayoutProps contain a few properties which are not * directly related to a specific widget type. */ enum LayoutProp { DefaultFrameWidth, ///< The FrameWidth used by LineEdit, etc..., default is \b 2 [sets QStyle::PM_DefaultFrameWidth] DefaultLayoutSpacing, ///< The spacing used by layouts, unless the style implements layoutSpacingImplementation(), default is \b 6 [sets QStyle::PM_DefaultLayoutSpacing] DefaultLayoutMargin ///< The margin used by layouts, default is \b 9 [sets QStyle::PM_DefaultChildMargin and QStyle::PM_DefaultTopLevelMargin] }; /** * Primitive drawing operations. * @note The arrows are centering primitives, which means they draw in * the center of the specified rectangle. */ enum Primitive { Text = 0xFFFF, ///< Passes in TextOption Icon, ///< Passes in IconOption FocusIndicator, ///< Indication that this widget has focus Frame, /**< Frame around widget * @note QFrame derived widgets are painted using * WT_Generic widget type and this Generic::Frame primitive. */ ArrowUp, ///< Up arrow (pointing up) ArrowDown, ///< Down arrow ArrowRight, ///< Right arrow ArrowLeft ///< Left arrow }; }; /** * @brief Describes widgets like QPushButton. * * @sa WT_PushButton */ struct PushButton { /** * The layout of a PushButton is structured as follows: * -# Between the very outside and the bevel is the default indicator * area, controlled by the @c PushButton::DefaultIndicatorMargin . * -# From the bevel, the content and focus rect margins are measured. * Only the content margin is used to size the content area. * -# Inside the content area, @c PushButton::MenuIndicatorSize is allocated to the down * arrow if there is a popup menu. * -# @c PushButton::TextToIconSpace is allocated between icon and text if both exist * * @sa setWidgetLayoutProp() */ enum LayoutProp { ContentsMargin, ///< (\b 5) space between the bevel and the button contents FocusMargin = ContentsMargin + MarginInc, ///< (\b 3) Used to calculate the area of the focus indicator. Measured from the bevel. DefaultIndicatorMargin = FocusMargin + MarginInc, ///< (\b 0 ?) Default indicator between the very outside and the bevel. KStyle may reserve this for auto-default buttons, too, for consistency's sake. [the MainMargin sets QStyle::PM_ButtonDefaultIndicator] PressedShiftHorizontal = DefaultIndicatorMargin + MarginInc, ///< (\b 2) horizontal contents shift for pressed buttons [sets QStyle::PM_ButtonShiftHorizontal] PressedShiftVertical, ///< (\b 2) vertical contents shift for pressed buttons [sets QStyle::PM_ButtonShiftVertical] MenuIndicatorSize, ///< (\b 8) Space inside the content area, which is allocated to the down arrow if there is a popup menu [sets QStyle::PM_MenuButtonIndicator, except for toolbuttons] TextToIconSpace ///< (\b 6) space between the icon and the text if both exist }; /** * Relevant Generic elements: * - @c Generic::Text the button's text * - @c Generic::FocusIndicator indicating that the button has keyboard focus * - @c Generic::ArrowDown indicating that the button has a popup menu associated to it * * [K4Style implements @c QStyle::CE_PushButtonBevel to compose the primitives] * * @sa drawKStylePrimitive() */ enum Primitive { Panel, /**< the pushbutton panel * [implements QStyle::PE_PanelButtonCommand] */ DefaultButtonFrame /**< frame indicating a default button, painted before * the button Panel * [implements QStyle::PE_FrameDefaultButton] */ }; }; /** * @brief Describes widgets like QSplitter. * * @sa WT_Splitter */ struct Splitter { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { Width ///< (\b 6) size of the splitter handle [sets QStyle::PM_SplitterWidth] }; /** * [the Handles implement QStyle::CE_Splitter] * * @sa drawKStylePrimitive() */ enum Primitive { HandleHor, /**< The splitter handle, horizontal. Flags: @c State_Enabled&&State_MouseOver for mouseOver */ HandleVert /**< The splitter handle, vertical. Flags: @c State_Enabled&&State_MouseOver for mouseOver */ }; }; /** * @brief Describes widgets like QCheckBox. * * @sa WT_CheckBox */ struct CheckBox { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { Size, ///< (\b 16) size of the checkbox [sets PM_IndicatorWidth, PM_IndicatorHeight] BoxTextSpace, ///< (\b 6) space to leave between checkbox and text (and icon between them in case there is one) NoLabelFocusMargin, /**< (\b 1) rectangle to apply to the checkbox rectangle * to get where to paint the focus rectangle in * case of a labelless checkbox */ FocusMargin = NoLabelFocusMargin + MarginInc ///< (\b 0) margin around the checkbox contents reserved for the focus rect @todo have a look, it isn't as nice as plastique etc. }; /** * Relevant elements: * - @c Generic::Text the CheckBox label alongside the CheckBox * - @c Generic::FocusIndicator the focus indicator. Usually drawn around the * text label. If no label exists, it is drawn around the CheckBox. * * [check primitives implement QStyle::PE_IndicatorCheckBox] * [K4Style implements QStyle::CE_CheckBox to compose a CheckBox using * the mentioned primitives] * * @sa drawKStylePrimitive() */ enum Primitive { CheckOn, ///< checkbox which is checked CheckOff, ///< checkbox which is not checked CheckTriState ///< tristate checkbox (neither off nor on) }; }; /** * @brief Describes widgets like QRadioButton. */ struct RadioButton { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { Size, /**< [sets QStyle::PM_ExclusiveIndicatorWidth, * QStyle::PM_ExclusiveIndicatorHeight] * @sa CheckBox::Size */ BoxTextSpace, ///< @sa CheckBox::BoxTextSpace FocusMargin ///< @sa CheckBox::FocusMargin }; /** * Relevant Generic elements: * - @c Generic::Text the RadioButton label alongside the RadioButton * - @c Generic::FocusIndicator the keyboard focus indicator * * [check primitives implement QStyle::PE_IndicatorRadioButton] * [K4Style implements QStyle::CE_RadioButton to compose a RadioButton using * the mentioned primitives] * * @sa drawKStylePrimitive() */ enum Primitive { RadioOn, ///< radiobutton which is checked RadioOff ///< radiobutton which is not checked }; }; /** * @brief Describes the title of a dock widget. * * @sa WT_DockWidget */ struct DockWidget { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { TitleTextColor, ///< (\b ColorMode(QPalette::HighlightedText)) color mode of the title text TitleMargin, ///< (\b 2) Margin around title contents: Note that the symmetric margin (MainMargin) is used to size the title! Additional the Left and Right margins can be used to position the title text a little, though (to set Top and Bottom is not advisable). [the MainMargin sets QStyle::PM_DockWidgetTitleMargin] FrameWidth = TitleMargin + MarginInc, ///< (\b 3) width of the frame around floating dockwidgets [sets QStyle::PM_DockWidgetFrameWidth] SeparatorExtent ///< (\b 6) width of the area which separates the (docked) dock window from the window contents [sets QStyle::PM_DockWidgetSeparatorExtent] }; /** * Relevant Generic elements: * - @c Generic::Text the title text * - @c Generic::Frame the frame around floating dockwidgets * * [K4Style implements @c QStyle::CE_DockWidgetTitle to split it into K4Style primitives] * * @sa drawKStylePrimitive() */ enum Primitive { TitlePanel, ///< the panel/background of the title bar SeparatorHandle ///< the splitter between dockwidgets }; }; /** * @brief Describes widgets like QProgressBar. * * @todo support for Qt > 4.1 orientation, bottomToTop, invertedAppearance properties! * * @sa WT_ProgressBar */ struct ProgressBar { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { GrooveMargin, ///< (\b 2) Margin to allocate for the groove. Content area will be inside of it. SideText = GrooveMargin + MarginInc, ///< (\b false) set this to true to have the text positionned to the side SideTextSpace, ///< (\b 3) Extra space besides that needed for text to allocate to side indicator (on both sides). Precision, ///< (\b 1) The indicator size will always be a multiple of this (modulo busy indicator size clamping). [sets QStyle::PM_ProgressBarChunkWidth] BusyIndicatorSize, ///< (\b 10) The busy indicator size, in percent of area size. MaxBusyIndicatorSize ///< (\b 10000) size limit on the busy indicator size }; /** * Relevant Generic elements: * - @c Generic::Text the progress label * * @sa drawKStylePrimitive() */ enum Primitive { Groove, /**< the progressbar groove, drawn before the progress * Indicator [implements QStyle::CE_ProgressBarGroove] */ Indicator, ///< The actual bar indicating the progress... BusyIndicator /**< Used to indicate business, for example when * no progress is known (minimum and maximum values * both set to 0) */ }; }; /** * @brief Describes widgets like QMenuBar. * * @sa WT_MenuBar */ struct MenuBar { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { Margin, /**< (MainMargin \b 2, Left \b 4, Right \b 4) * Margin rectangle for the contents. */ ItemSpacing = Margin + MarginInc ///< (\b 14) Space between items [sets QStyle::PM_MenuBarItemSpacing] }; /** * @sa drawKStylePrimitive() */ enum Property { EmptyArea /**< Empty area of a menu bar, e.g. background * color. Maybe the place to fake toolbar separators (?) * [implements QStyle::CE_MenuBarEmptyArea] */ }; }; /** * @brief Describes MenuBar items. * * Relevant elements: * - @c Generic::Text text appearing as menubar entry */ struct MenuBarItem { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { Margin, /**< (\b 1) Margin rectangle to allocate for any * bevel, etc. (Text will be drawn with * the inside rect). */ Dummy = Margin + MarginInc //Paranoia about underlying type }; /** * @sa drawKStylePrimitive() */ enum Primitive { Panel ///< The panel/background of a menubar item. Interesting flags: State_Selected && State_HasFocus for mouseOver, State_Sunken for pressed state. }; }; /** * @brief Describes a menu. * * @sa WT_Menu */ struct Menu { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { FrameWidth, ///< (\b 1) The width of the frame, note that this does not affect the layout. Margin, ///< (\b 3) The margin of the menu. @todo have a look at comments at PM_MenuHMargin... ScrollerHeight = Margin + MarginInc, ///< (\b 10) Height of a menu scroller. [sets QStyle::PM_MenuScrollerHeight] TearOffHeight ///< (\b 10) Height of the TearOff area. [sets QStyle::PM_MenuTearoffHeight] }; /** * Relevant Generic elements: * - @c Generic::Frame frame around the menu panel * * @sa drawKStylePrimitive() */ enum Primitive { Background, ///< Menu and MenuItem background TearOff, /**< paints the area where a menu can be teared off * [implements QStyle::CE_MenuTearoff] */ Scroller /**< scrolling areas in a QMenu * [implements QStyle::CE_MenuScroller] */ }; }; /** * @brief Describes an item in a menu. * * MenuItems are layouted like this: * -# There are two MenuItem modes, toggled by @c LP_MenuItem_CheckAlongsideIcon. * Horizontal layout inside the items is as follow: * - @c LP_MenuItem_CheckAlongsideIcon disabled: * |icon/checkmark|IconSpace|text|AccelSpace|accel|ArrowSpace|ArrowWidth| * - @c LP_MenuItem_CheckAlongsideIcon enabled: * |checkmark|CheckSpace|icon|IconSpace|text|AccelSpace|accel|ArrowSpace|ArrowWidth| * -# The icon/checkmark column is at least @c LP_MenuItem_CheckWidth wide in all cases. * -# Then Margin is applied outside that. * * @note For the subprimitives the passed rect is their own. * @note Background is erased with WT_Menu/Menu::Background. * * @sa WT_MenuItem */ struct MenuItem { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { Margin, ///< (\b 2) margin for each entry CheckAlongsideIcon = Margin + MarginInc, /**< (\b 0) Set to non-zero to have checkmarks painted * separate from icons. */ CheckWidth, /**< (\b 12) size of the checkmark column * (CheckAlongsideButton enabled). */ CheckSpace, /**< (\b 3) Space between the checkmark column and the icon * column (CheckAlongsideButton enabled).*/ IconWidth, ///< (\b 12) minimum size of the icon column IconSpace, ///< (\b 3) space between the icon column and text column AccelSpace, ///< (\b 0 ?) space between text and keyboard accelerator label ArrowSpace, ///< (\b 3) space between the text column and arrow column (indicating sub menus) ArrowWidth, ///< (\b 11) space to reserve for the menu arrow column SeparatorHeight,///< (\b 0) heigh of separator MinHeight, ///< (\b 16) limit on the size of item content ActiveTextColor,///< (\b ColorMode(QPalette::HighlightedText)) color for active text and arrow TextColor, ///< (\b ColorMode(QPalette::Text)) color for inactive text and arrow DisabledTextColor, ///< (\b ColorMode(QPalette::Text)) color for inactive + disabled text and arrow ActiveDisabledTextColor ///< (\b ColorMode(QPalette::Text)) color for active + disabled text and arrow }; /** * Relevant Generic elements: * - @c Generic::Text the text of the menu item * - @c Generic::ArrowLeft @c Generic::ArrowRight arrows indicating a sub-menu * * @sa drawKStylePrimitive() */ enum Primitive { CheckColumn, ///< Background of the checkmark/icon column CheckOn, ///< The checkmark - checked CheckOff, ///< The checkmark - not checked RadioOn, ///< The checkmark of exclusive actions - selected RadioOff, ///< The checkmark of exclusive actions - not selected CheckIcon, ///< When @c CheckAlongsideIcon is disabled and item is checked: checkmark Indicator painted below the icon Separator, //A separator item. ItemIndicator //Shows the active item }; }; /** * @brief Describes widgets like QScrollBar. * * @sa WT_ScrollBar */ struct ScrollBar { /** * @note Dimensions of LayoutProperties are generally specified with respect * to the vertical scrollbar. Of course, for horizontal ones they're flipped. * * @sa setWidgetLayoutProp() */ enum LayoutProp { DoubleTopButton, ///< (\b 0) set to non-zero to have two buttons on top DoubleBotButton, ///< (\b 1) set to non-zero to have two buttons on bottom SingleButtonHeight, ///< (\b 16) height of a single button DoubleButtonHeight, ///< (\b 32) height of a double button BarWidth, ///< (\b 16) width of a scrollbar [sets QStyle::PM_ScrollBarExtent] MinimumSliderHeight,/**< (\b 0 ?) the minimum slider height * @note If the scrollbar is too small to accommodate * this, this will not be enforced. */ ArrowColor, /**< (\b ColorMode(ColorMode::BWAutoContrastMode, QPalette::Button)) color mode of a button arrow * @sa ColorMode */ ActiveArrowColor /**< (\b ColorMode(ColorMode::BWAutoContrastMode, QPalette::ButtonText)) color mode of a pressed button arrow (?) */ }; /** * Relevant Generic elements: * - The @c Generic arrows * * [Groove Areas implement QStyle::CE_ScrollBarAddPage and QStyle::CE_ScrollBarSubPage] * [Sliders implement QStyle::CE_ScrollBarSlider] * * @sa drawKStylePrimitive() */ enum Primitive { SingleButtonVert, ///< used to draw a 1-button bevel, vertical SingleButtonHor, ///< used to draw a 1-button bevel, horizontal DoubleButtonVert, /**< Used to draw a 2-button bevel, vertical. * A DoubleButtonOption is passed to say which * button is pressed. */ DoubleButtonHor, /** @see DoubleButtonVert */ GrooveAreaVertBottom, ///< scrollbar groove area, vertical. An interesting flag is @c State_Sunken for pressed state GrooveAreaHorRight, ///< scrollbar groove area, horizontal. Flags: @c State_Sunken for pressed state GrooveAreaVertTop, ///< scrollbar groove area, vertical. An interesting flag is @c State_Sunken for pressed state GrooveAreaHorLeft, ///< scrollbar groove area, horizontal. Flags: @c State_Sunken for pressed state SliderVert, ///< scrollbar slider, vertical. Flags: @c State_On&&State_Sunken for pressed state SliderHor ///< scrollbar slider, horizontal. Flags: @c State_On&&State_Sunken for pressed state }; }; /** * @brief Describes a tab bar. * * @sa WT_TabBar */ struct TabBar { /** * Each tab is basically built hiearchically out of the following areas: * -# Content area, one of the following layouts: * - Icon <- TextToIconSpace -> Text * - Icon * - Text * -# Bevel: @c LP_TabBar_TabContentsMargin outside of the content area * -# Focus indicator is placed @c LP_TabBar_TabFocusMargin inside the bevel * * @note The side tabs just have those rotated, bottom tabs have the margins reversed. * * @sa setWidgetLayoutProp() */ enum LayoutProp { TabContentsMargin, ///< (\b 6) margin around the tab contents, used to size the tab TabFocusMargin = TabContentsMargin + MarginInc, /**< (\b 3) where the tab focus rect is placed, measured from the * tab sides (?) */ TabTextToIconSpace = TabFocusMargin + MarginInc, /**< (\b 0 ?) space between icon and text if the tab contains both */ TabOverlap, /**< (\b 0) Amount of pixels tabs should overlap. The * paint rectangle will be extended to the left for * all tabs which are not at the beginning (accordingly * extended to the right in RightToLeft mode; extended * to the top for East/West tabs). */ BaseHeight, ///< (\b 2) the height of the tabBar's base, usually the frame width [sets QStyle::PM_TabBarBaseHeight] @todo is this used for things like I intended TabWidget::ContentsMargin for? BaseOverlap, ///< (\b 2) the number of pixels the tabs overlap with the base (i.e. tabWidget frame) [sets QStyle::PM_TabBarBaseOverlap] ScrollButtonWidth ///< (\b 10) buttons which are shown when there's not enough space for tabs (A ToolButton is used for this) [sets QStyle::PM_TabBarScrollButtonWidth] }; /** * Relevant elements: * - @c Generic::Text for the TabBar labels * - @c Generic::FocusIndicator for focused tabs * - @c Generic::Icon for icons associated to tabs * - @c ToolButton::Panel paints the scroll button (when the tabs don't fit the tab bar) */ enum Primitive { EastText, /**< Special rotated text for east tabs. */ WestText, ///< @see EastText NorthTab, ///< @todo say something about triangular shape etc. EastTab, WestTab, SouthTab, BaseFrame, ///< [implements QStyle::PE_FrameTabBarBase] IndicatorTear /**< painted in the left edge of a tabbar when the left * tab is scrolled out * [implements PE_IndicatorTabTear] * @todo K4Style default implementation...? */ }; }; /** * @brief Describes a tab widget (frame). * * Relevant elements: * - @c Generic::Frame for the frame/panel of the TabWidget * * @sa WT_TabWidget */ struct TabWidget { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { ContentsMargin, /**< (\b 2) Width of the frame around a tab widget. * Margins for a tabwidget with tab position 'North' are * specified as expected. For other positions, the * sides are rotated accordingly, e.g. the left margin * of a 'West' tabwidget is the same as top for a 'North' * tabwidget. * [sets QStyle::SE_TabWidgetTabContents] */ DummyProp = ContentsMargin + MarginInc }; }; /** * @brief Describes a slider, like QSlider. * * @sa WT_Slider */ struct Slider { /** * @note The description applies to horizontal sliders. * * @sa setWidgetLayoutProp() */ enum LayoutProp { HandleThickness, ///< (\b 20) The height of a slider handle HandleLength ///< (\b 16) The width of a slider handle [sets QStyle::PM_SliderLength] }; /** * Relevant Generic elements: * - @c Generic::FocusIndicator indicating keyboard focus * * @sa drawKStylePrimitive() */ enum Primitive { HandleVert, ///< A vertical slider handle HandleHor, ///< A horizontal slider handle GrooveVert, ///< A vertical slider groove GrooveHor ///< A horizontal slider groove }; }; /** * @brief Describes an expandable tree, e.g. in a QListView. */ struct Tree { /** * For trees, all the control we provide here is to provide a cap on the size * of the expander widget, which is always square. There are 4 primitives to * implement: open and closed expander, and horizontal and vertical lines. * If you're using dots, it's suggested you use global brush alignment to * keep it all nicely aligned. * * @sa setWidgetLayoutProp() */ enum LayoutProp { MaxExpanderSize /**< (\b 9) @note If you set MaxExpanderSize to a value less * than 9, designer will look funny. The value should also * be odd, or value - 1 will be used. */ }; /** * @sa drawKStylePrimitive() */ enum Primitive { ExpanderClosed, ///< A closed tree expander, usually drawn as '+'. K4Style has a default implementation (Windows-like look). ExpanderOpen, ///< An opened tree expander, usually drawn as '-' K4Style has a default implementation. HorizontalBranch, /**< A horizontal tree line. * @note If you're using dots, it's suggested you * use global brush alignment to keep it all nicely * aligned. */ VerticalBranch /**< @see HorizontalBranch */ }; }; /** * @brief Describes a widget like QSpinBox. */ struct SpinBox { /** * @note The description applies to LTR (left to right) mode. * * -# @c FrameWidth and @c ButtonWidth are used to size * the contents area. To the EditField, @c FrameWidth * is added at the left, top, bottom while @c ButtonWidth is added * at the right. * -# The @c ButtonMargin is measured from the right side of the * EditField and the outside. Inside it, the up and down buttons are aligned with * spacing @c ButtonSpacing. * -# To make sure that both buttons are always of the same height, enable * @c SymmetricButtons. * * @sa setWidgetLayoutProp() */ enum LayoutProp { FrameWidth, /**< (\b 1) Space reserved left, top, bottom of the SpinBox * [sets QStyle::PM_SpinBoxFrameWidth] */ ButtonWidth, ///< (\b 16) Space reserved for the widget, right of the EditField ButtonMargin, /**< (MainMargin \b 0, Right Top Bot \b 1) * Where the up/down buttons are located, measured * from right of the edit field and the top/right/bottom * widget edges. */ ButtonSpacing = ButtonMargin + MarginInc, ///< (\b 1) spacing between up/down buttons SymmetricButtons, /**< (\b 0) Set to non-zero to make sure both buttons are * always of the same height. To achieve this, the * spacing of the buttons will be reduced by 1 if * necessary to avoid rounding problems. Needs to be * handled in your drawing code. */ SupportFrameless, /**< (\b 0) Set to non-zero to indicate that you are able to * handle frame-less SpinBoxes. For a SpinBox with no * frame, FrameWidth and Top/Bottom/Right ButtonMargin * is ignored. */ ContentsMargin /**< (\b 5) space between the bevel and the spinbox contents */ }; /** * Relevant Generic elements: * - @c Generic::Frame for the area around text input field and buttons * - @c Generic::ArrowUp @c Generic::ArrowDown drawn on the buttons */ enum Primitive { EditField, /**< the text contents area, painted after Generic::Frame * @note This is respected only if the combobox is not * editable. */ UpButton, /**< Panel of the spinbox button which increases the value */ DownButton, /**< Panel of the spinbox button which decreases the value */ ButtonArea, /**< Can be used in addition or instead of * @c KPE_SpinBox_UpButton and @c KPE_SpinBox_DownButton. * The button area is painted before them. */ PlusSymbol, /**< Plus symbol painted on top of the up button, * centering primitive */ MinusSymbol /**< Minus symbol painted on top of the down button, * centering primitive */ }; }; /** * @brief Describes a widget like QComboBox. */ struct ComboBox { /** * @note The description applies to LTR (left to right) mode. * * -# @c FrameWidth and @c ButtonWidth are used to size * the contents area. To the EditField, @c FrameWidth * is added at the left, top, bottom while @c ButtonWidth is added * at the right. * -# The @c ButtonMargin is measured from the right side of the * EditField and the outside. Inside it, the button is aligned. * -# The @c FocusMargin is measured from the EditField rect. */ enum LayoutProp { FrameWidth, /**< (\b 1) @see SpinBox::FrameWidth */ ButtonWidth, /**< (\b 16) @see SpinBox::ButtonWidth */ ButtonMargin, /**< (MainMargin \b 0, Right Top Bot \b 1) * @see SpinBox::ButtonMargin */ FocusMargin = ButtonMargin + MarginInc, /**< (\b 1) Focus margin for ComboBoxes that aren't * editable, measured from the EditField rect */ SupportFrameless = FocusMargin + MarginInc, /**< (\b 0) @see LP_SpinBox_SupportFrameless same description * applies here */ ContentsMargin /**< (\b 5) space between the bevel and the combobox contents */ }; /** * Relevant Generic elements: * - @c Generic::Frame for the area around text input field and button * - @c Generic::ArrowDown drawn on the button * - @c Generic::FocusIndicator to indicate keyboard focus * * @sa drawKStylePrimitive() */ enum Primitive { EditField, /**< @see SpinBox::EditField */ Button /**< The button panel of the combobox */ }; }; /** * @brief Describes a list header, like in QListView. * * @sa WT_Header */ struct Header { /** * @sa setWidgetLayoutProp() */ enum LayoutProp { ContentsMargin, /**< (\b 3) margin around contents used to size the header. */ TextToIconSpace = ContentsMargin + MarginInc, /**< (\b 3) space that is allocated between icon and text * if both exist * [sets QStyle::PM_HeaderMargin] */ MarkSize /**< (\b 9) size of the sort indicator in a header * [sets QStyle::PM_HeaderMarkSize] */ }; /** * Relevant Generic elements: * - @c Generic::Text for the header text label * - @c Generic::ArrowUp @c Generic::ArrowDown to indicate the sorting of the column * * [the Sections implement QStyle::CE_HeaderSection] */ enum Primitive { SectionHor, ///< header section, horizontal SectionVert ///< header section, vertical }; }; /** * @brief Describes a text edit widget like QLineEdit. * * The frame width of lineedits is determined using Generic::DefaultFrameWidth */ struct LineEdit { /** * Relevant Generic elements: * - @c Generic::Frame paints a lineedit frame only [implements QStyle::PE_FrameLineEdit] * * @sa drawKStylePrimitive() */ enum Primitive { Panel ///< the panel for a QLineEdit (including frame...) [implements QStyle::PE_PanelLineEdit] }; }; /** * @brief Describes something like QGroupBox. * * Relevant Generic elements: * - @c Generic::Frame frame around the group box * * [the Frames implement QStyle::PE_FrameGroupBox] * * @sa Generic::DefaultFrameWidth * * @sa WT_GroupBox */ struct GroupBox { /** * @sa setWidgetLayoutProp() */ enum LayoutProps { FrameWidth, /**< (\b 2) width of a groupbox frame */ TextAlignTop, /**< (\b 0) set to non-zero, the title will be aligned * above the groupbox frame, not vertically centered * [sets QStyle::SH_GroupBox_TextLabelVerticalAlignment] */ TitleTextColor ///< (\b ColorMode(QPalette::Text)) color of the title text label }; /** * @sa drawKStylePrimitive() */ enum Primitive { FlatFrame /**< For groupboxes which are set to be 'flat' (usually * a divider line from top left to top right). K4Style * has a basic default implementation */ }; }; /** * @brief Describes a status bar section. * * Relevant Generic elements: * - @c Generic::Frame paints the status bar section [implements QStyle::PE_FrameStatusBar] * * No LayoutProps for now. * * @sa WT_StatusBar */ struct StatusBar { /** No LayoutProps for now. */ }; /** * @brief Describes a tool bar. * * @sa WT_ToolBar */ struct ToolBar { /** * @sa setWidgetLayoutProp() */ enum LayoutProps { HandleExtent, ///< (\b 6) the width(hor)/height(vert) of a ToolBar handle [sets QStyle::PM_ToolBarHandleExtent] SeparatorExtent, ///< (\b 6) the width/height of a ToolBar separator [sets QStyle::PM_ToolBarSeparatorExtent] ExtensionExtent, ///< (\b 10) the width/height of a ToolBar extender, when there is not enough room for toolbar buttons [sets PM_ToolBarExtensionExtent] FrameWidth, /**< (\b 2) width of the frame around toolbars * [sets QStyle::PM_ToolBarFrameWidth] */ ItemMargin, ///< (\b 1) [sets QStyle::PM_ToolBarItemMargin] ItemSpacing ///< (\b 3) [sets QStyle::PM_ToolBarItemSpacing] }; /** * [the Handles implement QStyle::PE_IndicatorToolBarHandle] * [the Panels implement QStyle::CE_ToolBar] * * @sa drawKStylePrimitive() */ enum Primitive { HandleHor, ///< handle of a toolbar, horizontal HandleVert, ///< handle of a toolbar, vertical Separator, ///< [implements QStyle::PE_IndicatorToolBarSeparator] PanelHor, ///< the actual toolbar, horizontal PanelVert ///< the actual toolbar, vertical }; }; /** * @brief Describes a tab for a tool box, like QToolBox. * * @sa WT_ToolBoxTab */ struct ToolBoxTab { /** * @sa setWidgetLayoutProp() */ enum LayoutProps { Margin /**< (\b 0) used to specify the * position of the tab contents, doesn't influence the tab size * [sets QStyle::SE_ToolBoxTabContents] */ }; /** * @sa drawKStylePrimitive() */ enum Primitive { Panel /**< the panel of a toolbox tab, K4Style default implementation * paints WT_ToolButton/ToolButton::Panel * [implements CE_ToolBoxTab] */ }; }; /** * @brief Describes widgets like QToolButton (usually inside a QToolBar). * The drawing of ToolButton's is much like that of PushButtons; however, in some cases the widget is configured * to not have a separate arrow area, but to incorporate the area inside the button itself. To handle this mode, * set InlineMenuIndicatorSize to the size of the arrow, * and the InlineMenuIndicatorXOff, and InlineMenuIndicatorYOff to offset from the bottom-right corner to place that * rectangle. If InlineMenuIndicatorSize isn't set, the arrow won't be drawn. * * @sa WT_ToolButton */ struct ToolButton { /** * @sa setWidgetLayoutProp() */ enum LayoutProps { ContentsMargin, /**< (\b 5) Margin reserved around the contents size of * a toolbutton. Used to size the contents. */ FocusMargin = ContentsMargin + MarginInc, /**< (\b 3) Where the focus rect will be drawn, measured * from the widget sides */ MenuIndicatorSize, /**< (\b 11) Size for the separate menu arrows on tool buttons * [sets QStyle::PM_MenuButtonIndicator wheen a toolbutton option is passed in] */ InlineMenuIndicatorSize = FocusMargin + MarginInc, /**< (\b 0) Size of arrow when it's incorporated into * the button directly. If it's 0, it will not be drawn * @since 4.1 */ InlineMenuIndicatorXOff, /**< Horizontal offset off the bottom-right corner to place the arrow * if it's incorporated directly, and not in a separate area * @since 4.1 */ InlineMenuIndicatorYOff /**< Vertical offset off the bottom-right corner to place the arrow * if it's incorporated directly, and not in a separate area * @since 4.1 */ }; /** * Relevant Generic elements: * - @c Generic::ArrowDown indicating an associated sub-menu * * @todo Implement CE_ToolButtonLabel to have own Generic::Text, Generic::Icon, * and LayoutProps PressedShiftHorizontal, PressedShiftVertical, * TextToIconSpace, MenuIndicatorSize... * * @sa drawKStylePrimitive() */ enum Primitive { Panel /**< the toolbutton panel * [implements QStyle::PE_PanelButtonTool] */ }; }; /** * @brief Describes windows, like in QWorkspace. * * @todo SP_TitleBar* pixmaps * * @sa WT_Window */ struct Window { /** * @sa setWidgetLayoutProp() */ enum LayoutProps { TitleTextColor, ///< (\b ColorMode(QPalette::HighlightedText)) color mode of the titlebar text TitleHeight, ///< (\b 20) height of the titlebar [sets QStyle::PM_TitleBarHeight] NoTitleFrame, /**< (\b 0) if set to non-zero, the frame primitive is not * expected to paint around the titlebar area * [sets QStyle::SH_TitleBar_NoBorder] */ TitleMargin, /**< (\b 2) margin around titlebar contents (buttons, * text label), used to position them and determine the * height of titlebar buttons, doesn't influence size */ ButtonWidth = TitleMargin + MarginInc, ///< (\b 16) width of a titlebar button ButtonSpace, ///< (\b 2) space between titlebar buttons ButtonToTextSpace ///< (\b 3) space between buttons and the title text }; /** * Relevant Generic elements: * - @c Generic::Text paints the titlebar text label * - @c Generic::Frame indicating an associated sub-menu * * [titlebar elements implement CC_TitleBar] * * @sa drawKStylePrimitive() */ enum Primitive { TitlePanel, ///< whole titlebar panel/background, by K4Style default it's filled with plain highlight color ButtonMenu, ///< system menu button, passes TitleButtonOption ButtonMin, ///< minimize button, passes TitleButtonOption ButtonMax, ///< maximize button, passes TitleButtonOption ButtonRestore, ///< restore button, passes TitleButtonOption @todo split min/max restore? ButtonClose, ///< close button, passes TitleButtonOption ButtonShade, ///< shade button, passes TitleButtonOption ButtonUnshade, ///< button to remove the shade state, passes TitleButtonOption ButtonHelp ///< context help button, passes TitleButtonOption }; }; //@} ///Interface for the style to configure various metrics that K4Style has customizable. void setWidgetLayoutProp(WidgetType widget, int metric, int value); /** * @brief Used to obtain information about K4Style layout properties and metrics. * * The default implementation returns values which are set * using setWidgetLayoutProp(), so normally it's not necessary to implement * it yourself. * * @note This method is not meant to be accessible from outside K4Style. * * @param widgetType the widget type context where the @p metric property belongs to * @param metric the value of this property is requested * @param opt Qt option parameters * @param w the actual widget this call is related to */ virtual int widgetLayoutProp(WidgetType widgetType, int metric, const QStyleOption *opt = nullptr, const QWidget *w = nullptr) const; /** * @brief Draws primitives which are used inside K4Style. * * K4Style implements various elements of QStyle::ComplexControl * and QStyle::ControlElement for convenience. Usually complex drawing is * split into smaller pieces, which can be text, icons, or other K4Style primitives. * These are painted by this method. * * Common Qt option parameters are unpacked for convenience, and information * from K4Style are passed as a KStyleOption. * * @note This method is not meant to be accessible from outside K4Style. * @note You should make sure to use the @p r parameter for the rectangle, * since the QStyleOption is generally unaltered from the original request, * even if layout indicates a different painting rectangle. * * @param widgetType the widget context in which this call is happening in * @param primitive the primitive which should be called. Primitives from the Generic * struct are not directly coupled to the @p widgetType , other primitives are usually * defined in the struct corresponding to the widget type. * @param opt Qt option parameters * @param r parameter for the rectangle * @param pal the palette extracted from @p opt for convenience * @param flags state flags extracted from @p opt for convenience * @param p used to draw the primitive * @param widget the widget which is painted on * @param kOpt information passed from K4Style */ virtual void drawKStylePrimitive(WidgetType widgetType, int primitive, const QStyleOption *opt, const QRect &r, const QPalette &pal, State flags, QPainter *p, const QWidget *widget = nullptr, Option *kOpt = nullptr) const; private: ///Should we use a side text here? bool useSideText(const QStyleOptionProgressBar *opt) const; int sideTextWidth(const QStyleOptionProgressBar *pbOpt) const; ///Returns true if the tab is vertical bool isVerticalTab(const QStyleOptionTab *tbOpt) const; ///Returns true if the tab has reflected layout bool isReflectedTab(const QStyleOptionTab *tbOpt) const; enum Side { North, East, West, South }; Side tabSide(const QStyleOptionTab *tbOpt) const; ///Returns the tab rectangle adjusted for the tab direction QRect marginAdjustedTab(const QStyleOptionTab *tbOpt, int property) const; ///Wrapper around visualRect for easier use QRect handleRTL(const QStyleOption *opt, const QRect &subRect) const; QPoint handleRTL(const QStyleOption *opt, const QPoint &pos) const; ///Storage for metrics/flags QVector > metrics; ///Expands out the dimension to make sure it incorporates the margins QSize expandDim(const QSize &orig, WidgetType widget, int baseMarginMetric, const QStyleOption *opt, const QWidget *w, bool rotated = false) const; ///Calculates the contents rectangle by subtracting out the appropriate margins ///from the outside QRect insideMargin(const QRect &orig, WidgetType widget, int baseMarginMetric, const QStyleOption *opt, const QWidget *w) const; ///Internal subrect calculations, for e.g. scrollbar arrows, ///where we fake our output to get Qt to do what we want QRect internalSubControlRect(ComplexControl control, const QStyleOptionComplex *opt, SubControl subControl, const QWidget *w) const; // fitt's law label support: QLabel focusing its buddy widget const QObject *clickedLabel; public: /** @name QStyle Methods * These are methods reimplemented from QStyle. Usually it's not necessary to * reimplement them yourself. * * Some of them are there for binary compatibility reasons only; all they do is to call * the implementation from QCommonStyle. */ //@{ void drawControl(ControlElement elem, const QStyleOption *opt, QPainter *p, const QWidget *w) const Q_DECL_OVERRIDE; void drawPrimitive(PrimitiveElement elem, const QStyleOption *opt, QPainter *p, const QWidget *w) const Q_DECL_OVERRIDE; int pixelMetric(PixelMetric metric, const QStyleOption *opt = nullptr, const QWidget *w = nullptr) const Q_DECL_OVERRIDE; QRect subElementRect(SubElement subRect, const QStyleOption *opt, const QWidget *w) const Q_DECL_OVERRIDE; QSize sizeFromContents(ContentsType type, const QStyleOption *opt, const QSize &contentsSize, const QWidget *w) const Q_DECL_OVERRIDE; int styleHint(StyleHint hint, const QStyleOption *opt, const QWidget *w, QStyleHintReturn *returnData) const Q_DECL_OVERRIDE; QRect subControlRect(ComplexControl control, const QStyleOptionComplex *opt, SubControl subControl, const QWidget *w) const Q_DECL_OVERRIDE; SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, const QPoint &pt, const QWidget *w) const Q_DECL_OVERRIDE; void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p, const QWidget *w) const Q_DECL_OVERRIDE; void polish(QWidget *) Q_DECL_OVERRIDE; void unpolish(QWidget *) Q_DECL_OVERRIDE; void polish(QApplication *) Q_DECL_OVERRIDE; void unpolish(QApplication *) Q_DECL_OVERRIDE; void polish(QPalette &) Q_DECL_OVERRIDE; QRect itemTextRect(const QFontMetrics &fm, const QRect &r, int flags, bool enabled, const QString &text) const Q_DECL_OVERRIDE; QRect itemPixmapRect(const QRect &r, int flags, const QPixmap &pixmap) const Q_DECL_OVERRIDE; void drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole = QPalette::NoRole) const Q_DECL_OVERRIDE; void drawItemPixmap(QPainter *painter, const QRect &rect, int alignment, const QPixmap &pixmap) const Q_DECL_OVERRIDE; QPalette standardPalette() const Q_DECL_OVERRIDE; QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt, const QWidget *widget = nullptr) const Q_DECL_OVERRIDE; //### kde5 remove QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, const QStyleOption *opt) const Q_DECL_OVERRIDE; bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; int layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2, Qt::Orientation orientation, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const Q_DECL_OVERRIDE; QIcon standardIcon(StandardPixmap standardIcon, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const Q_DECL_OVERRIDE; //@} private: K4StylePrivate *const d; }; template const char *kstyleName() { return "default"; } /** * Template class which helps implementing the widget style plugin interface. * * You don't need to use this class directly. Use the following * macro (defined in kstyle.h) and you are done: * \code * K_EXPORT_STYLE("StyleName", StyleClassName) * \endcode */ template class K4StyleFactory: public QStylePlugin { QStringList keys() const { QStringList l; l << kstyleName(); return l; } QStyle *create(const QString &id) Q_DECL_OVERRIDE { QStringList names = keys(); //check whether included in the keys if (names.contains(id, Qt::CaseInsensitive)) { return new T(); } return nullptr; } }; template T K4Style::extractOption(Option *option) { if (option) { if (dynamic_cast(option)) { return static_cast(option); } // Ugly hacks for when RTLD_GLOBAL is not used (quite common with plugins, really) // and dynamic_cast fails. // This is still partially broken as it doesn't take into account subclasses. // ### KDE5 do this somehow differently if (qstrcmp(typeid(*option).name(), typeid(typename std::remove_pointer::type).name()) == 0) { return static_cast(option); } } //### warn if cast failed? //since T is a pointer type, need this to get to the static. return static_cast(nullptr)->defaultOption(); } #define K_EXPORT_K4STYLE(name,type) template<> const char* kstyleName() { return name; } \ Q_EXPORT_PLUGIN(K4StyleFactory) #endif diff --git a/src/kdeui/k4timezonewidget.h b/src/kdeui/k4timezonewidget.h index 5f8ca6e3..354cdcec 100644 --- a/src/kdeui/k4timezonewidget.h +++ b/src/kdeui/k4timezonewidget.h @@ -1,148 +1,148 @@ /* Copyright (C) 2005, S.R.Haque . This file is part of the KDE project 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 KTIMEZONEWIDGET_H #define KTIMEZONEWIDGET_H #include #include class KTimeZone; class KTimeZones; /** * @brief A time zone selection widget. * * \b Detail: * * This class provides for selection of one or more time zones. * * \b Example: * * To use the class to implement a system timezone selection feature: * \code * * // This adds a time zone widget to a dialog. * m_timezones = new K4TimeZoneWidget(this); * ... * \endcode * * To use the class to implement a multiple-choice custom time zone selector: * \code * * m_timezones = new K4TimeZoneWidget( this, "Time zones", vcalendarTimezones ); * m_timezones->setSelectionMode( QTreeView::MultiSelection ); * ... * \endcode * * \image html ktimezonewidget.png "KDE Time Zone Widget" * * @author S.R.Haque */ class KDELIBS4SUPPORT_EXPORT K4TimeZoneWidget : public QTreeWidget { Q_OBJECT Q_PROPERTY(bool itemsCheckable READ itemsCheckable WRITE setItemsCheckable) Q_PROPERTY(QAbstractItemView::SelectionMode selectionMode READ selectionMode WRITE setSelectionMode) public: /** * Constructs a time zone selection widget. * * @param parent The parent widget. * @param timeZones The time zone database to use. If 0, the system time zone * database is used. */ - explicit K4TimeZoneWidget(QWidget *parent = nullptr, KTimeZones *timeZones = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit K4TimeZoneWidget(QWidget *parent = nullptr, KTimeZones *timeZones = nullptr); /** * Destroys the time zone selection widget. */ virtual ~K4TimeZoneWidget(); /** * Makes all items show a checkbox, so that the user can select multiple * timezones by means of checking checkboxes, rather than via multi-selection. * * In "items checkable" mode, the selection(), setSelected() and clearSelection() * methods work on the check states rather than on selecting/unselecting. * * @since 4.4 */ void setItemsCheckable(bool enable); /** * @return true if setItemsCheckable(true) was called. * @since 4.4 */ bool itemsCheckable() const; /** * Allows to select multiple timezones. This is the same as * setSelectionMode(K4TimeZoneWidget::MultiSelection) normally, * but in "items checkable" mode, this is rather about allowing to * check multiple items. In that case, the actual QTreeWidget selection * mode remains unchanged. * @since 4.4 */ void setSelectionMode(QAbstractItemView::SelectionMode mode); /** * @return the selection mode set by setSelectionMode(). * @since 4.4 */ QAbstractItemView::SelectionMode selectionMode() const; /** * Returns the currently selected time zones. See QTreeView::selectionChanged(). * * @return a list of time zone names, in the format used by the database * supplied to the {@link K4TimeZoneWidget() } constructor. */ QStringList selection() const; /** * Select/deselect the named time zone. * * @param zone The time zone name to be selected. Ignored if not recognized! * @param selected The new selection state. */ void setSelected(const QString &zone, bool selected); /** * Unselect all timezones. * This is the same as QTreeWidget::clearSelection, except in checkable items mode, * where items are all unchecked. * The overload is @since 4.4. */ void clearSelection(); /** * Format a time zone name in a standardised manner. * * @return formatted time zone name. */ static QString displayName(const KTimeZone &zone); private: class Private; Private *const d; }; #endif diff --git a/src/kdeui/kaction.h b/src/kdeui/kaction.h index 79ff7633..18905774 100644 --- a/src/kdeui/kaction.h +++ b/src/kdeui/kaction.h @@ -1,548 +1,548 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Reginald Stadlbauer (C) 1999 Simon Hausmann (C) 2000 Nicolas Hadacek (C) 2000 Kurt Granroth (C) 2000 Michael Koch (C) 2001 Holger Freyther (C) 2002 Ellis Whitehead (C) 2005-2006 Hamish Rodda 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 KACTION_H #define KACTION_H #include #include #include class KShapeGesture; class KRockerGesture; class KShortcut; //TODO Reduce the word count. This is not very focused and takes too long to read. //Keep in mind that QAction also has documentation that we don't need to repeat here. /** * @short Class to encapsulate user-driven action or event * @extends QAction * * The KAction class (and derived and super classes) extends QAction, * which provides a way to easily encapsulate a "real" user-selected * action or event in your program. * * For instance, a user may want to @p paste the contents of * the clipboard, @p scroll @p down a document, or @p quit the * application. These are all \b actions -- events that the * user causes to happen. The KAction class allows the developer to * deal with these actions in an easy and intuitive manner, and conforms * to KDE's extended functionality requirements - including supporting * multiple user-configurable shortcuts, and KDE named icons. Actions * also improve accessibility. * * Specifically, QAction (and thus KAction) encapsulates the various attributes * of an event/action. For instance, an action might have an icon() * that provides a visual representation (a clipboard for a "paste" action or * scissors for a "cut" action). The action should also be described by some text(). * It will certainly be connected to a method that actually @p executes the action! * All these attributes are contained within the action object. * * The advantage of dealing with actions is that you can manipulate * the Action without regard to the GUI representation of it. For * instance, in the "normal" way of dealing with actions like "cut", * you would manually insert a item for Cut into a menu and a button * into a toolbar. If you want to disable the cut action for a moment * (maybe nothing is selected), you would have to hunt down the pointer * to the menu item and the toolbar button and disable both * individually. Setting the menu item and toolbar item up uses very * similar code - but has to be done twice! * * With the action concept, you simply add the action to whatever * GUI element you want. The KAction class will then take care of * correctly defining the menu item (with icons, accelerators, text, * etc), toolbar button, or other. From then on, if you * manipulate the action at all, the effect will propagate through all * GUI representations of it. Back to the "cut" example: if you want * to disable the Cut Action, you would simply call * 'cutAction->setEnabled(false)' and both the menuitem and button would * instantly be disabled! * * This is the biggest advantage to the action concept -- there is a * one-to-one relationship between the "real" action and @p all * GUI representations of it. * * KAction emits the hovered() signal on mouseover, and the triggered(bool checked) * signal on activation of a corresponding GUI element ( menu item, toolbar button, etc. ) * * If you are in the situation of wanting to map the triggered() * signal of multiple action objects to one slot, with a special * argument bound to each action, you have several options: * * Using QActionGroup: * \li Create a QActionGroup and assign it to each of the actions with setActionGroup(), then * \li Connect the QActionGroup::triggered(QAction*) signal to your slot. * * Using QSignalMapper: * \code * QSignalMapper *desktopNumberMapper = new QSignalMapper( this ); * connect( desktopNumberMapper, SIGNAL( mapped( int ) ), * this, SLOT( moveWindowToDesktop( int ) ) ); * * for ( uint i = 0; i < numberOfDesktops; ++i ) { * KAction *desktopAction = new KAction( i18n( "Move Window to Desktop %i" ).arg( i ), ... ); * connect( desktopAction, SIGNAL( triggered(bool) ), desktopNumberMapper, SLOT( map() ) ); * desktopNumberMapper->setMapping( desktopAction, i ); * } * \endcode * * \section kaction_general General Usage * * The steps to using actions are roughly as follows: * * @li Decide which attributes you want to associate with a given * action (icons, text, keyboard shortcut, etc) * @li Create the action using KAction (or derived or super class). * @li Add the action into whatever GUI element you want. Typically, * this will be a menu or toolbar. * * \section kaction_general The kinds of shortcuts * * Local shortcuts are active if their context has the focus, global shortcus * are active even if the program does not have the focus. If a global * shortcut and a local shortcut are ambiguous the global shortcut wins. * * @li Active shortcuts trigger a KAction if activated. * @li Default shortcuts are what the active shortcuts revert to if the user chooses * to reset shortcuts to default. * * \section kaction_example Detailed Example * * Here is an example of enabling a "New [document]" action * \code * KAction *newAct = actionCollection()->addAction( * KStandardAction::New, //< see KStandardAction * this, //< Receiver * SLOT(fileNew()) ); //< SLOT * \endcode * * This section creates our action. Text, Icon and Shortcut will be set from * KStandardAction. KStandardAction ensures your application complies to the * platform standards. When triggered the \c fileNew() slot will be called. * * @see KStandardAction for more information. * * If you want to create your own actions use * \code * KAction *newAct = actionCollection()->addAction("quick-connect"); * newAct->setText(i18n("Quick Connect")) * newAct->setIcon(QIcon::fromTheme("quick-connect")); * newAct->setShortcut(Qt::Key_F6); * connect(newAct, SIGNAL(triggered()), this, SLOT(quickConnect())); * \endcode * * This section creates our action. It displays the text "Quick Connect", * uses the Icon "quick-connect" and pressing \c F6 will trigger it. When * invoked, the slot quickConnect() is called. * * \code * QMenu *file = new QMenu; * file->addAction(newAct); * \endcode * That just inserted the action into the File menu. The point is, it's not * important in which menu it is: all manipulation of the item is * done through the newAct object. * * \code * toolBar()->addAction(newAct); * \endcode * And this added the action into the main toolbar as a button. * * That's it! * * If you want to disable that action sometime later, you can do so * with * \code * newAct->setEnabled(false) * \endcode * and both the menuitem in File and the toolbar button will instantly * be disabled. * * Unlike with previous versions of KDE, the action can simply be deleted * when you have finished with it - the destructor takes care of all * of the cleanup. * * \warning calling QAction::setShortcut() on a KAction may lead to unexpected * behavior. There is nothing we can do about it because QAction::setShortcut() * is not virtual. * * \note if you are using a "standard" action like "new", "paste", * "quit", or any other action described in the KDE UI Standards, * please use the methods in the KStandardAction class rather than * defining your own. * * \section Using QActions * * Mixing QActions and KActions in an application is not a * good idea. KShortcutsEditor doesn't handle QActions at all. * * \section kaction_xmlgui Usage Within the XML Framework * * If you are using KAction within the context of the XML menu and * toolbar building framework, you do not ever * have to add your actions to containers manually. The framework * does that for you. * * @see KStandardAction */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KAction : public QWidgetAction { Q_OBJECT Q_PROPERTY(KShortcut shortcut READ shortcut WRITE setShortcut) Q_PROPERTY(bool shortcutConfigurable READ isShortcutConfigurable WRITE setShortcutConfigurable) Q_PROPERTY(KShortcut globalShortcut READ globalShortcut WRITE setGlobalShortcut) #ifndef KDELIBS4SUPPORT_NO_DEPRECATED Q_PROPERTY(bool globalShortcutAllowed READ globalShortcutAllowed WRITE setGlobalShortcutAllowed) #endif Q_PROPERTY(bool globalShortcutEnabled READ isGlobalShortcutEnabled) Q_FLAGS(ShortcutType) public: /** * An enumeration about the two types of shortcuts in a KAction */ enum ShortcutType { /// The shortcut will immediately become active but may be reset to "default". ActiveShortcut = 0x1, /// The shortcut is a default shortcut - it becomes active when somebody decides to /// reset shortcuts to default. DefaultShortcut = 0x2 }; Q_DECLARE_FLAGS(ShortcutTypes, ShortcutType) /** * An enum about global shortcut setter semantics */ //This enum will be ORed with ShortcutType in calls to KGlobalAccel, so it must not contain //any value equal to a value in ShortcutType. enum GlobalShortcutLoading { /// Look up the action in global settings (using its main component's name and text()) /// and set the shortcut as saved there. /// @see setGlobalShortcut() Autoloading = 0x0, /// Prevent autoloading of saved global shortcut for action NoAutoloading = 0x4 }; /** * Constructs an action. */ - explicit KAction(QObject *parent); + KDELIBS4SUPPORT_DEPRECATED explicit KAction(QObject *parent); /** * Constructs an action with the specified parent and visible text. * * @param text The visible text for this action. * @param parent The parent for this action. */ KAction(const QString &text, QObject *parent); /** * Constructs an action with text and icon; a shortcut may be specified by * the ampersand character (e.g. \"&Option\" creates a shortcut with key \e O ) * * This is the other common KAction constructor used. Use it when you * \e do have a corresponding icon. * * @param icon The icon to display. * @param text The text that will be displayed. * @param parent The parent for this action. */ KAction(const QIcon &icon, const QString &text, QObject *parent); /** * Standard destructor */ virtual ~KAction(); /** * Sets the help text for the action. * This help text will be set for all help mechanisms: * - the status-bar help text * - the tooltip (for toolbar buttons) * - the "WhatsThis" help text (unless one was already set) * * This is more convenient than calling all three methods with the * same text, and this level of abstraction can allow to change * the default implementation of help one day more easily. * Of course you can also call setStatusTip, setToolTip and setWhatsThis * separately for more flexibility. * * This method is also the easiest way to port from KDE3's KAction::setToolTip. * * @since 4.3 */ void setHelpText(const QString &text); /** * Get the shortcut for this action. * * This is preferred over QAction::shortcut(), as it allows for multiple shortcuts * per action. The first and second shortcut as reported by shortcuts() will be the * primary and alternate shortcut of the shortcut returned. * * \param types the type of shortcut to return. Should both be specified, only the * active shortcut will be returned. Defaults to the active shortcut, if one exists. * \sa shortcuts() */ KShortcut shortcut(ShortcutTypes types = ActiveShortcut) const; /** * Set the shortcut for this action. * * This is preferred over QAction::setShortcut(), as it allows for multiple shortcuts * per action. * * \param shortcut shortcut(s) to use for this action in its specified shortcutContext() * \param type type of shortcut to be set: active shortcut, * default shortcut, or both (the default). */ void setShortcut(const KShortcut &shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut)); /** * \overload void setShortcut(const KShortcut& shortcut) * * Set the primary shortcut only for this action. * - * This function is there to explicitly override QAction::setShortcut(const QKeySequence&). + * This function is there to KDELIBS4SUPPORT_DEPRECATED explicitly override QAction::setShortcut(const QKeySequence&). * QAction::setShortcut() will bypass everything in KAction and may lead to unexpected behavior. * * \param shortcut shortcut(s) to use for this action in its specified shortcutContext() * \param type type of shortcut to be set: active shortcut, * default shortcut, or both (default argument value). */ void setShortcut(const QKeySequence &shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut)); /** * \overload void setShortcuts(const QList\& shortcuts). * * Set the shortcuts for this action. * - * This function is there to explicitly override QAction::setShortcut(const QList\&). + * This function is there to KDELIBS4SUPPORT_DEPRECATED explicitly override QAction::setShortcut(const QList\&). * QAction::setShortcuts() will bypass everything in KAction and may lead to unexpected behavior. * * \param shortcut shortcut(s) to use for this action in its specified shortcutContext() * \param type type of shortcut to be set: active shortcut, * default shortcut, or both (default argument value). */ void setShortcuts(const QList &shortcuts, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut)); /** * Returns true if this action's shortcut is configurable. */ bool isShortcutConfigurable() const; /** * Indicate whether the user may configure the action's shortcut. * * \param configurable set to \e true if this shortcut may be configured by the user, otherwise \e false. */ void setShortcutConfigurable(bool configurable); /** * Get the global shortcut for this action, if one exists. Global shortcuts * allow your actions to respond to accellerators independently of the focused window. * Unlike regular shortcuts, the application's window does not need focus * for them to be activated. * * \param type the type of shortcut to be returned. Should both be specified, only the * active shortcut will be returned. Defaults to the active shortcut, * if one exists. * * \sa KGlobalAccel * \sa setGlobalShortcut() */ KShortcut globalShortcut(ShortcutTypes type = ActiveShortcut) const; /** * Assign a global shortcut for this action. Global shortcuts * allow an action to respond to key shortcuts independently of the focused window, * i.e. the action will trigger if the keys were pressed no matter where in the X session. * * The action must have a per main component unique * objectName() to enable cross-application bookeeping. If the objectName() is empty this method will * do nothing, otherwise the isGlobalShortcutEnabled() property will be set to true and the * shortcut will be enabled. * It is mandatory that the objectName() doesn't change once isGlobalshortcutEnabled() * has become true. * * \note KActionCollection::insert(name, action) will set action's objectName to name so you often - * don't have to set an objectName explicitly. + * don't have to set an objectName KDELIBS4SUPPORT_DEPRECATED explicitly. * * When an action, identified by main component name and objectName(), is assigned * a global shortcut for the first time on a KDE installation the assignment will * be saved. The shortcut will then be restored every time setGlobalShortcut() is * called with @p loading == Autoloading. * * If you actually want to change the global shortcut you have to set * @p loading to NoAutoloading. The new shortcut will be automatically saved again. * * \param shortcut global shortcut(s) to assign. Will be ignored unless \p loading is set to NoAutoloading or this is the first time ever you call this method (see above). * \param type the type of shortcut to be set, whether the active shortcut, the default shortcut, * or both (the default). * \param loading if Autoloading, assign the global shortcut this action has previously had if any. * That way user preferences and changes made to avoid clashes will be conserved. * if NoAutoloading the given shortcut will be assigned without looking up old values. * You should only do this if the user wants to change the shortcut or if you have * another very good reason. Key combinations that clash with other shortcuts will be * dropped. * * \note the default shortcut will never be influenced by autoloading - it will be set as given. * \sa globalShortcut() */ void setGlobalShortcut(const KShortcut &shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut), GlobalShortcutLoading loading = Autoloading); /** * Returns true if this action is permitted to have a global shortcut. * Defaults to false. * Use isGlobalShortcutEnabled() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool globalShortcutAllowed() const; #endif /** * Indicate whether the programmer and/or user may define a global shortcut for this action. * Defaults to false. Note that calling setGlobalShortcut() turns this on automatically. * * \param allowed set to \e true if this action may have a global shortcut, otherwise \e false. * \param loading if Autoloading, assign to this action the global shortcut it has previously had * if any. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setGlobalShortcutAllowed(bool allowed, GlobalShortcutLoading loading = Autoloading); #endif /** * Returns true if this action is enabled to have a global shortcut. * This will be respected by \class KGlobalShortcutsEditor. * Defaults to false. */ bool isGlobalShortcutEnabled() const; /** * Sets the globalShortcutEnabled property to false and sets the global shortcut to an * empty shortcut. * This will also wipe out knowlegde about the existence of this action's global shortcut * so it will not be considered anymore for shortcut conflict resolution. It will also not be * visible anymore in the shortcuts KControl module. - * This method should not be used unless these effects are explicitly desired. + * This method should not be used unless these effects are KDELIBS4SUPPORT_DEPRECATED explicitly desired. * @since 4.1 */ void forgetGlobalShortcut(); KShapeGesture shapeGesture(ShortcutTypes type = ActiveShortcut) const; KRockerGesture rockerGesture(ShortcutTypes type = ActiveShortcut) const; void setShapeGesture(const KShapeGesture &gest, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut)); void setRockerGesture(const KRockerGesture &gest, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut)); /** * Returns the action object associated with this action, or 0 if it does not have one * * @returns the KAuth::Action associated with this action. */ KAuth::Action authAction() const; /** * Sets the action object associated with this action * * By setting a KAuth::Action, this action will become associated with it, and * whenever it gets clicked, it will trigger the authorization and execution process * for the action. The signal activated will also be emitted whenever the action gets * clicked and the action gets authorized. Pass 0 to this function to disassociate the action * * @param action the KAuth::Action to associate with this action. */ void setAuthAction(const KAuth::Action &action); /** * Sets the action object associated with this action * * Overloaded member to allow creating the action by name * * @param actionName the name of the action to associate */ void setAuthAction(const QString &actionName); Q_SIGNALS: #ifdef KDE3_SUPPORT /** * Emitted when this action is activated * * \deprecated use triggered(bool checked) instead. */ QT_MOC_COMPAT void activated(); #endif /** * Emitted when the action is triggered. Also provides the state of the * keyboard modifiers and mouse buttons at the time. * @deprecated since 5.0, use triggered() signal from QAction and check for * QApplication::mouseButtons() and QApplication::keyboardModifiers() in the slot. */ void triggered(Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers); /** * Signal emitted when the action is triggered and authorized * * If the action needs authorization, when the user triggers the action, * the authorization process automatically begins. * If it succeeds, this signal is emitted. The KAuth::Action object is provided for convenience * if you have multiple KAuthorizedAction objects, but of course it's always the same set with * setAuthAction(). * * WARNING: If your action needs authorization you should connect eventual slots processing * stuff to this signal, and NOT triggered. Triggered will be emitted even if the user has not * been authorized * * @param action The object set with setAuthAction() */ void authorized(const KAuth::Action &action); /** * Emitted when the global shortcut is changed. A global shortcut is * subject to be changed by the global shortcuts kcm. * @deprecated use KGlobalAccel::globalShortcutChanged instead */ void globalShortcutChanged(const QKeySequence &); private: friend class KGlobalAccelPrivate; // Needs access to the component friend class KActionCollectionPrivate; // Needs access to the component friend class KShortcutsEditorDelegate; // Needs access to the component Q_PRIVATE_SLOT(d, void slotTriggered()) Q_PRIVATE_SLOT(d, void _k_emitActionGlobalShortcutChanged(QAction *, const QKeySequence &)) class KActionPrivate *const d; friend class KActionPrivate; friend class KGlobalShortcutTest; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KAction::ShortcutTypes) #endif diff --git a/src/kdeui/kapplication.h b/src/kdeui/kapplication.h index c9b1cb62..f2db91ee 100644 --- a/src/kdeui/kapplication.h +++ b/src/kdeui/kapplication.h @@ -1,424 +1,424 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org) Copyright (c) 1998, 1999 KDE Team 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 KAPP_H #define KAPP_H // Version macros. Never put this further down. #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif class KConfig; #ifdef KDE3_SUPPORT #include #include #include #include #include #endif typedef unsigned long Atom; #include #include #include struct _IceConn; class QPixmap; #define kapp KApplication::kApplication() class KApplicationPrivate; /** * Controls and provides information to all KDE applications. * * Only one object of this class can be instantiated in a single app. * This instance is always accessible via the 'kapp' global variable. * * This class provides the following services to all KDE applications. * * @li It controls the event queue (see QApplication ). * @li It provides the application with KDE resources such as * accelerators, common menu entries, a KConfig object. session * management events, help invocation etc. * @li Installs an empty signal handler for the SIGPIPE signal. * If you want to catch this signal * yourself, you have set a new signal handler after KApplication's * constructor has run. * @li It can start new services * * * @short Controls and provides information to all KDE applications. * @author Matthias Kalle Dalheimer */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT_NOISE KApplication : public QApplication { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.KApplication") public: /** * This constructor is the one you should use. * It takes aboutData and command line arguments from KCmdLineArgs. * * @param GUIenabled Set to false to disable all GUI stuff. * Note that for a non-GUI daemon, you might want to use QCoreApplication * and a KComponentData instance instead. You'll save an unnecessary dependency * to kdeui. The main difference is that you will have to do a number of things yourself: *
    *
  • Register to DBus, if necessary.
  • *
  • Call KLocale::global(), if using multiple threads.
  • *
*/ - explicit KApplication(bool GUIenabled = true); + KDELIBS4SUPPORT_DEPRECATED explicit KApplication(bool GUIenabled = true); virtual ~KApplication(); /** * Returns the current application object. * * This is similar to the global QApplication pointer qApp. It * allows access to the single global KApplication object, since * more than one cannot be created in the same application. It - * saves you the trouble of having to pass the pointer explicitly + * saves you the trouble of having to pass the pointer KDELIBS4SUPPORT_DEPRECATED explicitly * to every function that may require it. * @return the current application object */ static KApplication *kApplication(); /** * @deprecated * Returns the application session config object. * * @return A pointer to the application's instance specific * KConfig object. * @see KConfigGui::sessionConfig */ KConfig *sessionConfig(); #ifdef KDE3_SUPPORT /** * Is the application restored from the session manager? * * @return If true, this application was restored by the session manager. * Note that this may mean the config object returned by * sessionConfig() contains data saved by a session closedown. * @see sessionConfig() * @deprecated use qApp->isSessionRestored() */ inline KDELIBS4SUPPORT_DEPRECATED bool isRestored() const { return QApplication::isSessionRestored(); } #endif /** * Disables session management for this application. * * Useful in case your application is started by the * initial "startkde" script. * * @deprecated, use qunsetenv("SESSION_MANAGER") or * call QSessionManager::setRestartHint(QSessionManager::RestartNever) * in the slot connected to commitDataRequest. * TODO: contribute a QGuiApplication::disableSessionManagement() method */ void disableSessionManagement(); /** * Enables session management for this application, formerly * disabled by calling disableSessionManagement(). You usually * shouldn't call this function, as session management is enabled * by default. */ void enableSessionManagement(); /** * @deprecated since 5.0, use QGuiApplication::isSavingSession() * * Returns true if the application is currently saving its session * data (most probably before KDE logout). This is intended for use * mainly in KMainWindow::queryClose() and KMainWindow::queryExit(). * * @see KMainWindow::queryClose * @see KMainWindow::queryExit */ bool sessionSaving() const; #ifdef KDE3_SUPPORT /** * Returns a QPixmap with the application icon. * @return the application icon * @deprecated Use QApplication::windowIcon() */ inline KDELIBS4SUPPORT_DEPRECATED QPixmap icon() const { int size = IconSize(KIconLoader::Desktop); return windowIcon().pixmap(size, size); } /** * Returns the mini-icon for the application as a QPixmap. * @return the application's mini icon * @deprecated Use QApplication::windowIcon() */ inline KDELIBS4SUPPORT_DEPRECATED QPixmap miniIcon() const { int size = IconSize(KIconLoader::Small); return windowIcon().pixmap(size, size); } #endif /** * Sets the top widget of the application. * This means basically applying the right window caption. * An application may have several top widgets. You don't * need to call this function manually when using KMainWindow. * * @param topWidget A top widget of the application. * * @see icon(), caption() * @deprecated since 5.0. This was doing two things: 1) setting the window title to * include the appname; Qt now takes care of that on platforms where this is wanted. * 2) setting the window startup ID, which Qt should take care of in the future. * -> simply remove this call. */ void setTopWidget(QWidget *topWidget); /** * Get a file name in order to make a temporary copy of your document. * * @param pFilename The full path to the current file of your * document. * @return A new filename for auto-saving. * @deprecated use QTemporaryFile, QSaveFile or KAutoSaveFile instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED static KDELIBS4SUPPORT_DEPRECATED QString tempSaveName(const QString &pFilename); #endif /** * Check whether an auto-save file exists for the document you want to * open. * * @param pFilename The full path to the document you want to open. * @param bRecover This gets set to true if there was a recover * file. * @return The full path of the file to open. */ static QString checkRecoverFile(const QString &pFilename, bool &bRecover); /** * @deprecated since 5.0, use QCoreApplication::installNativeEventFilter * Installs widget filter as global X11 event filter. * * The widget * filter receives XEvents in its standard QWidget::x11Event() function. * * Warning: Only do this when absolutely necessary. An installed X11 filter * can slow things down. */ void installX11EventFilter(QWidget *filter); /** * @deprecated since 5.0, use QCoreApplication::removeNativeEventFilter * Removes global X11 event filter previously installed by * installX11EventFilter(). */ void removeX11EventFilter(const QWidget *filter); #ifdef KDE3_SUPPORT /** * Generates a uniform random number. * @return A truly unpredictable number in the range [0, RAND_MAX) * @deprecated Use KRandom::random() */ static inline KDELIBS4SUPPORT_DEPRECATED int random() { return KRandom::random(); } /** * Generates a random string. It operates in the range [A-Za-z0-9] * @param length Generate a string of this length. * @return the random string * @deprecated use KRandom::randomString() instead. */ static inline KDELIBS4SUPPORT_DEPRECATED QString randomString(int length) { return KRandom::randomString(length); } #endif /** * @deprecated * Returns the app startup notification identifier for this running * application. * @return the startup notification identifier * @see KStartupInfo::startupId */ QByteArray startupId() const; /** * @internal * @deprecated * Sets a new value for the application startup notification window property for newly * created toplevel windows. * @param startup_id the startup notification identifier * @see KStartupInfo::setStartupId * @see KStartupInfo::setNewStartupId */ void setStartupId(const QByteArray &startup_id); /** * @internal * Used only by KStartupId. */ void clearStartupId(); /** * @deprecated * Returns the last user action timestamp or 0 if no user activity has taken place yet. * @see updateuserTimestamp * @see KUserTimestamp::userTimestamp */ unsigned long userTimestamp() const; /** * Updates the last user action timestamp in the application registered to DBUS with id service * to the given time, or to this application's user time, if 0 is given. * Use before causing user interaction in the remote application, e.g. invoking a dialog * in the application using a DCOP call. * Consult focus stealing prevention section in kdebase/kwin/README. */ void updateRemoteUserTimestamp(const QString &service, int time = 0); #ifdef KDE3_SUPPORT /** * Returns the argument to --geometry if any, so the geometry can be set * wherever necessary * @return the geometry argument, or QString() if there is none * @deprecated please use the following code instead: * * * QString geometry; * KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde"); * if (args && args->isSet("geometry")) * geometry = args->getOption("geometry"); * * */ static inline KDELIBS4SUPPORT_DEPRECATED QString geometryArgument() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs("kde"); return args->isSet("geometry") ? args->getOption("geometry") : QString(); } #endif public Q_SLOTS: /** * @deprecated * Updates the last user action timestamp to the given time, or to the current time, * if 0 is given. Do not use unless you're really sure what you're doing. * Consult focus stealing prevention section in kdebase/kwin/README. * @see KUserTimestamp::updateUserTimestamp */ Q_SCRIPTABLE void updateUserTimestamp(int time = 0); /** * Slot connected to QGuiApplication::commitDataRequest() to implement highlevel * handling of session management with KSessionManager. * @internal */ void commitData(QSessionManager &sm); /** * Slot connected to QGuiApplication::saveStateRequest() to implement highlevel * handling of session management with KSessionManager. * @internal */ void saveState(QSessionManager &sm); // D-Bus Q_SLOTS: Q_SCRIPTABLE void reparseConfiguration(); Q_SCRIPTABLE void quit(); Q_SIGNALS: /** @deprecated since 5.0, connect to saveStateRequest instead Session management asks you to save the state of your application. This signal is provided for compatibility only. For new applications, simply use KMainWindow. By reimplementing KMainWindow::queryClose(), KMainWindow::saveProperties() and KMainWindow::readProperties() you can simply handle session management for applications with multiple toplevel windows. For purposes without KMainWindow, create an instance of KSessionManager and reimplement the functions KSessionManager::commitData() and/or KSessionManager::saveState() If you still want to use this signal, here is what you should do: Connect to this signal in order to save your data. Do NOT manipulate the UI in that slot, it is blocked by the session manager. Use the sessionConfig() KConfig object to store all your instance specific data. Do not do any closing at this point! The user may still select Cancel wanting to continue working with your application. Cleanups could be done after aboutToQuit(). */ void saveYourself(); protected: /** * @internal Used by KUniqueApplication */ KApplication(bool GUIenabled, const KComponentData &cData); /// Current application object. static KApplication *KApp; private: KApplication(const KApplication &); KApplication &operator=(const KApplication &); private: // This is to catch invalid implicit conversions KApplication(bool, bool); friend class KApplicationPrivate; KApplicationPrivate *const d; Q_PRIVATE_SLOT(d, void _k_x11FilterDestroyed()) Q_PRIVATE_SLOT(d, void _k_slot_KToolInvocation_hook(QStringList &, QByteArray &)) }; #endif diff --git a/src/kdeui/karrowbutton.h b/src/kdeui/karrowbutton.h index 02e2d4cd..818fe934 100644 --- a/src/kdeui/karrowbutton.h +++ b/src/kdeui/karrowbutton.h @@ -1,102 +1,102 @@ /* This file is part of the KDE libraries Copyright (C) 2001, 2002 Frerich Raabe 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 karrowbutton_h #define karrowbutton_h #include #include class KArrowButtonPrivate; /** * @deprecated Use a QToolButton with the arrowType property set instead * * @short Draws a button with an arrow. * * Draws a button which shows an arrow pointing into a certain direction. The * arrow's alignment on the button depends on the direction it's pointing to, * e.g. a left arrow is aligned at the left border, a upwards arrow at the top * border. This class honors the currently configured KStyle when drawing * the arrow. * * \image html karrowbutton.png "KDE Arrow Buttons" * * @author Frerich Raabe */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KArrowButton : public QPushButton { Q_OBJECT /** * Arrow type for this button, from Qt::ArrowType. */ Q_PROPERTY(int arrowType READ arrowTp WRITE setArrowTp) public: /** * Constructs an arrow button. * * @param parent This button's parent * @param arrow The direction the arrrow should be pointing in */ - explicit KArrowButton(QWidget *parent = nullptr, Qt::ArrowType arrow = Qt::UpArrow); + KDELIBS4SUPPORT_DEPRECATED explicit KArrowButton(QWidget *parent = nullptr, Qt::ArrowType arrow = Qt::UpArrow); /** * Destructor. */ virtual ~KArrowButton(); /** * Reimplemented from QPushButton. */ QSize sizeHint() const Q_DECL_OVERRIDE; /** * Returns the arrow type */ Qt::ArrowType arrowType() const; /// hack for moc braindamage with enums, use arrowType() instead int arrowTp() const { return (int) arrowType(); } /// hack for moc braindamage with enums, use setArrowType() instead void setArrowTp(int tp) { setArrowType((Qt::ArrowType) tp); } public Q_SLOTS: /** * Defines in what direction the arrow is pointing to. Will repaint the * button if necessary. * * @param a The direction this arrow should be pointing in */ void setArrowType(Qt::ArrowType a); protected: /** * Reimplemented from QPushButton. */ void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; private: KArrowButtonPrivate *const d; }; #endif // karrowbutton_h diff --git a/src/kdeui/kbuttongroup.h b/src/kdeui/kbuttongroup.h index 7f6a33d2..cab21b11 100644 --- a/src/kdeui/kbuttongroup.h +++ b/src/kdeui/kbuttongroup.h @@ -1,115 +1,115 @@ /* This file is part of the KDE Libraries Copyright (C) 2006 Pino Toscano This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License 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 KBUTTONGROUP_H #define KBUTTONGROUP_H #include #include class QAbstractButton; /** * @deprecated since 5.0, use QGroupBox and QButtonGroup instead * * @brief Group box with index of the selected button. * * KButtonGroup is a simple group box that can keep track of the current selected * button of the ones added to it. * * Use normally as you would with a QGroupBox. * * \image html kbuttongroup.png "KDE Button Group containing 3 KPushButtons" * * @author Pino Toscano */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KButtonGroup : public QGroupBox { Q_OBJECT Q_PROPERTY(int current READ selected WRITE setSelected NOTIFY changed USER true) public: /** * Construct a new empty KGroupBox. */ - explicit KButtonGroup(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KButtonGroup(QWidget *parent = nullptr); /** * Destroys the widget. */ ~KButtonGroup(); /** * Return the index of the selected QAbstractButton, among the QAbstractButton's * added to the widget. * @return the index of the selected button */ int selected() const; /** * @return the index of @p button. * @since 4.3 */ int id(QAbstractButton *button) const; public Q_SLOTS: /** * Select the \p id -th button */ void setSelected(int id); Q_SIGNALS: /** * The button with index \p id was clicked */ void clicked(int id); /** * The button with index \p id was pressed */ void pressed(int id); /** * The button with index \p id was released */ void released(int id); /** * Emitted when anything (a click on a button, or calling setSelected()) * change the id of the current selected. \p id is the index of the new * selected button. */ void changed(int id); protected: /** * Reimplemented from QGroupBox. */ void childEvent(QChildEvent *event) Q_DECL_OVERRIDE; private: Q_PRIVATE_SLOT(d, void slotClicked(int id)) class Private; friend class Private; Private *const d; }; #endif diff --git a/src/kdeui/kcolordialog.h b/src/kdeui/kcolordialog.h index ba0f0969..14e39d82 100644 --- a/src/kdeui/kcolordialog.h +++ b/src/kdeui/kcolordialog.h @@ -1,347 +1,347 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Martin Jones (mjones@kde.org) 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. */ //---------------------------------------------------------------------- // KDE color selection dialog. // layout management added Oct 1997 by Mario Weilguni // #ifndef KCOLORDIALOG_H #define KCOLORDIALOG_H #include #include #include #include #include #include /** * A table of editable color cells. * * @author Martin Jones */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KColorCells : public QTableWidget { Q_OBJECT Q_PROPERTY(bool acceptDrags READ acceptDrags WRITE setAcceptDrags) Q_PROPERTY(bool shading READ shading WRITE setShading) public: /** * Constructs a new table of color cells, consisting of * @p rows * @p columns colors. * * @param parent The parent of the new widget * @param rows The number of rows in the table * @param columns The number of columns in the table */ KColorCells(QWidget *parent, int rows, int columns); ~KColorCells(); /** Sets the color in the given index in the table */ void setColor(int index, const QColor &col); /** Returns the color at a given index in the table */ QColor color(int index) const; /** Returns the total number of color cells in the table */ int count() const; void setShading(bool shade); bool shading() const; void setAcceptDrags(bool acceptDrags); bool acceptDrags() const; /** Sets the currently selected cell to @p index */ void setSelected(int index); /** Returns the index of the cell which is currently selected */ int selectedIndex() const; Q_SIGNALS: /** Emitted when a color is selected in the table */ void colorSelected(int index, const QColor &color); /** Emitted when a color in the table is double-clicked */ void colorDoubleClicked(int index, const QColor &color); protected: // the three methods below are used to ensure equal column widths and row heights // for all cells and to update the widths/heights when the widget is resized int sizeHintForColumn(int column) const Q_DECL_OVERRIDE; int sizeHintForRow(int column) const Q_DECL_OVERRIDE; void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE; void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE; void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE; void dragMoveEvent(QDragMoveEvent *) Q_DECL_OVERRIDE; void dropEvent(QDropEvent *) Q_DECL_OVERRIDE; void mouseDoubleClickEvent(QMouseEvent *) Q_DECL_OVERRIDE; int positionToCell(const QPoint &pos, bool ignoreBorders = false) const; private: class KColorCellsPrivate; friend class KColorCellsPrivate; KColorCellsPrivate *const d; Q_DISABLE_COPY(KColorCells) }; /** * @short A color displayer. * * The KColorPatch widget is a (usually small) widget showing * a selected color e.g. in the KColorDialog. It * automatically handles drag and drop from and on the widget. * * \image html kcolorpatch.png "KDE Color Patch" */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KColorPatch : public QFrame { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor) public: KColorPatch(QWidget *parent); virtual ~KColorPatch(); /** * Get the currently displayed color */ QColor color() const; /** * Set the color to display and update the display * * @param col color to display */ void setColor(const QColor &col); Q_SIGNALS: /** * This signal is emitted whenever the current color * changes due to a drop event */ void colorChanged(const QColor &); protected: void paintEvent(QPaintEvent *pe) Q_DECL_OVERRIDE; void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE; void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE; void dropEvent(QDropEvent *) Q_DECL_OVERRIDE; private: class KColorPatchPrivate; KColorPatchPrivate *const d; Q_DISABLE_COPY(KColorPatch) }; /** * @short A color selection dialog. * * Features:\n * * @li Color selection from a wide range of palettes. * @li Color selection from a palette of H vs S and V selectors. * @li Direct input of HSV or RGB values. * @li Saving of custom colors * * In most cases, you will want to use the static method KColorDialog::getColor(). * This pops up the dialog (with an initial selection provided by you), lets the * user choose a color, and returns. * * Example: * * \code * QColor myColor; * int result = KColorDialog::getColor( myColor ); * if ( result == KColorDialog::Accepted ) * ... * \endcode * * To react to the color selection as it is being selected, the colorSelected() signal * can be used. This can be used still in a modal way, for example: * * \code * KColorDialog dialog(this); * connect(&dialog, SIGNAL(colorSelected(const QColor &)), this, SLOT(temporarilyChangeColor(const QColor &))); * QColor myColor; * dialog.setColor(myColor); * int result = dialog.exec(); * * if ( result == KColorDialog::Accepted ) * changeColor( dialog.color() ); * else * temporarilyChangeColor(myColor); //change back to original color * \endcode * * * @image html kcolordialog.png "KDE Color Dialog" * * The color dialog is really a collection of several widgets which can * you can also use separately: the quadratic plane in the top left of * the dialog is a KXYSelector. Right next to it is a KHSSelector * for choosing hue/saturation. * * On the right side of the dialog you see a KColorTable showing * a number of colors with a combo box which offers several predefined * palettes or a palette configured by the user. The small field showing * the currently selected color is a KColorPatch. * **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KColorDialog : public KDialog { Q_OBJECT Q_PROPERTY(bool isAlphaChannelEnabled READ isAlphaChannelEnabled WRITE setAlphaChannelEnabled) Q_PROPERTY(QColor defaultColor READ defaultColor WRITE setDefaultColor) Q_PROPERTY(QColor color READ color WRITE setColor) public: /** * Constructs a color selection dialog. */ - explicit KColorDialog(QWidget *parent = nullptr, bool modal = false); + KDELIBS4SUPPORT_DEPRECATED explicit KColorDialog(QWidget *parent = nullptr, bool modal = false); /** * Destroys the color selection dialog. */ ~KColorDialog(); /** * Returns the currently selected color. **/ QColor color() const; /** * Creates a modal color dialog, let the user choose a * color, and returns when the dialog is closed. * * The selected color is returned in the argument @p theColor. * * @param theColor if valid, specifies the color to be initially selected. On * return, holds the selected color. * @returns QDialog::result(). */ static int getColor(QColor &theColor, QWidget *parent = nullptr); /** * Creates a modal color dialog, lets the user choose a * color, and returns when the dialog is closed. * * The selected color is returned in the argument @p theColor. * * This version takes a @p defaultColor argument, which sets the color * selected by the "default color" checkbox. When this checkbox is checked, * the invalid color (QColor()) is returned into @p theColor. * * @param theColor if valid, specifies the color to be initially selected. On * return, holds the selected color. * @param defaultColor color selected by the "default color" checkbox * @returns QDialog::result(). */ static int getColor(QColor &theColor, const QColor &defaultColor, QWidget *parent = nullptr); /** * Gets the color from the pixel at point p on the screen. */ static QColor grabColor(const QPoint &p); /** * Call this to make the dialog show a "Default Color" checkbox. * If this checkbox is selected, the dialog will return an "invalid" color (QColor()). * This can be used to mean "the default text color", for instance, * the one with the KDE text color on screen, but black when printing. */ void setDefaultColor(const QColor &defaultCol); /** * @return the value passed to setDefaultColor */ QColor defaultColor() const; /** * When set to true, the user is allowed to change the alpha component of the color. * The default value is false. * @since 4.5 */ void setAlphaChannelEnabled(bool alpha); /** * Returns true when the user can change the alpha channel. * @since 4.5 */ bool isAlphaChannelEnabled() const; public Q_SLOTS: /** * Preselects a color. */ void setColor(const QColor &col); Q_SIGNALS: /** * Emitted when a color is selected. * Connect to this to monitor the color as it as selected if you are * not running modal. */ void colorSelected(const QColor &col); private: Q_PRIVATE_SLOT(d, void slotRGBChanged(void)) Q_PRIVATE_SLOT(d, void slotAlphaChanged(void)) Q_PRIVATE_SLOT(d, void slotHSVChanged(void)) Q_PRIVATE_SLOT(d, void slotHtmlChanged(void)) Q_PRIVATE_SLOT(d, void slotHSChanged(int, int)) Q_PRIVATE_SLOT(d, void slotVChanged(int)) Q_PRIVATE_SLOT(d, void slotAChanged(int)) Q_PRIVATE_SLOT(d, void slotColorSelected(const QColor &col)) Q_PRIVATE_SLOT(d, void slotColorSelected(const QColor &col, const QString &name)) Q_PRIVATE_SLOT(d, void slotColorDoubleClicked(const QColor &col, const QString &name)) Q_PRIVATE_SLOT(d, void slotColorPicker()) Q_PRIVATE_SLOT(d, void slotAddToCustomColors()) Q_PRIVATE_SLOT(d, void slotDefaultColorClicked()) Q_PRIVATE_SLOT(d, void slotModeChanged(int id)) /** * Write the settings of the dialog to config file. **/ Q_PRIVATE_SLOT(d, void slotWriteSettings()) private: /** * Read the settings for the dialog from config file. **/ void readSettings(); protected: void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE; bool eventFilter(QObject *obj, QEvent *ev) Q_DECL_OVERRIDE; private: class KColorDialogPrivate; KColorDialogPrivate *const d; Q_DISABLE_COPY(KColorDialog) }; #endif // KCOLORDIALOG_H diff --git a/src/kdeui/kcolordialog_p.h b/src/kdeui/kcolordialog_p.h index 457ab95a..838d2487 100644 --- a/src/kdeui/kcolordialog_p.h +++ b/src/kdeui/kcolordialog_p.h @@ -1,77 +1,77 @@ /* This file is part of the KDE libraries Copyright (C) 2007 Olivier Goffart 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 KCOLORDIALOGP_H #define KCOLORDIALOGP_H #include namespace KDEPrivate { /** * A color palette in table form. * * @author Waldo Bastian **/ class KColorTable : public QWidget { Q_OBJECT public: - explicit KColorTable(QWidget *parent, int minWidth = 210, int cols = 16); + KDELIBS4SUPPORT_DEPRECATED explicit KColorTable(QWidget *parent, int minWidth = 210, int cols = 16); ~KColorTable(); void addToCustomColors(const QColor &); void addToRecentColors(const QColor &); QString name() const; public Q_SLOTS: void setColors(const QString &collectionName); Q_SIGNALS: void colorSelected(const QColor &, const QString &); void colorDoubleClicked(const QColor &, const QString &); private: Q_PRIVATE_SLOT(d, void slotColorCellSelected(int index, const QColor &)) Q_PRIVATE_SLOT(d, void slotColorCellDoubleClicked(int index, const QColor &)) Q_PRIVATE_SLOT(d, void slotColorTextSelected(const QString &colorText)) Q_PRIVATE_SLOT(d, void slotSetColors(const QString &_collectionName)) Q_PRIVATE_SLOT(d, void slotShowNamedColorReadError(void)) void readNamedColor(void); private: virtual void setPalette(const QPalette &p) { QWidget::setPalette(p); } private: class KColorTablePrivate; friend class KColorTablePrivate; KColorTablePrivate *const d; Q_DISABLE_COPY(KColorTable) }; } #endif diff --git a/src/kdeui/kcolorvalueselector.h b/src/kdeui/kcolorvalueselector.h index 0c705dd0..7f63581d 100644 --- a/src/kdeui/kcolorvalueselector.h +++ b/src/kdeui/kcolorvalueselector.h @@ -1,137 +1,137 @@ /* This file is part of the KDE libraries * * Copyright (C) 1997 Martin Jones (mjones@kde.org) * * 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 KCOLORVALUESELECTOR_H #define KCOLORVALUESELECTOR_H #include "kselector.h" #include "kcolorchoosermode.h" #include #include class KDELIBS4SUPPORT_DEPRECATED_EXPORT KColorValueSelector : public KSelector { Q_OBJECT Q_PROPERTY(int hue READ hue WRITE setHue) Q_PROPERTY(int saturation READ saturation WRITE setSaturation) Q_PROPERTY(int colorValue READ colorValue WRITE setColorValue) public: /** * Constructs a widget for color selection. */ - explicit KColorValueSelector(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KColorValueSelector(QWidget *parent = nullptr); /** * Constructs a widget for color selection with a given orientation */ - explicit KColorValueSelector(Qt::Orientation o, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KColorValueSelector(Qt::Orientation o, QWidget *parent = nullptr); ~KColorValueSelector(); /** * Updates the widget's contents. */ void updateContents(); /** * Returns the current hue value. * * @return The hue value (0-359) */ int hue() const; /** * Sets the hue value. Doesn't automatically update the widget; * you have to call updateContents manually. * * @param hue Sets the hue value (0-359) */ void setHue(int hue); /** * Returns the current saturation value. * * @return The saturation value (0-255) */ int saturation() const; /** * Sets the saturation value. Doesn't automatically update the widget; * you have to call updateContents manually. * * @param saturation Sets the saturation value (0-255) */ void setSaturation(int saturation); /** * Returns the current color value. * * @return The color value (0-255) */ int colorValue() const; /** * Sets the color value. Doesn't automatically update the widget; * you have to call updateContents manually. * * @param colorValue Sets the color value (0-255) */ void setColorValue(int colorValue); /** * Sets the chooser mode. Doesn't automatically update the widget; * you have to call updateContents manually. * * @param chooserMode Sets the chooser mode (one of the KColorChooserMode constants) */ void setChooserMode(KColorChooserMode chooserMode); /** * Returns the current chooser mode. * * @return The chooser mode (one of the KColorChooserMode constants) */ KColorChooserMode chooserMode() const; protected: /** * Draws the contents of the widget on a pixmap, * which is used for buffering. */ virtual void drawPalette(QPixmap *pixmap); void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; /** * Reimplemented from KSelector. The drawing is * buffered in a pixmap here. As real drawing * routine, drawPalette() is used. */ void drawContents(QPainter *painter) Q_DECL_OVERRIDE; private: class Private; friend class Private; Private *const d; Q_DISABLE_COPY(KColorValueSelector) }; #endif /* KCOLORVALUESELECTOR_H */ diff --git a/src/kdeui/kdatetimewidget.h b/src/kdeui/kdatetimewidget.h index b8288e93..1a5680fb 100644 --- a/src/kdeui/kdatetimewidget.h +++ b/src/kdeui/kdatetimewidget.h @@ -1,90 +1,90 @@ /* This file is part of the KDE libraries Copyright (C) 2002 Hans Petter bieker 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 KDATETIMEWIDGET #define KDATETIMEWIDGET #include #include #include /** * @short A combination of a date and a time selection widget. * * This widget can be used to display or allow user selection of date and time. * * @see KDateWidget * * \image html kdatetimewidget.png "KDE Date Time Widget" * * @author Hans Petter Bieker */ class KDELIBS4SUPPORT_EXPORT KDateTimeWidget : public QWidget { Q_OBJECT Q_PROPERTY(QDateTime dateTime READ dateTime WRITE setDateTime NOTIFY valueChanged USER true) public: /** * Constructs a date and time selection widget. */ - explicit KDateTimeWidget(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDateTimeWidget(QWidget *parent = nullptr); /** * Constructs a date and time selection widget with the initial date and * time set to @p datetime. */ - explicit KDateTimeWidget(const QDateTime &datetime, + KDELIBS4SUPPORT_DEPRECATED explicit KDateTimeWidget(const QDateTime &datetime, QWidget *parent = nullptr); /** * Destructs the date and time selection widget. */ virtual ~KDateTimeWidget(); /** * Returns the currently selected date and time. */ QDateTime dateTime() const; public Q_SLOTS: /** * Changes the selected date and time to @p datetime. */ void setDateTime(const QDateTime &datetime); Q_SIGNALS: /** * Emitted whenever the date or time of the widget * is changed, either with setDateTime() or via user selection. */ void valueChanged(const QDateTime &datetime); private: void initWidget(); private Q_SLOTS: void slotValueChanged(); private: class KDateTimeWidgetPrivate; KDateTimeWidgetPrivate *const d; }; #endif diff --git a/src/kdeui/kdatewidget.h b/src/kdeui/kdatewidget.h index 55b4fcda..e0ef89bc 100644 --- a/src/kdeui/kdatewidget.h +++ b/src/kdeui/kdatewidget.h @@ -1,124 +1,124 @@ /* This file is part of the KDE libraries Copyright (C) 2001 Waldo Bastian (bastian@kde.org) Copyright (c) 2007 John Layt 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 KDATEWIDGET_H #define KDATEWIDGET_H #include #include #include "klocale.h" class KCalendarSystem; class QDate; /** * @short A date selection widget. * * This widget can be used to display or allow user selection of a date. * * \image html kdatewidget.png "KDE Date Widget" * * @see KDatePicker * * @author Waldo Bastian , John Layt */ class KDELIBS4SUPPORT_EXPORT KDateWidget : public QWidget { Q_OBJECT Q_PROPERTY(QDate date READ date WRITE setDate NOTIFY changed USER true) //FIXME Q_PROPERTY( KCalendarSystem calendar READ calendar WRITE setCalendar USER true ) public: /** * Constructs a date selection widget. */ - explicit KDateWidget(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDateWidget(QWidget *parent = nullptr); /** * Constructs a date selection widget with the initial date set to @p date. */ - explicit KDateWidget(const QDate &date, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDateWidget(const QDate &date, QWidget *parent = nullptr); /** * Destructs the date selection widget. */ virtual ~KDateWidget(); // KDE5 remove const & /** * Returns the currently selected date. */ const QDate &date() const; /** * Changes the selected date to @p date. * * @return @c true if the date was successfully set, @c false otherwise */ bool setDate(const QDate &date); /** * Returns the currently selected calendar system. * * @return a KCalendarSystem object */ const KCalendarSystem *calendar() const; /** * Changes the calendar system to use. Can use its own local locale if set. * * @param calendar the calendar system object to use, defaults to global * * @return @c true if the calendar system was successfully set, @c false otherwise */ bool setCalendar(KCalendarSystem *calendar = nullptr); /** * @since 4.6 * * Changes the calendar system to use. Will always use global locale. * * @param calendarSystem the calendar system to use * @return @c true if the calendar system was successfully set, @c false otherwise */ bool setCalendarSystem(KLocale::CalendarSystem calendarSystem); Q_SIGNALS: /** * Emitted whenever the date of the widget * is changed, either with setDate() or via user selection. */ void changed(const QDate &date); protected: void initWidget(const QDate &date); protected Q_SLOTS: void slotDateChanged(); private: class KDateWidgetPrivate; KDateWidgetPrivate *const d; }; #endif // KDATEWIDGET_H diff --git a/src/kdeui/kdialog.h b/src/kdeui/kdialog.h index b684dab6..af8ca554 100644 --- a/src/kdeui/kdialog.h +++ b/src/kdeui/kdialog.h @@ -1,878 +1,878 @@ /* This file is part of the KDE Libraries * Copyright (C) 1998 Thomas Tanghus (tanghus@earthling.net) * Additions 1999-2000 by Espen Sand (espen@kde.org) * and Holger Freyther * 2005-2009 Olivier Goffart * 2006 Tobias Koenig * * 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 KDIALOG_H #define KDIALOG_H class QPushButton; class QMenu; class KDialogPrivate; #include #include #include #include /** * @short A dialog base class with standard buttons and predefined layouts. * * Provides basic functionality needed by nearly all dialogs. * * It offers the standard action buttons you'd expect to find in a * dialog as well as the capability to define at most three configurable * buttons. You can define a main widget that contains your specific * dialog layout * * The class takes care of the geometry management. You only need to define * a minimum size for the widget you want to use as the main widget. * * By default, the dialog is non-modal. * * Standard buttons (action buttons):\n * * You select which buttons should be displayed, but you do not choose the * order in which they are displayed. This ensures a standard interface in * KDE. The button order can be changed, but this ability is only available * for a central KDE control tool. The following buttons are available: * OK, Cancel/Close, Apply/Try, Default, Help and three user definable * buttons: User1, User2 and User3. You must specify the text of the UserN * buttons. Each button emit a signal, so you can choose to connect that signal. * * The default action of the Help button will open the help system if you have * provided a path to the help text. * The default action of Ok and Cancel will run QDialog::accept() and QDialog::reject(), * which you can override by reimplementing slotButtonClicked(). The default * action of the Close button will close the dialog. * * Note that the KDialog will animate a button press * when the user presses Escape. The button that is enabled is either Cancel, * Close or the button that is defined by setEscapeButton(). * Your custom dialog code should reimplement the keyPressEvent and * animate the cancel button so that the dialog behaves like regular * dialogs. * * Layout:\n * * The dialog consists of a help area on top (becomes visible if you define * a help path and use enableLinkedHelp()), the main area which is * the built-in dialog face or your own widget in the middle and by default * a button box at the bottom. The button box can also be placed at the * right edge (to the right of the main widget). Use * setButtonsOrientation() to control this behavior. A separator * can be placed above the button box (or to the left when the button box * is at the right edge). * * Standard compliance:\n * * The marginHint() and spacingHint() sizes shall be used * whenever you lay out the interior of a dialog. One special note. If * you make your own action buttons (OK, Cancel etc), the space * between the buttons shall be spacingHint(), whereas the space * above, below, to the right and to the left shall be marginHint(). * If you add a separator line above the buttons, there shall be a * marginHint() between the buttons and the separator and a * marginHint() above the separator as well. * * Example:\n * * \code * KDialog *dialog = new KDialog( this ); * dialog->setCaption( "My title" ); * dialog->setButtons( KDialog::Ok | KDialog::Cancel | KDialog::Apply ); * * FooWidget *widget = new FooWidget( dialog ); * dialog->setMainWidget( widget ); * connect( dialog, SIGNAL( applyClicked() ), widget, SLOT( save() ) ); * connect( dialog, SIGNAL( okClicked() ), widget, SLOT( save() ) ); * connect( widget, SIGNAL( changed( bool ) ), dialog, SLOT( enableButtonApply( bool ) ) ); * * dialog->enableButtonApply( false ); * dialog->show(); * \endcode * * \image html kdialog.png "KDE Dialog example" * * This class can be used in many ways. Note that most KDE ui widgets * and many of KDE core applications use the KDialog so for more * inspiration you should study the code for these. * * * @see KPageDialog * @author Thomas Tanghus * @author Espen Sand * @author Mirko Boehm * @author Olivier Goffart * @author Tobias Koenig */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDialog : public QDialog //krazy:exclude=qclasses { Q_OBJECT Q_ENUMS(ButtonCode) Q_DECLARE_PRIVATE(KDialog) public: enum ButtonCode { None = 0x00000000, Help = 0x00000001, ///< Show Help button. (this button will run the help set with setHelp) Default = 0x00000002, ///< Show Default button. Ok = 0x00000004, ///< Show Ok button. (this button accept()s the dialog; result set to QDialog::Accepted) Apply = 0x00000008, ///< Show Apply button. Try = 0x00000010, ///< Show Try button. Cancel = 0x00000020, ///< Show Cancel-button. (this button reject()s the dialog; result set to QDialog::Rejected) Close = 0x00000040, ///< Show Close-button. (this button closes the dialog) No = 0x00000080, ///< Show No button. (this button closes the dialog and sets the result to KDialog::No) Yes = 0x00000100, ///< Show Yes button. (this button closes the dialog and sets the result to KDialog::Yes) Reset = 0x00000200, ///< Show Reset button Details = 0x00000400, ///< Show Details button. (this button will show the detail widget set with setDetailsWidget) User1 = 0x00001000, ///< Show User defined button 1. User2 = 0x00002000, ///< Show User defined button 2. User3 = 0x00004000, ///< Show User defined button 3. NoDefault = 0x00008000 ///< Used when specifying a default button; indicates that no button should be marked by default. }; // TODO KDE5: remove NoDefault and use the value None instead Q_DECLARE_FLAGS(ButtonCodes, ButtonCode) enum ButtonPopupMode { InstantPopup = 0, DelayedPopup = 1 }; Q_DECLARE_FLAGS(ButtonPopupModes, ButtonPopupMode) public: /** * Creates a dialog. * * @param parent The parent of the dialog. * @param flags The widget flags passed to the QDialog constructor */ - explicit KDialog(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDialog(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr); /** * Destroys the dialog. */ ~KDialog(); /** * Creates (or recreates) the button box and all the buttons in it. * * Note that some combinations are not possible. That means, you can't * have the following pairs of buttons in a dialog: * - Default and Details * - Cancel and Close * - Ok and Try * * This will reset all default KGuiItem of all button. * * @param buttonMask Specifies what buttons will be made. * * @deprecated Since 5.0 use QDialogButtonBox */ void setButtons(ButtonCodes buttonMask); /** * Sets the orientation of the button box. * * It can be @p Vertical or @p Horizontal. If @p Horizontal * (default), the button box is positioned at the bottom of the * dialog. If @p Vertical it will be placed at the right edge of the * dialog. * * @param orientation The button box orientation. */ void setButtonsOrientation(Qt::Orientation orientation); /** * Sets the button that will be activated when the Escape key * is pressed. * * By default, the Escape key is mapped to either the Cancel or the Close button * if one of these buttons are defined. The user expects that Escape will * cancel an operation so use this function with caution. * * @param id The button code. */ void setEscapeButton(ButtonCode id); /** * Sets the button that will be activated when the Enter key * is pressed. * * By default, this is the Ok button if it is present * * @param id The button code. */ void setDefaultButton(ButtonCode id); /** * Returns the button code of the default button, * or NoDefault if there is no default button. */ ButtonCode defaultButton() const; /** * Hide or display the a separator line drawn between the action * buttons an the main widget. */ void showButtonSeparator(bool state); /** * Hide or display a general action button. * * Only buttons that have * been created in the constructor can be displayed. This method will * not create a new button. * * @param id Button identifier. * @param state true display the button(s). */ void showButton(ButtonCode id, bool state); /** * Sets the text of any button. * * @param id The button identifier. * @param text Button text. */ void setButtonText(ButtonCode id, const QString &text); /** * Returns the text of any button. */ QString buttonText(ButtonCode id) const; /** * Sets the icon of any button. * * @param id The button identifier. * @param icon Button icon. */ void setButtonIcon(ButtonCode id, const QIcon &icon); /** * Returns the icon of any button. */ QIcon buttonIcon(ButtonCode id) const; /** * Sets the tooltip text of any button. * * @param id The button identifier. * @param text Button text. */ void setButtonToolTip(ButtonCode id, const QString &text); /** * Returns the tooltip of any button. */ QString buttonToolTip(ButtonCode id) const; /** * Sets the "What's this?" text of any button. * * @param id The button identifier. * @param text Button text. */ void setButtonWhatsThis(ButtonCode id, const QString &text); /** * Returns the "What's this?" text of any button. */ QString buttonWhatsThis(ButtonCode id) const; /** * Sets the KGuiItem directly for the button instead of using 3 methods to * set the text, tooltip and whatsthis strings. This also allows to set an * icon for the button which is otherwise not possible for the extra * buttons beside Ok, Cancel and Apply. * * @param id The button identifier. * @param item The KGuiItem for the button. */ void setButtonGuiItem(ButtonCode id, const KGuiItem &item); /** * Sets the menu of any button. * * @param id The button identifier. * @param menu The menu. * @param popupmode Choose if QPushButton setMenu or setDelayedMenu is used */ void setButtonMenu(ButtonCode id, QMenu *menu, ButtonPopupMode popupmode = InstantPopup); /** * Sets the focus to the button of the passed @p id. */ void setButtonFocus(ButtonCode id); /** * Convenience method. Sets the initial dialog size. * * This method should only be called right before show() or exec(). * The initial size will be ignored if smaller than * the dialog's minimum size. * * @param size Startup size. */ void setInitialSize(const QSize &size); /** * Convenience method. Add a size to the default minimum size of a * dialog. * * This method should only be called right before show() or exec(). * * @param size Size added to minimum size. */ void incrementInitialSize(const QSize &size); /** * Restores the dialog's size from the configuration according to * the screen size. * * @note the group must be set before calling * * @param config The config group to read from. * @deprecated use KWindowConfig::restoreWindowSize() instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void restoreDialogSize(const KConfigGroup &config); #endif /** * Saves the dialog's size dependent on the screen dimension either to the * global or application config file. * * @note the group must be set before calling * * @param config The config group to read from. * @param options passed to KConfigGroup::writeEntry() * @deprecated use KWindowConfig::saveWindowSize() instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void saveDialogSize(KConfigGroup &config, KConfigGroup::WriteConfigFlags options = KConfigGroup::Normal) const; #endif /** * Returns the help link text. * * If no text has been defined, * "Get help..." (internationalized) is returned. * * @return The help link text. * * @see enableLinkedHelp() * @see setHelpLinkText() * @see setHelp() */ QString helpLinkText() const; /** * Returns whether any button is enabled. */ bool isButtonEnabled(ButtonCode id) const; /** * Returns the button that corresponds to the @p id. * * Normally you should not use this function. * @em Never delete the object returned by this function. * See also enableButton(), showButton(), setButtonGuiItem(). * * @param id Identifier of the button. * @return The button or 0 if the button does not exist. */ QPushButton *button(ButtonCode id) const; /** * Returns the number of pixels that should be used between a * dialog edge and the outermost widget(s) according to the KDE standard. * * @deprecated Use the style's pixelMetric() function to query individual margins. * Different platforms may use different values for the four margins. */ static int marginHint(); /** * Returns the number of pixels that should be used between * widgets inside a dialog according to the KDE standard. * * @deprecated Use the style's layoutSpacing() function to query individual spacings. * Different platforms may use different values depending on widget types and pairs. */ static int spacingHint(); /** * Returns the number of pixels that should be used to visually * separate groups of related options in a dialog according to * the KDE standard. * @since 4.2 */ static int groupSpacingHint(); /** * @enum StandardCaptionFlag * Used to specify how to construct a window caption * * @value AppName Indicates that the method shall include * the application name when making the caption string. * @value Modified Causes a 'modified' sign will be included in the * returned string. This is useful when indicating that a file is * modified, i.e., it contains data that has not been saved. * @value HIGCompliant The base minimum flags required to align a * caption with the KDE Human Interface Guidelines */ enum CaptionFlag { NoCaptionFlags = 0, AppNameCaption = 1, ModifiedCaption = 2, HIGCompliantCaption = AppNameCaption }; Q_DECLARE_FLAGS(CaptionFlags, CaptionFlag) /** * Builds a caption that contains the application name along with the * userCaption using a standard layout. * * To make a compliant caption for your window, simply do: * @p setWindowTitle(KDialog::makeStandardCaption(yourCaption)); * * To ensure that the caption is appropriate to the desktop in which the * application is running, pass in a pointer to the window the caption will * be applied to. * * If using a KDialog or KMainWindow subclass, call setCaption instead and * an appropraite standard caption will be created for you * * @param userCaption The caption string you want to display in the * window caption area. Do not include the application name! * @param window a pointer to the window this application will apply to * @param flags * @return the created caption */ static QString makeStandardCaption(const QString &userCaption, QWidget *window = nullptr, CaptionFlags flags = HIGCompliantCaption); /** * Resize every layout manager used in @p widget and its nested children. * * @param widget The widget used. * @param margin The new layout margin. * @param spacing The new layout spacing. * * @deprecated Use QLayout functions where necessary. Setting margin and spacing * values recursively for all children prevents QLayout from creating platform native * layouts. */ static void resizeLayout(QWidget *widget, int margin, int spacing); /** * Resize every layout associated with @p lay and its children. * * @param lay layout to be resized * @param margin The new layout margin * @param spacing The new layout spacing * * @deprecated Use QLayout functions where necessary. Setting margin and spacing * values recursively for all children prevents QLayout from creating platform native * layouts. */ static void resizeLayout(QLayout *lay, int margin, int spacing); /** * Centers @p widget on the desktop, taking multi-head setups into * account. If @p screen is -1, @p widget will be centered on its * current screen (if it was shown already) or on the primary screen. * If @p screen is -3, @p widget will be centered on the screen that * currently contains the mouse pointer. * @p screen will be ignored if a merged display (like Xinerama) is not * in use, or merged display placement is not enabled in kdeglobals. */ static void centerOnScreen(QWidget *widget, int screen = -1); /** * Places @p widget so that it doesn't cover a certain @p area of the screen. * This is typically used by the "find dialog" so that the match it finds can * be read. * For @p screen, see centerOnScreen * @return true on success (widget doesn't cover area anymore, or never did), * false on failure (not enough space found) */ static bool avoidArea(QWidget *widget, const QRect &area, int screen = -1); /** * Sets the main widget of the dialog. */ void setMainWidget(QWidget *widget); /** * @return The current main widget. Will create a QWidget as the mainWidget * if none was set before. This way you can write * \code * ui.setupUi(mainWidget()); * \endcode * when using designer. */ QWidget *mainWidget(); /** * Reimplemented from QDialog. */ QSize sizeHint() const Q_DECL_OVERRIDE; /** * Reimplemented from QDialog. */ QSize minimumSizeHint() const Q_DECL_OVERRIDE; /** * Allow embedding the dialogs based on KDialog into a graphics view. By default embedding is not allowed, dialogs * will appear as separate windows. * @since 4.6 */ static void setAllowEmbeddingInGraphicsView(bool allowEmbedding); public Q_SLOTS: /** * Make a KDE compliant caption. * * @param caption Your caption. Do @p not include the application name * in this string. It will be added automatically according to the KDE * standard. * * @deprecated Since 5.0 use QWidget::setWindowTitle */ virtual void setCaption(const QString &caption); /** * Makes a KDE compliant caption. * * @param caption Your caption. @em Do @em not include the application name * in this string. It will be added automatically according to the KDE * standard. * @param modified Specify whether the document is modified. This displays * an additional sign in the title bar, usually "**". * * @deprecated Since 5.0 use QWidget::setWindowTitle and QWidget::setWindowModified. */ virtual void setCaption(const QString &caption, bool modified); /** * Make a plain caption without any modifications. * * @param caption Your caption. This is the string that will be * displayed in the window title. */ virtual void setPlainCaption(const QString &caption); /** * Enable or disable (gray out) a general action button. * * @param id Button identifier. * @param state @p true enables the button(s). */ void enableButton(ButtonCode id, bool state); /** * Enable or disable (gray out) the OK button. * * @param state @p true enables the button. */ void enableButtonOk(bool state); /** * Enable or disable (gray out) the Apply button. * * @param state true enables the button. */ void enableButtonApply(bool state); /** * Enable or disable (gray out) the Cancel button. * * @param state true enables the button. */ void enableButtonCancel(bool state); /** * Display or hide the help link area on the top of the dialog. * * @param state @p true will display the area. * * @see helpLinkText() * @see setHelpLinkText() * @see setHelp() */ void enableLinkedHelp(bool state); /** * Sets the text that is shown as the linked text. * * If text is empty, * the text "Get help..." (internationalized) is used instead. * * @param text The link text. * * @see helpLinkText() * @see enableLinkedHelp() * @see setHelp() */ void setHelpLinkText(const QString &text); /** * Sets the help path and topic. * * @param anchor Defined anchor in your docbook sources * @param appname Defines the appname the help belongs to * If empty it's the current one * * @note The help button works differently for the class * KCMultiDialog, so it does not make sense to call this * function for Dialogs of that type. See * KCMultiDialog::slotHelp() for more information. */ void setHelp(const QString &anchor, const QString &appname = QString()); /** * Returns the status of the Details button. */ bool isDetailsWidgetVisible() const; /** * Sets the status of the Details button. */ void setDetailsWidgetVisible(bool visible); /** * Sets the widget that gets shown when "Details" is enabled. * * The dialog takes over ownership of the widget. * Any previously set widget gets deleted. */ void setDetailsWidget(QWidget *detailsWidget); /** * Destruct the dialog delayed. * * You can call this function from slots like closeClicked() and hidden(). * You should not use the dialog any more after calling this function. * @deprecated use hide()+deleteLater() */ void delayedDestruct(); Q_SIGNALS: /** * Emitted when the margin size and/or spacing size * have changed. * * Use marginHint() and spacingHint() in your slot * to get the new values. * * @deprecated This signal is not emitted. Listen to QEvent::StyleChange events instead. */ void layoutHintChanged(); /** * The Help button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void helpClicked(); /** * The Default button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void defaultClicked(); /** * The Reset button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void resetClicked(); /** * The User3 button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void user3Clicked(); /** * The User2 button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void user2Clicked(); /** * The User1 button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void user1Clicked(); /** * The Apply button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void applyClicked(); /** * The Try button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void tryClicked(); /** * The OK button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void okClicked(); /** * The Yes button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void yesClicked(); /** * The No button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void noClicked(); /** * The Cancel button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void cancelClicked(); /** * The Close button was pressed. This signal is only emitted if * slotButtonClicked() is not replaced */ void closeClicked(); /** * A button has been pressed. This signal is only emitted if * slotButtonClicked() is not replaced * @param button is the code of the pressed button. */ void buttonClicked(KDialog::ButtonCode button); /** * The dialog is about to be hidden. * * A dialog is hidden after a user clicks a button that ends * the dialog or when the user switches to another desktop or * minimizes the dialog. */ void hidden(); /** * The dialog has finished. * * A dialog emits finished after a user clicks a button that ends * the dialog. * * This signal is also emitted when you call hide() * * If you have stored a pointer to the * dialog do @em not try to delete the pointer in the slot that is * connected to this signal. * * You should use deleteLater() instead. */ void finished(); /** * The detailsWidget is about to get shown. This is your last chance * to call setDetailsWidget if you haven't done so yet. */ void aboutToShowDetails(); protected: /** * Emits the #hidden signal. You can connect to that signal to * detect when a dialog has been closed. */ void hideEvent(QHideEvent *) Q_DECL_OVERRIDE; /** * Detects when a dialog is being closed from the window manager * controls. If the Cancel or Close button is present then the button * is activated. Otherwise standard QDialog behavior * will take place. */ void closeEvent(QCloseEvent *e) Q_DECL_OVERRIDE; /** * @internal */ void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE; protected Q_SLOTS: /** * Activated when the button @p button is clicked * * Sample that shows how to catch and handle button clicks within * an own dialog; * @code * class MyDialog : public KDialog { * protected Q_SLOTS: * virtual void slotButtonClicked(int button) { * if (button == KDialog::Ok) * accept(); * else * KDialog::slotButtonClicked(button); * } * } * @endcode * * @param button is the type @a KDialog::ButtonCode * * @deprecated since 5.0 use QDialogButtonBox and connect to the clicked signal */ virtual void slotButtonClicked(int button); /** * Updates the margins and spacings. * * @deprecated KDialog respects the style's margins and spacings automatically. Calling * this function has no effect. */ void updateGeometry(); protected: KDialog(KDialogPrivate &dd, QWidget *parent, Qt::WindowFlags flags = nullptr); KDialogPrivate *const d_ptr; private: Q_DISABLE_COPY(KDialog) Q_PRIVATE_SLOT(d_ptr, void queuedLayoutUpdate()) Q_PRIVATE_SLOT(d_ptr, void helpLinkClicked()) }; Q_DECLARE_OPERATORS_FOR_FLAGS(KDialog::ButtonCodes) Q_DECLARE_OPERATORS_FOR_FLAGS(KDialog::CaptionFlags) #endif // KDIALOG_H diff --git a/src/kdeui/kdialogbuttonbox.h b/src/kdeui/kdialogbuttonbox.h index dcc8e921..ea28c603 100644 --- a/src/kdeui/kdialogbuttonbox.h +++ b/src/kdeui/kdialogbuttonbox.h @@ -1,101 +1,101 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Mario Weilguni (mweilguni@sime.com) Copyright (C) 2006 Olivier Goffart 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 KDIALOGBUTTONBOX_H #define KDIALOGBUTTONBOX_H #include #include class QPushButton; class KPushButton; class KGuiItem; class KDialogButtonBoxPrivate; /** * Container widget for buttons. * * An extension of QDialogButtonBox which allow the use of KGuiItem and * conveniance slot connection. * * \image html kdialogbuttonbox.png "Various KDE Dialog Button Boxes with different buttons" * * @author Mario Weilguni * @author Olivier Goffart **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDialogButtonBox : public QDialogButtonBox { Q_OBJECT public: /** * Create an empty container for buttons. * * If @p _orientation is @p Vertical, the buttons inserted with * addButton() are laid out from top to bottom, otherwise they * are laid out from left to right. */ - explicit KDialogButtonBox(QWidget *parent, Qt::Orientation _orientation = Qt::Horizontal); + KDELIBS4SUPPORT_DEPRECATED explicit KDialogButtonBox(QWidget *parent, Qt::Orientation _orientation = Qt::Horizontal); /** * Free private data field */ ~KDialogButtonBox(); /** * Creates a push button with the given text, adds it to the button box for the specified role, and returns the corresponding push button. * If role is invalid, no button is created, and zero is returned. * * The clicked signal of the button is automatically connected to the slot * * @param text the text of the button to add. * @param role the button role * @param receiver An object to connect to. * @param slot A Qt slot to connect the 'clicked()' signal to. * * @return A pointer to the new button. */ QPushButton *addButton(const QString &text, ButtonRole role, QObject *receiver, const char *slot); /** * Creates a push button with the given KUiItem, adds it to the button box for the specified role, and returns the corresponding push button. * If role is invalid, the button is created, but not added. * * The clicked signal of the button is automatically connected to the slot * * @param guiitem text and icon on the button * @param role the button role * @param receiver An object to connect to. * @param slot A Qt slot to connect the 'clicked()' signal to. * * @return A pointer to the new button. */ KPushButton *addButton(const KGuiItem &guiitem, ButtonRole role, QObject *receiver = nullptr, const char *slot = nullptr); using QDialogButtonBox::addButton; private: KDialogButtonBoxPrivate *const d; }; #endif diff --git a/src/kdeui/keditlistbox.h b/src/kdeui/keditlistbox.h index 9ac17fb0..34517fb9 100644 --- a/src/kdeui/keditlistbox.h +++ b/src/kdeui/keditlistbox.h @@ -1,296 +1,296 @@ /* This file is part of the KDE libraries Copyright (C) 2000 David Faure , Alexander Neundorf 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 KEDITLISTBOX_H #define KEDITLISTBOX_H #include #include #include class KLineEdit; class KComboBox; class QListView; class QPushButton; class QItemSelection; class KEditListBoxPrivate; /** * @brief An editable listbox * * @deprecated since 5.0 in favor of KEditListWidget embedded in a QGroupBox. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KEditListBox : public QGroupBox { Q_OBJECT Q_FLAGS(Buttons) Q_PROPERTY(Buttons buttons READ buttons WRITE setButtons) Q_PROPERTY(QStringList items READ items WRITE setItems NOTIFY changed USER true) public: class CustomEditorPrivate; /** * Custom editor class **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT CustomEditor { public: CustomEditor(); CustomEditor(QWidget *repWidget, KLineEdit *edit); CustomEditor(KComboBox *combo); virtual ~CustomEditor(); void setRepresentationWidget(QWidget *repWidget); void setLineEdit(KLineEdit *edit); virtual QWidget *representationWidget() const; virtual KLineEdit *lineEdit() const; private: friend class CustomEditorPrivate; CustomEditorPrivate *const d; Q_DISABLE_COPY(CustomEditor) }; public: /** * Enumeration of the buttons, the listbox offers. Specify them in the * constructor in the buttons parameter, or in setButtons. */ enum Button { Add = 0x0001, Remove = 0x0002, UpDown = 0x0004, All = Add | Remove | UpDown }; Q_DECLARE_FLAGS(Buttons, Button) /** * Create an editable listbox. */ - explicit KEditListBox(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KEditListBox(QWidget *parent = nullptr); /** * Create an editable listbox. * * The same as the other constructor, additionally it takes * @p title, which will be the title of the groupbox around the listbox. */ - explicit KEditListBox(const QString &title, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KEditListBox(const QString &title, QWidget *parent = nullptr); // ### KDE5: remove name arguments and simplify (merge?!) constructors /** * Create an editable listbox. * * \deprecated * * If @p checkAtEntering is true, after every character you type * in the line edit KEditListBox will enable or disable * the Add-button, depending whether the current content of the * line edit is already in the listbox. Maybe this can become a * performance hit with large lists on slow machines. * If @p checkAtEntering is false, * it will be checked if you press the Add-button. It is not * possible to enter items twice into the listbox. */ - explicit KDELIBS4SUPPORT_DEPRECATED KEditListBox(QWidget *parent, const char *name, + KDELIBS4SUPPORT_DEPRECATED explicit KDELIBS4SUPPORT_DEPRECATED KEditListBox(QWidget *parent, const char *name, bool checkAtEntering = false, Buttons buttons = All); /** * Create an editable listbox. * * \deprecated * * The same as the other constructor, additionally it takes * @p title, which will be the title of the frame around the listbox. */ - explicit KDELIBS4SUPPORT_DEPRECATED KEditListBox(const QString &title, QWidget *parent, + KDELIBS4SUPPORT_DEPRECATED explicit KDELIBS4SUPPORT_DEPRECATED KEditListBox(const QString &title, QWidget *parent, const char *name, bool checkAtEntering = false, Buttons buttons = All); /** * Another constructor, which allows to use a custom editing widget * instead of the standard KLineEdit widget. E.g. you can use a * KUrlRequester or a KComboBox as input widget. The custom * editor must consist of a lineedit and optionally another widget that * is used as representation. A KComboBox or a KUrlRequester have a * KLineEdit as child-widget for example, so the KComboBox is used as * the representation widget. * * @see KUrlRequester::customEditor(), setCustomEditor */ KEditListBox(const QString &title, const CustomEditor &customEditor, QWidget *parent = nullptr, const char *name = nullptr, bool checkAtEntering = false, Buttons buttons = All); virtual ~KEditListBox(); /** * Return a pointer to the embedded QListView. */ QListView *listView() const; /** * Return a pointer to the embedded KLineEdit. */ KLineEdit *lineEdit() const; /** * Return a pointer to the Add button */ QPushButton *addButton() const; /** * Return a pointer to the Remove button */ QPushButton *removeButton() const; /** * Return a pointer to the Up button */ QPushButton *upButton() const; /** * Return a pointer to the Down button */ QPushButton *downButton() const; /** * See Q3ListBox::count() */ int count() const; /** * See Q3ListBox::insertStringList() */ void insertStringList(const QStringList &list, int index = -1); /** * See Q3ListBox::insertItem() */ void insertItem(const QString &text, int index = -1); /** * Clears both the listbox and the line edit. */ void clear(); /** * See Q3ListBox::text() */ QString text(int index) const; /** * See Q3ListBox::currentItem() */ int currentItem() const; /** * See Q3ListBox::currentText() */ QString currentText() const; /** * @returns a stringlist of all items in the listbox */ QStringList items() const; /** * Clears the listbox and sets the contents to @p items */ void setItems(const QStringList &items); /** * Returns which buttons are visible */ Buttons buttons() const; /** * Specifies which buttons should be visible */ void setButtons(Buttons buttons); /** * If @p check is true, after every character you type * in the line edit KEditListBox will enable or disable * the Add-button, depending whether the current content of the * line edit is already in the listbox. Maybe this can become a * performance hit with large lists on slow machines. * If @p check is false, * it will be checked if you press the Add-button. It is not * possible to enter items twice into the listbox. * Default is false. */ void setCheckAtEntering(bool check); /** * Returns true if check at entering is enabled. */ bool checkAtEntering(); /** * Allows to use a custom editing widget * instead of the standard KLineEdit widget. E.g. you can use a * KUrlRequester or a KComboBox as input widget. The custom * editor must consist of a lineedit and optionally another widget that * is used as representation. A KComboBox or a KUrlRequester have a * KLineEdit as child-widget for example, so the KComboBox is used as * the representation widget. * * @since 4.1 */ void setCustomEditor(const CustomEditor &editor); /** * Reimplented for interal reasons. The API is not affected. */ bool eventFilter(QObject *o, QEvent *e) Q_DECL_OVERRIDE; Q_SIGNALS: void changed(); /** * This signal is emitted when the user adds a new string to the list, * the parameter is the added string. */ void added(const QString &text); /** * This signal is emitted when the user removes a string from the list, * the parameter is the removed string. */ void removed(const QString &text); protected Q_SLOTS: // KDE5: make private? void moveItemUp(); void moveItemDown(); void addItem(); void removeItem(); void enableMoveButtons(const QModelIndex &, const QModelIndex &); void typedSomething(const QString &text); private Q_SLOTS: void slotSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); private: friend class KEditListBoxPrivate; KEditListBoxPrivate *const d; Q_DISABLE_COPY(KEditListBox) }; Q_DECLARE_OPERATORS_FOR_FLAGS(KEditListBox::Buttons) #endif diff --git a/src/kdeui/kfontcombobox.cpp b/src/kdeui/kfontcombobox.cpp index 361479b4..3405dcac 100644 --- a/src/kdeui/kfontcombobox.cpp +++ b/src/kdeui/kfontcombobox.cpp @@ -1,407 +1,407 @@ /* This file is part of the KDE libraries Copyright (C) 2008 Chusslove Illich 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. */ #include "kfontcombobox.h" #include "fonthelpers_p.h" #include "kdebug.h" #include "klocalizedstring.h" #include "kcolorscheme.h" #include "kfontchooser.h" #include "kcompletion.h" #include #include #include #include #include #include #include #include #include #include static QString alphabetSample() { return i18nc("short", // i18n: A shorter version of the alphabet test phrase translated in // another message. It is displayed in the dropdown list of font previews // (the font selection combo box), so keep it under the length equivalent // to 60 or so proportional Latin characters. "The Quick Brown Fox Jumps Over The Lazy Dog"); } class KFontFamilyDelegate : public QAbstractItemDelegate { Q_OBJECT public: - explicit KFontFamilyDelegate(QObject *parent); + KDELIBS4SUPPORT_DEPRECATED explicit KFontFamilyDelegate(QObject *parent); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; QIcon truetype; QIcon bitmap; double sizeFactFamily; double sizeFactSample; QHash fontFamilyTrMap; }; KFontFamilyDelegate::KFontFamilyDelegate(QObject *parent) : QAbstractItemDelegate(parent) { truetype = QIcon(QLatin1String(":/trolltech/styles/commonstyle/images/fonttruetype-16.png")); bitmap = QIcon(QLatin1String(":/trolltech/styles/commonstyle/images/fontbitmap-16.png")); // Font size factors for family name and text sample in font previes, // multiplies normal font size. sizeFactFamily = 1.0; sizeFactSample = 1.0; // better leave at 1, so that user can relate sizes to default } void KFontFamilyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QBrush sampleBrush; if (option.state & QStyle::State_Selected) { painter->save(); painter->setBrush(option.palette.highlight()); painter->setPen(Qt::NoPen); painter->drawRect(option.rect); painter->setPen(QPen(option.palette.highlightedText(), 0)); sampleBrush = option.palette.highlightedText(); } else { sampleBrush = KColorScheme(QPalette::Normal).foreground(KColorScheme::InactiveText); } QFont baseFont = QFontDatabase::systemFont(QFontDatabase::GeneralFont); QString trFontFamily = index.data(Qt::DisplayRole).toString(); QString fontFamily = fontFamilyTrMap[trFontFamily]; // Writing systems provided by the font. QList availableSystems = QFontDatabase().writingSystems(fontFamily); // Intersect font's writing systems with that specified for // the language's sample text, to see if the sample can be shown. // If the font reports no writing systems, assume it can show the sample. bool canShowLanguageSample = true; if (availableSystems.count() > 0) { canShowLanguageSample = false; QString scriptsSpec = i18nc("Numeric IDs of scripts for font previews", // i18n: Integer which indicates the script you used in the sample text // for font previews in your language. For the possible values, see // https://doc.qt.io/qt-5/qfontdatabase.html#WritingSystem-enum // If the sample text contains several scripts, their IDs can be given // as a comma-separated list (e.g. for Japanese it is "1,27"). "1"); QStringList scriptStrIds = scriptsSpec.split(','); foreach (const QString &scriptStrId, scriptStrIds) { bool convOk; int ws = scriptStrId.toInt(&convOk); if (convOk && ws > 0 && ws < QFontDatabase::WritingSystemsCount && availableSystems.contains(static_cast(ws))) { canShowLanguageSample = true; break; } } } // Choose and paint an icon according to the font type, scalable or bitmat. const QIcon *icon = &bitmap; if (QFontDatabase().isSmoothlyScalable(fontFamily)) { icon = &truetype; } QRect r = option.rect; icon->paint(painter, r, Qt::AlignLeft | Qt::AlignTop); // Claim space taken up by the icon. QSize actualSize = icon->actualSize(r.size()); if (option.direction == Qt::RightToLeft) { r.setRight(r.right() - actualSize.width() - 4); } else { r.setLeft(r.left() + actualSize.width() + 4); } // Draw the font family. QFont oldPainterFont = painter->font(); QFont familyFont = baseFont; familyFont.setPointSizeF(familyFont.pointSizeF() * sizeFactFamily); painter->setFont(familyFont); painter->drawText(r, Qt::AlignTop | Qt::AlignLeading | Qt::TextSingleLine, trFontFamily); // Claim space taken up by the font family name. int h = painter->fontMetrics().lineSpacing(); r.setTop(r.top() + h); // Show text sample in user's language if the writing system is supported, // otherwise show a collage of generic script samples provided by Qt. // If the font does not report what it supports, assume all. QString sample; if (canShowLanguageSample) { sample = alphabetSample(); } else { foreach (const QFontDatabase::WritingSystem &ws, availableSystems) { sample += QFontDatabase::writingSystemSample(ws) + " "; if (sample.length() > 40) { // do not let the sample be too long break; } } sample = sample.trimmed(); } QFont sampleFont; sampleFont.setFamily(fontFamily); sampleFont.setPointSizeF(sampleFont.pointSizeF() * sizeFactSample); painter->setFont(sampleFont); QPen oldPen = painter->pen(); painter->setPen(sampleBrush.color()); painter->drawText(r, Qt::AlignTop | Qt::AlignLeading | Qt::TextSingleLine, sample); painter->setFont(oldPainterFont); painter->setPen(oldPen); if (option.state & QStyle::State_Selected) { painter->restore(); } } QSize KFontFamilyDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option); QFont baseFont = QFontDatabase::systemFont(QFontDatabase::GeneralFont); QString trFontFamily = index.data(Qt::DisplayRole).toString(); QString fontFamily = fontFamilyTrMap[trFontFamily]; QFont familyFont = baseFont; familyFont.setPointSizeF(familyFont.pointSizeF() * sizeFactFamily); QFontMetrics familyMetrics(familyFont); QFont sampleFont = baseFont; sampleFont.setFamily(fontFamily); sampleFont.setPointSizeF(sampleFont.pointSizeF() * sizeFactSample); QFontMetrics sampleMetrics(sampleFont); QString sample = alphabetSample(); // Only the hight matters here, the width is mandated by KFontComboBox::event() return QSize(qMax(familyMetrics.width(trFontFamily), sampleMetrics.width(sample)), qRound(familyMetrics.lineSpacing() + sampleMetrics.lineSpacing() * 1.2)); } class KFontComboBoxPrivate { public: KFontComboBoxPrivate(KFontComboBox *parent); void updateDatabase(); void updateIndexToFont(); void _k_currentFontChanged(int index); KFontComboBox *k; QFont currentFont; bool onlyFixed; bool signalsAllowed; KFontFamilyDelegate *delegate; QStringListModel *model; QStringList fontList; }; KFontComboBoxPrivate::KFontComboBoxPrivate(KFontComboBox *parent) : k(parent), currentFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont)), onlyFixed(false), signalsAllowed(true) { } void KFontComboBoxPrivate::updateDatabase() { QStringList fontFamilies = fontList; if (fontList.isEmpty()) { KFontChooser::getFontList(fontFamilies, onlyFixed ? KFontChooser::FixedWidthFonts : 0); } // Translate font families for the list model. delegate->fontFamilyTrMap.clear(); QStringList trFontFamilies = translateFontNameList(fontFamilies, &(delegate->fontFamilyTrMap)); // Add families to the list model and completion. model->setStringList(trFontFamilies); KCompletion *completion = k->completionObject(); if (completion) { completion->setItems(trFontFamilies); completion->setIgnoreCase(true); } } void KFontComboBoxPrivate::updateIndexToFont() { // QFontInfo necessary to return the family with proper casing. QString selectedFontFamily = QFontInfo(currentFont).family(); QString trSelectedFontFamily = translateFontName(selectedFontFamily); const QStringList trFontFamilies = model->stringList(); if (!trFontFamilies.count()) { return; } // Match the font's family with an item in the list. int index = 0; foreach (const QString &trFontFamily, trFontFamilies) { if (trSelectedFontFamily == trFontFamily) { break; } ++index; } if (index == trFontFamilies.count()) { // If no family matched, change font to first on the list. index = 0; currentFont = QFont(delegate->fontFamilyTrMap[trFontFamilies[0]]); emit k->currentFontChanged(currentFont); } // Set the new list item. signalsAllowed = false; k->setCurrentIndex(index); signalsAllowed = true; } void KFontComboBoxPrivate::_k_currentFontChanged(int index) { if (!signalsAllowed) { return; } QString trFontFamily = k->itemText(index); QString fontFamily = delegate->fontFamilyTrMap[trFontFamily]; if (!fontFamily.isEmpty()) { currentFont = QFont(fontFamily); emit k->currentFontChanged(currentFont); } else { // Unknown font family given. Just remove from the list. // This should not happen, as adding arbitrary font names is prevented. QStringList lst = model->stringList(); lst.removeAll(trFontFamily); model->setStringList(lst); } } KFontComboBox::KFontComboBox(QWidget *parent) : KComboBox(true, parent), d(new KFontComboBoxPrivate(this)) { // Inputing arbitrary font names does not make sense. setInsertPolicy(QComboBox::NoInsert); // Special list item painter showing font previews and its list model. d->delegate = new KFontFamilyDelegate(this); setItemDelegate(d->delegate); d->model = new QStringListModel(this); setModel(d->model); // Set current font when a new family has been chosen in the combo. connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(_k_currentFontChanged(int))); // Initialize font selection and list of available fonts. d->updateDatabase(); d->updateIndexToFont(); } KFontComboBox::~KFontComboBox() { delete d; } void KFontComboBox::setOnlyFixed(bool onlyFixed) { if (onlyFixed != d->onlyFixed) { d->onlyFixed = onlyFixed; d->updateDatabase(); } } void KFontComboBox::setFontList(const QStringList &fontList) { if (fontList != d->fontList) { d->fontList = fontList; d->updateDatabase(); } } QFont KFontComboBox::currentFont() const { return d->currentFont; } void KFontComboBox::setCurrentFont(const QFont &font) { if (font != d->currentFont) { d->currentFont = font; emit currentFontChanged(d->currentFont); d->updateIndexToFont(); } } bool KFontComboBox::event(QEvent *e) { if (e->type() == QEvent::Resize) { QListView *lview = qobject_cast(view()); if (lview) { QString sample = alphabetSample(); // Limit text sample length to avoid too wide list view. if (sample.length() > 60) { sample = sample.left(57) + "..."; } QFont approxFont = QFontDatabase::systemFont(QFontDatabase::GeneralFont); approxFont.setPointSizeF(approxFont.pointSizeF() * d->delegate->sizeFactSample); int widgetWidth = width(); int sampleWidth = QFontMetrics(approxFont).width(sample); sampleWidth = qRound(sampleWidth * 1.1); // extra for wider fonts int iconWidth = d->delegate->truetype.actualSize(size()).width(); int vsbarWidth = 0; if (lview->verticalScrollBar()) { vsbarWidth = lview->verticalScrollBar()->width(); } lview->window()->setFixedWidth(qMax(widgetWidth, sampleWidth) + iconWidth + vsbarWidth); } } return KComboBox::event(e); } QSize KFontComboBox::sizeHint() const { QSize sz = KComboBox::sizeHint(); QFontMetrics fm(QFontDatabase::systemFont(QFontDatabase::GeneralFont)); sz.setWidth(fm.width("m") * 14); return sz; } #include "fonthelpers.cpp" #include "kfontcombobox.moc" #include "moc_kfontcombobox.moc" diff --git a/src/kdeui/kfontcombobox.h b/src/kdeui/kfontcombobox.h index e0469413..a837d0c4 100644 --- a/src/kdeui/kfontcombobox.h +++ b/src/kdeui/kfontcombobox.h @@ -1,137 +1,137 @@ /* This file is part of the KDE libraries Copyright (C) 2008 Chusslove Illich 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 KFONTCOMBOBOX_P_H #define KFONTCOMBOBOX_P_H #include #include class KFontComboBoxPrivate; /** * @short A lightweight font selection widget. * * A combobox to select the font from. Lightweight counterpart to KFontChooser, * for situations where only the font family should be selected, while the * font style and size are handled by other means. Like in KFontChooser, * this widget will show the font previews in the unrolled dropdown list. * * @note The class is similar to QFontComboBox, but more tightly integrated * with KDE desktop. Use it instead of QFontComboBox by default in KDE code. * * \image html kfontcombobox.png "KDE Font Combo Box" * * @author Chusslove Illich \ * * @see KFontAction * @see KFontChooser * * @since 4.1 * * @deprecated Since KF 5.0, use QFontComboBox instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFontComboBox : public KComboBox { Q_OBJECT Q_PROPERTY(QFont currentFont READ currentFont WRITE setCurrentFont NOTIFY currentFontChanged USER true) public: /** * Constructor. * * @param parent the parent widget */ - explicit KFontComboBox(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KFontComboBox(QWidget *parent = nullptr); /** * Toggle selectable fonts to be only those of fixed width or all. * * @param onlyFixed only fixed width fonts when @p true, * all fonts when @p false * * @deprecated use QFontComboBox::setFontFilters(QFontComboBox::MonospacedFonts) */ void setOnlyFixed(bool onlyFixed); /** * Set selectable fonts to be only those present in the list. * * @param fontList a list of fonts as returned by QFontDatabase::families() or * QFontChooser::getFontList(). If this is empty (default), then the list * of fonts is constructed according to the @p onlyFixed setting. * @since 4.9.2 */ void setFontList(const QStringList &fontList); /** * Destructor. */ virtual ~KFontComboBox(); /** * The font currently selected from the list. * * @return the selected font */ QFont currentFont() const; /** * The recommended size of the widget. * Reimplemented to make the recommended width independent * of the particular fonts installed. * * @return recommended size */ QSize sizeHint() const Q_DECL_OVERRIDE; public Q_SLOTS: /** * Set the font to show as selected in the combobox. * * @param font the new font */ void setCurrentFont(const QFont &font); Q_SIGNALS: /** * Emitted when a new font has been selected, * either through user input or by setFont(). * * @param font the new font */ void currentFontChanged(const QFont &font); protected: bool event(QEvent *e) Q_DECL_OVERRIDE; private: friend class KFontComboBoxPrivate; KFontComboBoxPrivate *const d; Q_DISABLE_COPY(KFontComboBox) Q_PRIVATE_SLOT(d, void _k_currentFontChanged(int)) }; #endif diff --git a/src/kdeui/kfontdialog.h b/src/kdeui/kfontdialog.h index 20c18db9..8a55e15d 100644 --- a/src/kdeui/kfontdialog.h +++ b/src/kdeui/kfontdialog.h @@ -1,222 +1,222 @@ /* Requires the Qt widget libraries, available at no cost at http://www.troll.no Copyright (C) 1997 Bernd Johannes Wuebben Copyright (c) 1999 Preston Brown Copyright (c) 1999 Mario Weilguni 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 K_FONT_DIALOG_H #define K_FONT_DIALOG_H #include #include #include class QFont; class QStringList; /** * @short A font selection dialog. * * The KFontDialog provides a dialog for interactive font selection. * It is basically a thin wrapper around the KFontChooser widget, * which can also be used standalone. In most cases, the simplest * use of this class is the static method KFontDialog::getFont(), * which pops up the dialog, allows the user to select a font, and * returns when the dialog is closed. * * Example: * * \code * QFont myFont; * int result = KFontDialog::getFont( myFont ); * if ( result == KFontDialog::Accepted ) * ... * \endcode * * \image html kfontdialog.png "KDE Font Dialog" * * @author Preston Brown , Bernd Wuebben * * @deprecated since 5.0, use QFontDialog instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFontDialog : public KDialog { Q_OBJECT public: /** * Constructs a font selection dialog. * * @param parent The parent widget of the dialog, if any. * @param flags Defines how the font chooser is displayed. * @see KFontChooser::DisplayFlags * @param fontlist a list of fonts to display, in XLFD format. If * no list is formatted, the internal KDE font list is used. * If that has not been created, X is queried, and all fonts * available on the system are displayed. * @param sizeIsRelativeState If not zero the widget will show a * checkbox where the user may choose whether the font size * is to be interpreted as relative size. * Initial state of this checkbox will be set according to * *sizeIsRelativeState, user choice may be retrieved by * calling sizeIsRelative(). * */ - explicit KFontDialog(QWidget *parent = nullptr, + KDELIBS4SUPPORT_DEPRECATED explicit KFontDialog(QWidget *parent = nullptr, const KFontChooser::DisplayFlags &flags = KFontChooser::NoDisplayFlags, const QStringList &fontlist = QStringList(), Qt::CheckState *sizeIsRelativeState = nullptr); ~KFontDialog(); /** * Sets the currently selected font in the dialog. * * @param font The font to select. * @param onlyFixed readjust the font list to display only fixed * width fonts if true, or vice-versa */ void setFont(const QFont &font, bool onlyFixed = false); /** * @return The currently selected font in the dialog. */ QFont font() const; /** * Sets the state of the checkbox indicating whether the font size * is to be interpreted as relative size. * NOTE: If parameter sizeIsRelative was not set in the constructor * of the dialog this setting will be ignored. */ void setSizeIsRelative(Qt::CheckState relative); /** * @return Whether the font size is to be interpreted as relative size * (default: false) */ Qt::CheckState sizeIsRelative() const; /** * Creates a modal font dialog, lets the user choose a font, * and returns when the dialog is closed. * * @param theFont a reference to the font to write the chosen font * into. * @param flags Defines how the font chooser is displayed. * @see KFontChooser::DisplayFlags * @param parent Parent widget of the dialog. Specifying a widget different * from 0 (Null) improves centering (looks better). * @param makeFrame Draws a frame with titles around the contents. * @param sizeIsRelativeState If not zero the widget will show a * checkbox where the user may choose whether the font size * is to be interpreted as relative size. * Initial state of this checkbox will be set according to * *sizeIsRelativeState and user choice will be returned * therein. * * @return QDialog::result(). */ static int getFont(QFont &theFont, const KFontChooser::DisplayFlags &flags = KFontChooser::NoDisplayFlags, QWidget *parent = nullptr, Qt::CheckState *sizeIsRelativeState = nullptr); /** * Creates a modal font difference dialog, lets the user choose a selection * of changes that should be made to a set of fonts, and returns when the * dialog is closed. Useful for choosing slight adjustments to the font set * when the user would otherwise have to manually edit a number of fonts. * * @param theFont a reference to the font to write the chosen font * into. * @param flags Defines how the font chooser is displayed. * @see KFontChooser::DisplayFlags * @param diffFlags a reference to the int into which the chosen * difference selection bitmask should be written. * Check the returned bitmask like: * \code * if ( diffFlags & KFontChooser::FontDiffFamily ) * [...] * if ( diffFlags & KFontChooser::FontDiffStyle ) * [...] * if ( diffFlags & KFontChooser::FontDiffSize ) * [...] * \endcode * @param parent Parent widget of the dialog. Specifying a widget different * from 0 (Null) improves centering (looks better). * @param sizeIsRelativeState If not zero the widget will show a * checkbox where the user may choose whether the font size * is to be interpreted as relative size. * Initial state of this checkbox will be set according to * *sizeIsRelativeState and user choice will be returned * therein. * * @returns QDialog::result(). */ static int getFontDiff(QFont &theFont, KFontChooser::FontDiffFlags &diffFlags, const KFontChooser::DisplayFlags &flags = KFontChooser::NoDisplayFlags, QWidget *parent = nullptr, Qt::CheckState *sizeIsRelativeState = nullptr); /** * When you are not only interested in the font selected, but also * in the example string typed in, you can call this method. * * @param theFont a reference to the font to write the chosen font * into. * @param theString a reference to the example text that was typed. * @param flags Defines how the font chooser is displayed. * @see KFontChooser::DisplayFlags * @param parent Parent widget of the dialog. Specifying a widget different * from 0 (Null) improves centering (looks better). * @param sizeIsRelativeState If not zero the widget will show a * checkbox where the user may choose whether the font size * is to be interpreted as relative size. * Initial state of this checkbox will be set according to * *sizeIsRelativeState and user choice will be returned * therein. * @return The result of the dialog. */ static int getFontAndText(QFont &theFont, QString &theString, const KFontChooser::DisplayFlags &flags = KFontChooser::NoDisplayFlags, QWidget *parent = nullptr, Qt::CheckState *sizeIsRelativeState = nullptr); Q_SIGNALS: /** * Emitted whenever the currently selected font changes. * Connect to this to monitor the font as it is selected if you are * not running modal. */ void fontSelected(const QFont &font); private: class Private; Private *const d; Q_DISABLE_COPY(KFontDialog) }; #endif diff --git a/src/kdeui/kglobalsettings.h b/src/kdeui/kglobalsettings.h index a2726989..5ac64fb0 100644 --- a/src/kdeui/kglobalsettings.h +++ b/src/kdeui/kglobalsettings.h @@ -1,706 +1,706 @@ /* This file is part of the KDE libraries Copyright (C) 2000,2006 David Faure This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KGLOBALSETTINGS_H #define _KGLOBALSETTINGS_H #include #include #include #include #include #define KDE_DEFAULT_SINGLECLICK true #define KDE_DEFAULT_INSERTTEAROFFHANDLES 0 #define KDE_DEFAULT_AUTOSELECTDELAY -1 #define KDE_DEFAULT_CHANGECURSOR true #define KDE_DEFAULT_LARGE_CURSOR false #define KDE_DEFAULT_WHEEL_ZOOM false #define KDE_DEFAULT_ICON_ON_PUSHBUTTON true #define KDE_DEFAULT_OPAQUE_RESIZE true #define KDE_DEFAULT_BUTTON_LAYOUT 0 #define KDE_DEFAULT_SHADE_SORT_COLUMN true #define KDE_DEFAULT_ALLOW_DEFAULT_BACKGROUND_IMAGES true #define KDE_DEFAULT_NATURAL_SORTING true class QColor; class QFont; class QPoint; class QRect; class QWidget; /** * Access the KDE global configuration. * * @author David Faure \ */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KGlobalSettings : public QObject { Q_OBJECT public: ~KGlobalSettings(); /** * Returns a threshold in pixels for drag & drop operations. * As long as the mouse movement has not exceeded this number * of pixels in either X or Y direction no drag operation may * be started. This prevents spurious drags when the user intended * to click on something but moved the mouse a bit while doing so. * * For this to work you must save the position of the mouse (oldPos) * in the QWidget::mousePressEvent(). * When the position of the mouse (newPos) * in a QWidget::mouseMoveEvent() exceeds this threshold * you may start a drag * which should originate from oldPos. * * Example code: * \code * void KColorCells::mousePressEvent( QMouseEvent *e ) * { * mOldPos = e->pos(); * } * * void KColorCells::mouseMoveEvent( QMouseEvent *e ) * { * if( !(e->state() && LeftButton)) return; * * int delay = QApplication::startDragDistance(); * QPoint newPos = e->pos(); * if(newPos.x() > mOldPos.x()+delay || newPos.x() < mOldPos.x()-delay || * newPos.y() > mOldPos.y()+delay || newPos.y() < mOldPos.y()-delay) * { * // Drag color object * int cell = posToCell(mOldPos); // Find color at mOldPos * if ((cell != -1) && colors[cell].isValid()) * { * KColorDrag *d = KColorDrag::makeDrag( colors[cell], this); * d->dragCopy(); * } * } * } * \endcode * @return the threshold for drag & drop in pixels * @deprecated since 5.0, use QApplication::startDragDistance() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED static KDELIBS4SUPPORT_DEPRECATED int dndEventDelay(); #endif /** * Returns whether KDE runs in single (default) or double click * mode. * see http://developer.kde.org/documentation/standards/kde/style/mouse/index.html * @return true if single click mode, or false if double click mode. * @deprecated since 5.0, use style->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, 0, widget) **/ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED static KDELIBS4SUPPORT_DEPRECATED bool singleClick(); #endif /** * Checks whether the cursor changes over icons. * @return the KDE setting for "change cursor over icon" */ static bool changeCursorOverIcon(); /** * Returns the KDE setting for the auto-select option. * * @return the auto-select delay or -1 if auto-select is disabled. */ static int autoSelectDelay(); /** * Returns the KDE setting for context menus. * * @return whether context menus should be shown on button press * or button release (click). */ static bool showContextMenusOnPress(); /** * This enum describes the completion mode used for by the KCompletion class. * See * the styleguide. * * @deprecated Use KCompletion **/ enum Completion { /** * No completion is used. */ CompletionNone = 1, /** * Text is automatically filled in whenever possible. */ CompletionAuto, /** * Same as automatic except shortest match is used for completion. */ CompletionMan, /** * Complete text much in the same way as a typical *nix shell would. */ CompletionShell, /** * Lists all possible matches in a popup list-box to choose from. */ CompletionPopup, /** * Lists all possible matches in a popup list-box to choose from, and automatically * fill the result whenever possible. */ CompletionPopupAuto }; /** * Returns the preferred completion mode setting. * * @return Completion. Default is @p CompletionPopup. */ static Completion completionMode(); /** * Describes the mouse settings. */ struct KMouseSettings { enum { RightHanded = 0, LeftHanded = 1 }; int handed; // left or right }; /** * This returns the current mouse settings. * On Windows, settings are retrieved from the system. * @return the current mouse settings */ static KMouseSettings &mouseSettings(); /** * The path to the desktop directory of the current user. * @return the user's desktop directory * @deprecated since 5.0, use QStandardPaths::writableLocation(QStandardPaths::DesktopLocation). */ static KDELIBS4SUPPORT_DEPRECATED QString desktopPath(); /** * The path to the autostart directory of the current user. * @return the path of the autostart directory */ //static QString autostartPath(); // Removed in KDE5, use XDG autostart paths /** * The path where documents are stored of the current user. * @return the path of the document directory * @deprecated since 5.0, use QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation). */ static KDELIBS4SUPPORT_DEPRECATED QString documentPath(); /** * The path where music are stored of the current user. * @return the path of the music directory * @deprecated since 5.0, use QStandardPaths::writableLocation(QStandardPaths::MusicLocation). */ static KDELIBS4SUPPORT_DEPRECATED QString musicPath(); /** * The path where videos are stored of the current user. * @return the path of the video directory * @deprecated since 5.0, use QStandardPaths::writableLocation(QStandardPaths::MoviesLocation). */ static KDELIBS4SUPPORT_DEPRECATED QString videosPath(); /** * The path where download are stored of the current user. * @return the path of the download directory * @deprecated since 5.0, use QStandardPaths::writableLocation(QStandardPaths::DownloadLocation). */ static KDELIBS4SUPPORT_DEPRECATED QString downloadPath(); /** * The path where pictures are stored of the current user. * @return the path of the pictures directory * @deprecated since 5.0, use QStandardPaths::writableLocation(QStandardPaths::PicturesLocation). */ static KDELIBS4SUPPORT_DEPRECATED QString picturesPath(); /** * The default color to use for inactive titles. * @return the inactive title color * @deprecated since 5.0, This used to export the color of the titlebar. * If you wanted to query the color of the inactive window background, use * KColorScheme(QPalette::Inactive, KColorScheme::Window).background().color(), * otherwise please read the setting from kdeglobals/WM/inactiveBackground directly */ static KDELIBS4SUPPORT_DEPRECATED QColor inactiveTitleColor(); /** * The default color to use for inactive texts. * @return the inactive text color * @deprecated since 5.0, This used to export the color of the titlebar. * If you wanted to query the color of the inactive window foreground, use * KColorScheme(QPalette::Inactive, KColorScheme::Window).foreground().color() * otherwise please read the setting from kdeglobals/WM/inactiveForeground directly */ static KDELIBS4SUPPORT_DEPRECATED QColor inactiveTextColor(); /** * The default color to use for active titles. * @return the active title color * @deprecated since 5.0, This used to export the color of the titlebar. * If you wanted to query the color of the active window background, use * KColorScheme(QPalette::Active, KColorScheme::Window).background(KColorScheme::ActiveBackground).color(), * otherwise please read the setting from kdeglobals/WM/activeBackground directly */ static KDELIBS4SUPPORT_DEPRECATED QColor activeTitleColor(); /** * The default color to use for active texts. * @return the active text color * @deprecated since 5.0, This used to export the color of the titlebar. * If you wanted to query the color of the active window foreground, use * KColorScheme(QPalette::Active, KColorScheme::Window).foreground(KColorScheme::ActiveText).color(), * otherwise please read the setting from kdeglobals/WM/activeForeground directly */ static KDELIBS4SUPPORT_DEPRECATED QColor activeTextColor(); /** * Returns the contrast for borders. * @return the contrast (between 0 for minimum and 10 for maximum * contrast) * @deprecated since 5.0, use KColorScheme::contrast() */ static KDELIBS4SUPPORT_DEPRECATED int contrast(); /** * Returns the contrast for borders as a floating point value. * @param config pointer to the config from which to read the contrast * setting (the default is to use KSharedConfig::openConfig()) * @return the contrast (between 0.0 for minimum and 1.0 for maximum * contrast) * @deprecated since 5.0, use KColorScheme::contrastF(config) */ static KDELIBS4SUPPORT_DEPRECATED qreal contrastF(const KSharedConfigPtr &config = KSharedConfigPtr()); /** * Returns if the sorted column in a K3ListView shall be drawn with a * shaded background color. * @return true if the sorted column shall be shaded */ static bool shadeSortColumn(); /** * Returns if default background images are allowed by the color scheme. * A "default" background image is just that, i.e. the user has not * actively selected a background image to use. * @return true if default background images may be used */ static bool allowDefaultBackgroundImages(); /** * Returns the default general font. * @return the default general font. */ static QFont generalFont(); /** * Returns the default fixed font. * @return the default fixed font. * @deprecated since 5.0, use QFontDatabase::systemFont(QFontDatabase::FixedFont) */ static KDELIBS4SUPPORT_DEPRECATED QFont fixedFont(); /** * Returns the default toolbar font. * @return the default toolbar font. */ static QFont toolBarFont(); /** * Returns the default menu font. * @return the default menu font. */ static QFont menuFont(); /** * Returns the default window title font. * @return the default window title font. */ static QFont windowTitleFont(); /** * Returns the default taskbar font. * @return the default taskbar font. */ static QFont taskbarFont(); /** * Returns a font of approx. 48 pt. capable of showing @p text. * @param text the text to test * @return the font that is capable to show the text with 48 pt */ static QFont largeFont(const QString &text = QString()); /** * Returns the smallest readable font. This can be used in dockers, * rulers and other places where space is at a premium. */ static QFont smallestReadableFont(); /** * Returns if the user specified multihead. In case the display * has multiple screens, the return value of this function specifies * if the user wants KDE to run on all of them or just on the primary * On Windows, settings are retrieved from the system. * @return true if the user chose multi head */ static bool isMultiHead(); /** * Typically, QScrollView derived classes can be scrolled fast by * holding down the Ctrl-button during wheel-scrolling. * But QTextEdit and derived classes perform zooming instead of fast * scrolling. * * This value determines whether the user wants to zoom or scroll fast * with Ctrl-wheelscroll. * @return true if the user wishes to zoom with the mouse wheel, * false for scrolling */ static bool wheelMouseZooms(); /** * This function returns the desktop geometry for an application's splash * screen. It takes into account the user's display settings (number of * screens, Xinerama, etc), and the user's preferences (if KDE should be * Xinerama aware). * * @return the geometry to use for the desktop. Note that it might not * start at (0,0). * @deprecated use QApplication::desktop()->screenGeometry(QCursor::pos()) */ static KDELIBS4SUPPORT_DEPRECATED QRect splashScreenDesktopGeometry(); /** * This function returns the desktop geometry for an application that needs * to set the geometry of a widget on the screen manually. It takes into * account the user's display settings (number of screens, Xinerama, etc), * and the user's preferences (if KDE should be Xinerama aware). * * Note that this can break in multi-head (not Xinerama) mode because this * point could be on multiple screens. Use with care. * * @param point a reference point for the widget, for instance one that the * widget should be adjacent or on top of. * * @return the geometry to use for the desktop. Note that it might not * start at (0,0). * @deprecated use QApplication::desktop()->screenGeometry(point) */ static KDELIBS4SUPPORT_DEPRECATED QRect desktopGeometry(const QPoint &point); /** * This function returns the desktop geometry for an application that needs * to set the geometry of a widget on the screen manually. It takes into * account the user's display settings (number of screens, Xinerama, etc), * and the user's preferences (if KDE should be Xinerama aware). * * @param w the widget in question. This is used to determine which screen * to use in Xinerama or multi-head mode. * * @return the geometry to use for the desktop. Note that it might not * start at (0,0). * @deprecated use QApplication::desktop()->screenGeometry(w) */ static KDELIBS4SUPPORT_DEPRECATED QRect desktopGeometry(const QWidget *w); /** * This function determines if the user wishes to see icons on the * push buttons. * * @return Returns true if user wants to show icons. * @deprecated since 5.0, use style->styleHint(QStyle::SH_DialogButtonBox_ButtonsHaveIcons, 0, widget); */ static KDELIBS4SUPPORT_DEPRECATED bool showIconsOnPushButtons(); /** * Returns true, if user visible strings should be sorted in a natural way: * image 1.jpg * image 2.jpg * image 10.jpg * image 11.jpg * If false is returned, the strings are sorted by their unicode values: * image 1.jpg * image 10.jpg * image 11.jpg * image 2.jpg * * @since 4.4 */ static bool naturalSorting(); enum GraphicEffect { NoEffects = 0x0000, ///< GUI with no effects at all. GradientEffects = 0x0001, ///< GUI with only gradients enabled. SimpleAnimationEffects = 0x0002, ///< GUI with simple animations enabled. ComplexAnimationEffects = 0x0006 ///< GUI with complex animations enabled. ///< Note that ComplexAnimationsEffects implies SimpleAnimationEffects. }; Q_DECLARE_FLAGS(GraphicEffects, GraphicEffect) /** * This function determines the desired level of effects on the GUI. * * @since 4.1 */ static GraphicEffects graphicEffectsLevel(); /** * This function determines the default level of effects on the GUI * depending on the system capabilities. * * @since 4.1 */ static GraphicEffects graphicEffectsLevelDefault(); /** * This function determines if the user wishes to see previews * for the selected url * * @return Returns true if user wants to show previews. * @deprecated since 5.0, use KProtocolInfo::showFilePreview */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED static KDELIBS4SUPPORT_DEPRECATED bool showFilePreview(const QUrl &); #endif /** * Whether the user wishes to use opaque resizing. Primarily * intended for QSplitter::setOpaqueResize() * * @return Returns true if user wants to use opaque resizing. */ static bool opaqueResize(); /** * The layout scheme to use for dialog buttons * * @return Returns the number of the scheme to use. */ static int buttonLayout(); /** * Used to obtain the QPalette that will be used to set the application palette. * * This is only useful for configuration modules such as krdb and should not be * used in normal circumstances. * @param config KConfig from which to load the colors (passed as-is to * ::KColorScheme). * * @return the QPalette * * @deprecated since 5.0, use KColorScheme::createApplicationPalette() */ static KDELIBS4SUPPORT_DEPRECATED QPalette createApplicationPalette(const KSharedConfigPtr &config = KSharedConfigPtr()); /** * Used to obtain the QPalette that will be used to set the application palette. * * This is only useful for configuration modules such as krdb and should not be * used in normal circumstances. * @param config KConfig from which to load the colors (passed as-is to * ::KColorScheme). * * @note The difference between this and the previous is that this never caches. * @since 4.6.3 * * @return the QPalette * * @deprecated since 5.0, use KColorScheme::createApplicationPalette() */ static KDELIBS4SUPPORT_DEPRECATED QPalette createNewApplicationPalette(const KSharedConfigPtr &config = KSharedConfigPtr()); /** * An identifier for change signals. * \see emitChange */ enum ChangeType { PaletteChanged = 0, FontChanged, StyleChanged, SettingsChanged, IconChanged, CursorChanged, ToolbarStyleChanged, BlockShortcuts, NaturalSortingChanged }; /** * Notifies all KDE applications on the current display of a change. * * This is typically called by kcontrol modules after changing the corresponding * config file. Do not call this from a normal KDE application. * * @deprecated since 5.0 : * @li emitChange(ToolbarStyleChanged) is now KToolBar::emitToolbarStyleChanged() * @li emitChange(IconChanged, group) is now KIconLoader::emitChange(group) * TODO: complete this list */ static KDELIBS4SUPPORT_DEPRECATED void emitChange(ChangeType changeType, int arg = 0); /** * Return the KGlobalSettings singleton. * This is used to connect to its signals, to be notified of changes. */ static KGlobalSettings *self(); /** * Specifies options passed to activate(). * * @since 4.6 */ enum ActivateOption { ApplySettings = 0x1, ///< Make all globally applicable settings take effect. ListenForChanges = 0x2 ///< Listen for changes to the settings. }; Q_DECLARE_FLAGS(ActivateOptions, ActivateOption) /** * Makes all globally applicable settings take effect * and starts listening for changes to these settings. * * This is usually called only by the KApplication constructor. * * @since 4.3.3 */ void activate(); //KDE5: Merge with the overloaded method below /** * @overload * * @since 4.6 */ void activate(ActivateOptions options); /** * Valid values for the settingsChanged signal */ enum SettingsCategory { SETTINGS_MOUSE, SETTINGS_COMPLETION, SETTINGS_PATHS, SETTINGS_POPUPMENU, SETTINGS_QT, SETTINGS_SHORTCUTS, SETTINGS_LOCALE, SETTINGS_STYLE }; Q_SIGNALS: /** * Emitted when the application has changed its palette due to a KControl request. * * Normally, widgets will update their palette automatically, but you * should connect to this to program special behavior. * * Note: If you derive from a QWidget-based class, a faster method is to * reimplement QWidget::changeEvent() and catch QEvent::PaletteChange. * This is the preferred way to get informed about palette updates. */ void kdisplayPaletteChanged(); /** * Emitted when the application has changed its GUI style in response to a KControl request. * * Normally, widgets will update their styles automatically (as they would - * respond to an explicit setGUIStyle() call), but you should connect to + * respond to an KDELIBS4SUPPORT_DEPRECATED explicit setGUIStyle() call), but you should connect to * this to program special behavior. * * Note: If you derive from a QWidget-based class, a faster method is to * reimplement QWidget::changeEvent() and catch QEvent::StyleChange. * This is the preferred way to get informed about style updates. */ void kdisplayStyleChanged(); /** * Emitted when the application has changed its font in response to a KControl request. * * Normally widgets will update their fonts automatically, but you should * connect to this to monitor global font changes, especially if you are - * using explicit fonts. + * using KDELIBS4SUPPORT_DEPRECATED explicit fonts. * * Note: If you derive from a QWidget-based class, a faster method is to * reimplement QWidget::changeEvent() and catch QEvent::FontChange. * This is the preferred way to get informed about font updates. */ void kdisplayFontChanged(); /** * Emitted when the application has changed either its GUI style, its font or its palette * in response to a kdisplay request. Normally, widgets will update their styles * automatically, but you should connect to this to program special * behavior. */ void appearanceChanged(); /** * Emitted when the settings for toolbars have been changed. KToolBar will know what to do. */ void toolbarAppearanceChanged(int); /** * Emitted when the global settings have been changed. * KGlobalSettings takes care of calling reparseConfiguration on KSharedConfig::openConfig() * so that applications/classes using this only have to re-read the configuration * @param category the category among the SettingsCategory enum. */ void settingsChanged(int category); /** * Emitted when the global icon settings have been changed. * @param group the new group * * @deprecated since 5.0, use KIconLoader::iconChanged(int) */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void iconChanged(int group); #endif /** * Emitted when the cursor theme has been changed. */ void cursorChanged(); /** * Emitted by BlockShortcuts */ void blockShortcuts(int data); /** * Emitted when the natural sorting has been changed. * @since 4.4 */ void naturalSortingChanged(); private: friend class KApplication; friend class KGlobalSettingsSingleton; KGlobalSettings(); class Private; Private *const d; Q_PRIVATE_SLOT(d, void _k_slotNotifyChange(int, int)) Q_PRIVATE_SLOT(d, void _k_slotIconChange(int)) }; Q_DECLARE_OPERATORS_FOR_FLAGS(KGlobalSettings::GraphicEffects) Q_DECLARE_OPERATORS_FOR_FLAGS(KGlobalSettings::ActivateOptions) #endif diff --git a/src/kdeui/khbox.h b/src/kdeui/khbox.h index d8468e73..7200f261 100644 --- a/src/kdeui/khbox.h +++ b/src/kdeui/khbox.h @@ -1,98 +1,98 @@ /* This file is part of the KDE libraries Copyright (C) 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 KHBOX_H #define KHBOX_H #include #include class QChildEvent; /** * A container widget which arranges its children horizontally. * When using a KHBox you don't need to create a layout nor * to add the child widgets to it. * * Both margin and spacing are initialized to 0. Use QHBoxLayout * if you need standard layout margins. * * \image html khbox.png "KDE Horizontal Box containing three buttons" * * @see KVBox */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KHBox : public QFrame { Q_OBJECT public: /** * Creates a new hbox. */ - explicit KHBox(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KHBox(QWidget *parent = nullptr); /** * Destructor. */ ~KHBox(); /** * Sets the @p margin of the hbox. */ void setMargin(int margin); /** * Sets the spacing between the child widgets to @p space. * * To get the default layout spacing, set @p space to -1. */ void setSpacing(int space); /** * Sets the stretch factor of @p widget to @p stretch. */ void setStretchFactor(QWidget *widget, int stretch); /** * Calculate the recommended size for this hbox. */ QSize sizeHint() const Q_DECL_OVERRIDE; /** * Calculate the recommended minimum size for this hbox. */ QSize minimumSizeHint() const Q_DECL_OVERRIDE; protected: /* * @internal */ KHBox(bool vertical, QWidget *parent); void childEvent(QChildEvent *ev) Q_DECL_OVERRIDE; private: class Private; friend class Private; Private *const d; Q_DISABLE_COPY(KHBox) }; #endif diff --git a/src/kdeui/khuesaturationselect.h b/src/kdeui/khuesaturationselect.h index a4d1c299..b9c85695 100644 --- a/src/kdeui/khuesaturationselect.h +++ b/src/kdeui/khuesaturationselect.h @@ -1,128 +1,128 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Martin Jones (mjones@kde.org) 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 KHUESATURATIONSELECT_H_ #define KHUESATURATIONSELECT_H_ #include #include "kxyselector.h" #include "kcolorchoosermode.h" class KDELIBS4SUPPORT_DEPRECATED_EXPORT KHueSaturationSelector : public KXYSelector { Q_OBJECT public: /** * Constructs a hue/saturation selection widget. */ - explicit KHueSaturationSelector(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KHueSaturationSelector(QWidget *parent = nullptr); /** * Destructor. */ ~KHueSaturationSelector(); /** * Sets the chooser mode. The allowed modes are defined * in KColorChooserMode. * * @param The chooser mode as defined in KColorChooserMode */ void setChooserMode(KColorChooserMode chooserMode); /** * Returns the chooser mode. * * @return The chooser mode (defined in KColorChooserMode) */ KColorChooserMode chooserMode() const; /** * Returns the hue value * * @return The hue value (0-360) */ int hue() const; /** * Sets the hue value (0-360) * * @param hue The hue value (0-360) */ void setHue(int hue); /** * Returns the saturation (0-255) * * @return The saturation (0-255) */ int saturation() const; /** * Sets the saturation (0-255) * * @param saturation The saturation (0-255) */ void setSaturation(int saturation); /** * Returns the color value (also known as lumniousity, 0-255) * * @return The color value (0-255) */ int colorValue() const; /** * Sets the color value (0-255) * * @param colorValue The color value (0-255) */ void setColorValue(int colorValue); /** * Updates the contents */ void updateContents(); protected: /** * Draws the contents of the widget on a pixmap, * which is used for buffering. */ virtual void drawPalette(QPixmap *pixmap); void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; /** * Reimplemented from KXYSelector. This drawing is * buffered in a pixmap here. As real drawing * routine, drawPalette() is used. */ void drawContents(QPainter *painter) Q_DECL_OVERRIDE; private: class Private; friend class Private; Private *const d; Q_DISABLE_COPY(KHueSaturationSelector) }; #endif /*KHUESATURATIONSELECT_H_*/ diff --git a/src/kdeui/kicon.h b/src/kdeui/kicon.h index b9ef5253..d980a570 100644 --- a/src/kdeui/kicon.h +++ b/src/kdeui/kicon.h @@ -1,96 +1,96 @@ /* This file is part of the KDE libraries Copyright (C) 2006 Hamish Rodda 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 KICON_H #define KICON_H #include #ifdef KDELIBS4SUPPORT_NO_DEPRECATED_NOISE #warning "This file is deprecated." #endif #include class KIconLoader; class QStringList; /** * \short A wrapper around QIcon that provides KDE icon features * * KIcon is a convenience class for creating a QIcon with an appropriate * KIconEngine to perform loading and rendering. KIcons thus adhere to * KDE style and effect standards. * * \sa KIconEngine, KIconLoader, KIconTheme * * \author Hamish Rodda * * @deprecated use QIcon::fromTheme */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KIcon : public QIcon { public: /** * Constructor which takes a kde style icon name, and optionally * a custom icon loader. * * \param iconName The name of the kde icon to load * \param iconLoader The icon loader to use in loading this icon, or * null to use the default global icon loader. * @param overlays A list of overlays to apply to this icon. They are * loaded from the emblems icons and up to four (one per * corner) is currently supported */ - explicit KIcon(const QString &iconName, KIconLoader *iconLoader, + KDELIBS4SUPPORT_DEPRECATED explicit KIcon(const QString &iconName, KIconLoader *iconLoader, const QStringList &overlays); /** * \overload */ - explicit KIcon(const QString &iconName, KIconLoader *iconLoader); + KDELIBS4SUPPORT_DEPRECATED explicit KIcon(const QString &iconName, KIconLoader *iconLoader); /** * \overload */ - explicit KIcon(const QString &iconName); + KDELIBS4SUPPORT_DEPRECATED explicit KIcon(const QString &iconName); /** * Copy constructor which takes any QIcon. * * \param copy the icon to copy. This should have once been a KIcon, * if you want to preserve KDE icon effects. */ - explicit KIcon(const QIcon ©); + KDELIBS4SUPPORT_DEPRECATED explicit KIcon(const QIcon ©); /** * Constructor for a null icon. */ KIcon(); /** * Destroys the icon. */ ~KIcon(); private: class Private; Private *const d; }; #endif diff --git a/src/kdeui/kinputdialog.cpp b/src/kdeui/kinputdialog.cpp index 4dc36421..b49d32ba 100644 --- a/src/kdeui/kinputdialog.cpp +++ b/src/kdeui/kinputdialog.cpp @@ -1,532 +1,532 @@ /* Copyright (C) 2003 Nadeem Hasan 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. */ #include "kinputdialog.h" #include "kinputdialog_p.h" #include #include #include #include #include #include #include #include #include #include #include #include #include KInputDialogHelper::KInputDialogHelper(const QString &caption, const QString &label, const QString &value, QWidget *parent, QValidator *validator, const QString &mask) : QDialog(parent), m_label(nullptr), m_lineEdit(nullptr), m_intSpinBox(nullptr), m_doubleSpinBox(nullptr), m_comboBox(nullptr), m_listBox(nullptr), m_buttonBox(nullptr) { setWindowTitle(caption); setModal(true); QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); m_label = new QLabel(label, this); m_label->setWordWrap(true); layout->addWidget(m_label); m_lineEdit = new KLineEdit(value, this); m_lineEdit->setClearButtonShown(true); layout->addWidget(m_lineEdit); m_lineEdit->setFocus(); m_label->setBuddy(m_lineEdit); layout->addStretch(); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(m_buttonBox); if (validator) { m_lineEdit->setValidator(validator); } if (!mask.isEmpty()) { m_lineEdit->setInputMask(mask); } connect(m_lineEdit, SIGNAL(textChanged(QString)), SLOT(slotEditTextChanged(QString))); slotEditTextChanged(value); setMinimumWidth(350); } KInputDialogHelper::KInputDialogHelper(const QString &caption, const QString &label, const QString &value, QWidget *parent) : QDialog(parent), m_label(nullptr), m_lineEdit(nullptr), m_intSpinBox(nullptr), m_doubleSpinBox(nullptr), m_comboBox(nullptr), m_buttonBox(nullptr) { setWindowTitle(caption); setModal(true); QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); m_label = new QLabel(label, this); m_label->setWordWrap(true); layout->addWidget(m_label); m_textEdit = new KTextEdit(this); m_textEdit->insertPlainText(value); layout->addWidget(m_textEdit, 10); m_textEdit->setFocus(); m_label->setBuddy(m_textEdit); m_buttonBox = new QDialogButtonBox(this); QPushButton *clearButton = new QPushButton(m_buttonBox); KGuiItem::assign(clearButton, KStandardGuiItem::clear()); m_buttonBox->addButton(clearButton, QDialogButtonBox::ActionRole); m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(m_buttonBox); connect(clearButton, SIGNAL(clicked()), m_textEdit, SLOT(clear())); connect(clearButton, SIGNAL(clicked()), m_textEdit, SLOT(setFocus())); setMinimumWidth(400); } KInputDialogHelper::KInputDialogHelper(const QString &caption, const QString &label, int value, int minValue, int maxValue, int step, int base, QWidget *parent) : QDialog(parent), m_label(nullptr), m_lineEdit(nullptr), m_intSpinBox(nullptr), m_doubleSpinBox(nullptr), m_comboBox(nullptr), m_listBox(nullptr), m_buttonBox(nullptr) { setWindowTitle(caption); setModal(true); QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); m_label = new QLabel(label, this); m_label->setWordWrap(true); layout->addWidget(m_label); m_intSpinBox = new QSpinBox(this); m_intSpinBox->setMinimum(minValue); m_intSpinBox->setMaximum(maxValue); m_intSpinBox->setSingleStep(step); m_intSpinBox->setValue(value); m_intSpinBox->setDisplayIntegerBase(base); layout->addWidget(m_intSpinBox); layout->addStretch(); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(m_buttonBox); m_intSpinBox->setFocus(); setMinimumWidth(300); } KInputDialogHelper::KInputDialogHelper(const QString &caption, const QString &label, double value, double minValue, double maxValue, double step, int decimals, QWidget *parent) : QDialog(parent), m_label(nullptr), m_lineEdit(nullptr), m_intSpinBox(nullptr), m_doubleSpinBox(nullptr), m_comboBox(nullptr), m_listBox(nullptr), m_buttonBox(nullptr) { setWindowTitle(caption); setModal(true); QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); m_label = new QLabel(label, this); m_label->setWordWrap(true); layout->addWidget(m_label); m_doubleSpinBox = new QDoubleSpinBox(this); m_doubleSpinBox->setRange(minValue, maxValue); m_doubleSpinBox->setSingleStep(step); m_doubleSpinBox->setValue(value); m_doubleSpinBox->setDecimals(decimals); layout->addWidget(m_doubleSpinBox); layout->addStretch(); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(m_buttonBox); m_doubleSpinBox->setFocus(); setMinimumWidth(300); } KInputDialogHelper::KInputDialogHelper(const QString &caption, const QString &label, const QStringList &list, int current, bool editable, QWidget *parent) : QDialog(parent), m_label(nullptr), m_lineEdit(nullptr), m_intSpinBox(nullptr), m_doubleSpinBox(nullptr), m_comboBox(nullptr), m_listBox(nullptr), m_buttonBox(nullptr) { setWindowTitle(caption); setModal(true); QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); m_label = new QLabel(label, this); m_label->setWordWrap(true); layout->addWidget(m_label); if (editable) { m_comboBox = new KComboBox(editable, this); m_lineEdit = new KLineEdit(this); m_lineEdit->setClearButtonShown(true); m_comboBox->setLineEdit(m_lineEdit); m_comboBox->insertItems(0, list); m_comboBox->setCurrentIndex(current); layout->addWidget(m_comboBox); connect(m_comboBox, SIGNAL(editTextChanged(QString)), SLOT(slotUpdateButtons(QString))); m_comboBox->setFocus(); } else { m_listBox = new QListWidget(this); m_listBox->addItems(list); m_listBox->setCurrentRow(current); layout->addWidget(m_listBox, 10); connect(m_listBox, SIGNAL(itemActivated(QListWidgetItem*)), SLOT(accept())); m_listBox->setFocus(); } layout->addStretch(); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(m_buttonBox); if (editable) { slotUpdateButtons(m_comboBox->currentText()); } setMinimumWidth(320); } KInputDialogHelper::KInputDialogHelper(const QString &caption, const QString &label, const QStringList &list, const QStringList &select, bool multiple, QWidget *parent) : QDialog(parent), m_label(nullptr), m_lineEdit(nullptr), m_intSpinBox(nullptr), m_doubleSpinBox(nullptr), m_comboBox(nullptr), m_listBox(nullptr), m_buttonBox(nullptr) { setWindowTitle(caption); setModal(true); QVBoxLayout *layout = new QVBoxLayout; setLayout(layout); m_label = new QLabel(label, this); m_label->setWordWrap(true); layout->addWidget(m_label); m_listBox = new QListWidget(this); m_listBox->addItems(list); layout->addWidget(m_listBox); if (multiple) { m_listBox->setSelectionMode(QAbstractItemView::ExtendedSelection); for (QStringList::ConstIterator it = select.begin(); it != select.end(); ++it) { const QList matches = m_listBox->findItems(*it, Qt::MatchCaseSensitive | Qt::MatchExactly); if (!matches.isEmpty()) { m_listBox->setCurrentItem(matches.first()); } } } else { connect(m_listBox, SIGNAL(itemActivated(QListWidgetItem*)), SLOT(accept())); if (!select.isEmpty()) { QString text = select.first(); const QList matches = m_listBox->findItems(text, Qt::MatchCaseSensitive | Qt::MatchExactly); if (!matches.isEmpty()) { m_listBox->setCurrentItem(matches.first()); } } } m_listBox->setFocus(); layout->addStretch(); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); layout->addWidget(m_buttonBox); setMinimumWidth(320); } KInputDialogHelper::~KInputDialogHelper() { } void KInputDialogHelper::slotEditTextChanged(const QString &text) { bool on; if (m_lineEdit->validator()) { QString str = m_lineEdit->text(); int index = m_lineEdit->cursorPosition(); on = (m_lineEdit->validator()->validate(str, index) == QValidator::Acceptable); } else { on = !text.trimmed().isEmpty(); } m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(on); } void KInputDialogHelper::slotUpdateButtons(const QString &text) { m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!text.isEmpty()); } KLineEdit *KInputDialogHelper::lineEdit() const { return m_lineEdit; } QSpinBox *KInputDialogHelper::intSpinBox() const { return m_intSpinBox; } QDoubleSpinBox *KInputDialogHelper::doubleSpinBox() const { return m_doubleSpinBox; } KComboBox *KInputDialogHelper::comboBox() const { return m_comboBox; } QListWidget *KInputDialogHelper::listBox() const { return m_listBox; } KTextEdit *KInputDialogHelper::textEdit() const { return m_textEdit; } // KInputDialog namespace namespace KInputDialog { QString getText(const QString &caption, const QString &label, const QString &value, bool *ok, QWidget *parent, QValidator *validator, const QString &mask, const QString &whatsThis, const QStringList &completionList) { KInputDialogHelper dlg(caption, label, value, parent, validator, mask); if (!whatsThis.isEmpty()) { dlg.lineEdit()->setWhatsThis(whatsThis); } if (!completionList.isEmpty()) { KCompletion *comp = dlg.lineEdit()->completionObject(); for (QStringList::const_iterator it = completionList.constBegin(); it != completionList.constEnd(); ++it) { comp->addItem(*it); } } bool _ok = (dlg.exec() == QDialog::Accepted); if (ok) { *ok = _ok; } QString result; if (_ok) { result = dlg.lineEdit()->text(); } - // A validator may explicitly allow leading and trailing whitespace + // A validator may KDELIBS4SUPPORT_DEPRECATED explicitly allow leading and trailing whitespace if (!validator) { result = result.trimmed(); } return result; } QString getMultiLineText(const QString &caption, const QString &label, const QString &value, bool *ok, QWidget *parent) { KInputDialogHelper dlg(caption, label, value, parent); dlg.textEdit()->setAcceptRichText(false); bool _ok = (dlg.exec() == QDialog::Accepted); if (ok) { *ok = _ok; } QString result; if (_ok) { result = dlg.textEdit()->toPlainText(); } return result; } int getInteger(const QString &caption, const QString &label, int value, int minValue, int maxValue, int step, int base, bool *ok, QWidget *parent) { KInputDialogHelper dlg(caption, label, value, minValue, maxValue, step, base, parent); bool _ok = (dlg.exec() == QDialog::Accepted); if (ok) { *ok = _ok; } int result = 0; if (_ok) { result = dlg.intSpinBox()->value(); } return result; } int getInteger(const QString &caption, const QString &label, int value, int minValue, int maxValue, int step, bool *ok, QWidget *parent) { return getInteger(caption, label, value, minValue, maxValue, step, 10, ok, parent); } double getDouble(const QString &caption, const QString &label, double value, double minValue, double maxValue, double step, int decimals, bool *ok, QWidget *parent) { KInputDialogHelper dlg(caption, label, value, minValue, maxValue, step, decimals, parent); bool _ok = (dlg.exec() == QDialog::Accepted); if (ok) { *ok = _ok; } double result = 0; if (_ok) { result = dlg.doubleSpinBox()->value(); } return result; } double getDouble(const QString &caption, const QString &label, double value, double minValue, double maxValue, int decimals, bool *ok, QWidget *parent) { return getDouble(caption, label, value, minValue, maxValue, 0.1, decimals, ok, parent); } QString getItem(const QString &caption, const QString &label, const QStringList &list, int current, bool editable, bool *ok, QWidget *parent) { KInputDialogHelper dlg(caption, label, list, current, editable, parent); if (!editable) { dlg.connect(dlg.listBox(), SIGNAL(itemActivated(QListWidgetItem*)), &dlg, SLOT(accept())); } bool _ok = (dlg.exec() == QDialog::Accepted); if (ok) { *ok = _ok; } QString result; if (_ok) { if (editable) { result = dlg.comboBox()->currentText(); } else if (dlg.listBox()->currentItem()) { result = dlg.listBox()->currentItem()->text(); } } return result; } QStringList getItemList(const QString &caption, const QString &label, const QStringList &list, const QStringList &select, bool multiple, bool *ok, QWidget *parent) { KInputDialogHelper dlg(caption, label, list, select, multiple, parent); bool _ok = (dlg.exec() == QDialog::Accepted); if (ok) { *ok = _ok; } QStringList result; if (_ok) { for (int i = 0; i < dlg.listBox()->count(); i++) { QListWidgetItem *item = dlg.listBox()->item(i); if (item->isSelected()) { result.append(item->text()); } } } return result; } } #include "moc_kinputdialog_p.cpp" diff --git a/src/kdeui/klistwidget.h b/src/kdeui/klistwidget.h index c07d3c6e..415f2311 100644 --- a/src/kdeui/klistwidget.h +++ b/src/kdeui/klistwidget.h @@ -1,112 +1,112 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Reginald Stadlbauer 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 KLISTWIDGET_H #define KLISTWIDGET_H #include #include /** * @deprecated since 5.0, use QListWidget instead * @short A variant of QListWidget that honors KDE's system-wide settings. * * Extends the functionality of QListWidget to honor the system * wide settings for Single Click/Double Click mode, Auto Selection and * Change Cursor over Link. * * There is a new signal executed(). It gets connected to either * QListWidget::itemClicked() or QListWidget::itemDoubleClicked() * depending on the KDE wide Single Click/Double Click settings. It is * strongly recommended that you use this signal instead of the above * mentioned. This way you don't need to care about the current * settings. If you want to get informed when the user selects * something connect to the QListWidget::itemSelectionChanged() signal. **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KListWidget : public QListWidget { Q_OBJECT public: - explicit KListWidget(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KListWidget(QWidget *parent = nullptr); ~KListWidget(); Q_SIGNALS: /** * Emitted whenever the user executes an listbox item. * * That means depending on the KDE wide Single Click/Double Click * setting the user clicked or double clicked on that item. * @param item is the pointer to the executed listbox item. * * Note that you may not delete any QListWidgetItem objects in slots * connected to this signal. */ void executed(QListWidgetItem *item); /** * Emitted whenever the user executes an listbox item. * * That means depending on the KDE wide Single Click/Double Click * setting the user clicked or double clicked on that item. * @param item is the pointer to the executed listbox item. * @param pos is the position where the user has clicked * * Note that you may not delete any QListWidgetItem objects in slots * connected to this signal. */ void executed(QListWidgetItem *item, const QPoint &pos); /** * This signal gets emitted whenever the user double clicks into the * listbox. * * @param item The pointer to the clicked listbox item. * @param pos The position where the user has clicked. * * Note that you may not delete any QListWidgetItem objects in slots * connected to this signal. * * This signal is more or less here for the sake of completeness. * You should normally not need to use this. In most cases it's better * to use executed() instead. */ void doubleClicked(QListWidgetItem *item, const QPoint &pos); protected: void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; void focusOutEvent(QFocusEvent *e) Q_DECL_OVERRIDE; void leaveEvent(QEvent *e) Q_DECL_OVERRIDE; void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE; void mouseDoubleClickEvent(QMouseEvent *e) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE; private: class KListWidgetPrivate; KListWidgetPrivate *const d; Q_PRIVATE_SLOT(d, void _k_slotItemEntered(QListWidgetItem *)) Q_PRIVATE_SLOT(d, void _k_slotOnViewport()) Q_PRIVATE_SLOT(d, void _k_slotSettingsChanged(int)) Q_PRIVATE_SLOT(d, void _k_slotAutoSelect()) Q_PRIVATE_SLOT(d, void _k_slotEmitExecute(QListWidgetItem *)) }; #endif // KLISTWIDGET_H diff --git a/src/kdeui/kmenu.h b/src/kdeui/kmenu.h index cb90b650..e8c82cf1 100644 --- a/src/kdeui/kmenu.h +++ b/src/kdeui/kmenu.h @@ -1,163 +1,163 @@ /* This file is part of the KDE libraries Copyright (C) 2000 Daniel M. Duley Copyright (C) 2006 Olivier Goffart 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 KMENU_H #define KMENU_H #include #include /** * @short A menu with keyboard searching * * KMenu is a class for menus with keyboard * accessibility for popups with many options and/or varying options. It acts * identically to QMenu, with the addition of setKeyboardShortcutsEnabled() and * setKeyboardShortcutsExecute() methods. * * * The keyboard search algorithm is incremental with additional underlining * for user feedback. * * @author Daniel M. Duley * @author Hamish Rodda */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KMenu : public QMenu { Q_OBJECT public: /** * Constructs a KMenu. */ - explicit KMenu(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KMenu(QWidget *parent = nullptr); /** * Constructs a KMenu. * \param title The text displayed in a parent menu when it is inserted * into another menu as a submenu. * \param parent the parent QWidget object */ - explicit KMenu(const QString &title, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KMenu(const QString &title, QWidget *parent = nullptr); /** * Destructs the object */ ~KMenu(); /** * Inserts a title item with no icon. */ QAction *addTitle(const QString &text, QAction *before = nullptr); /** * Inserts a title item with the given icon and title. */ QAction *addTitle(const QIcon &icon, const QString &text, QAction *before = nullptr); /** * Enables keyboard navigation by searching for the entered key sequence. * Also underlines the currently selected item, providing feedback on the search. * * Defaults to off. * * \warning calls to text() of currently keyboard-selected items will * contain additional ampersand characters. * * \warning though pre-existing keyboard shortcuts will not interfere with the * operation of this feature, they may be confusing to the user as the existing * shortcuts will not work. In addition, where text already contains ampersands, * the underline produced is likely to confuse the user (as this feature uses * underlining of text to indicate the current key selection sequence). */ void setKeyboardShortcutsEnabled(bool enable); /** * Enables execution of the menu item once it is uniquely specified. * Defaults to off. */ void setKeyboardShortcutsExecute(bool enable); /** * Returns the context menu associated with this menu * The data property of all actions inserted into the context menu is modified * all the time to point to the action and menu it has been shown for */ QMenu *contextMenu(); /** * Returns the context menu associated with this menu */ const QMenu *contextMenu() const; /** * Hides the context menu if shown */ void hideContextMenu(); /** * Returns the KMenu associated with the current context menu */ static KMenu *contextMenuFocus(); /** * returns the QAction associated with the current context menu */ static QAction *contextMenuFocusAction(); /** * Return the state of the mouse buttons when the last menuitem was activated. */ Qt::MouseButtons mouseButtons() const; /** * Return the state of the keyboard modifiers when the last menuitem was activated. */ Qt::KeyboardModifiers keyboardModifiers() const; Q_SIGNALS: /** * connect to this signal to be notified when a context menu is about to be shown * @param menu The menu that the context menu is about to be shown for * @param menuAction The action that the context menu is currently on * @param ctxMenu The context menu itself */ void aboutToShowContextMenu(KMenu *menu, QAction *menuAction, QMenu *ctxMenu); protected: void closeEvent(QCloseEvent *) Q_DECL_OVERRIDE; void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE; void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE; bool focusNextPrevChild(bool next) Q_DECL_OVERRIDE; void contextMenuEvent(QContextMenuEvent *e) Q_DECL_OVERRIDE; void hideEvent(QHideEvent *) Q_DECL_OVERRIDE; private: QString underlineText(const QString &text, uint length); class KMenuPrivate; KMenuPrivate *const d; Q_PRIVATE_SLOT(d, void resetKeyboardVars(bool b = false)) Q_PRIVATE_SLOT(d, void actionHovered(QAction *)) Q_PRIVATE_SLOT(d, void showCtxMenu(const QPoint &)) }; #endif diff --git a/src/kdeui/kmenubar.h b/src/kdeui/kmenubar.h index 58a3e385..68d405da 100644 --- a/src/kdeui/kmenubar.h +++ b/src/kdeui/kmenubar.h @@ -1,107 +1,107 @@ /* This file is part of the KDE libraries Copyright (C) 1997, 1998, 1999, 2000 Sven Radej (radej@kde.org) Copyright (C) 1997, 1998, 1999, 2000 Matthias Ettrich (ettrich@kde.org) Copyright (C) 1999, 2000 Daniel "Mosfet" Duley (mosfet@kde.org) 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 KMENUBAR_H #define KMENUBAR_H #include #include /** * %KDE Style-able menubar. * * This is required since QMenuBar is currently not handled by * QStyle. * * @author Daniel "Mosfet" Duley. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KMenuBar : public QMenuBar { Q_OBJECT Q_PROPERTY(bool topLevelMenu READ isTopLevelMenu WRITE setTopLevelMenu) public: - explicit KMenuBar(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KMenuBar(QWidget *parent = nullptr); ~KMenuBar(); /** * This controls whether or not this menubar will be a top-level * bar similar to the way Macintosh handles menubars. This * overrides any global config settings. * * Keep in mind that it is probably a really bad idea to use this * unless you really know what you're doing. A feature like a * top-level menubar is one that should really be shared by all * applications. If your app is the only one with a top-level * bar, then things might look very... odd. * * This is included only for those people that @p do know that * they need to use it. * * @param top_level If set to true, then this menubar will be a * top-level menu */ void setTopLevelMenu(bool top_level = true); /** * Is our menubar a top-level (Macintosh style) menubar? * * @return True if it is top-level. */ bool isTopLevelMenu() const; // TT are overloading virtuals :( virtual void setGeometry(const QRect &r); virtual void setGeometry(int x, int y, int w, int h); virtual void resize(int w, int h); void resize(const QSize &s); virtual void setFrameStyle(int); virtual void setLineWidth(int); virtual void setMargin(int); QSize sizeHint() const Q_DECL_OVERRIDE; protected Q_SLOTS: void slotReadConfig(); protected: void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; #pragma message("Port to Qt5 native filter") #if 0 virtual bool x11Event(XEvent *); #endif void closeEvent(QCloseEvent *) Q_DECL_OVERRIDE; void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; private Q_SLOTS: void updateFallbackSize(); void selectionTimeout(); private: void setTopLevelMenuInternal(bool top_level); void updateMenuBarSize(); void checkSize(int &w, int &h); private: class KMenuBarPrivate; KMenuBarPrivate *const d; }; #endif diff --git a/src/kdeui/kmessageboxmessagehandler.h b/src/kdeui/kmessageboxmessagehandler.h index 47fe7c20..361a38aa 100644 --- a/src/kdeui/kmessageboxmessagehandler.h +++ b/src/kdeui/kmessageboxmessagehandler.h @@ -1,58 +1,58 @@ /* This file is part of the KDE libraries Copyright (C) 2006 Michaël Larouche 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; version 2 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 KDEUI_KMESSAGEBOXMESSAGEHANDLER_H #define KDEUI_KMESSAGEBOXMESSAGEHANDLER_H #include #include #include class QWidget; class KMessageBoxMessageHandlerPrivate; /** * @brief This is a convience KMessageHandler that use KMessageBox. * * @author Michaël Larouche */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KMessageBoxMessageHandler : public QObject, public KMessageHandler { Q_OBJECT public: /** * @brief Create a new KMessageBoxMessageHandler * @param parent Parent widget to use for the KMessageBox. */ - explicit KMessageBoxMessageHandler(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KMessageBoxMessageHandler(QWidget *parent = nullptr); /** * Destroys the KMessageBoxMessageHandler. */ virtual ~KMessageBoxMessageHandler(); /** * @copydoc KMessageHandler::message */ void message(KMessage::MessageType messageType, const QString &text, const QString &caption) Q_DECL_OVERRIDE; private: KMessageBoxMessageHandlerPrivate *const d; }; #endif diff --git a/src/kdeui/knuminput.h b/src/kdeui/knuminput.h index 94b45057..2956fc76 100644 --- a/src/kdeui/knuminput.h +++ b/src/kdeui/knuminput.h @@ -1,812 +1,812 @@ /* This file is part of the KDE libraries * Copyright (c) 1997 Patrick Dowler * Copyright (c) 2000 Dirk Mueller * Copyright (c) 2002 Marc Mutz * * 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 K_NUMINPUT_H #define K_NUMINPUT_H #include #include #include class QSlider; class QSpinBox; class QValidator; class KIntSpinBox; class KNumInputPrivate; class KLocalizedString; /** * @deprecated since 5.0, use QSpinBox instead * * You need to inherit from this class if you want to implement K*NumInput * for a different variable type * */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KNumInput : public QWidget { Q_OBJECT Q_PROPERTY(QString label READ label WRITE setLabel) public: /** * Default constructor * @param parent If parent is 0, the new widget becomes a top-level * window. If parent is another widget, this widget becomes a child * window inside parent. The new widget is deleted when its parent is deleted. */ - explicit KNumInput(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KNumInput(QWidget *parent = nullptr); /** * @param below A pointer to another KNumInput. * @param parent parent widget * \deprecated - use the version without the below parameter instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED KNumInput(QWidget *parent, KNumInput *below); #endif /** * Destructor */ ~KNumInput(); /** * Sets the text and alignment of the main description label. * * @param label The text of the label. * Use QString() to remove an existing one. * * @param a The alignment of the label (Qt::Alignment). * Default is @p Qt:AlignLeft | @p Qt:AlignTop. * * The vertical alignment flags have special meaning with this * widget: * * @li @p Qt:AlignTop The label is placed above the edit/slider * @li @p Qt:AlignVCenter The label is placed left beside the edit * @li @p Qt:AlignBottom The label is placed below the edit/slider * */ virtual void setLabel(const QString &label, Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop); /** * @return the text of the label. */ QString label() const; /** * @return if the num input has a slider. */ bool showSlider() const; /** * Sets the spacing of tickmarks for the slider. * * @param minor Minor tickmark separation. * @param major Major tickmark separation. */ void setSteps(int minor, int major); /** * Returns a size which fits the contents of the control. * * @return the preferred size necessary to show the control */ QSize sizeHint() const Q_DECL_OVERRIDE; protected: /** * @return the slider widget. * @internal */ QSlider *slider() const; /** * Call this function whenever you change something in the geometry * of your KNumInput child. * */ void layout(bool deep); /** * You need to overwrite this method and implement your layout * calculations there. * * See KIntNumInput::doLayout and KDoubleNumInput::doLayout implementation * for details. * */ virtual void doLayout() = 0; private: friend class KNumInputPrivate; KNumInputPrivate *const d; Q_DISABLE_COPY(KNumInput) }; /* ------------------------------------------------------------------------ */ /** * @deprecated since 5.0, use QSpinBox instead * * @short An input widget for integer numbers, consisting of a spinbox and a slider. * * KIntNumInput combines a QSpinBox and optionally a QSlider * with a label to make an easy to use control for setting some integer * parameter. This is especially nice for configuration dialogs, * which can have many such combinated controls. * * The slider is created only when the user specifies a range * for the control using the setRange function or when the user * calls setSliderEnabled. * * A special feature of KIntNumInput, designed specifically for * the situation when there are several KIntNumInputs in a column, * is that you can specify what portion of the control is taken by the * QSpinBox (the remaining portion is used by the slider). This makes * it very simple to have all the sliders in a column be the same size. * * It uses KIntValidator validator class. KIntNumInput enforces the * value to be in the given range, and can display it in any base * between 2 and 36. * * \image html kintnuminput.png "KDE Int Number Input Spinbox" */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KIntNumInput : public KNumInput { Q_OBJECT Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged USER true) Q_PROPERTY(int minimum READ minimum WRITE setMinimum) Q_PROPERTY(int maximum READ maximum WRITE setMaximum) Q_PROPERTY(int singleStep READ singleStep WRITE setSingleStep) Q_PROPERTY(int referencePoint READ referencePoint WRITE setReferencePoint) Q_PROPERTY(double relativeValue READ relativeValue WRITE setRelativeValue) Q_PROPERTY(QString suffix READ suffix WRITE setSuffix) Q_PROPERTY(QString prefix READ prefix WRITE setPrefix) Q_PROPERTY(QString specialValueText READ specialValueText WRITE setSpecialValueText) Q_PROPERTY(bool sliderEnabled READ showSlider WRITE setSliderEnabled) public: /** * Constructs an input control for integer values * with base 10 and initial value 0. */ - explicit KIntNumInput(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KIntNumInput(QWidget *parent = nullptr); /** * Constructor * It constructs a QSpinBox that allows the input of integer numbers * in the range of -INT_MAX to +INT_MAX. To set a descriptive label, * use setLabel(). To enforce the value being in a range and optionally to * attach a slider to it, use setRange(). * * @param value initial value for the control * @param base numeric base used for display * @param parent parent QWidget */ - explicit KIntNumInput(int value, QWidget *parent = nullptr, int base = 10); + KDELIBS4SUPPORT_DEPRECATED explicit KIntNumInput(int value, QWidget *parent = nullptr, int base = 10); /** * Constructor * * the difference to the one above is the "below" parameter. It tells * this instance that it is visually put below some other KNumInput widget. * Note that these two KNumInput's need not to have the same parent widget * or be in the same layout group. * The effect is that it'll adjust its layout in correspondence * with the layout of the other KNumInput's (you can build an arbitrary long * chain). * * @param below append KIntNumInput to the KNumInput chain * @param value initial value for the control * @param base numeric base used for display * @param parent parent QWidget * * \deprecated use the version without the below parameter instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED KIntNumInput(KNumInput *below, int value, QWidget *parent, int base = 10); #endif /** * Destructor * * */ virtual ~KIntNumInput(); /** * @return the current value. */ int value() const; /** * @return the curent value in units of the referencePoint. */ double relativeValue() const; /** * @return the current reference point */ int referencePoint() const; /** * @return the suffix displayed behind the value. * @see setSuffix() */ QString suffix() const; /** * @return the prefix displayed in front of the value. * @see setPrefix() */ QString prefix() const; /** * @return the string displayed for a special value. * @see setSpecialValueText() */ QString specialValueText() const; /** * Sets the allowed input range and the step size for the slider and the * spin box. * * @param min minimum value * @param max maximum value * @param step step size */ void setRange(int min, int max, int singleStep = 1); /** * @deprecated Use the other setRange function and setSliderEnabled instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setRange(int min, int max, int singleStep, bool slider); #endif /** * @param enabled Show the slider * @default enabled */ void setSliderEnabled(bool enabled = true); /** * Sets the minimum value. */ void setMinimum(int min); /** * @return the minimum value. */ int minimum() const; /** * Sets the maximum value. */ void setMaximum(int max); /** * @return the maximum value. */ int maximum() const; /** * @return the step of the spin box */ int singleStep() const; /** * @return the step of the spin box */ void setSingleStep(int step); /** * Sets the special value text. If set, the SpinBox will display * this text instead of the numeric value whenever the current * value is equal to minVal(). Typically this is used for indicating * that the choice has a special (default) meaning. */ void setSpecialValueText(const QString &text); void setLabel(const QString &label, Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop) Q_DECL_OVERRIDE; /** * This method returns the minimum size necessary to display the * control. The minimum size is enough to show all the labels * in the current font (font change may invalidate the return value). * * @return the minimum size necessary to show the control */ QSize minimumSizeHint() const Q_DECL_OVERRIDE; public Q_SLOTS: /** * Sets the value of the control. */ void setValue(int); /** * Sets the value in units of the referencePoint */ void setRelativeValue(double); /** * Sets the reference point for relativeValue. */ void setReferencePoint(int); /** * Sets the suffix to @p suffix. * Use QString() to disable this feature. * Formatting has to be provided (e.g. a space separator between the * prepended @p value and the suffix's text has to be provided * as the first character in the suffix). * * @see QSpinBox::setSuffix(), #setPrefix() */ void setSuffix(const QString &suffix); /** * Sets the suffix to @p suffix. * Use this to add a plural-aware suffix, e.g. by using ki18np("singular", "plural"). * * @since 4.3 */ void setSuffix(const KLocalizedString &suffix); /** * Sets the prefix to @p prefix. * Use QString() to disable this feature. * Formatting has to be provided (see above). * * @see QSpinBox::setPrefix(), #setSuffix() */ void setPrefix(const QString &prefix); /** * sets focus to the edit widget and marks all text in if mark == true * */ void setEditFocus(bool mark = true); Q_SIGNALS: /** * Emitted every time the value changes (by calling setValue() or * by user interaction). */ void valueChanged(int); /** * Emitted whenever valueChanged is. Contains the change * relative to the referencePoint. */ void relativeValueChanged(double); private Q_SLOTS: void spinValueChanged(int); void slotEmitRelativeValueChanged(int); protected: /** * @return the spin box widget. * @internal */ QSpinBox *spinBox() const; void doLayout() Q_DECL_OVERRIDE; void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; private: void initWidget(int value, int _base); private: class KIntNumInputPrivate; friend class KIntNumInputPrivate; KIntNumInputPrivate *const d; Q_DISABLE_COPY(KIntNumInput) }; /* ------------------------------------------------------------------------ */ class KDoubleLine; /** * @deprecated since 5.0, use QSpinBox instead * * @short An input control for real numbers, consisting of a spinbox and a slider. * * KDoubleNumInput combines a QSpinBox and optionally a QSlider * with a label to make an easy to use control for setting some float * parameter. This is especially nice for configuration dialogs, * which can have many such combinated controls. * * The slider is created only when the user specifies a range * for the control using the setRange function with the slider * parameter set to "true". * * A special feature of KDoubleNumInput, designed specifically for * the situation when there are several instances in a column, * is that you can specify what portion of the control is taken by the * QSpinBox (the remaining portion is used by the slider). This makes * it very simple to have all the sliders in a column be the same size. * * \image html kdoublenuminput.png "KDE Double Number Input Spinbox" * * @see KIntNumInput */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDoubleNumInput : public KNumInput { Q_OBJECT Q_PROPERTY(double value READ value WRITE setValue NOTIFY valueChanged USER true) Q_PROPERTY(double minimum READ minimum WRITE setMinimum) Q_PROPERTY(double maximum READ maximum WRITE setMaximum) Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep) Q_PROPERTY(QString suffix READ suffix WRITE setSuffix) Q_PROPERTY(QString prefix READ prefix WRITE setPrefix) Q_PROPERTY(QString specialValueText READ specialValueText WRITE setSpecialValueText) Q_PROPERTY(int decimals READ decimals WRITE setDecimals) Q_PROPERTY(double referencePoint READ referencePoint WRITE setReferencePoint) Q_PROPERTY(double relativeValue READ relativeValue WRITE setRelativeValue) Q_PROPERTY(bool sliderEnabled READ showSlider WRITE setSliderEnabled) Q_PROPERTY(double exponentRatio READ exponentRatio WRITE setExponentRatio) public: /** * Constructs an input control for double values * with initial value 0.00. */ - explicit KDoubleNumInput(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDoubleNumInput(QWidget *parent = nullptr); /** * Constructor * * @param lower lower boundary value * @param upper upper boundary value * @param value initial value for the control * @param singleStep step size to use for up/down arrow clicks * @param precision number of digits after the decimal point * @param parent parent QWidget */ KDoubleNumInput(double lower, double upper, double value, QWidget *parent = nullptr, double singleStep = 0.01, int precision = 2); /** * destructor */ virtual ~KDoubleNumInput(); /** * Constructor * * the difference here is the "below" parameter. It tells this * instance that it is visually put below some other KNumInput * widget. Note that these two KNumInput's need not to have the * same parent widget or be in the same layout group. The effect * is that it'll adjust its layout in correspondence with the * layout of the other KNumInput's (you can build an arbitrary long * chain). * * @param below append KDoubleNumInput to the KDoubleNumInput chain * @param lower lower boundary value * @param upper upper boundary value * @param value initial value for the control * @param singleStep step size to use for up/down arrow clicks * @param precision number of digits after the decimal point * @param parent parent QWidget * * \deprecated use the version without below instead */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED KDoubleNumInput(KNumInput *below, double lower, double upper, double value, QWidget *parent = nullptr, double singleStep = 0.02, int precision = 2); #endif /** * @return the current value. */ double value() const; /** * @return the suffix. * @see setSuffix() */ QString suffix() const; /** * @return the prefix. * @see setPrefix() */ QString prefix() const; /** * @return number of decimals. * @see setDecimals() */ int decimals() const; /** * @return the string displayed for a special value. * @see setSpecialValueText() */ QString specialValueText() const; /** * @param min minimum value * @param max maximum value * @param singleStep step size for the QSlider * @param slider whether the slider is created or not */ void setRange(double min, double max, double singleStep = 1, bool slider = true); /** * @param enabled Show the slider * @default enabled */ void setSliderEnabled(bool enabled); /** * Sets the minimum value. */ void setMinimum(double min); /** * @return the minimum value. */ double minimum() const; /** * Sets the maximum value. */ void setMaximum(double max); /** * @return the maximum value. */ double maximum() const; /** * @return the step of the spin box */ double singleStep() const; /** * @return the step of the spin box */ void setSingleStep(double singleStep); /** * Specifies the number of digits to use. */ void setDecimals(int decimals); #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setPrecision(int precision) { setDecimals(precision); } #endif /** * @return the reference point for relativeValue calculation */ double referencePoint() const; /** * @return the current value in units of referencePoint. */ double relativeValue() const; /** * Sets the special value text. If set, the spin box will display * this text instead of the numeric value whenever the current * value is equal to minVal(). Typically this is used for indicating * that the choice has a special (default) meaning. */ void setSpecialValueText(const QString &text); void setLabel(const QString &label, Qt::Alignment a = Qt::AlignLeft | Qt::AlignTop) Q_DECL_OVERRIDE; QSize minimumSizeHint() const Q_DECL_OVERRIDE; /** * @return the value of the exponent use to map the slider to the * spin box. */ double exponentRatio() const; /** * @param dbl the value of the exponent use to map the slider to the * spin box (dbl need to be strictly positive). */ void setExponentRatio(double dbl); public Q_SLOTS: /** * Sets the value of the control. */ void setValue(double); /** * Sets the value in units of referencePoint. */ void setRelativeValue(double); /** * Sets the reference Point to @p ref. It @p ref == 0, emitting of * relativeValueChanged is blocked and relativeValue * just returns 0. */ void setReferencePoint(double ref); /** * Sets the suffix to be displayed to @p suffix. Use QString() to disable * this feature. Note that the suffix is attached to the value without any * spacing. So if you prefer to display a space separator, set suffix * to something like " cm". * @see setSuffix() */ void setSuffix(const QString &suffix); /** * Sets the prefix to be displayed to @p prefix. Use QString() to disable * this feature. Note that the prefix is attached to the value without any * spacing. * @see setPrefix() */ void setPrefix(const QString &prefix); Q_SIGNALS: /** * Emitted every time the value changes (by calling setValue() or * by user interaction). */ void valueChanged(double); /** * This is an overloaded member function, provided for * convenience. It essentially behaves like the above function. * * Contains the value in units of referencePoint. */ void relativeValueChanged(double); private Q_SLOTS: void sliderMoved(int); void spinBoxChanged(double); void slotEmitRelativeValueChanged(double); protected: void doLayout() Q_DECL_OVERRIDE; void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; friend class KDoubleLine; private: void initWidget(double value, double lower, double upper, double singleStep, int precision); double mapSliderToSpin(int) const; void updateLegacyMembers(); private: class KDoubleNumInputPrivate; friend class KDoubleNumInputPrivate; KDoubleNumInputPrivate *const d; Q_DISABLE_COPY(KDoubleNumInput) }; /* ------------------------------------------------------------------------ */ /** * @deprecated since 5.0, use QSpinBox instead * * @short A QSpinBox with support for arbitrary base numbers. * * A QSpinBox with support for arbitrary base numbers * (e.g. hexadecimal). * * The class provides an easy interface to use other * numeric systems than the decimal. * * \image html kintspinbox.png "KDE Integer Input Spinboxes with hexadecimal and binary input" */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KIntSpinBox : public QSpinBox { Q_OBJECT Q_PROPERTY(int base READ base WRITE setBase) public: /** * Constructor. * * Constructs a widget with an integer inputline with a little scrollbar * and a slider, with minimal value 0, maximal value 99, step 1, base 10 * and initial value 0. */ - explicit KIntSpinBox(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KIntSpinBox(QWidget *parent = nullptr); /** * Constructor. * * Constructs a widget with an integer inputline with a little scrollbar * and a slider. * * @param lower The lowest valid value. * @param upper The greatest valid value. * @param singleStep The step size of the scrollbar. * @param value The actual value. * @param base The base of the used number system. * @param parent The parent of the widget. */ KIntSpinBox(int lower, int upper, int singleStep, int value, QWidget *parent, int base = 10); /** * Destructor. */ virtual ~KIntSpinBox(); /** * Sets the base in which the numbers in the spin box are represented. * * @deprecated since 5.0, use QSpinBox::setDisplayIntegerBase(base) instead. */ void setBase(int base); /** * @return the base in which numbers in the spin box are represented. * * @deprecated since 5.0, use int displayIntegerBase() */ int base() const; /** * sets focus and optionally marks all text * */ void setEditFocus(bool mark); /** * Sets the suffix to @p suffix. * Use this to add a plural-aware suffix, e.g. by using ki18np("singular", "plural"). * * @since 4.3 */ void setSuffix(const KLocalizedString &suffix); using QSpinBox::setSuffix; protected: /** * Overloaded the method in QSpinBox * to make use of the base given in the constructor. */ QString textFromValue(int) const Q_DECL_OVERRIDE; /** * Overloaded the method in QSpinBox * to make use of the base given in the constructor. */ int valueFromText(const QString &text) const Q_DECL_OVERRIDE; private: class KIntSpinBoxPrivate; friend class KIntSpinBoxPrivate; KIntSpinBoxPrivate *const d; Q_DISABLE_COPY(KIntSpinBox) Q_PRIVATE_SLOT(d, void updateSuffix(int)) }; #endif // K_NUMINPUT_H diff --git a/src/kdeui/knumvalidator.h b/src/kdeui/knumvalidator.h index 74aba074..0e570aa8 100644 --- a/src/kdeui/knumvalidator.h +++ b/src/kdeui/knumvalidator.h @@ -1,138 +1,138 @@ /********************************************************************** ** ** Copyright (C) 1999 Glen Parker ** Copyright (C) 2002 Marc Mutz ** ** 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; if not, write to the Free ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ** *****************************************************************************/ #ifndef KNUMVALIDATOR_H #define KNUMVALIDATOR_H #include #include class QWidget; class QString; /** * QValidator for integers. This can be used by QLineEdit or subclass to provide validated text entry. Can be provided with a base value (default is 10), to allow the proper entry of hexadecimal, octal, or any other base numeric data. @author Glen Parker @deprecated use QIntValidator (or fix KIntValidator for non-decimal bases) */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KIntValidator : public QValidator { public: /** * Constructor. Also sets the base value. */ - explicit KIntValidator(QWidget *parent, int base = 10); + KDELIBS4SUPPORT_DEPRECATED explicit KIntValidator(QWidget *parent, int base = 10); /** * Constructor. Also sets the minimum, maximum, and numeric base values. */ KIntValidator(int bottom, int top, QWidget *parent, int base = 10); /** * Destructs the validator. */ virtual ~KIntValidator(); /** * Validates the text, and return the result. Does not modify the parameters. */ State validate(QString &, int &) const Q_DECL_OVERRIDE; /** * Fixes the text if possible, providing a valid string. The parameter may be modified. */ void fixup(QString &) const Q_DECL_OVERRIDE; /** * Sets the minimum and maximum values allowed. * If @p top is greater than @p bottom, it is set to the value of @p bottom. */ virtual void setRange(int bottom, int top); /** * Sets the numeric base value. @p base must be between 2 and 36. */ virtual void setBase(int base); /** * Returns the current minimum value allowed. */ virtual int bottom() const; /** * Returns the current maximum value allowed. */ virtual int top() const; /** * Returns the current numeric base. */ virtual int base() const; private: class KIntValidatorPrivate; KIntValidatorPrivate *const d; }; /** @short A locale-aware QDoubleValidator KDoubleValidator extends QDoubleValidator to be locale-aware. That means that - subject to not being disabled - KLocale::decimalSymbol(), KLocale::thousandsSeparator() and KLocale::positiveSign() and KLocale::negativeSign() are respected. @author Marc Mutz @deprecated use QDoubleValidator (and QLocale) **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDoubleValidator : public QDoubleValidator { Q_OBJECT Q_PROPERTY(bool acceptLocalizedNumbers READ acceptLocalizedNumbers WRITE setAcceptLocalizedNumbers) public: /** Constuct a locale-aware KDoubleValidator with default range (whatever QDoubleValidator uses for that) and parent @p parent */ - explicit KDoubleValidator(QObject *parent); + KDELIBS4SUPPORT_DEPRECATED explicit KDoubleValidator(QObject *parent); /** Constuct a locale-aware KDoubleValidator for range [@p bottom,@p top] and a precision of @p decimals decimals after the decimal point. */ KDoubleValidator(double bottom, double top, int decimals, QObject *parent); /** Destructs the validator. */ virtual ~KDoubleValidator(); /** Overloaded for internal reasons. The API is not affected. */ QValidator::State validate(QString &input, int &pos) const Q_DECL_OVERRIDE; /** @return whether localized numbers are accepted (default: true) */ bool acceptLocalizedNumbers() const; /** Sets whether to accept localized numbers (default: true) */ void setAcceptLocalizedNumbers(bool accept); private: typedef QDoubleValidator base; class KDoubleValidatorPrivate; KDoubleValidatorPrivate *const d; }; #endif diff --git a/src/kdeui/kpassivepopupmessagehandler.h b/src/kdeui/kpassivepopupmessagehandler.h index ec011e87..a28d946d 100644 --- a/src/kdeui/kpassivepopupmessagehandler.h +++ b/src/kdeui/kpassivepopupmessagehandler.h @@ -1,63 +1,63 @@ /* This file is part of the KDE libraries Copyright (C) 2006 Michaël Larouche 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; version 2 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 KDEUI_KPASSIVEPOPUPMESSAGEHANDLER_H #define KDEUI_KPASSIVEPOPUPMESSAGEHANDLER_H #include #include #include class QWidget; /** * @brief This is a convenience KMessageHandler that uses KPassivePopup. * * @author Michaël Larouche */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KPassivePopupMessageHandler : public QObject, public KMessageHandler { Q_OBJECT public: /** * @brief Create a new KPassivePopupMessageHandler * @param parent Parent widget to use for the KPassivePopup. */ - explicit KPassivePopupMessageHandler(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KPassivePopupMessageHandler(QWidget *parent = nullptr); /** * @copydoc KMessageHandler::message */ void message(KMessage::MessageType messageType, const QString &text, const QString &caption) Q_DECL_OVERRIDE; private: /** * @internal Actual call of KPassivePopup. * @param messageType Message type. * @param text the text to display. * @param caption the caption of the passive popup. */ void showPassivePopup(KMessage::MessageType messageType, const QString &text, const QString &caption); /** * @internal Get the parent widget to be used by the KPassivePopup. * @return the parent widget. */ QWidget *parentWidget(); }; #endif diff --git a/src/kdeui/kpixmapcache.h b/src/kdeui/kpixmapcache.h index f72f23b9..9db85669 100644 --- a/src/kdeui/kpixmapcache.h +++ b/src/kdeui/kpixmapcache.h @@ -1,384 +1,384 @@ /* * * This file is part of the KDE project. * Copyright (C) 2007 Rivo Laks * * 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 KPIXMAPCACHE_H #define KPIXMAPCACHE_H #include #include #include #include #include class QString; class QPixmap; /** * @brief General-purpose pixmap cache for KDE. * * The pixmap cache can be used to store pixmaps which can later be loaded * from the cache very quickly. * * Its most common use is storing SVG images which might be expensive to * render every time they are used. With the cache you can render each SVG * only once and later use the stored version unless the SVG file or requested * pixmap size changes. * * KPixmapCache's API is similar to that of the QPixmapCache so if you're * already using the latter then all you need to do is creating a KPixmapCache * object (unlike QPixmapCache, KPixmapCache doesn't have many static methods) * and calling @ref insert() and @ref find() method on that object: * @code * // Create KPixmapCache object * KPixmapCache* cache = new KPixmapCache("myapp-pixmaps"); * // Load a pixmap * QPixmap pix; * if (!cache->find("pixmap-1", pix)) { * // Pixmap isn't in the cache, create it and insert to cache * pix = createPixmapFromData(); * cache->insert("pixmap-1", pix); * } * // Use pix * @endcode * * The above example illustrates that you can also cache pixmaps created from * some data. In case such data is updated, you might need to discard cache * contents using @ref discard() method: * @code * // Discard the cache if it's too old * if (cache->timestamp() < mydataTimestamp()) { * cache->discard(); * } * // Now the cache contains up-to-date data * @endcode * As demonstrated, you can use cache's @ref timestamp() method to see when * the cache was created. If necessary, you can also change the timestamp * using @ref setTimestamp() method. * * @deprecated KPixmapCache is susceptible to various non-trivial locking bugs and * inefficiencies, and is supported for backward compatibility only (since it exposes * a QDataStream API for subclasses). Users should port to KImageCache for a very close * work-alike, or KSharedDataCache if they need more control. * * @see KImageCache, KSharedDataCache * * @author Rivo Laks */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KPixmapCache { public: /** * Constucts the pixmap cache object. * @param name unique name of the cache */ - explicit KPixmapCache(const QString &name); + KDELIBS4SUPPORT_DEPRECATED explicit KPixmapCache(const QString &name); virtual ~KPixmapCache(); /** * Tries to load pixmap with the specified @a key from cache. If the pixmap * is found it is stored in @a pix, otherwise @a pix is unchanged. * * @return true when pixmap was found and loaded from cache, false otherwise */ virtual bool find(const QString &key, QPixmap &pix); /** * Inserts the pixmap @a pix into the cache, associated with the key @a key. * * Any existing pixmaps associated with @a key are overwritten. */ virtual void insert(const QString &key, const QPixmap &pix); /** * Loads a pixmap from given file, using the cache. If the file does not * exist on disk, an empty pixmap is returned, even if that file had * previously been cached. In addition, if the file's modified-time is * more recent than cache's @ref timestamp(), the @em entire cache is * discarded (to be regenerated). This behavior may change in a future * KDE Platform release. If the cached data is current the pixmap * is returned directly from the cache without any file loading. * * @note The mapping between @a filename and the actual key used internally * is implementation-dependent and can change without warning. Use insert() * manually if you need control of the key, otherwise consistently use this * function. * * @param filename The name of the pixmap to load, cache, and return. * @return The given pixmap, or an empty pixmap if the file was invalid or did * not exist. */ QPixmap loadFromFile(const QString &filename); /** * Same as loadFromFile(), but using an SVG file instead. You may optionally * pass in a @a size to control the size of the output pixmap. * * @note The returned pixmap is only cached for identical filenames and sizes. * If you change the size in between calls to this function then the * pixmap will have to be regenerated again. * * @param filename The filename of the SVG file to load. * @param size size of the pixmap where the SVG is render to. If not given * then the SVG file's default size is used. * @return an empty pixmap if the file does not exist or was invalid, otherwise * a pixmap of the desired @a size. */ QPixmap loadFromSvg(const QString &filename, const QSize &size = QSize()); /** * @note KPixmapCache does not ever change the timestamp, so the application * must set the timestamp if it to be used. * @return Timestamp of the cache, set using the setTimestamp() method. */ QDateTime timestamp() const; /** * Sets the timestamp of app-specific cache. It's saved in the cache file * and can later be retrieved using the timestamp() method. * By default the timestamp is set to the cache creation time. */ void setTimestamp(const QDateTime &time); /** * Sets whether QPixmapCache (memory caching) should be used in addition * to disk cache. QPixmapCache is used by default. * * @note On most systems KPixmapCache can use shared-memory to share cached * pixmaps with other applications attached to the same shared pixmap, * which means additional memory caching is unnecessary and actually * wasteful of memory. * * @warning QPixmapCache is shared among the entire process and therefore * can cause strange interactions with other instances of KPixmapCache. * This may be fixed in the future and should be not relied upon. */ // KDE5 Get rid of QPixmapCache and use a sane cache instead. void setUseQPixmapCache(bool use); /** * Whether QPixmapCache should be used to cache pixmaps in memory in * addition to caching them on the disk. * * @b NOTE: The design of QPixmapCache means that the entries stored in * the cache are shared throughout the entire process, and not just in * this particular KPixmapCache. KPixmapCache makes an effort to ensure * that entries from other KPixmapCaches do not inadvertently spill over * into this one, but is not entirely successful (see discard()) */ bool useQPixmapCache() const; /** * @return approximate size of the cache, in kilobytes (1 kilobyte == 1024 bytes) */ int size() const; /** * @return maximum size of the cache (in kilobytes). * Default setting is 3 megabytes (1 megabyte = 2^20 bytes). */ int cacheLimit() const; /** * Sets the maximum size of the cache (in kilobytes). If cache gets bigger * than the limit then some entries are removed (according to * removeEntryStrategy()). * * Setting the cache limit to 0 disables caching (as all entries will get * immediately removed). * * Note that the cleanup might not be done immediately, so the cache might * temporarily (for a few seconds) grow bigger than the limit. */ void setCacheLimit(int kbytes); /** * Describes which entries will be removed first during cache cleanup. * @see removeEntryStrategy(), @see setRemoveEntryStrategy() */ enum RemoveStrategy { /// oldest entries are removed first. RemoveOldest, /// least used entries are removed first. RemoveSeldomUsed, /// least recently used entries are removed first. RemoveLeastRecentlyUsed }; /** * @return current entry removal strategy. * Default is RemoveLeastRecentlyUsed. */ RemoveStrategy removeEntryStrategy() const; /** * Sets the removeEntryStrategy used when removing entries. */ void setRemoveEntryStrategy(RemoveStrategy strategy); /** * Cache will be disabled when e.g. its data file cannot be created or * read. * * @return true when the cache is enabled. */ bool isEnabled() const; /** * @return true when the cache is ready to be used. Not being valid usually * means that some additional initialization has to be done before the * cache can be used. */ bool isValid() const; /** * Deletes a pixmap cache. * @param name unique name of the cache to be deleted */ // KDE5: Static function oh how I hate you, this makes it very difficult to perform // appropriate locking and synchronization to actually remove the cache. static void deleteCache(const QString &name); /** * Deletes all entries and reinitializes this cache. * * @b NOTE: If useQPixmapCache is set to true then that cache must also * be cleared. There is only one QPixmapCache for the entire process * however so other KPixmapCaches and other QPixmapCache users may also * be affected, leading to a temporary slowdown until the QPixmapCache is * repopulated. */ void discard(); /** * Removes some of the entries in the cache according to current * removeEntryStrategy(). * * @param newsize wanted size of the cache, in bytes. If 0 is given then * current cacheLimit() is used. * * @warning This currently works by copying some entries to a new cache and * then replacing the old cache with the new one. Thus it might be slow and * will temporarily use extra disk space. */ void removeEntries(int newsize = 0); protected: /** * Makes sure that the cache is initialized correctly, including the loading of the * cache index and data, and any shared memory attachments (for systems where that * is enabled). * * @note Although this method is protected you should not use it from any subclasses. * * @internal */ // KDE5: rename to ensureInitialized() // KDE5: Make private or move to Private void ensureInited() const; /** * Can be used by subclasses to load custom data from the stream. * This function will be called by KPixmapCache immediately following the * image data for a single image being read from @a stream. * (This function is called once for every single image). * * @see writeCustomData * @see loadCustomIndexHeader * @param stream the QDataStream to read data from * @return true if custom data was successfully loaded, false otherwise. If * false is returned then the cached item is assumed to be invalid and * will not be available to find() or contains(). */ virtual bool loadCustomData(QDataStream &stream); /** * Can be used by subclasses to write custom data into the stream. * This function will be called by KPixmapCache immediately after the * image data for a single image has been written to @a stream. * (This function is called once for every single image). * * @see loadCustomData * @see writeCustomIndexHeader * @param stream the QDataStream to write data to */ virtual bool writeCustomData(QDataStream &stream); /** * Can be used by subclasses to load custom data from cache's header. * This function will be called by KPixmapCache immediately after the * index header has been written out. (This function is called one time * only for the entire cache). * * @see loadCustomData * @see writeCustomIndexHeader * @param stream the QDataStream to read data from * @return true if custom index header data was successfully read, false * otherwise. If false is returned then the cache is assumed to * be invalid and further processing does not occur. */ virtual bool loadCustomIndexHeader(QDataStream &stream); /** * Can be used by subclasses to write custom data into cache's header. * This function will be called by KPixmapCache immediately following the * index header has being loaded. (This function is called one time * only for the entire cache). * * @see writeCustomData * @see loadCustomIndexHeader * @param stream the QDataStream to write data to */ virtual void writeCustomIndexHeader(QDataStream &stream); /** * Sets whether this cache is valid or not. (The cache must be enabled in addition * for isValid() to return true. @see isEnabled(), @see setEnabled()). * * Most cache functions do not work if the cache is not valid. KPixmapCache assumes * the cache is valid as long as its cache files were able to be created (see * recreateCacheFiles()) even if the cache is not enabled. * * Can be used by subclasses to indicate that cache needs some additional * initialization before it can be used (note that KPixmapCache will @em not handle * actually performing this extra initialization). */ void setValid(bool valid); /** * This function causes the cache files to be recreate by invalidating the cache. * Any shared memory mappings (if enabled) are dropped temporarily as well. * * @note The recreated cache will be initially empty, but with the same size limits * and entry removal strategy (see removeEntryStrategy()). * * If you use this in a subclass be prepared to handle writeCustomData() and * writeCustomIndexHeader(). * * @return true if the cache was successfully recreated. */ bool recreateCacheFiles(); private: /// @internal class Private; friend class Private; Private *const d; ///< @internal }; #endif // KPIXMAPCACHE_H diff --git a/src/kdeui/kprintpreview.h b/src/kdeui/kprintpreview.h index db65e396..dbb66564 100644 --- a/src/kdeui/kprintpreview.h +++ b/src/kdeui/kprintpreview.h @@ -1,78 +1,78 @@ /* * This file is part of the KDE libraries * Copyright (c) 2007 Alex Merry * * 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 KPRINTPREVIEW_H #define KPRINTPREVIEW_H #include #include #include class KPrintPreviewPrivate; /** * KPrintPreview provides a print preview dialog. * * Use it like this: * * @code * QPrinter printer; * KPrintPreview preview(&printer); * doPrint(printer); // draws to the QPrinter * preview.exec(); * @endcode * * @deprecated since 5.0, use QPrintPreviewDialog instead */ class KDELIBS4SUPPORT_EXPORT KPrintPreview : public QDialog { Q_OBJECT public: /** * Create a KPrintPreview object. * * This will change the settings on the QPrinter, so you * should not re-use the QPrinter object for printing * normally. * * @param printer pointer to a QPrinter to configure for * print preview * @param parent pointer to the parent widget for the dialog */ - explicit KPrintPreview(QPrinter *printer, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KPrintPreview(QPrinter *printer, QWidget *parent = nullptr); virtual ~KPrintPreview(); /** * Returns true if the print preview system is available * @since KDE 4.5 */ static bool isAvailable(); protected: void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; private: KPrintPreviewPrivate *const d; }; #endif // KPRINTPREVIEW_H diff --git a/src/kdeui/kprogressdialog.h b/src/kdeui/kprogressdialog.h index 9309f622..37af3731 100644 --- a/src/kdeui/kprogressdialog.h +++ b/src/kdeui/kprogressdialog.h @@ -1,214 +1,214 @@ /* This file is part of the KDE libraries Copyright (C) 1996 Martynas Kunigelis // krazy:exclude=copyright (email unknown) Copyright (C) 2006-2007 Urs Wolfer 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 KPROGRESSDIALOG_H #define KPROGRESSDIALOG_H #include #include #include /** * @short A dialog with a progress bar * * KProgressDialog provides a dialog with a text label, a progress bar * and an optional cancel button with a KDE look 'n feel. * * Since knowing how long it can take to complete an action and it is * undesirable to show a dialog for a split second before hiding it, * there are a few ways to control the timing behavior of KProgressDialog. * There is a time out that can be set before showing the dialog as well * as an option to autohide or keep displaying the dialog once complete. * * All the functionality of QProgressBar is available through direct access * to the progress bar widget via progressBar(); * * \image html kprogressdialog.png "KDE Progress Dialog" * * @author Aaron J. Seigo * @author Urs Wolfer uwolfer @ kde.org * * @deprecated since 5.0, use QProgressDialog instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KProgressDialog : public KDialog { Q_OBJECT public: /** * Constructs a KProgressDialog * * @param parent Parent of the widget * @param caption Text to display in window title bar * @param text Text to display in the dialog * @param flags The widget flags */ - explicit KProgressDialog(QWidget *parent = nullptr, const QString &caption = QString(), + KDELIBS4SUPPORT_DEPRECATED explicit KProgressDialog(QWidget *parent = nullptr, const QString &caption = QString(), const QString &text = QString(), Qt::WindowFlags flags = nullptr); /** * Destructor */ ~KProgressDialog(); /** * Returns the QProgressBar used in this dialog. * To set the number of steps or other progress bar related * settings, access the QProgressBar object directly via this method. */ QProgressBar *progressBar(); /** * Returns the QProgressBar used in this dialog. * To set the number of steps or other progress bar related * settings, access the QProgressBar object directly via this method. */ const QProgressBar *progressBar() const; /** * Sets the text in the dialog * * @param text the text to display */ void setLabelText(const QString &text); /** * Returns the current dialog text */ QString labelText() const; /** * Sets whether or not the user can cancel the process. * If the dialog is cancellable, the Cancel button will be shown * and the user can close the window using the window decorations. * If the process is not (or should not be) interuptable, * set the dialog to be modal and not cancellable. * * The default is true. * * @param allowCancel Set to true to make the dialog non-closable */ void setAllowCancel(bool allowCancel); /** * Returns true if the dialog can be canceled, false otherwise */ bool allowCancel() const; /** * Sets whether the cancel button is visible. setAllowCancel(false) * implies showCancelButton(false) * * The default is true. * * @param show Whether or not the cancel button should be shown */ void showCancelButton(bool show); /** * Sets whether the dialog should close automagically when * all the steps in the QProgressBar have been completed. * * The default is true. */ void setAutoClose(bool close); /** * Returns true if the dialog will close upon completion, * or false otherwise */ bool autoClose() const; /** * Sets whether the dialog should reset the QProgressBar dialog * back to 0 steps compelete when all steps have been completed. * This is useful for KProgressDialogs that will be reused. * * The default is false. */ void setAutoReset(bool autoReset); /** * Returns true if the QProgressBar widget will be reset * upon completion, or false otherwise */ bool autoReset() const; /** * Returns true if the dialog was closed or canceled * before completion. If the dialog is not cancellable * it will always return false. */ bool wasCancelled() const; /** * Ignores the last cancel action if the cancel button was * pressed. Useful for kdialog when combined with a KMessageBox * to display a message like "Are you sure you want to cancel?" */ void ignoreCancel(); /** * Sets the text to appear on the cancel button. */ void setButtonText(const QString &text); /** * Returns the text on the cancel button */ QString buttonText() const; /** * Set the minimum number of milliseconds to wait before * actually showing the dialog. * * If the expected duration of the task is less than the minimumDuration, the dialog will * not appear at all. This prevents the dialog popping up for tasks that are quickly over. * For tasks that are expected to exceed the minimumDuration, the dialog will pop up after * the minimumDuration time. * If set to 0, the dialog is always shown immediately. The default is * 2000 milliseconds. */ void setMinimumDuration(int ms); /** * Returns the time that must pass before the dialog appears. * @see setMinimumDuration */ int minimumDuration() const; void reject() Q_DECL_OVERRIDE; protected: void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; private: Q_PRIVATE_SLOT(d, void slotAutoShow()) Q_PRIVATE_SLOT(d, void slotAutoActions(int percentage)) private: class KProgressDialogPrivate; friend class KProgressDialogPrivate; KProgressDialogPrivate *const d; Q_DISABLE_COPY(KProgressDialog) }; #endif diff --git a/src/kdeui/kpushbutton.h b/src/kdeui/kpushbutton.h index 00ccc271..9def98ca 100644 --- a/src/kdeui/kpushbutton.h +++ b/src/kdeui/kpushbutton.h @@ -1,226 +1,226 @@ /* 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 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 KPUSHBUTTON_H #define KPUSHBUTTON_H #include #include #include #include class QDrag; class QMenu; /** * @deprecated since 5.0, use QPushButton instead * * @brief A QPushButton with drag-support and KGuiItem support * * This is nothing but a QPushButton with drag-support and KGuiItem support. * You must call #setDragEnabled (true) and override the virtual method * dragObject() to specify the QDragObject to be used. * * \image html kpushbutton.png "KDE Push Button" * * @author Carsten Pfeiffer */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KPushButton : public QPushButton { Q_OBJECT Q_PROPERTY(bool isDragEnabled READ isDragEnabled WRITE setDragEnabled) public: /** * Default constructor. */ - explicit KPushButton(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KPushButton(QWidget *parent = nullptr); /** * Constructor, that sets the button-text to @p text */ - explicit KPushButton(const QString &text, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KPushButton(const QString &text, QWidget *parent = nullptr); /** * Constructor, that sets an icon and the button-text to @p text */ KPushButton(const QIcon &icon, const QString &text, QWidget *parent = nullptr); /** * Constructor that takes a KGuiItem for the text, the icon, the tooltip * and the what's this help * @deprecated since 5.0, use QPushButton and KGuiItem::assign(QPushButton *button, const KGuiItem &item). */ - explicit KPushButton(const KGuiItem &item, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KPushButton(const KGuiItem &item, QWidget *parent = nullptr); /** * Destructs the button. */ ~KPushButton(); /** * Enables/disables drag-support. Default is disabled. */ void setDragEnabled(bool enable); /** * @returns if drag support is enabled or not. */ bool isDragEnabled() const; /** * Sets the KGuiItem for this button. */ void setGuiItem(const KGuiItem &item); /** * Sets the standard KGuiItem for this button. */ void setGuiItem(KStandardGuiItem::StandardItem item); /** * Reads the standard KGuiItem for this button. */ KStandardGuiItem::StandardItem guiItem() const; /** * Sets the Icon Set for this button. It also takes into account the * "show icons on push buttons" user setting. */ void setIcon(const QIcon &icon); /** * Sets the text of the button */ void setText(const QString &text); /** * Sets a delayed popup menu * for consistency, since menu() isn't virtual */ void setDelayedMenu(QMenu *delayed_menu); /** * returns a delayed popup menu * since menu() isn't virtual */ QMenu *delayedMenu(); /** * Reimplemented to add arrow for delayed menu * @since 4.4 */ QSize sizeHint() const Q_DECL_OVERRIDE; /** * Returns the action object associated with this button, or 0 if it does not have one * * @returns the KAuth::Action associated with this button. */ KAuth::Action authAction() const; /** * Sets the action object associated with this button * * By setting a KAuth::Action, this button will become associated with it, and * whenever it gets clicked, it will trigger the authorization and execution process * for the action. The signal activated will also be emitted whenever the button gets * clicked and the action gets authorized. Pass 0 to this function to disassociate the button * * @param action the KAuth::Action to associate with this button. */ void setAuthAction(const KAuth::Action &action); /** * Sets the action object associated with this button * * Overloaded member to allow creating the action by name * * @param actionName the name of the action to associate */ void setAuthAction(const QString &actionName); protected: /** * Reimplement this and return the QDrag object that should be used * for the drag. Remember to give it "this" as parent. * * Default implementation returns 0, so that no drag is initiated. */ virtual QDrag *dragObject(); /** * Reimplemented to add drag-support */ void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE; /** * Reimplemented to add drag-support */ void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE; /** * Reimplemented to add arrow for delayed menu * @since 4.4 */ void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; /** * Starts a drag (dragCopy() by default) using dragObject() */ virtual void startDrag(); Q_SIGNALS: /** * Signal emitted when the button is triggered and authorized * * If the button needs authorization, whenever the user triggers it, * the authorization process automatically begins. * If it succeeds, this signal is emitted. The KAuth::Action object is provided for convenience * if you have multiple Action objects, but of course it's always the same set with * setAuthAction(). * * WARNING: If your button needs authorization you should connect eventual slots processing * stuff to this signal, and NOT clicked. Clicked will be emitted even if the user has not * been authorized * * @param action The object set with setAuthAction() */ void authorized(const KAuth::Action &action); private: /** * Internal. * Initialize the KPushButton instance */ void initWidget(const KGuiItem &item); private: class KPushButtonPrivate; KPushButtonPrivate *const d; Q_PRIVATE_SLOT(d, void slotPressedInternal()) Q_PRIVATE_SLOT(d, void slotClickedInternal()) Q_PRIVATE_SLOT(d, void slotDelayedMenuTimeout()) }; #endif // KPUSHBUTTON_H diff --git a/src/kdeui/krestrictedline.h b/src/kdeui/krestrictedline.h index 2a534719..428a4816 100644 --- a/src/kdeui/krestrictedline.h +++ b/src/kdeui/krestrictedline.h @@ -1,93 +1,93 @@ /* * Definition of KRestrictedLine * * Copyright (C) 1997 Michael Wiedmann, * * 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; if not, write to the Free * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KRESTRICTEDLINE_H #define KRESTRICTEDLINE_H #include #include class KRestrictedLinePrivate; /** * @short A line editor for restricted character sets. * * The KRestrictedLine widget is a variant of QLineEdit which * accepts only a restricted set of characters as input. * All other characters will be discarded and the signal invalidChar() * will be emitted for each of them. * * Valid characters can be passed as a QString to the constructor * or set afterwards via setValidChars(). * The default key bindings of QLineEdit are still in effect. * * This is almost like setting a QRegExpValidator on a KLineEdit; * the difference is that with KRestrictedLine it can all be done in Qt designer. * * \image html krestrictedline.png "KDE Restricted Line Edit allowing all characters but 'o'" * * @author Michael Wiedmann * * @deprecated from KF 5.0. Use QLineEdit instead, with a QValidator */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KRestrictedLine : public KLineEdit { Q_OBJECT Q_PROPERTY(QString validChars READ validChars WRITE setValidChars) public: /** * Constructor * @param parent pointer to the parent widget */ - explicit KRestrictedLine(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KRestrictedLine(QWidget *parent = nullptr); /** * Destructs the restricted line editor. */ ~KRestrictedLine(); /** * All characters in the string valid are treated as * acceptable characters. */ void setValidChars(const QString &valid); /** * @return the string of acceptable characters. */ QString validChars() const; Q_SIGNALS: /** * Emitted when an invalid character was typed. */ void invalidChar(int); protected: void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE; void inputMethodEvent(QInputMethodEvent *e) Q_DECL_OVERRIDE; private: KRestrictedLinePrivate *const d; }; #endif // KRESTRICTEDLINE_H diff --git a/src/kdeui/kshortcut.h b/src/kdeui/kshortcut.h index 2b964898..06ee8b66 100644 --- a/src/kdeui/kshortcut.h +++ b/src/kdeui/kshortcut.h @@ -1,266 +1,266 @@ /* This file is part of the KDE libraries Copyright (C) 2001,2002 Ellis Whitehead Copyright (C) 2006 Hamish Rodda Copyright (C) 2006 Andreas Hartmetz 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. */ /** * @file kshortcut.h * Defines platform-independent classes for keyboard shortcut handling. */ #ifndef KSHORTCUT_H #define KSHORTCUT_H #include #include #include #include #include class KShortcutPrivate; /** * @short Represents a keyboard shortcut * * The KShortcut class is used to represent a keyboard shortcut to an action. * A shortcut is normally a single key with modifiers, such as Ctrl+V. * A KShortcut object may also contain an alternate key sequence which will also * activate the action it's associated with, as long as no other actions have * defined that key as their primary key. Ex: Ctrl+V;Shift+Insert. * * This can be used to add additional accelerators to a KAction. For example, * the below code binds the escape key to the close action. * * \code * KAction *closeAction = KStandardAction::close(this, SLOT( close() ), actionCollection()); * KShortcut closeShortcut = closeAction->shortcut(); * closeShortcut.setAlternate(Qt::Key_Escape); * closeAction->setShortcut(closeShortcut); * \endcode */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KShortcut { public: /** * An enum about the behavior of operations that treat a KShortcut like a list of QKeySequences. */ enum EmptyHandling { ///if a shortcut is or becomes empty, let it stay as a placeholder KeepEmpty = 0, ///remove empty QKeySequences, possibly changing the positions of QKeySequences due to the ensuing reshuffling. RemoveEmpty }; /** * Creates a new empty shortcut. * @see isEmpty() * @see clear() */ KShortcut(); /** * Creates a new shortcut that contains the given Qt key * sequence as primary shortcut. * @param primary Qt key sequence to add */ - explicit KShortcut(const QKeySequence &primary); + KDELIBS4SUPPORT_DEPRECATED explicit KShortcut(const QKeySequence &primary); /** * Creates a new shortcut with the given Qt key sequences * as primary and secondary shortcuts. * @param primary Qt keycode of primary shortcut * @param alternate Qt keycode of alternate shortcut * @see Qt::Key */ // TODO KDE5 move to QShortcut KShortcut(const QKeySequence &primary, const QKeySequence &alternate); /** * Creates a new shortcut with the given Qt key codes * as primary and secondary shortcuts. * You can only assign single-key shortcuts this way. * @param keyQtPri Qt keycode of primary shortcut * @param keyQtAlt Qt keycode of alternate shortcut * @see Qt::Key */ // TODO KDE5 move to QShortcut - explicit KShortcut(int keyQtPri, int keyQtAlt = 0); + KDELIBS4SUPPORT_DEPRECATED explicit KShortcut(int keyQtPri, int keyQtAlt = 0); /** * Copy constructor. */ KShortcut(const KShortcut &other); /** * Creates a new shortcut that contains the key sequences described * in @p description. The format of description is the same as * used in QKeySequence::fromString(const QString&). * Up to two key sequences separated by a semicolon followed by a * space "; " may be given. * @param description the description of key sequence(s) * @see QKeySequence::fromString(const QString&, SequenceFormat) */ // TODO KDE5 move to QShortcut - explicit KShortcut(const QString &description); + KDELIBS4SUPPORT_DEPRECATED explicit KShortcut(const QString &description); /** * Creates a new shortcut with the given Qt key sequences. * The first sequence in the list is considered to be the primary * sequence, the second one the alternate. * @param seqs List of key sequeces. */ // TODO KDE5 move to QShortcut KShortcut(const QList &seqs); /** * Destructor. */ ~KShortcut(); /** @name Query methods */ /** @{ */ /** * Returns the primary key sequence of this shortcut. * @return primary key sequence */ QKeySequence primary() const; /** * Returns the alternate key sequence of this shortcut. * @return alternate key sequence */ QKeySequence alternate() const; /** * Returns whether this shortcut contains any nonempty key sequences. * @return whether this shortcut is empty */ bool isEmpty() const; /** * Returns whether at least one of the key sequences is equal to @p needle. * @return whether this shortcut contains @p needle */ bool contains(const QKeySequence &needle) const; /** * Returns whether at least one of the key sequences conflicts witho @p needle. * @return whether this shortcut conflicts with @p needle */ bool conflictsWith(const QKeySequence &needle) const; /** * Returns a description of the shortcut as a semicolon-separated * list of key sequences, as returned by QKeySequence::toString(). * @return the string represenation of this shortcut * @see QKeySequence::toString() * @see KShortcut(const QString &description) */ QString toString() const; /** * Returns a description of the shortcut as a semicolon-separated * list of key sequences, as returned by QKeySequence::toString(). * @return the string represenation of this shortcut * @see QKeySequence::toString() * @see KShortcut(const QString &description) * @since KDE 4.2 */ QString toString(QKeySequence::SequenceFormat format) const; bool operator==(const KShortcut &other) const; bool operator!=(const KShortcut &other) const; /** * Returns shortcut as QList\, and is equivalent to toList(RemoveEmpty). * Be aware that empty shortcuts will not be included in the list; * due to this, conversion operations like * KShortcut b = (QList\)KShortcut a * will not always result in b == a. * @return the shortcut converted to a QList\ */ operator QList() const; /** * The same as operator QList\() * If @p handleEmpty equals RemoveEmpty, empty key sequences will be left out of the result. * Otherwise, empy key sequences will be included; you can be sure that * shortcut.alternate() == shortcut.toList(KeepEmpty).at(1). * @return the shortcut converted to a QList\ */ QList toList(enum EmptyHandling handleEmpty = RemoveEmpty) const; /** * Returns shortcut as QVariant. */ operator QVariant() const; /** @} */ /** @name Mutator methods */ /** @{ */ /** * Set the primary key sequence of this shortcut to the given key sequence. * @param keySeq set primary key sequence to this */ void setPrimary(const QKeySequence &keySeq); /** * Set the alternate key sequence of this shortcut to the given key sequence. * @param keySeq set alternate key sequence to this */ void setAlternate(const QKeySequence &keySeq); /** * Remove @p keySeq from this shortcut. * If @p handleEmpty equals RemoveEmpty, following key sequences will move up to take the place of * @p keySeq. Otherwise, key sequences equal to @p keySeq will be set to empty. * @param keySeq remove this key sequence from the shortcut */ void remove(const QKeySequence &keySeq, enum EmptyHandling handleEmpty = RemoveEmpty); /** * Assignment operator. */ KShortcut &operator=(const KShortcut &other); private: class KShortcutPrivate *const d; }; inline uint qHash(const KShortcut &key) { return qHash(key.primary()[0]) + qHash(key.primary()[1]); } inline uint qHash(const QKeySequence &key) { uint hash = 0; for (int i = 0; i < static_cast(key.count()); i++) { hash += qHash(key[uint(i)]); } return hash; } Q_DECLARE_METATYPE(KShortcut) #endif // KSHORTCUT_H diff --git a/src/kdeui/ksplashscreen.h b/src/kdeui/ksplashscreen.h index 770a77a1..a6eea9d9 100644 --- a/src/kdeui/ksplashscreen.h +++ b/src/kdeui/ksplashscreen.h @@ -1,67 +1,67 @@ /* This file is part of the KDE libraries Copyright (C) 2003 Chris Howells (howells@kde.org) 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 KSPLASHSCREEN_H #define KSPLASHSCREEN_H #include #include class QPixmap; /** * @short %KDE splash screen * * This class is based on QSplashScreen and exists solely to make * splash screens obey KDE's Xinerama settings. * * For documentation on how to use the class, see the documentation * for QSplashScreen. * * \image html ksplashscreen.png "KDE Splash Screen" * * @author Chris Howells (howells@kde.org) */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KSplashScreen : public QSplashScreen //krazy:exclude=qclasses { Q_OBJECT public: /** * Constructs a splash screen. */ - explicit KSplashScreen(const QPixmap &pixmap, Qt::WindowFlags f = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KSplashScreen(const QPixmap &pixmap, Qt::WindowFlags f = nullptr); /** * Destructor. * * Deletes all internal objects. */ ~KSplashScreen(); private: class Private; Private *const d; Q_DISABLE_COPY(KSplashScreen) }; #endif //KSPLASHSCREEN_H diff --git a/src/kdeui/kstatusbar.h b/src/kdeui/kstatusbar.h index 0d1b9f4a..6d2cc04c 100644 --- a/src/kdeui/kstatusbar.h +++ b/src/kdeui/kstatusbar.h @@ -1,194 +1,194 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Mark Donohoe (donohoe@kde.org) Copyright (C) 1997, 1998 1998 Sven Radej (sven@lisa.exp.univie.ac.at) Copyright (C) 2007 Aron Boström (aron.bostrom@gmail.com) 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 KSTATUSBAR_H #define KSTATUSBAR_H #include #include class QObject; class QEvent; class KStatusBarPrivate; /** * @short %KDE statusbar widget * * Display status messages. * * You can insert text labels or custom widgets. Their geometry is managed * internally. KStatusBar resizes itself, but positioning is left to * KMainWindow (or to you, if you don't use KMainWindow ). * * A special type of item is a message which is a temporary text-message * displayed on top of other items in full-width. Messages are visible for * specified time, or until you call the slot QStatusBar::clearMessage(). See * QStatusBar::showMessage for details. * * It is useful to connect the KActionCollection signals to the * QStatusBar::showMessage slots. * * KStatusBar inherits QStatusBar, you can freely use all QStatusBar * methods. * * Empty text items are not visible. They will become visible when you change * (add) text. * * @author Mark Donohoe and Sven Radej * @see KActionCollection */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KStatusBar : public QStatusBar { Q_OBJECT public: /** * Constructs a status bar. @p parent is usually KMainWindow. */ - explicit KStatusBar(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KStatusBar(QWidget *parent = nullptr); /** * Destructor. * * Deletes all internal objects. */ ~KStatusBar(); /** * Inserts a temporary text label into the status bar. * Parameter @p stretch is passed to QStatusBar::addWidget . * * @param text The label's text string. * @param id id of item * @param stretch stretch passed to QStatusBar::addWidget * * @see QStatusbar::addWidget * */ void insertItem(const QString &text, int id, int stretch = 0); /** * Inserts a permanent text label into the status bar. * Parameter @p stretch is passed to QStatusBar::addWidget . * * @param text The label's text string. * @param id id of item * @param stretch stretch passed to QStatusBar::addPermanentWidget * * @see QStatusbar::addPermanentWidget * */ void insertPermanentItem(const QString &text, int id, int stretch = 0); /** * Inserts a fixed width temporary text label into status bar. The width * will be set according to @p text, but will remain fixed even if you * change text. You can change fixed width by calling setItemFixed. * * @param text The label's text string * @param id id of item */ void insertFixedItem(const QString &text, int id); /** * Inserts a fixed width permanent text label into status bar. The width * will be set according to @p text, but will remain fixed even if you * change text. You can change fixed width by calling setItemFixed. * * @param text The label's text string * @param id id of item */ void insertPermanentFixedItem(const QString &text, int id); /** * Removes an item. * * @param id The item to remove. */ void removeItem(int id); /** * Returns true if an item with @p id exists already in KStatusBar, * otherwise returns false. * * @param id id of the item */ bool hasItem(int id) const; /** * The text of an item, if it exists. */ QString itemText(int id) const; /** * Changes the text in a status bar field. * * The item will be resized to fit the text. If you change text to be empty, * item will not be visible (until you add some text). * * @param text The label's text string * @param id The id of item. */ void changeItem(const QString &text, int id); /** * Sets the alignment of item @p id. By default all fields are aligned * @p AlignHCenter | @p AlignVCenter. See QLabel::setAlignment for details. * */ void setItemAlignment(int id, Qt::Alignment alignment); /** * Sets item @p id to have fixed width. This cannot be undone, but you can * always set new fixed width. * * @param id id of item * @param width fixed width in pixels. Default -1 is to adapt to text width. */ void setItemFixed(int id, int width = -1); Q_SIGNALS: /** * Emitted when mouse is pressed over item @p id. * * Connect to this signal if you want to respond to mouse press events. * */ void pressed(int); /** * Emitted when mouse is released over item @p id. * * Connect to this signal if you want to respond to mouse release events (clicks). */ void released(int); protected: bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE; private: KStatusBarPrivate *const d; }; #endif // KSTATUSBAR_H diff --git a/src/kdeui/kstringvalidator.h b/src/kdeui/kstringvalidator.h index 5efdef7f..f49c1969 100644 --- a/src/kdeui/kstringvalidator.h +++ b/src/kdeui/kstringvalidator.h @@ -1,137 +1,137 @@ /* kstringvalidator.h Copyright (c) 2001 Marc Mutz 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; version 2.0 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KSTRINGVALIDATOR_H #define KSTRINGVALIDATOR_H #include #include #include /** * @deprecated since 5.0 * @short A QValidator to (dis)allow certain strings * * This validator allows you to accept only certain or to accept all * but certain strings. * * When used in rejecting mode, accepts only strings not in the * stringlist. This mode is the default and comes in handy when asking * the user for a name of some listed entity. Set the list of already * used names to prevent the user from entering duplicate names. * * When used in non-rejecting mode, accepts only strings that appear * in the stringlist. Use with care! From a user's point of view this * mode is hard to grasp. * * This validator can also fix strings. In rejecting mode, a number * will be appended to the string until it is Acceptable. E.g. if * "foo" and "foo 1" are in the stringlist, then fixup will change * "foo" to "foo 2", provided "foo 2" isn't in the list of forbidden * strings. * * In accepting mode, when the input starts with an Acceptable * substring, truncates to the longest Acceptable string. When the * input is the start of an Acceptable string, completes to the * shortest Acceptable string. * * NOTE: fixup isn't yet implemented. * * @author Marc Mutz **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KStringListValidator : public QValidator { Q_OBJECT Q_PROPERTY(QStringList stringList READ stringList WRITE setStringList) Q_PROPERTY(bool rejecting READ isRejecting WRITE setRejecting) Q_PROPERTY(bool fixupEnabled READ isFixupEnabled WRITE setFixupEnabled) public: /** * Creates a new string validator. * * @param list The list of strings to (dis)allow. * @param rejecting Selects the validator's mode * (rejecting: true; accepting: false) * @param fixupEnabled Selects whether to fix strings or not. * @param parent Passed to lower level constructor. * **/ - explicit KStringListValidator(const QStringList &list = QStringList(), + KDELIBS4SUPPORT_DEPRECATED explicit KStringListValidator(const QStringList &list = QStringList(), bool rejecting = true, bool fixupEnabled = false, QObject *parent = nullptr); /** * Destroys the string validator. */ ~KStringListValidator(); /** * Sets whether the string validator is in rejecting mode or not. * If in rejecting mode, the strings from @see stringList are not * allowed to appear in the validation string. */ void setRejecting(bool rejecting); /** * Returns whether the string validator is in rejecting mode. */ bool isRejecting() const; /** * Sets the fixup flag. If enabled, wrong input is corrected * automatically. */ void setFixupEnabled(bool fixupEnabled); /** * Returns whether the fixup flag is set. */ bool isFixupEnabled() const; /** * Sets the @param list of string which is used as black or * white list, depending on the rejecting mode (@see isRejecting()). */ void setStringList(const QStringList &list); /** * Returns the string list of the validator. */ QStringList stringList() const; /** * Reimplemented from @see QValidator. */ State validate(QString &input, int &pos) const Q_DECL_OVERRIDE; /** * Reimplemented from @see QValidator. */ void fixup(QString &input) const Q_DECL_OVERRIDE; private: class Private; Private *const d; }; #endif // KSTRINGVALIDATOR_H diff --git a/src/kdeui/ksystemtrayicon.h b/src/kdeui/ksystemtrayicon.h index fec702f6..fac4559e 100644 --- a/src/kdeui/ksystemtrayicon.h +++ b/src/kdeui/ksystemtrayicon.h @@ -1,190 +1,190 @@ /* This file is part of the KDE libraries Copyright (C) 1999 Matthias Ettrich Copyright (C) 2007 by Charles Connell Copyright (C) 2008 Lukas Appelhans 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 KSYSTEMTRAY_H #define KSYSTEMTRAY_H #include #include #include class KActionCollection; class KSystemTrayIconPrivate; class QAction; class QMovie; /** * \brief %KDE System Tray Window class * * This class implements system tray windows. * * A tray window is a small window (typically 22x22 pixel) that docks * into the system tray in the desktop panel. It usually displays an * icon or an animated icon there. The icon represents * the application, similar to a taskbar button, but consumes less * screen space. * * When the user clicks with the left mouse button on the icon, the * main application window is shown/raised and activated. With the * right mouse button, she gets a popupmenu with application specific * commands, including "Minimize/Restore" and "Quit". * * Please note that this class is being phased out in favor of the KStatusNotifierItem * class, you should consider to use it instead if you are writing a new application * or consider porting the code that uses this class to the KStatusNotifierItem API. * * Also, QSystemTrayIcon::showMessage(..) should not be * used for KDE application because the popup message has no KDE standard * look & feel and cannot be controlled by KDE configurations. * Use KNotification or KPassivePopup instead. * * @author Matthias Ettrich **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KSystemTrayIcon : public QSystemTrayIcon //krazy:exclude=qclasses { Q_OBJECT public: /** * Construct a system tray icon. * * The parent widget @p parent has a special meaning: * Besides owning the tray window, the parent widget will * disappear from taskbars when it is iconified while the tray * window is visible. This is the desired behavior. After all, * the tray window @p is the parent's taskbar icon. * * Furthermore, the parent widget is shown or raised respectively * when the user clicks on the tray window with the left mouse * button. **/ - explicit KSystemTrayIcon(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KSystemTrayIcon(QWidget *parent = nullptr); /** * Same as above but allows one to define the icon by name that should * be used for the system tray icon. */ - explicit KSystemTrayIcon(const QString &icon, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KSystemTrayIcon(const QString &icon, QWidget *parent = nullptr); /** * Same as above but allows one to define the icon by name that should * be used for the system tray icon. */ - explicit KSystemTrayIcon(const QIcon &icon, QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KSystemTrayIcon(const QIcon &icon, QWidget *parent = nullptr); /** * Same as above but allows one to define the movie by QMovie that should * be used for the system tray icon. Memory management for the movie will * be handled by KSystemTrayIcon. */ - explicit KSystemTrayIcon(QMovie *movie, QWidget *parent); + KDELIBS4SUPPORT_DEPRECATED explicit KSystemTrayIcon(QMovie *movie, QWidget *parent); /** * Destructor */ ~KSystemTrayIcon(); /** * Set the movie to use. To manipulate the movie (start, stop, pause), call * @see movie() and make calls on the QMovie* that it returns. * Memory management for the movie will be handled by KSystemTrayIcon. * @since 4.2 */ void setMovie(QMovie *movie); /** * Get a pointer to the movie. Use this pointer to manipulate the movie * (start, stop, pause). * Will return null if no movie has been set * @since 4.2 */ const QMovie *movie() const; /** Easy access to the actions in the context menu Currently includes KStandardAction::Quit and minimizeRestore */ KActionCollection *actionCollection(); /** Returns the QWidget set by the constructor */ QWidget *parentWidget() const; /** Function to be used from function handling closing of the window associated with the tray icon (i.e. QWidget::closeEvent(), KMainWindow::queryClose() or similar). When false is returned, the window closing should proceed normally, when true is returned, special systray-related handling should take place. */ bool parentWidgetTrayClose() const; /** * Loads an icon @p icon using the icon loader class of the given componentData @p componentData. * The icon is applied the panel effect as it should only be used to be shown in the * system tray. * It's commonly used in the form : systray->setPixmap( systray->loadIcon( "mysystray" ) ); */ static QIcon loadIcon(const QString &icon, const KComponentData &componentData = KComponentData::mainComponent()); /** * Sets the context menu title action to @p action. * The following code shows how to change the current title. * * QAction *titleAction = contextMenuTitle(); * titleAction->setText("New Title"); * setContextMenuTitle(titleAction); * * @since 4.1 */ void setContextMenuTitle(QAction *action); /** * Returns the context menu title action. * @since 4.1 */ QAction *contextMenuTitle() const; Q_SIGNALS: /** * Emitted when quit is selected in the menu. If you want to perform any other * action than to close the main application window please connect to this signal. */ void quitSelected(); public Q_SLOTS: void toggleActive(); private Q_SLOTS: void contextMenuAboutToShow(); void minimizeRestoreAction(); void maybeQuit(); void activateOrHide(QSystemTrayIcon::ActivationReason reasonCalled); private: void init(QWidget *); void minimizeRestore(bool restore); KSystemTrayIconPrivate *const d; Q_PRIVATE_SLOT(d, void _k_slotNewFrame()) }; #endif diff --git a/src/kdeui/ktabbar.h b/src/kdeui/ktabbar.h index b1d7f137..6a73d4b5 100644 --- a/src/kdeui/ktabbar.h +++ b/src/kdeui/ktabbar.h @@ -1,247 +1,247 @@ /* This file is part of the KDE libraries Copyright (C) 2003 Stephan Binner Copyright (C) 2003 Zack Rusin Copyright (C) 2009 Urs Wolfer 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 KTABBAR_H #define KTABBAR_H #include #include /** * A QTabBar with extended features. * * \image html ktabbar.png "KDE Tab Bar" */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KTabBar: public QTabBar //krazy:exclude=qclasses { Q_OBJECT public: /** * Creates a new tab bar. * * @param parent The parent widget. */ - explicit KTabBar(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KTabBar(QWidget *parent = nullptr); /** * Destroys the tab bar. */ virtual ~KTabBar(); /** * Sets the tab reordering enabled or disabled. If enabled, * the user can reorder the tabs by drag and drop the tab * headers with the middle mouse button. * * @deprecated Use QTabBar::setMovable() instead. * * Note, however, that QTabBar::setMovable(true) disables * dragging tabs out of the KTabBar (e.g., dragging the tab * URL from Konqueror to another application)! */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setTabReorderingEnabled(bool enable); #endif /** * Returns whether tab reordering is enabled. * * @deprecated Use QTabBar::isMovable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool isTabReorderingEnabled() const; #endif /** * If enabled, a close button is shown above the tab icon. * The signal KTabBar::closeRequest() is emitted, if the * close button has been clicked. Note that the tab must have * an icon to use this feature. * * @deprecated Use QTabBar::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setHoverCloseButton(bool); #endif /** @deprecated Use QTabBar::tabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool hoverCloseButton() const; #endif /** * If enabled, the close button cannot get clicked until a * minor delay has been passed. This prevents that user * accidentally closes a tab. * * @deprecated Use QTabBar::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setHoverCloseButtonDelayed(bool); #endif /** @deprecated Use QTabBar::tabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool hoverCloseButtonDelayed() const; #endif /** * If enabled, a close button is available for each tab. The * signal KTabBar::closeRequest() is emitted, if the close button * has been clicked. * * @since 4.1 * * @deprecated Use QTabBar::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setCloseButtonEnabled(bool); #endif /** * Returns true if the close button is shown on tabs. * * @since 4.1 * * @deprecated Use QTabBar::tabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool isCloseButtonEnabled() const; #endif /** * Sets the 'activate previous tab on close' feature enabled * or disabled. If enabled, as soon as you close a tab, the * previously selected tab is activated again. * * @deprecated Use QTabBar::setSelectionBehaviorOnRemove() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setTabCloseActivatePrevious(bool); #endif /** * Returns whether the 'activate previous tab on close' feature * is enabled. * * @deprecated Use QTabBar::selectionBehaviorOnRemove() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool tabCloseActivatePrevious() const; #endif /** * Selects the tab which has a tab header at * given @param position. * * @param position the coordinates of the tab */ int selectTab(const QPoint &position) const; Q_SIGNALS: /** * A right mouse button click was performed over the tab with the @param index. * The signal is emitted on the press of the mouse button. */ void contextMenu(int index, const QPoint &globalPos); /** * A right mouse button click was performed over the empty area on the tab bar. * The signal is emitted on the press of the mouse button. */ void emptyAreaContextMenu(const QPoint &globalPos); /** @deprecated use tabDoubleClicked(int) and newTabRequest() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void mouseDoubleClick(int); #endif /** * A double left mouse button click was performed over the tab with the @param index. * The signal is emitted on the second press of the mouse button, before the release. */ void tabDoubleClicked(int index); /** * A double left mouse button click was performed over the empty area on the tab bar. * The signal is emitted on the second press of the mouse button, before the release. */ void newTabRequest(); /** * A double middle mouse button click was performed over the tab with the @param index. * The signal is emitted on the release of the mouse button. */ void mouseMiddleClick(int index); void initiateDrag(int); void testCanDecode(const QDragMoveEvent *, bool &); void receivedDropEvent(int, QDropEvent *); /** * Used internally by KTabBar's/KTabWidget's middle-click tab moving mechanism. * Tells the KTabWidget which owns the KTabBar to move a tab. */ void moveTab(int, int); /** @deprecated Use QTabBar::tabCloseRequested(int) instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void closeRequest(int); #endif #ifndef QT_NO_WHEELEVENT void wheelDelta(int); #endif protected: void mouseDoubleClickEvent(QMouseEvent *event) Q_DECL_OVERRIDE; void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; #ifndef QT_NO_WHEELEVENT void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; #endif void dragEnterEvent(QDragEnterEvent *event) Q_DECL_OVERRIDE; void dragMoveEvent(QDragMoveEvent *event) Q_DECL_OVERRIDE; void dropEvent(QDropEvent *event) Q_DECL_OVERRIDE; void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; void leaveEvent(QEvent *event) Q_DECL_OVERRIDE; QSize tabSizeHint(int index) const Q_DECL_OVERRIDE; protected Q_SLOTS: /** @deprecated */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void closeButtonClicked(); #endif /** @deprecated */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void enableCloseButton(); #endif virtual void activateDragSwitchTab(); protected: void tabLayoutChange() Q_DECL_OVERRIDE; private: QPoint closeButtonPos(int tabIndex) const; QRect closeButtonRect(int tabIndex) const; private: class Private; Private *const d; }; #endif diff --git a/src/kdeui/ktabwidget.h b/src/kdeui/ktabwidget.h index 916e6acd..f7c6296e 100644 --- a/src/kdeui/ktabwidget.h +++ b/src/kdeui/ktabwidget.h @@ -1,422 +1,422 @@ /* This file is part of the KDE libraries Copyright (C) 2003 Stephan Binner Copyright (C) 2003 Zack Rusin Copyright (C) 2009 Urs Wolfer 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 KTABWIDGET_H #define KTABWIDGET_H #include #include class QTab; /** * \brief A widget containing multiple tabs * * It extends the Qt QTabWidget, providing extra optionally features such as close buttons when you hover * over the icon in the tab, and also adds functionality such as responding to mouse wheel scroll events to switch * the active tab. * * It is recommended to use KTabWidget instead of QTabWidget unless you have a good reason not to. * * See also the QTabWidget documentation. * * \image html ktabwidget.png "KDE Tab Widget" */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KTabWidget : public QTabWidget //krazy:exclude=qclasses { Q_OBJECT #ifndef KDELIBS4SUPPORT_NO_DEPRECATED Q_PROPERTY(bool tabReorderingEnabled READ isTabReorderingEnabled WRITE setTabReorderingEnabled) Q_PROPERTY(bool hoverCloseButton READ hoverCloseButton WRITE setHoverCloseButton) Q_PROPERTY(bool hoverCloseButtonDelayed READ hoverCloseButtonDelayed WRITE setHoverCloseButtonDelayed) Q_PROPERTY(bool closeButtonEnabled READ isCloseButtonEnabled WRITE setCloseButtonEnabled) Q_PROPERTY(bool tabCloseActivatePrevious READ tabCloseActivatePrevious WRITE setTabCloseActivatePrevious) #endif Q_PROPERTY(bool automaticResizeTabs READ automaticResizeTabs WRITE setAutomaticResizeTabs) public: /** * Creates a new tab widget. * * @param parent The parent widgets. * @param flags The Qt window flags @see QWidget. */ - explicit KTabWidget(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr); + KDELIBS4SUPPORT_DEPRECATED KDELIBS4SUPPORT_DEPRECATED explicit KTabWidget(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr); /** * Destroys the tab widget. */ virtual ~KTabWidget(); /** * Set the tab of the given widget to \a color. * This is simply a convenience method for QTabBar::setTabTextColor. */ void setTabTextColor(int index, const QColor &color); /** * Returns the tab color for the given widget. * This is simply a convenience method for QTabBar::tabTextColor. */ QColor tabTextColor(int index) const; /** * Returns true if tab ordering with the middle mouse button * has been enabled. * * @deprecated Use QTabWidget::isMovable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool isTabReorderingEnabled() const; #endif /** * Returns true if the close button is shown on tabs * when mouse is hovering over them. * * @deprecated Use QTabWidget::tabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool hoverCloseButton() const; #endif /** * Returns true if the close button is shown on tabs * after a delay. * * @deprecated Use QTabWidget::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool hoverCloseButtonDelayed() const; #endif /** * Returns true if the close button is shown on tabs. * * @since 4.1 * * @deprecated Use QTabWidget::tabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool isCloseButtonEnabled() const; #endif /** * Returns true if closing the current tab activates the previous * actice tab instead of the one to the right. * * @deprecated Use tabBar()->selectionBehaviorOnRemove() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool tabCloseActivatePrevious() const; #endif /** * Returns true if calling setTitle() will resize tabs * to the width of the tab bar. */ bool automaticResizeTabs() const; /** * If \a hide is true, the tabbar is hidden along with any corner * widgets. * * @deprecated since 5.0, use tabBar()->hide() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void setTabBarHidden(bool hide); #endif /** * Returns true if the tabbar was hidden by a call to setTabBarHidden( true ). * Returns false if the widget itself is hidden, but no call to setTabBarHidden( true ) * has been made. * * @deprecated since 5.0, use tabBar()->isHidden() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED bool isTabBarHidden() const; #endif /** Reimplemented for internal reasons. * virtual void insertTab( QWidget *, const QString &, int index = -1 ); *! Reimplemented for internal reasons. * virtual void insertTab( QWidget *child, const QIcon& iconset, const QString &label, int index = -1 ); *! Reimplemented for internal reasons. * virtual void insertTab( QWidget *, QTab *, int index = -1 );*/ /** * Reimplemented for internal reasons. */ QString tabText(int) const; // but it's not virtual... #ifdef KDE3_SUPPORT /** * @deprecated use tabText */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED inline KDELIBS4SUPPORT_DEPRECATED QString label(int index) const { return tabText(index); } #endif /** * @deprecated use tabText */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED inline KDELIBS4SUPPORT_DEPRECATED QString tabLabel(QWidget *w) const { return tabText(indexOf(w)); } #endif /** * @deprecated use setTabText */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED inline KDELIBS4SUPPORT_DEPRECATED void setTabLabel(QWidget *w, const QString &l) { setTabText(indexOf(w), l); } #endif #endif /** * Reimplemented for internal reasons. */ void setTabText(int, const QString &); using QTabWidget::tabBar; public Q_SLOTS: /** * Move a widget's tab from first to second specified index and emit * signal movedTab( int, int ) afterwards. */ virtual void moveTab(int, int); /** * Removes the widget, reimplemented for * internal reasons (keeping labels in sync). * @deprecated since 4.0 */ virtual QT_MOC_COMPAT void removePage(QWidget *w); /** * Removes the widget, reimplemented for * internal reasons (keeping labels in sync). */ virtual void removeTab(int index); // but it's not virtual in QTabWidget... /** * If \a enable is true, tab reordering with middle button will be enabled. * * Note that once enabled you shouldn't rely on previously queried * currentPageIndex() or indexOf( QWidget * ) values anymore. * * You can connect to signal movedTab(int, int) which will notify * you from which index to which index a tab has been moved. * * @deprecated Use QTabWidget::setMovable() instead. * * Note, however, that QTabWidget::setMovable(true) disables * dragging tabs out of the KTabBar (e.g., dragging the tab * URL from Konqueror to another application)! */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void setTabReorderingEnabled(bool enable); #endif /** * If \a enable is true, a close button will be shown on mouse hover * over tab icons which will emit signal closeRequest( QWidget * ) * when pressed. * * @deprecated Use QTabWidget::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void setHoverCloseButton(bool enable); #endif /** * If \a delayed is true, a close button will be shown on mouse hover * over tab icons after mouse double click delay else immediately. * * @deprecated Use QTabWidget::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void setHoverCloseButtonDelayed(bool delayed); #endif /** * If enabled, a close button is available for each tab. The * signal KTabWidget::closeRequest() is emitted, if the close button * has been clicked. * * @since 4.1 * * @deprecated Use QTabWidget::setTabsClosable() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void setCloseButtonEnabled(bool); #endif /** * If \a previous is true, closing the current tab activates the * previous active tab instead of the one to the right. * * @deprecated Use tabBar()->setSelectionBehaviorOnRemove() instead. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED QT_MOC_COMPAT void setTabCloseActivatePrevious(bool previous); #endif /** * If \a enable is true, tabs will be resized to the width of the tab bar. * * Does not work reliably with "QTabWidget* foo=new KTabWidget()" and if * you change tabs via the tabbar or by accessing tabs directly. */ void setAutomaticResizeTabs(bool enable); Q_SIGNALS: /** * Connect to this and set accept to true if you can and want to decode the event. */ void testCanDecode(const QDragMoveEvent *e, bool &accept /* result */); /** * Received an event in the empty space beside tabbar. Usually creates a new tab. * This signal is only possible after testCanDecode and positive accept result. */ void receivedDropEvent(QDropEvent *); /** * Received an drop event on given widget's tab. * This signal is only possible after testCanDecode and positive accept result. */ void receivedDropEvent(QWidget *, QDropEvent *); /** * Request to start a drag operation on the given tab. */ void initiateDrag(QWidget *); /** * The right mouse button was pressed over empty space besides tabbar. */ void contextMenu(const QPoint &); /** * The right mouse button was pressed over a widget. */ void contextMenu(QWidget *, const QPoint &); #ifndef KDELIBS4SUPPORT_NO_DEPRECATED /** * A tab was moved from first to second index. This signal is only * possible after you have called setTabReorderingEnabled( true ). */ void movedTab(int, int); #endif /** * A double left mouse button click was performed over empty space besides tabbar. * The signal is emitted on the second press of the mouse button, before the release. */ void mouseDoubleClick(); /** * A double left mouse button click was performed over the widget. * The signal is emitted on the second press of the mouse button, before the release. */ void mouseDoubleClick(QWidget *); /** * A middle mouse button click was performed over empty space besides tabbar. * The signal is emitted on the release of the mouse button. */ void mouseMiddleClick(); /** * A middle mouse button click was performed over the widget. * The signal is emitted on the release of the mouse button. */ void mouseMiddleClick(QWidget *); /** * The close button of a widget's tab was clicked. This signal is * only possible after you have called setCloseButtonEnabled( true ). */ void closeRequest(QWidget *); protected: void mouseDoubleClickEvent(QMouseEvent *) Q_DECL_OVERRIDE; void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE; void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE; void dragMoveEvent(QDragMoveEvent *) Q_DECL_OVERRIDE; void dropEvent(QDropEvent *) Q_DECL_OVERRIDE; int tabBarWidthForMaxChars(int); #ifndef QT_NO_WHEELEVENT void wheelEvent(QWheelEvent *) Q_DECL_OVERRIDE; #endif void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; void tabInserted(int) Q_DECL_OVERRIDE; void tabRemoved(int) Q_DECL_OVERRIDE; /** * @deprecated This method has no effect and should not be called */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED void currentChanged(int); #endif protected Q_SLOTS: virtual void receivedDropEvent(int, QDropEvent *); virtual void initiateDrag(int); virtual void contextMenu(int, const QPoint &); virtual void mouseDoubleClick(int); virtual void mouseMiddleClick(int); virtual void closeRequest(int); #ifndef QT_NO_WHEELEVENT virtual void wheelDelta(int); #endif private: class Private; Private *const d; Q_PRIVATE_SLOT(d, void slotTabMoved(int, int)) }; #endif diff --git a/src/kdeui/ktextbrowser.h b/src/kdeui/ktextbrowser.h index c89665df..760fd894 100644 --- a/src/kdeui/ktextbrowser.h +++ b/src/kdeui/ktextbrowser.h @@ -1,141 +1,141 @@ /* This file is part of the KDE Libraries * Copyright (C) 1999 Espen Sand (espensa@online.no) * Copyright (C) 2006 Urs Wolfer * * 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 KTEXTBROWSER_H #define KTEXTBROWSER_H #include #include /** * @deprecated since 5.0, use QTextBrowser instead * * @brief Extended QTextBrowser. * * Porting from KTextBrowser to QTextBrowser: * - setNotifyClick becomes setOpenLinks, isNotifyClick is set to openLinks. * - use the signal QTextBrowser::anchorClicked for KTextBrowser::urlClick * * By default KTextBrowser will * invoke the system mailer or the system browser when a link is * activated, or it can emit the signal urlClick() or mailClick() * when a link is activated. * * If the link starts with the text "whatsthis:" a QWhatsThis * box will appear and then display the rest of the text. * * @warning The "whatsthis:" feature is considered deprecated: it is not * available in KDE Frameworks 5, because KDE Frameworks 5 does * not provide KTextBrowser anymore. * * \image html ktextbrowser.png "KDE Text Browser" * * @author Espen Sand (espensa@online.no) * * @see QTextBrowser */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KTextBrowser : public QTextBrowser { Q_OBJECT Q_PROPERTY(bool notifyClick READ isNotifyClick WRITE setNotifyClick) public: /** * Creates a new text browser. * * @param parent Parent of the widget. * @param notifyClick @p true causes signals to be emitted. */ - explicit KTextBrowser(QWidget *parent = nullptr, bool notifyClick = false); + KDELIBS4SUPPORT_DEPRECATED explicit KTextBrowser(QWidget *parent = nullptr, bool notifyClick = false); /** * Destroys the text browser. */ ~KTextBrowser(); /** * Decide whether a click on a link should be handled internally * or if a signal should be emitted. * * @param notifyClick @p true causes signals to be emitted. */ void setNotifyClick(bool notifyClick); /** * Returns whether a click on a link should be handled internally * or if a signal should be emitted. */ bool isNotifyClick() const; protected: /** * Reimplemented to NOT set the source but to do the special handling * of links being clicked. Do not call this. * * If you need to set an initial source url in the text browser, call - * the QTextBrowser method explicitly, like this: + * the QTextBrowser method KDELIBS4SUPPORT_DEPRECATED explicitly, like this: * myTextBrowser->QTextBrowser::setSource(url) */ void setSource(const QUrl &name) Q_DECL_OVERRIDE; /** * Makes sure Key_Escape is ignored */ void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE; /** * Reimplemented to support Qt2 behavior (Ctrl-Wheel = fast scroll) */ void wheelEvent(QWheelEvent *event) Q_DECL_OVERRIDE; /** * Re-implemented for internal reasons. API not affected. * * See QLineEdit::createPopupMenu(). */ void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE; Q_SIGNALS: /** * Emitted when a mail link has been activated and the widget has * been configured to emit the signal. * * @param name The destination name. It is QString() at the moment. * @param address The destination address. */ void mailClick(const QString &name, const QString &address); /** * Emitted if mailClick() is not emitted and the widget has been * configured to emit the signal. * * @param url The destination address. */ void urlClick(const QString &url); private: class Private; Private *const d; }; #endif diff --git a/src/kdeui/kuniqueapplication.h b/src/kdeui/kuniqueapplication.h index 88125f48..c675d1de 100644 --- a/src/kdeui/kuniqueapplication.h +++ b/src/kdeui/kuniqueapplication.h @@ -1,208 +1,208 @@ /* This file is part of the KDE libraries Copyright (c) 1999 Preston Brown Copyright (c) 2000-2001 Waldo Bastian 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 KUNIQUEAPP_H #define KUNIQUEAPP_H #include #include /** * KUniqueApplication is a KApplication which only uses a single process. When * a KUniqueApplication is started, it attempts to contact an existing copy * of the application. If successful, the program asks the * existing process to create a new instance by calling its newInstance() method * and then exits. If there is no existing process then the program forks and * calls the newInstance() method. When newInstance() is called, the application * will typically create a new window or activate an existing one. * * Instances of KUniqueApplication can be made to behave like a normal application by passing * the StartFlag::NonUniqueInstance flag to start(). * * Please note that this supports only one process per KDE session. If * your application can only be opened once per user or once per host, you * need to ensure this independently of KUniqueApplication. * * The .desktop file for the application should state X-DBUS-StartupType=Unique, * see ktoolinvocation.h * * If you use command line options before start() is called, you MUST call addCmdLineOptions() * so that the KUniqueApplication-specific command-line options can still work. * * If your application is used to open files, it should also support the --tempfile * option (see KCmdLineArgs::addTempFileOption()), to delete tempfiles after use. * Add X-KDE-HasTempFileOption=true to the .desktop file to indicate this. * * @see KApplication * @author Preston Brown */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KUniqueApplication : public KApplication { Q_OBJECT public: /** * Constructor. Takes command line arguments from KCmdLineArgs * * @param GUIenabled Set to false to disable all GUI stuff. This implies * no styles either. * @param configUnique If true, the uniqueness of the application will * depend on the value of the "MultipleInstances" * key in the "KDE" group of the application config file. */ - explicit KUniqueApplication(bool GUIenabled = true, + KDELIBS4SUPPORT_DEPRECATED explicit KUniqueApplication(bool GUIenabled = true, bool configUnique = false); /** * Adds command line options specific for KUniqueApplication. * * Should be called before calling KUniqueApplication constructor * and / or start(). */ static void addCmdLineOptions(); /** * These flags can be used to specify how new instances of * unique applications are created. */ enum StartFlag { /** * Create a new instance of the application in a new process and * do not attempt to re-use an existing process. * * With this flag set, the new instance of the application will * behave as if it were a plain KApplication rather than a KUniqueApplication. * * This is useful if you have an application where all instances are typically run * in a single process but under certain circumstances new instances may require * their own process. */ NonUniqueInstance = 0x1 }; Q_DECLARE_FLAGS(StartFlags, StartFlag) /** * Forks and registers with D-Bus. * * The command line arguments are being sent via D-Bus to newInstance() * and will be received once the application enters the event loop. * * Typically this is used like: * \code * int main(int argc, char **argv) { * KAboutData about("myappname", 0, ki18n("myAppName"), .....); * KCmdLineArgs::init(argc, argv, &about); * KCmdLineArgs::addCmdLineOptions( myCmdOptions ); * KUniqueApplication::addCmdLineOptions(); * * if (!KUniqueApplication::start()) { * fprintf(stderr, "myAppName is already running!\n"); * return 0; * } * KUniqueApplication a; * return a.exec(); * } * \endcode - * Note that it's not necessary to call start() explicitly. It will be + * Note that it's not necessary to call start() KDELIBS4SUPPORT_DEPRECATED explicitly. It will be * called automatically before creating KUniqueApplication if it hasn't * been called yet, without any performance impact. * * Also note that you MUST call KUniqueApplication::addCmdLineOptions(), * if you use command line options before start() is called. * * @param flags Optional flags which control how a new instance * of the application is started. * @return true if registration is successful. * false if another process was already running. */ static bool start(StartFlags flags); // BIC: merge with start(StartFlags flags = StartFlags()) static bool start(); /** * Destructor */ virtual ~KUniqueApplication(); /** * Creates a new "instance" of the application. * * Usually this will involve making some calls into the GUI portion of your * application asking for a new window to be created, possibly with * some data already loaded based on the arguments received. * * Command line arguments have been passed to KCmdLineArgs before this * function is called and can be checked in the usual way. * * The default implementation ensures the mainwindow of the already * running instance is shown and activated if necessary. If your * application has only one mainwindow, you should call this default * implementation and only add your special handling if needed. * * Note that newInstance() is called also in the first started * application process. * * For applications that share one process for several mainwindows, * the reimplementation could be: * \code int MyApp::newInstance() { KCmdLineArgs::setCwd(QDir::currentPath().toUtf8()); KCmdLineArgs* args = KCmdLineArgs::parsedArgs(); static bool first = true; if (args->count() > 0) { for (int i = 0; i < args->count(); ++i) { openWindow(args->url(i)); } } else if( !first || !isSessionRestored()) { openWindow(KUrl()); // create a new window } first = false; args->clear(); return 0; } * \endcode * * @return An exit value. The calling process will exit with this value. */ virtual int newInstance(); /** * Returns whether newInstance() is being called while session * restoration is in progress. */ bool restoringSession(); /** * @internal */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED static void setHandleAutoStarted(); #endif private: friend class KUniqueApplicationAdaptor; class Private; Private *const d; Q_PRIVATE_SLOT(d, void _k_newInstanceNoFork()) }; Q_DECLARE_OPERATORS_FOR_FLAGS(KUniqueApplication::StartFlags) #endif diff --git a/src/kdeui/kvbox.h b/src/kdeui/kvbox.h index 53a230e2..d33f0426 100644 --- a/src/kdeui/kvbox.h +++ b/src/kdeui/kvbox.h @@ -1,61 +1,61 @@ /* This file is part of the KDE libraries Copyright (C) 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 KVBOX_H #define KVBOX_H #include /** * A container widget which arranges its children vertically. * When using a KVBox you don't need to create a layout nor * to add the child widgets to it. * * Both margin and spacing are initialized to 0. Use QVBoxLayout * if you need standard layout margins. * * \image html kvbox.png "KDE Vertical Box containing three buttons" * * @see KHBox */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KVBox : public KHBox { Q_OBJECT public: /** * Creates a new vbox. * * @param parent The parent widget. */ - explicit KVBox(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KVBox(QWidget *parent = nullptr); /** * Destructor. */ ~KVBox(); private: class Private; friend class Private; Private *const d; Q_DISABLE_COPY(KVBox) }; #endif diff --git a/src/kdeui/kxerrorhandler.h b/src/kdeui/kxerrorhandler.h index c849b0a6..28ac221b 100644 --- a/src/kdeui/kxerrorhandler.h +++ b/src/kdeui/kxerrorhandler.h @@ -1,121 +1,121 @@ /* Copyright (c) 2003 Lubos Lunak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef KXERRORHANDLER_H #define KXERRORHANDLER_H #include #include #include #include class KXErrorHandlerPrivate; /** * This class simplifies handling of X errors. It shouldn't be necessary to use * with Qt classes, as the toolkit should handle X errors itself, so this * class will be mainly used with direct Xlib usage, and some lowlevel classes * like NETWinInfo. * * The usual usage is to create a KXErrorHandler instance right before starting * operations that might cause X errors, and checking if there was an error * by calling error() after the operations are finished. The handlers * may be nested, but must be destroyed in reverse order they were created. * * There's no need to do X sync before creating an instance, every instance * will handle only errors for request issued after the instance was created. * Errors for older requests will be passed to previous error handler. * When checking for error by calling error() at the end, it is necessary * to sync with X, to catch all errors that were caused by requests issued * before the call to error(). This can be done by passing true to error() - * to cause explicit XSync(), however, if the last X request needed a roundtrip + * to cause KDELIBS4SUPPORT_DEPRECATED explicit XSync(), however, if the last X request needed a roundtrip * (e.g. XGetWindowAttributes(), XGetGeometry(), etc.), it is not required - * to do an explicit sync. + * to do an KDELIBS4SUPPORT_DEPRECATED explicit sync. * * @author Lubos Lunak * @short Handler for X errors */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KXErrorHandler { public: /** This function simply wraps QX11Info::display(), to make sure the public interface doesn't require QtX11Extras */ static Display *display(); /** * Creates error handler that will set error flag after encountering * any X error. */ - explicit KXErrorHandler(Display *dpy = display()); + KDELIBS4SUPPORT_DEPRECATED explicit KXErrorHandler(Display *dpy = display()); /** * This constructor takes pointer to a function whose prototype matches * the one that's used with the XSetErrorHandler() Xlib function. * NOTE: For the error flag to be set, the function must return a non-zero * value. */ - explicit KXErrorHandler(int (*handler)(Display *, XErrorEvent *), Display *dpy = display()); + KDELIBS4SUPPORT_DEPRECATED explicit KXErrorHandler(int (*handler)(Display *, XErrorEvent *), Display *dpy = display()); /** * This constructor takes pointer to a function that will get request number, * error code number and resource id of the failed request, as provided * by XErrorEvent. If the function returns true, the error flag will be set. * @deprecated Use the variant with XErrorEvent. */ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED - explicit KXErrorHandler(bool (*handler)(int request, int error_code, unsigned long resource_id), Display *dpy = display()) KDELIBS4SUPPORT_DEPRECATED; + KDELIBS4SUPPORT_DEPRECATED explicit KXErrorHandler(bool (*handler)(int request, int error_code, unsigned long resource_id), Display *dpy = display()) KDELIBS4SUPPORT_DEPRECATED; #endif /** * This function returns true if the error flag is set (i.e. no custom handler * function was used and there was any error, or the custom handler indicated * an error by its return value). * - * @param sync if true, an explicit XSync() will be done. Not necessary + * @param sync if true, an KDELIBS4SUPPORT_DEPRECATED explicit XSync() will be done. Not necessary * when the last X request required a roundtrip. */ bool error(bool sync) const; /** * This function returns the error event for the first X error that occurred. * The return value is useful only if error() returned true. * @since 4.0.1 */ XErrorEvent errorEvent() const; /** * Returns error message for the given error. The error message is not translated, * as it is meant for debugging. * @since 4.0.1 */ static QByteArray errorMessage(const XErrorEvent &e, Display *dpy = display()); ~KXErrorHandler(); private: void addHandler(); int handle(Display *dpy, XErrorEvent *e); bool (*user_handler1)(int request, int error_code, unsigned long resource_id); int (*user_handler2)(Display *, XErrorEvent *); int (*old_handler)(Display *, XErrorEvent *); static int handler_wrapper(Display *, XErrorEvent *); static KXErrorHandler **handlers; static int pos; static int size; Q_DISABLE_COPY(KXErrorHandler) KXErrorHandlerPrivate *const d; }; #endif diff --git a/src/kio/kcommentwidget_p.h b/src/kio/kcommentwidget_p.h index 4339fc1e..eec0a690 100644 --- a/src/kio/kcommentwidget_p.h +++ b/src/kio/kcommentwidget_p.h @@ -1,69 +1,69 @@ /***************************************************************************** * Copyright (C) 2008 by Sebastian Trueg * * Copyright (C) 2009 by Peter Penz * * * * 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 KCOMMENT_WIDGET #define KCOMMENT_WIDGET #include #include class QLabel; /** * @brief Allows to edit and show a comment as part of KMetaDataWidget. */ class KCommentWidget : public QWidget { Q_OBJECT public: - explicit KCommentWidget(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KCommentWidget(QWidget *parent = nullptr); virtual ~KCommentWidget(); void setText(const QString &comment); QString text() const; /** * If set to true, the comment cannot be changed by the user. * Per default read-only is disabled. */ // TODO: provide common interface class for metadatawidgets void setReadOnly(bool readOnly); bool isReadOnly() const; QSize sizeHint() const Q_DECL_OVERRIDE; Q_SIGNALS: void commentChanged(const QString &comment); protected: bool event(QEvent *event) Q_DECL_OVERRIDE; private Q_SLOTS: void slotLinkActivated(const QString &link); private: bool m_readOnly; QLabel *m_label; QLabel *m_sizeHintHelper; // see comment in KCommentWidget::sizeHint() QString m_comment; }; #endif diff --git a/src/kio/kdevicelistmodel.h b/src/kio/kdevicelistmodel.h index bc68ed29..5c30b7c7 100644 --- a/src/kio/kdevicelistmodel.h +++ b/src/kio/kdevicelistmodel.h @@ -1,109 +1,109 @@ /* This file is part of the KDE project Copyright (C) 2006 Michael Larouche 2007 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 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 KDEVICELISTMODEL_H #define KDEVICELISTMODEL_H #include #include #include #include /** * @brief Device list model in Qt's Interview framework. * * This class is a tree view model. Each device has a parent * excluding the main device(the computer). Only revelant when * used with QTreeView. * * @author Michaël Larouche */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDeviceListModel : public QAbstractItemModel { Q_OBJECT public: - explicit KDeviceListModel(QObject *parent = nullptr); - explicit KDeviceListModel(const QString &predicate, QObject *parent = nullptr); - explicit KDeviceListModel(const Solid::Predicate &predicate, + KDELIBS4SUPPORT_DEPRECATED explicit KDeviceListModel(QObject *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDeviceListModel(const QString &predicate, QObject *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDeviceListModel(const Solid::Predicate &predicate, QObject *parent = nullptr); ~KDeviceListModel(); /** * @brief Get a visible data based on Qt role for the given index. * Return the device information for the give index. * * @param index The QModelIndex which contains the row, column to fetch the data. * @param role The Interview data role(ex: Qt::DisplayRole). * * @return the data for the given index and role. */ QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; /** * @brief Get the header data for a given section, orientation and role. * This method return a value to display in header in a view. * Only support Qt::Horizontal direction and Qt::DisplayRole role. * * @param section Section of Header to get the data of. * @param orientation Orientation of the header. * @param role The Interview data role(ex: Qt::DisplayRole). * * @return the header data for the given section. */ QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; /** * @brief Get the children model index for the given row and column. */ QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; QModelIndex rootIndex() const; /** * @brief Get the parent QModelIndex for the given model child. */ QModelIndex parent(const QModelIndex &child) const Q_DECL_OVERRIDE; /** * @brief Get the number of rows for a model index. */ int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; /** * @brief Get the number of columns for a model index. */ int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; Solid::Device deviceForIndex(const QModelIndex &index) const; Q_SIGNALS: void modelInitialized(); private: Q_PRIVATE_SLOT(d, void _k_initDeviceList()) Q_PRIVATE_SLOT(d, void _k_deviceAdded(const QString &)) Q_PRIVATE_SLOT(d, void _k_deviceRemoved(const QString &)) class Private; Private *const d; }; #endif diff --git a/src/kio/kdirselectdialog.h b/src/kio/kdirselectdialog.h index d8d90270..568c47be 100644 --- a/src/kio/kdirselectdialog.h +++ b/src/kio/kdirselectdialog.h @@ -1,126 +1,126 @@ /* Copyright (C) 2001 Michael Jarrett Copyright (C) 2001 Carsten Pfeiffer Copyright (C) 2009 Shaun Reich 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 KDIRSELECTDIALOG_H #define KDIRSELECTDIALOG_H #include #include #include class QAbstractItemView; /** * A pretty dialog for a KDirSelect control for selecting directories. * @author Michael Jarrett * @deprecated since 5.0, use QFileDialog::getExistingDirectoryUrl instead. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDirSelectDialog : public QDialog { Q_OBJECT public: /** * Creates a new directory selection dialog. * @internal use the static selectDirectory function * @param startDir the directory, initially shown * @param localOnly unused. You can only select paths below the startDir * @param parent the parent for the dialog, usually 0L */ - explicit KDirSelectDialog(const QUrl &startDir = QUrl(), + KDELIBS4SUPPORT_DEPRECATED explicit KDirSelectDialog(const QUrl &startDir = QUrl(), bool localOnly = false, QWidget *parent = nullptr); /** * Destroys the directory selection dialog. */ ~KDirSelectDialog(); /** * Returns the currently selected URL, or an empty one if no item is selected. * * If the URL entered in the combobox is valid and exists, it is returned. * Otherwise, the URL selected in the treeview is returned instead. */ QUrl url() const; /** * Returns a pointer to the view which is used for displaying the directories. */ QAbstractItemView *view() const; /** * Returns whether only local directories can be selected. */ bool localOnly() const; /** * Creates a KDirSelectDialog, and returns the result. * @param startDir the directory, initially shown * The tree will display this directory and subdirectories of it. * @param localOnly unused. You can only select paths below the startDir * @param parent the parent widget to use for the dialog, or NULL to create a parent-less dialog * @param caption the caption to use for the dialog, or QString() for the default caption * @return The URL selected, or an empty URL if the user canceled * or no URL was selected. * * @deprecated since 5.0, use QFileDialog::getExistingDirectory (if localOnly was true) * or QFileDialog::getExistingDirectoryUrl (if localOnly was false) instead. */ static KDELIBS4SUPPORT_DEPRECATED QUrl selectDirectory(const QUrl &startDir = QUrl(), bool localOnly = false, QWidget *parent = nullptr, const QString &caption = QString()); /** * @return The path for the root node */ QUrl startDir() const; public Q_SLOTS: /** * Sets the current @p url in the dialog. */ void setCurrentUrl(const QUrl &url); protected: void accept() Q_DECL_OVERRIDE; /** * Reimplemented for saving the dialog geometry. */ void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE; private: class Private; Private *const d; Q_PRIVATE_SLOT(d, void slotCurrentChanged()) Q_PRIVATE_SLOT(d, void slotExpand(const QModelIndex &)) Q_PRIVATE_SLOT(d, void slotUrlActivated(const QString &)) Q_PRIVATE_SLOT(d, void slotComboTextChanged(const QString &)) Q_PRIVATE_SLOT(d, void slotContextMenuRequested(const QPoint &)) Q_PRIVATE_SLOT(d, void slotNewFolder()) Q_PRIVATE_SLOT(d, void slotMoveToTrash()) Q_PRIVATE_SLOT(d, void slotDelete()) Q_PRIVATE_SLOT(d, void slotProperties()) }; #endif diff --git a/src/kio/kdiskfreespace.h b/src/kio/kdiskfreespace.h index 1388e893..fcfff56b 100644 --- a/src/kio/kdiskfreespace.h +++ b/src/kio/kdiskfreespace.h @@ -1,95 +1,95 @@ /* * kdiskfreespace.h * * Copyright 2007 David Faure * Copyright 2008 Dirk Mueller * * 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 KDISKFREESP_H #define KDISKFREESP_H #include #include #include /** * \deprecated Use KDiskFreeSpaceInfo */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KDiskFreeSpace : public QObject { Q_OBJECT public: /** * Constructor */ - explicit KDiskFreeSpace(QObject *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KDiskFreeSpace(QObject *parent = nullptr); /** * Destructor - this object autodeletes itself when it's done */ ~KDiskFreeSpace(); /** * Call this to fire a search on the disk usage information * for @p mountPoint. * The foundMountPoint() signal will be emitted * if this mount point is found, with the info requested. * The done() signal is emitted in any case. * * @return true if the request could be handled, false if another * request is happening already. readDF() can only be called once * on a given instance of KDiskFreeSpace, given that it handles only * the request for one mount point and then auto-deletes itself. * Suicidal objects are not reusable... */ bool readDF(const QString &mountPoint); /** * Call this to fire a search on the disk usage information * for the mount point containing @p path. * The foundMountPoint() signal will be emitted * if this mount point is found, with the info requested. * The done() signal is emitted in any case. */ static KDiskFreeSpace *findUsageInfo(const QString &path); Q_SIGNALS: /** * Emitted when the information about the requested mount point was found. * @param mountPoint the requested mount point * @param kibSize the total size of the partition in KiB * @param kibUsed the amount of KiB being used on the partition * @param kibAvail the available space on the partition in KiB */ void foundMountPoint(const QString &mountPoint, quint64 kibSize, quint64 kibUsed, quint64 kibAvail); /** * Emitted when the request made via readDF is over, whether foundMountPoint was emitted or not. */ void done(); private: class Private; Private *const d; Q_PRIVATE_SLOT(d, bool _k_calculateFreeSpace()) }; #endif diff --git a/src/kio/kfilemetadataconfigurationwidget.h b/src/kio/kfilemetadataconfigurationwidget.h index 60fda8b2..6b774eb0 100644 --- a/src/kio/kfilemetadataconfigurationwidget.h +++ b/src/kio/kfilemetadataconfigurationwidget.h @@ -1,84 +1,84 @@ /***************************************************************************** * Copyright (C) 2009 by Peter Penz * * * * 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 KFILEMETADATACONFIGURATIONWIDGET_H #define KFILEMETADATACONFIGURATIONWIDGET_H #include #include #include /** * @deprecated since 4.12, use Nepomuk2::FileMetaDataConfigurationWidget * * @brief Widget which allows to configure which meta data should be shown * in the KFileMetaDataWidget. * * Note that the class is marked as internal and the API might change. * It is planned to make the class public in future KDE SC's, after the API has * been stabilized. * * @see KFileMetaDataWidget * @since 4.5 * @internal */ // TODO: A signal is required which indicates configuration changes. Otherwise // it would not be possible for an application developer to enable/disable an // "Apply" button of a dialog. class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFileMetaDataConfigurationWidget : public QWidget { Q_OBJECT public: - explicit KFileMetaDataConfigurationWidget(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KFileMetaDataConfigurationWidget(QWidget *parent = nullptr); virtual ~KFileMetaDataConfigurationWidget(); /** * Sets the items, for which the visibility of the meta data should * be configured. Note that the visibility of the meta data is not * bound to the items itself, the items are only used to determine * which meta data should be configurable. For example when a JPEG image * is set as item, it will be configurable which EXIF data should be * shown. If an audio file is set as item, it will be configurable * whether the artist, album name, ... should be shown. */ void setItems(const KFileItemList &items); KFileItemList items() const; /** * Saves the modified configuration. */ void save(); /** @see QWidget::sizeHint() */ QSize sizeHint() const Q_DECL_OVERRIDE; protected: bool event(QEvent *event) Q_DECL_OVERRIDE; private: class Private; Private *const d; Q_PRIVATE_SLOT(d, void loadMetaData()) Q_PRIVATE_SLOT(d, void slotLoadingFinished()) }; #endif diff --git a/src/kio/kfilemetadataprovider_p.h b/src/kio/kfilemetadataprovider_p.h index 31137b2d..deea46f7 100644 --- a/src/kio/kfilemetadataprovider_p.h +++ b/src/kio/kfilemetadataprovider_p.h @@ -1,142 +1,142 @@ /***************************************************************************** * Copyright (C) 2010 by Peter Penz * * * * 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 KFILEMETADATAMODEL_H #define KFILEMETADATAMODEL_H #include #include #include #include #if ! KIO_NO_NEPOMUK #define DISABLE_NEPOMUK_LEGACY #include #endif class KFileItemList; class QUrl; class QWidget; /** * @brief Provides the data for the KMetaDataWidget. * * The default implementation provides all meta data * that are available due to Strigi and Nepomuk. If custom * meta data should be added, the method KFileMetaDataProvider::loadData() * must be overwritten. * * @see KFileMetaDataWidget */ class KFileMetaDataProvider : public QObject { Q_OBJECT public: - explicit KFileMetaDataProvider(QObject *parent = 0); + KDELIBS4SUPPORT_DEPRECATED explicit KFileMetaDataProvider(QObject *parent = 0); virtual ~KFileMetaDataProvider(); /** * Sets the items, where the meta data should be * requested. The loading of the meta data is done * asynchronously. The signal loadingFinished() is * emitted, as soon as the loading has been finished. * The meta data can be retrieved by * KFileMetaDataProvider::data() afterwards. The label for * each item can be retrieved by KFileMetaDataProvider::label(). */ void setItems(const KFileItemList &items); KFileItemList items() const; /** * If set to true, data such as the comment, tag or rating cannot be changed by the user. * Per default read-only is disabled. The method readOnlyChanged() can be overwritten * to react on the change. */ void setReadOnly(bool readOnly); bool isReadOnly() const; /** * @return Translated string for the label of the meta data represented * by \p metaDataUri. If no custom translation is provided, the * base implementation must be invoked. */ virtual QString label(const QUrl &metaDataUri) const; /** * Meta data items are sorted alphabetically by their translated * label per default. However it is possible to provide an internal * prefix to the label, so that specific items are grouped together. * For example it makes sense that the meta data for 'width' and 'height' * of an image are shown below each other. By adding a common prefix, * a grouping is done. * @return Returns the name of the group the meta data indicated * by \p metaDataUri belongs to. Per default an empty string * is returned. */ virtual QString group(const QUrl &metaDataUri) const; #if ! KIO_NO_NEPOMUK /** * @return Meta data for the items that have been set by * KFileMetaDataProvider::setItems(). The method should * be invoked after the signal loadingFinished() has * been received (otherwise no data will be returned). */ virtual QHash data() const; /** * @return Factory method that returns a widget that should be used * to show the meta data represented by \p metaDataUri. If * no custom value widget is used for the given URI, the base * implementation must be invoked. Per default an instance * of QLabel will be returned. */ virtual QWidget *createValueWidget(const QUrl &metaDataUri, const Nepomuk::Variant &value, QWidget *parent) const; #endif Q_SIGNALS: /** * Is emitted after the loading triggered by KFileMetaDataProvider::setItems() * has been finished. */ void loadingFinished(); void urlActivated(const QUrl &url); void dataChangeStarted(); void dataChangeFinished(); private: class Private; Private *const d; Q_PRIVATE_SLOT(d, void slotLoadingFinished()) Q_PRIVATE_SLOT(d, void slotRatingChanged(unsigned int rating)) Q_PRIVATE_SLOT(d, void slotTagsChanged(const QList &tags)) Q_PRIVATE_SLOT(d, void slotCommentChanged(const QString &comment)) Q_PRIVATE_SLOT(d, void slotTagClicked(const Nepomuk::Tag &tag)) Q_PRIVATE_SLOT(d, void slotLinkActivated(const QString &)) friend class KLoadMetaDataThread; // invokes KMetaDataObject::loadData() }; #endif diff --git a/src/kio/kfilemetadatareader_p.h b/src/kio/kfilemetadatareader_p.h index 5f3225be..3bb34ac9 100644 --- a/src/kio/kfilemetadatareader_p.h +++ b/src/kio/kfilemetadatareader_p.h @@ -1,91 +1,91 @@ /***************************************************************************** * Copyright (C) 2011 by Peter Penz * * * * 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 KFILEMETADATAREADER_H #define KFILEMETADATAREADER_H #include #include #include #include #include #include #include /** * @brief Provides metadata extracted from files. * * The reading of the metadata is done asynchronously in a process. * This assures that the caller won't get blocked and also prevents * that the caller crashes in case if a metadata-analyzer plugin is instable. * * @since 4.7 * @internal */ class KFileMetaDataReader : public QObject { Q_OBJECT public: /** * @param urls List of files where the metadata should be extracted from. * @param parent Parent object. */ - explicit KFileMetaDataReader(const QList &urls, QObject *parent = 0); + KDELIBS4SUPPORT_DEPRECATED explicit KFileMetaDataReader(const QList &urls, QObject *parent = 0); virtual ~KFileMetaDataReader(); /** * If \p read is set to true also metadata that is persisted outside the * files itself (like e.g. rating, comments or tags) are read. Per * default the reading of context data is enabled. Pass false if only the metadata * persisted inside the file should be read. */ void setReadContextData(bool read); bool readContextData() const; /** * Starts the reading of the metadata inside a custom process. * The signal finished() will get emitted if the reading has been finished. * Use metaData() to access the read metadata. */ void start(); /** * @return The read metadata of the given files. The method provides valid values * after the signal finished() has been emitted. If it is invoked before * an empty hash-table will be returned. */ QHash metaData() const; Q_SIGNALS: /** * Is emitted if the reading of the metadata inside a custom process has been finished. * The method metaData() can be used afterwards to access the metadata. */ void finished(); private: class Private; Private *d; Q_PRIVATE_SLOT(d, void slotLoadingFinished(int, QProcess::ExitStatus)) }; #endif diff --git a/src/kio/kfilemetadatawidget.h b/src/kio/kfilemetadatawidget.h index 7b8597e2..4835b875 100644 --- a/src/kio/kfilemetadatawidget.h +++ b/src/kio/kfilemetadatawidget.h @@ -1,98 +1,98 @@ /***************************************************************************** * Copyright (C) 2008 by Sebastian Trueg * * Copyright (C) 2009-2010 by Peter Penz * * * * 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 KFILEMETADATAWIDGET_H #define KFILEMETADATAWIDGET_H #include #include #include #include /** * @deprecated since 4.12 use Nepomuk2::FileMetaDataWidget * * @brief Shows the meta data of one or more file items. * * Meta data like name, size, rating, comment, ... are * shown as several rows containing a description and * the meta data value. It is possible for the user * to change specific meta data like rating, tags and * comment. The changes are stored automatically by the * meta data widget. * * @since 4.5 */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFileMetaDataWidget : public QWidget { Q_OBJECT Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) public: - explicit KFileMetaDataWidget(QWidget *parent = nullptr); + KDELIBS4SUPPORT_DEPRECATED explicit KFileMetaDataWidget(QWidget *parent = nullptr); virtual ~KFileMetaDataWidget(); /** * Sets the items for which the meta data should be shown. * The signal metaDataRequestFinished() will be emitted, * as soon as the meta data for the items has been received. */ void setItems(const KFileItemList &items); KFileItemList items() const; /** * If set to true, data such as the comment, tag or rating cannot be * changed by the user. Per default read-only is disabled. */ void setReadOnly(bool readOnly); bool isReadOnly() const; /** @see QWidget::sizeHint() */ QSize sizeHint() const Q_DECL_OVERRIDE; Q_SIGNALS: /** * Is emitted, if a meta data represents an URL that has * been clicked by the user. */ void urlActivated(const QUrl &url); /** * Is emitted after the meta data has been received for the items * set by KFileMetaDataWidget::setItems(). * @since 4.6 */ void metaDataRequestFinished(const KFileItemList &items); protected: bool event(QEvent *event) Q_DECL_OVERRIDE; private: class Private; Private *d; Q_PRIVATE_SLOT(d, void slotLoadingFinished()) Q_PRIVATE_SLOT(d, void slotLinkActivated(QString)) Q_PRIVATE_SLOT(d, void slotDataChangeStarted()) Q_PRIVATE_SLOT(d, void slotDataChangeFinished()) }; #endif diff --git a/src/kio/kfilemetainfo.h b/src/kio/kfilemetainfo.h index 276580f0..2cc4008b 100644 --- a/src/kio/kfilemetainfo.h +++ b/src/kio/kfilemetainfo.h @@ -1,167 +1,167 @@ /* This file is part of the KDE libraries Copyright (c) 2001,2002 Carsten Pfeiffer 2007 Jos van den Oever This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License (LGPL) 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 KFILEMETAINFO_H #define KFILEMETAINFO_H #include "predicateproperties.h" #include "kfilemetainfoitem.h" #include #include #include class QUrl; typedef QList KFileMetaInfoItemList; class KFileMetaInfoGroupPrivate; class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFileMetaInfoGroup { public: KFileMetaInfoGroup(); KFileMetaInfoGroup(const KFileMetaInfoGroup &); ~KFileMetaInfoGroup(); const KFileMetaInfoGroup &operator=(const KFileMetaInfoGroup &); KFileMetaInfoItemList items() const; const QString &name() const; const QStringList &keys() const; private: QSharedDataPointer d; }; typedef QList KFileMetaInfoGroupList; class KFileMetaInfoPrivate; /** * KFileMetaInfo provides metadata extracted from a file or other resource. * * When instantiating an instance of this class, the metadata related to it * will be retrieved and stored in the instance. The data can be inspected * through KFileMetaInfoItem objects. **/ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFileMetaInfo { public: /** * This is used to specify what a KFileMetaInfo object should read, so * you can specify if you want to read "expensive" items or not. * This is like a preset which can be customized by passing additional * parameters to constructors. */ enum What { Fastest = 0x1, /**< do the fastest possible read and omit all items that might need a significantly longer time than the others */ // Deprecated // DontCare = 0x2, ///< let the plugin decide what to read. TechnicalInfo = 0x4, /**< extract technical details about the file, like e.g. play time, resolution or a compressioni type */ ContentInfo = 0x8, /**< read information about the content of the file like comments or id3 tags */ ExternalSources = 0x10, /** &items() const; KFileMetaInfoItem &item(const QString &key); const KFileMetaInfoItem &item(const QString &key) const; bool isValid() const; /** * Deprecated **/ QStringList preferredKeys() const; /** * Deprecated **/ QStringList supportedKeys() const; KDELIBS4SUPPORT_DEPRECATED_EXPORT friend QDataStream &operator >>(QDataStream &s, KFileMetaInfo &) ; KDELIBS4SUPPORT_DEPRECATED_EXPORT friend QDataStream &operator <<(QDataStream &s, const KFileMetaInfo &); /** * Deprecated **/ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED KFileMetaInfoGroupList preferredGroups() const; #endif /** * Deprecated **/ #ifndef KDELIBS4SUPPORT_NO_DEPRECATED KDELIBS4SUPPORT_DEPRECATED KFileMetaInfoGroupList supportedGroups() const; #endif KFileMetaInfoGroupList groups() const; QStringList keys() const; QUrl url() const; private: QSharedDataPointer d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KFileMetaInfo::WhatFlags) #endif diff --git a/src/kio/kfilemetainfowidget.h b/src/kio/kfilemetainfowidget.h index e4d214f2..8ba5c63e 100644 --- a/src/kio/kfilemetainfowidget.h +++ b/src/kio/kfilemetainfowidget.h @@ -1,93 +1,93 @@ /* This file is part of the KDE libraries Copyright (C) 2001,2002 Rolf Magnus 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 __KFILEMETAINFOWIDGET_H__ #define __KFILEMETAINFOWIDGET_H__ #include #include #include #include class KFileMetaInfoWidgetPrivate; /*! * @deprecated since 5.0 * A widget to display file meta information (like id3 for mp3) */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KFileMetaInfoWidget: public QWidget { Q_OBJECT public: enum Mode { ReadOnly = 1, ///Only display the meta information, and do not permit the user to edit them ReadWrite = 0, ///Permits user to edit the displayed meta-info Reserve = 0xff }; - explicit KFileMetaInfoWidget(KFileMetaInfoItem item, + KDELIBS4SUPPORT_DEPRECATED explicit KFileMetaInfoWidget(KFileMetaInfoItem item, QValidator *val = nullptr, QWidget *parent = nullptr); KFileMetaInfoWidget(KFileMetaInfoItem item, Mode mode, QValidator *val = nullptr, QWidget *parent = nullptr); virtual ~KFileMetaInfoWidget(); bool apply(); void setValue(const QVariant &value); QVariant value() const; QValidator *validator() const; KFileMetaInfoItem item() const; Q_SIGNALS: void valueChanged(const QVariant &value); protected: void reparentValidator(QWidget *widget, QValidator *validator); virtual QWidget *makeWidget(); QWidget *makeBoolWidget(); QWidget *makeIntWidget(); QWidget *makeDoubleWidget(); QWidget *makeStringWidget(); QWidget *makeDateWidget(); QWidget *makeTimeWidget(); QWidget *makeDateTimeWidget(); private Q_SLOTS: void slotChanged(bool value); void slotChanged(int value); void slotChanged(double value); void slotComboChanged(const QString &value); void slotLineEditChanged(const QString &value); void slotMultiLineEditChanged(); void slotDateChanged(const QDate &value); void slotTimeChanged(const QTime &value); void slotDateTimeChanged(const QDateTime &value); private: friend class KFileMetaInfoWidgetPrivate; KFileMetaInfoWidgetPrivate *const d; Q_DISABLE_COPY(KFileMetaInfoWidget) }; #endif diff --git a/src/kio/kscan.h b/src/kio/kscan.h index 74a0608e..5d045492 100644 --- a/src/kio/kscan.h +++ b/src/kio/kscan.h @@ -1,236 +1,236 @@ /* This file is part of the KDE libraries Copyright (C) 2001 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 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 KSCAN_H #define KSCAN_H #include #include #include class QByteArray; class QImage; /** * This is a base class for scanning dialogs. You can derive from this class * and implement your own dialog. An implementation is available in * kdegraphics/libkscan. * * Application developers that wish to add scanning support to their program * can use the static method @p KScanDialog::getScanDialog() to get an instance * of the user's preferred scanning dialog. * * Typical usage looks like this (e.g. in a slotShowScanDialog() method): * * \code * if ( !m_scanDialog ) { * m_scanDialog = KScanDialog::getScanDialog( this ); * if ( !m_scanDialog ) // no scanning support installed? * return; * * connect( m_scanDialog, SIGNAL( finalImage( const QImage&, int )), * SLOT( slotScanned( const QImage&, int ) )); * } * * if ( m_scanDialog->setup() ) // only if scanner configured/available * m_scanDialog->show(); * \endcode * * This will create and show a non-modal scanning dialog. Connect to more * signals if you like. * * @short A baseclass and accessor for Scanning Dialogs * @author Carsten Pfeiffer * @deprecated since 5.0, use libksane instead */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KScanDialog : public KPageDialog { Q_OBJECT public: /** * Creates the user's preferred scanning dialog and returns it, * or 0L if no scan-support * is available. Pass a suitable @p parent widget, if you like. If you * don't you have to 'delete' the returned pointer yourself. * @param parent the QWidget's parent, or 0 * @return the KScanDialog, or 0 if the function failed */ static KScanDialog *getScanDialog(QWidget *parent = nullptr); /** * Destructs the scan dialog. */ ~KScanDialog(); /** * Reimplement this if you need to set up some things, before showing the * dialog, e.g. to ask the user for the scanner device to use. If you * return false (e.g. there is no device available or the user aborted * device selection), the dialog will not be shown. * * @return true by default. */ virtual bool setup(); protected: /** * Constructs the scan dialog. If you implement an own dialog, you can * customize it with the usual KPageDialog flags. * * @param dialogFace The KPageDialog::FaceType * @param buttonMask An ORed mask of all buttons (see * QDialogButtonBox::StandardButton) * @param parent The QWidget's parent, or 0 * @see KPageDialog */ - explicit KScanDialog(int dialogFace = Tabbed, + KDELIBS4SUPPORT_DEPRECATED explicit KScanDialog(int dialogFace = Tabbed, int buttonMask = QDialogButtonBox::Close | QDialogButtonBox::Help, QWidget *parent = nullptr); /** * Returns the current id for an image. You can use that in your subclass * for the signals. The id is used in the signals to let people know * which preview and which text-recognition belongs to which scan. * * @return the current id for the image * @see nextId * @see finalImage * @see preview * @see textRecognized */ int id() const; /** * Returns the id for the next image. You can use that in your subclass * for the signals. * * @return the id for the next image * @see id * @see finalImage * @see preview * @see textRecognized * */ int nextId(); Q_SIGNALS: /** * Informs you that an image has been previewed. * @param img the image * @param id the image's id */ void preview(const QImage &img, int id); /** * Informs you that an image has scanned. @p id is the same as in the * @p preview() signal, if this image had been previewed before. * * Note, that those id's may not be properly implemented in the current * libkscan. * @param img the image * @param id the image's id */ void finalImage(const QImage &img, int id); /** * Informs you that the image with the id @p id has been run through * text-recognition. The text is in the QString parameter. In the future, * a compound document, using rich text will be used instead. * * @param text the text that has been recognized * @param id the id of the image */ void textRecognized(const QString &text, int id); private: class KScanDialogPrivate; KScanDialogPrivate *const d; }; /** * Base class for OCR Dialogs. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT KOCRDialog : public KPageDialog { Q_OBJECT public: /** * Creates the user's preferred OCR dialog and returns it, * or 0L if no OCR-support * is available. Pass a suitable @p parent widget, if you like. If you * don't you have to 'delete' the returned pointer yourself. * @param parent the QWidget's parent, or 0 * @return the KOCRDialog, or 0 if the function failed */ static KOCRDialog *getOCRDialog(QWidget *parent = nullptr); ~KOCRDialog(); protected: /** * Constructs the OCR dialog. If you implement an own dialog, you can * customize it with the usual KPageDialog flags. * * @param dialogFace the KPageDialog::FaceType * @param buttonMask a ORed mask of all buttons (see * KDialog::ButtonCode) * @param parent the QWidget's parent, or 0 * @param modal if true the dialog is model */ - explicit KOCRDialog(int dialogFace = Tabbed, int buttonMask = QDialogButtonBox::Close | QDialogButtonBox::Help, + KDELIBS4SUPPORT_DEPRECATED explicit KOCRDialog(int dialogFace = Tabbed, int buttonMask = QDialogButtonBox::Close | QDialogButtonBox::Help, QWidget *parent = nullptr, bool modal = false); /** * Returns the current id for an image. You can use that in your subclass * for the signals. The id is used in the signals to let people know * which text-recognition belongs to which scan. * * @return the current id for the image * @see nextId * @see textRecognized */ int id() const; /** * Returns the id for the next image. You can use that in your subclass * for the signals. * * @return the id for the next image * @see id * @see textRecognized */ int nextId(); Q_SIGNALS: /** * Informs you that the image with the id @p id has been run through * text-recognition. The text is in the QString parameter. In the future, * a compound document, using rich text will be used instead. * * @param text the text that has been recognized * @param id the id of the image */ void textRecognized(const QString &text, int id); private: class KOCRDialogPrivate; KOCRDialogPrivate *const d; }; #endif // KSCAN_H diff --git a/src/kio/metainfojob.h b/src/kio/metainfojob.h index 46498904..c0ba966a 100644 --- a/src/kio/metainfojob.h +++ b/src/kio/metainfojob.h @@ -1,133 +1,133 @@ // -*- c++ -*- /* This file is part of the KDE libraries Copyright (C) 2001 Rolf Magnus parts of this taken from previewjob.h 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 version 2.0. 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_METAINFOJOB_H #define KIO_METAINFOJOB_H #include #include #include #include namespace KIO { class MetaInfoJobPrivate; /** * MetaInfoJob is a KIO Job to retrieve meta information from files. * * @short KIO Job to retrieve meta information from files. * @deprecated use Nepomuk or Strigi * Note: this job doesn't even work as before, KFileItem::setMetaInfo * doesn't exist anymore. */ class KDELIBS4SUPPORT_DEPRECATED_EXPORT MetaInfoJob : public KIO::Job { Q_OBJECT public: /** * Creates a new MetaInfoJob. * @param items A list of KFileItems to get the metainfo for * @param w Flags which serve as a preset which can be customized * with other parameters. * @param iocost The allowed cost in terms of io to retrieve the * metainfo. The approximate maximum number of bytes to * be read is 10^iocost. Negative values mean that * there is no limit on the cost. 0 means that no fields * other than the required fields will be retrieved. * The default value of 3 means about 1024 bytes per * file may be read. This is merely a suggestion and not * a hard limit. * @param cpucost The allowed cost in terms of cpu to determine the * information in the fields. The number mean the amount * of instructions allowed is 10^cpucost and is a suggestion only. * The default value of 6 means that about a million * instructions (10^6) are allowed. This is useful for * expensive fields like md5 or thumbnails. * @param requiredfields The names of fields or groups of fields that should * be retrieved regardless of cost. * @param requestedfields The names of fields or groups of fields that should * be retrieved first. */ - explicit MetaInfoJob(const KFileItemList &items, KFileMetaInfo::WhatFlags w = KFileMetaInfo::Everything, + KDELIBS4SUPPORT_DEPRECATED explicit MetaInfoJob(const KFileItemList &items, KFileMetaInfo::WhatFlags w = KFileMetaInfo::Everything, int iocost = 3, int cpucost = 6, const QStringList &requiredfields = QStringList(), const QStringList &requestedfields = QStringList()); virtual ~MetaInfoJob(); /** * Removes an item from metainfo extraction. * * @param item the item that should be removed from the queue */ void removeItem(const KFileItem &item); Q_SIGNALS: /** * Emitted when the meta info for @p item has been successfully * retrieved. * @param item the KFileItem describing the fetched item */ void gotMetaInfo(const KFileItem &item); /** * Emitted when metainfo for @p item could not be extracted, * either because a plugin for its MIME type does not * exist, or because something went wrong. * @param item the KFileItem of the file that failed */ void failed(const KFileItem &item); protected: void getMetaInfo(); protected Q_SLOTS: void slotResult(KJob *job) Q_DECL_OVERRIDE; private Q_SLOTS: void start() Q_DECL_OVERRIDE; void slotMetaInfo(KIO::Job *, const QByteArray &); private: void determineNextFile(); // void saveMetaInfo(const QByteArray info); private: Q_DECLARE_PRIVATE(MetaInfoJob) MetaInfoJobPrivate *d; }; /** * Retrieves meta information for the given items. * * @param items files to get metainfo for * @return the MetaInfoJob to retrieve the items * @deprecated use strigi or KFileMetaInfo */ KDELIBS4SUPPORT_DEPRECATED_EXPORT MetaInfoJob *fileMetaInfo(const KFileItemList &items); /** * Retrieves meta information for the given items. * * @param items files to get metainfo for * @return the MetaInfoJob to retrieve the items * @deprecated use strigi or KFileMetaInfo */ KDELIBS4SUPPORT_DEPRECATED_EXPORT MetaInfoJob *fileMetaInfo(const QList &items); } #endif