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