aboutsummaryrefslogtreecommitdiffstats
path: root/qt-models/messagehandlermodel.cpp
blob: e14aaf89c3e6effc16c3793d1402eb323b6ce3a0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// SPDX-License-Identifier: GPL-2.0
#include "messagehandlermodel.h"

/* based on logging bits from libdivecomputer */
#if !defined(Q_OS_ANDROID)
#define INFO(fmt, ...)	fprintf(stderr, "INFO: " fmt "\n", ##__VA_ARGS__)
#else
extern void writeToAppLogFile(QString logText);
#include <android/log.h>
#define INFO(fmt, ...)	__android_log_print(ANDROID_LOG_DEBUG, __FILE__, "INFO: " fmt "\n", ##__VA_ARGS__);
#endif

void logMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
	Q_UNUSED(context)
	MessageHandlerModel::self()->addLog(type, msg);
}

MessageHandlerModel * MessageHandlerModel::self()
{
	static MessageHandlerModel *self = new MessageHandlerModel();
	return self;
}

MessageHandlerModel::MessageHandlerModel(QObject *parent)
{
	Q_UNUSED(parent)
	// no more than one message handler.
	qInstallMessageHandler(logMessageHandler);
}

int MessageHandlerModel::rowCount(const QModelIndex& parent) const
{
	Q_UNUSED(parent)
	return m_data.size();
}

#include <iostream>

void MessageHandlerModel::addLog(QtMsgType type, const QString& message)
{
	beginInsertRows(QModelIndex(), rowCount(), rowCount());
	m_data.append({message, type});
	endInsertRows();
	INFO("%s", qPrintable(message));
#if defined (Q_OS_ANDROID)
	writeToAppLogFile(message);
#endif
}

QVariant MessageHandlerModel::data(const QModelIndex& idx, int role) const
{
	switch(role) {
		case Message:
		case Qt::DisplayRole:
			return m_data.at(idx.row()).message;
	}
	return QVariant(QString("Role: %1").arg(role));
};

QHash<int, QByteArray> MessageHandlerModel::roleNames() const {
	static QHash<int, QByteArray> roles = {
		{Message, "message"},
		{Severity, "severity"}
	};
	return roles;
};

void MessageHandlerModel::reset()
{
	beginRemoveRows(QModelIndex(), 0, m_data.size()-1);
	m_data.clear();
	endRemoveRows();

}