modernize: Use raw string literals instead of escaped strings
[quassel.git] / src / common / quassel.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #pragma once
22
23 #include "common-export.h"
24
25 #include <functional>
26 #include <vector>
27
28 #include <QCommandLineParser>
29 #include <QCoreApplication>
30 #include <QFile>
31 #include <QLocale>
32 #include <QObject>
33 #include <QString>
34 #include <QStringList>
35
36 #include "abstractsignalwatcher.h"
37 #include "singleton.h"
38
39 class QFile;
40
41 class Logger;
42
43 class COMMON_EXPORT Quassel : public QObject, public Singleton<Quassel>
44 {
45     // TODO Qt5: Use Q_GADGET
46     Q_OBJECT
47
48 public:
49     enum RunMode {
50         Monolithic,
51         ClientOnly,
52         CoreOnly
53     };
54
55     struct BuildInfo {
56         QString fancyVersionString; // clickable rev
57         QString plainVersionString; // no <a> tag
58
59         QString baseVersion;
60         QString generatedVersion;
61         QString commitHash;
62         QString commitDate;
63
64         uint protocolVersion; // deprecated
65
66         QString applicationName;
67         QString coreApplicationName;
68         QString clientApplicationName;
69         QString organizationName;
70         QString organizationDomain;
71     };
72
73     /**
74      * This enum defines the optional features supported by cores/clients prior to version 0.13.
75      *
76      * Since the number of features declared this way is limited to 16 (due to the enum not having a defined
77      * width in cores/clients prior to 0.13), and for more robustness when negotiating features on connect,
78      * the bitfield-based representation was replaced by a string-based representation in 0.13, support for
79      * which is indicated by having the ExtendedFeatures flag set. Extended features are defined in the Feature
80      * enum.
81      *
82      * @warning Do not alter this enum; new features must be added (only) to the @a Feature enum.
83      *
84      * @sa Feature
85      */
86     enum class LegacyFeature : quint32 {
87         SynchronizedMarkerLine = 0x0001,
88         SaslAuthentication     = 0x0002,
89         SaslExternal           = 0x0004,
90         HideInactiveNetworks   = 0x0008,
91         PasswordChange         = 0x0010,
92         CapNegotiation         = 0x0020,
93         VerifyServerSSL        = 0x0040,
94         CustomRateLimits       = 0x0080,
95         // DccFileTransfer     = 0x0100,  // never in use
96         AwayFormatTimestamp    = 0x0200,
97         Authenticators         = 0x0400,
98         BufferActivitySync     = 0x0800,
99         CoreSideHighlights     = 0x1000,
100         SenderPrefixes         = 0x2000,
101         RemoteDisconnect       = 0x4000,
102         ExtendedFeatures       = 0x8000,
103     };
104     Q_FLAGS(LegacyFeature)
105     Q_DECLARE_FLAGS(LegacyFeatures, LegacyFeature)
106
107     /**
108      * A list of features that are optional in core and/or client, but need runtime checking.
109      *
110      * Some features require an uptodate counterpart, but don't justify a protocol break.
111      * This is what we use this enum for. Add such features to it and check at runtime on the other
112      * side for their existence.
113      *
114      * For feature negotiation, these enum values are serialized as strings, so order does not matter. However,
115      * do not rename existing enum values to avoid breaking compatibility.
116      *
117      * This list should be cleaned up after every protocol break, as we can assume them to be present then.
118      */
119     enum class Feature : uint32_t {
120         SynchronizedMarkerLine,
121         SaslAuthentication,
122         SaslExternal,
123         HideInactiveNetworks,
124         PasswordChange,           ///< Remote password change
125         CapNegotiation,           ///< IRCv3 capability negotiation, account tracking
126         VerifyServerSSL,          ///< IRC server SSL validation
127         CustomRateLimits,         ///< IRC server custom message rate limits
128         AwayFormatTimestamp,      ///< Timestamp formatting in away (e.g. %%hh:mm%%)
129         Authenticators,           ///< Whether or not the core supports auth backends
130         BufferActivitySync,       ///< Sync buffer activity status
131         CoreSideHighlights,       ///< Core-Side highlight configuration and matching
132         SenderPrefixes,           ///< Show prefixes for senders in backlog
133         RemoteDisconnect,         ///< Allow this peer to be remotely disconnected
134         ExtendedFeatures,         ///< Extended features
135         LongTime,                 ///< Serialize time as 64-bit values
136         RichMessages,             ///< Real Name and Avatar URL in backlog
137         BacklogFilterType,        ///< BacklogManager supports filtering backlog by MessageType
138         EcdsaCertfpKeys,          ///< ECDSA keys for CertFP in identities
139         LongMessageId,            ///< 64-bit IDs for messages
140         SyncedCoreInfo,           ///< CoreInfo dynamically updated using signals
141     };
142     Q_ENUMS(Feature)
143
144     class Features;
145
146     Quassel();
147
148     void init(RunMode runMode);
149
150     /**
151      * Provides access to the Logger instance.
152      *
153      * @returns The Logger instance
154      */
155     Logger *logger() const;
156
157     static void setupBuildInfo();
158     static const BuildInfo &buildInfo();
159     static RunMode runMode();
160
161     static QString configDirPath();
162
163     //! Returns a list of data directory paths
164     /** There are several locations for applications to install their data files in. On Unix,
165     *  a common location is /usr/share; others include $PREFIX/share and additional directories
166     *  specified in the env variable XDG_DATA_DIRS.
167     *  \return A list of directory paths to look for data files in
168     */
169     static QStringList dataDirPaths();
170
171     //! Searches for a data file in the possible data directories
172     /** Data files can reside in $DATA_DIR/apps/quassel, where $DATA_DIR is one of the directories
173     *  returned by \sa dataDirPaths().
174     *  \Note With KDE integration enabled, files are searched (only) in KDE's appdata dirs.
175     *  \return The full path to the data file if found; a null QString else
176     */
177     static QString findDataFilePath(const QString &filename);
178
179     static QString translationDirPath();
180
181     //! Returns a list of directories we look for scripts in
182     /** We look for a subdirectory named "scripts" in the configdir and in all datadir paths.
183     *   \return A list of directory paths containing executable scripts for /exec
184     */
185     static QStringList scriptDirPaths();
186
187     static void loadTranslation(const QLocale &locale);
188
189     static QString optionValue(const QString &option);
190     static bool isOptionSet(const QString &option);
191
192     using ReloadHandler = std::function<bool()>;
193
194     static void registerReloadHandler(ReloadHandler handler);
195
196     using QuitHandler = std::function<void()>;
197
198     /**
199      * Registers a handler that is called when the application is supposed to quit.
200      *
201      * @note If multiple handlers are registered, they are processed in order of registration.
202      * @note If any handler is registered, quit() will not call QCoreApplication::quit(). It relies
203      *       on one of the handlers doing so, instead.
204      * @param quitHandler Handler to register
205      */
206     static void registerQuitHandler(QuitHandler quitHandler);
207
208     const QString &coreDumpFileName();
209
210 public slots:
211     /**
212      * Requests to quit the application.
213      *
214      * Calls any registered quit handlers. If no handlers are registered, calls QCoreApplication::quit().
215      */
216     void quit();
217
218 signals:
219     void messageLogged(const QDateTime &timeStamp, const QString &msg);
220
221 private:
222     void registerMetaTypes();
223     void setupSignalHandling();
224     void setupEnvironment();
225     void setupCliParser();
226
227     /**
228      * Requests a reload of relevant runtime configuration.
229      *
230      * Calls any registered reload handlers, and returns the cumulative result. If no handlers are registered,
231      * does nothing and returns true.
232      *
233      * @returns True if configuration reload successful, otherwise false
234      */
235     bool reloadConfig();
236
237     void logBacktrace(const QString &filename);
238
239 private slots:
240     void handleSignal(AbstractSignalWatcher::Action action);
241
242 private:
243     BuildInfo _buildInfo;
244     RunMode _runMode;
245     bool _quitting{false};
246
247     QString _coreDumpFileName;
248     QString _configDirPath;
249     QStringList _dataDirPaths;
250     QString _translationDirPath;
251
252     QCommandLineParser _cliParser;
253
254     Logger *_logger;
255     AbstractSignalWatcher *_signalWatcher{nullptr};
256
257     std::vector<ReloadHandler> _reloadHandlers;
258     std::vector<QuitHandler> _quitHandlers;
259 };
260
261 // --------------------------------------------------------------------------------------------------------------------
262
263 /**
264  * Class representing a set of supported core/client features.
265  *
266  * @sa Quassel::Feature
267  */
268 class COMMON_EXPORT Quassel::Features
269 {
270 public:
271     /**
272      * Default constructor.
273      *
274      * Creates a Feature instance with all known features (i.e., all values declared in the Quassel::Feature enum) set.
275      * This is useful for easily creating a Feature instance that represent the current version's capabilities.
276      */
277     Features();
278
279     /**
280      * Constructs a Feature instance holding the given list of features.
281      *
282      * Both the @a features and the @a legacyFeatures arguments are considered (additively).
283      * This is useful when receiving a list of features from another peer.
284      *
285      * @param features       A list of strings matching values in the Quassel::Feature enum. Strings that don't match are
286      *                       can be accessed after construction via unknownFeatures(), but are otherwise ignored.
287      * @param legacyFeatures Holds a bit-wise combination of LegacyFeature flag values, which are each added to the list of
288      *                       features represented by this Features instance.
289      */
290     Features(const QStringList &features, LegacyFeatures legacyFeatures);
291
292     /**
293      * Check if a given feature is marked as enabled in this Features instance.
294      *
295      * @param feature The feature to be queried
296      * @returns Whether the given feature is marked as enabled
297      */
298     bool isEnabled(Feature feature) const;
299
300     /**
301      * Provides a list of all features marked as either enabled or disabled (as indicated by the @a enabled argument) as strings.
302      *
303      * @param enabled Whether to return the enabled or the disabled features
304      * @return A string list containing all enabled or disabled features
305      */
306     QStringList toStringList(bool enabled = true) const;
307
308     /**
309      * Provides a list of all enabled legacy features (i.e. features defined prior to v0.13) as bit-wise combination in a
310      * LegacyFeatures type.
311      *
312      * @note Extended features cannot be represented this way, and are thus ignored even if set.
313      * @return A LegacyFeatures type holding the bit-wise combination of all legacy features enabled in this Features instance
314      */
315     LegacyFeatures toLegacyFeatures() const;
316
317     /**
318      * Provides the list of strings that could not be mapped to Quassel::Feature enum values on construction.
319      *
320      * Useful for debugging/logging purposes.
321      *
322      * @returns A list of strings that could not be mapped to the Feature enum on construction of this Features instance, if any
323      */
324     QStringList unknownFeatures() const;
325
326 private:
327     std::vector<bool> _features;
328     QStringList _unknownFeatures;
329 };