AppMessages.cc 2.44 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
9 10


11 12 13

// Allows QGlobalStatic to work on this translation unit
#define _LOG_CTOR_ACCESS_ public
14
#include "AppMessages.h"
15
#include <QFile>
16
#include <QStringListModel>
17 18
#include <QtConcurrent>
#include <QTextStream>
19

20 21
Q_GLOBAL_STATIC(AppLogModel, debug_model)

22 23 24 25 26 27 28 29 30
static QtMessageHandler old_handler;

static void msgHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    const char symbols[] = { 'D', 'E', '!', 'X', 'I' };
    QString output = QString("[%1] at %2:%3 - \"%4\"").arg(symbols[type]).arg(context.file).arg(context.line).arg(msg);

    // Avoid recursion
    if (!QString(context.category).startsWith("qt.quick")) {
31
        debug_model->log(output);
32 33 34 35 36 37 38 39
    }

    if (old_handler != nullptr) {
        old_handler(type, context, msg);
    }
    if( type == QtFatalMsg ) abort();
}

40
void AppMessages::installHandler()
41
{
42
    old_handler = qInstallMessageHandler(msgHandler);
43

44 45
    // Force creation of debug model on installing thread
    Q_UNUSED(*debug_model);
46 47
}

48
AppLogModel *AppMessages::getModel()
49
{
50
    return debug_model;
51 52 53 54
}

AppLogModel::AppLogModel() : QStringListModel()
{
55 56 57 58 59 60
#ifdef __mobile__
    Qt::ConnectionType contype = Qt::QueuedConnection;
#else
    Qt::ConnectionType contype = Qt::AutoConnection;
#endif
    connect(this, &AppLogModel::emitLog, this, &AppLogModel::threadsafeLog, contype);
61 62
}

DonLakeFlyer's avatar
DonLakeFlyer committed
63
void AppLogModel::writeMessages(const QString dest_file)
64 65 66 67
{
    const QString writebuffer(stringList().join('\n').append('\n'));

    QtConcurrent::run([dest_file, writebuffer] {
68
        emit debug_model->writeStarted();
69
        bool success = false;
DonLakeFlyer's avatar
DonLakeFlyer committed
70
        QFile file(dest_file);
71 72 73 74 75
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << writebuffer;
            success = out.status() == QTextStream::Ok;
        }
76
        emit debug_model->writeFinished(success);
77
    });
78
}
79 80 81 82 83 84 85 86 87 88 89 90

void AppLogModel::log(const QString message)
{
    emit debug_model->emitLog(message);
}

void AppLogModel::threadsafeLog(const QString message)
{
    const int line = rowCount();
    insertRows(line, 1);
    setData(index(line), message, Qt::DisplayRole);
}