4c75f9e
/*
4c75f9e
    Copyright (c) 2017, Lukas Holecek <hluk@email.cz>
4c75f9e
4c75f9e
    This file is part of CopyQ.
4c75f9e
4c75f9e
    CopyQ is free software: you can redistribute it and/or modify
4c75f9e
    it under the terms of the GNU General Public License as published by
4c75f9e
    the Free Software Foundation, either version 3 of the License, or
4c75f9e
    (at your option) any later version.
4c75f9e
4c75f9e
    CopyQ is distributed in the hope that it will be useful,
4c75f9e
    but WITHOUT ANY WARRANTY; without even the implied warranty of
4c75f9e
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
4c75f9e
    GNU General Public License for more details.
4c75f9e
4c75f9e
    You should have received a copy of the GNU General Public License
4c75f9e
    along with CopyQ.  If not, see <http://www.gnu.org/licenses/>.
4c75f9e
*/
4c75f9e
4c75f9e
#ifndef APPLICATIONEXCEPTIONHANDLER_H
4c75f9e
#define APPLICATIONEXCEPTIONHANDLER_H
4c75f9e
4c75f9e
#include <QObject>
4c75f9e
4c75f9e
#include <exception>
4c75f9e
4c75f9e
class QCoreApplication;
4c75f9e
class QEvent;
4c75f9e
4c75f9e
void logException(const char *what = nullptr);
4c75f9e
4c75f9e
namespace detail {
4c75f9e
4c75f9e
class ApplicationExceptionHandlerBase : public QObject
4c75f9e
{
4c75f9e
    Q_OBJECT
4c75f9e
4c75f9e
protected:
4c75f9e
    /// Exit application (thread-safe).
4c75f9e
    void exit(int exitCode);
4c75f9e
4c75f9e
private slots:
4c75f9e
    void exitSlot(int exitCode);
4c75f9e
};
4c75f9e
4c75f9e
} // namespace detail
4c75f9e
4c75f9e
template <typename QtApplication>
4c75f9e
class ApplicationExceptionHandler : public detail::ApplicationExceptionHandlerBase, public QtApplication
4c75f9e
{
4c75f9e
public:
4c75f9e
    ApplicationExceptionHandler(int &argc, char **argv)
4c75f9e
        : QtApplication(argc, argv)
4c75f9e
    {
4c75f9e
    }
4c75f9e
4c75f9e
    bool notify(QObject *receiver, QEvent *event) override
4c75f9e
    {
4c75f9e
        try {
4c75f9e
            return QtApplication::notify(receiver, event);
4c75f9e
        } catch (const std::exception &e) {
4c75f9e
            logException(e.what());
4c75f9e
        } catch (...) {
4c75f9e
            logException();
4c75f9e
        }
4c75f9e
4c75f9e
        detail::ApplicationExceptionHandlerBase::exit(1);
4c75f9e
        return true;
4c75f9e
    }
4c75f9e
};
4c75f9e
4c75f9e
#endif // APPLICATIONEXCEPTIONHANDLER_H