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