1 /*
2     Copyright (c) 2020, Lukas Holecek <hluk@email.cz>
3 
4     This file is part of CopyQ.
5 
6     CopyQ is free software: you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation, either version 3 of the License, or
9     (at your option) any later version.
10 
11     CopyQ is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15 
16     You should have received a copy of the GNU General Public License
17     along with CopyQ.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 #include "messagehandlerforqt.h"
21 
22 #include "common/log.h"
23 
24 #include <QString>
25 #include <QtGlobal>
26 
27 #include <exception>
28 
29 namespace {
30 
31 class ExceptionQtFatal final : public std::exception {
32 public:
ExceptionQtFatal(const QByteArray & message)33     explicit ExceptionQtFatal(const QByteArray &message)
34         : m_message(message)
35     {
36     }
37 
what() const38     const char* what() const noexcept override
39     {
40         return m_message.constData();
41     }
42 
43 private:
44     QByteArray m_message;
45 };
46 
messageHandlerForQt5(QtMsgType type,const QMessageLogContext & context,const QString & msg)47 void messageHandlerForQt5(QtMsgType type, const QMessageLogContext &context, const QString &msg)
48 {
49     QString message = msg;
50     if ( context.file != QLatin1String() ) {
51         message.append(
52             QString::fromLatin1(" (%1:%2, %3)")
53                 .arg(context.file, QString::number(context.line), context.function));
54     }
55 
56     const QString format = QString::fromLatin1("[%1] %3: %2");
57     const QLatin1String category(context.category);
58     switch (type) {
59     case QtDebugMsg:
60         log( format.arg(category, message, QLatin1String("QtDebug")), LogDebug);
61         break;
62     case QtInfoMsg:
63         log( format.arg(category, message, QLatin1String("QtInfo")), LogDebug);
64         break;
65     case QtWarningMsg:
66         log( format.arg(category, message, QLatin1String("QtWarning")), LogDebug);
67         break;
68     case QtCriticalMsg:
69         log( format.arg(category, message, QLatin1String("QtCritical")), LogError);
70         break;
71     case QtFatalMsg:
72         log( format.arg(category, message, QLatin1String("QtFatal")), LogError);
73         throw ExceptionQtFatal( message.toUtf8() );
74     }
75 }
76 
77 } // namespace
78 
installMessageHandlerForQt()79 void installMessageHandlerForQt()
80 {
81     qInstallMessageHandler(messageHandlerForQt5);
82 }
83