summaryrefslogtreecommitdiffstats
path: root/src/gui/logviewform.cpp
blob: eafeb91e92352110daf1325250bbb79ecfad4d02 (plain)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "logviewform.h"

#include <QScrollBar>
#include <QTimer>
#include "audits/memman.h"
#include "log.h"

/*
 *  Constructs a LogViewForm which is a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  true to construct a modal dialog.
 */
LogViewForm::LogViewForm(QWidget* parent)
	: QDialog(parent)
{
	setupUi(this);
}

/*
 *  Destroys the object and frees any allocated resources
 */
LogViewForm::~LogViewForm()
{
	// no need to delete child widgets, Qt does it all for us
}

bool LogViewForm::isOnBottom() const
{
	const QScrollBar* vsb = logTextEdit->verticalScrollBar();
	return (vsb->value() == vsb->maximum());
}

void LogViewForm::scrollToBottom()
{
	QScrollBar* vsb = logTextEdit->verticalScrollBar();
	vsb->setValue(vsb->maximum());
	logTextEdit->update();
}

void LogViewForm::show()
{
    if (isVisible()) {
		raise();
		return;
	}

	QString fname = log_file->get_filename().c_str();
	logfile = new QFile(fname);
	MEMMAN_NEW(logfile);
	logstream = NULL;
	if (logfile->open(QIODevice::ReadOnly)) {
		logstream = new QTextStream(logfile);
		MEMMAN_NEW(logstream);
        logTextEdit->setPlainText(logstream->readAll());
	}
	log_file->enable_inform_user(true);

	QDialog::show();

	// Couldn't get it to scroll AND show contents(!) without this hack
	QTimer::singleShot(50, this, SLOT(scrollToBottom()));
	raise();
}

void LogViewForm::closeEvent(QCloseEvent* ev)
{
	log_file->enable_inform_user(false);
	// logTextEdit->clear(); // causes crashes with Qt5

	if (logstream) {
		MEMMAN_DELETE(logstream);
		delete logstream;
		logstream = NULL;
	}

	logfile->close();
	MEMMAN_DELETE(logfile);
	delete logfile;
	logfile = NULL;

	QDialog::closeEvent(ev);
}

void LogViewForm::update(bool log_zapped)
{
    if (!isVisible()) return;

	if (log_zapped) {
		close();
		show();
		return;
	}

	if (logstream) {
        QString s = logstream->readAll();
		if (!s.isNull() && !s.isEmpty()) {
			bool bottom = isOnBottom();
			logTextEdit->appendPlainText(s);
			if (bottom)
				scrollToBottom();
		}
	}
}

void LogViewForm::clear()
{
	logTextEdit->clear();
}