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