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