1 | /*
|
---|
2 | * QDebugStream.hpp
|
---|
3 | *
|
---|
4 | * Created on: Jun 19, 2014
|
---|
5 | * Author: heber
|
---|
6 | */
|
---|
7 |
|
---|
8 | #ifndef QDEBUGSTREAM_HPP_
|
---|
9 | #define QDEBUGSTREAM_HPP_
|
---|
10 |
|
---|
11 | // include config.h
|
---|
12 | #ifdef HAVE_CONFIG_H
|
---|
13 | #include <config.h>
|
---|
14 | #endif
|
---|
15 |
|
---|
16 | #include <QObject>
|
---|
17 | #include <QPlainTextEdit>
|
---|
18 | #include <QMutex>
|
---|
19 |
|
---|
20 | /**
|
---|
21 | * Taken from http://www.qtforum.de/forum/viewtopic.php?t=7970
|
---|
22 | */
|
---|
23 | class QDebugStream : public QObject, std::basic_streambuf<char>{
|
---|
24 |
|
---|
25 | Q_OBJECT
|
---|
26 |
|
---|
27 | signals:
|
---|
28 | void sendString(QString text);
|
---|
29 |
|
---|
30 | public:
|
---|
31 | QDebugStream(std::ostream &stream, QPlainTextEdit* text_edit) : m_stream(stream){
|
---|
32 | log_window = text_edit;
|
---|
33 | m_old_buf = stream.rdbuf();
|
---|
34 | stream.rdbuf(this);
|
---|
35 |
|
---|
36 | connect(this, SIGNAL(sendString(QString)), text_edit, SLOT(appendPlainText (QString)));
|
---|
37 | }
|
---|
38 | ~QDebugStream(){
|
---|
39 | // output anything that is left
|
---|
40 | if (!m_string.empty())
|
---|
41 | emit sendString(m_string.c_str());
|
---|
42 | //log_window->appendPlainText(m_string.c_str());
|
---|
43 | m_stream.rdbuf(m_old_buf);
|
---|
44 | }
|
---|
45 |
|
---|
46 | protected:
|
---|
47 | virtual int_type overflow(int_type v){
|
---|
48 | mutex.lock();
|
---|
49 | if (v == '\n'){
|
---|
50 | emit sendString(m_string.c_str());
|
---|
51 | //log_window->appendPlainText(m_string.c_str());
|
---|
52 | m_string.erase(m_string.begin(), m_string.end());
|
---|
53 | }
|
---|
54 | else
|
---|
55 | m_string += v;
|
---|
56 |
|
---|
57 | mutex.unlock();
|
---|
58 | return v;
|
---|
59 | }
|
---|
60 |
|
---|
61 | virtual std::streamsize xsputn(const char *p, std::streamsize n){
|
---|
62 | mutex.lock();
|
---|
63 |
|
---|
64 | m_string.append(p, p + n);
|
---|
65 | size_t pos = 0;
|
---|
66 | while (pos != std::string::npos){
|
---|
67 | pos = m_string.find('\n');
|
---|
68 | if (pos != std::string::npos){
|
---|
69 | std::string tmp(m_string.begin(), m_string.begin() + pos);
|
---|
70 | emit sendString(tmp.c_str());
|
---|
71 | //log_window->appendPlainText(tmp.c_str());
|
---|
72 | m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
|
---|
73 | }
|
---|
74 | }
|
---|
75 |
|
---|
76 | mutex.unlock();
|
---|
77 | return n;
|
---|
78 | }
|
---|
79 |
|
---|
80 | private:
|
---|
81 | std::ostream &m_stream;
|
---|
82 | std::streambuf *m_old_buf;
|
---|
83 | std::string m_string;
|
---|
84 | QPlainTextEdit* log_window;
|
---|
85 | QMutex mutex;
|
---|
86 | };
|
---|
87 |
|
---|
88 |
|
---|
89 | #endif // QDEBUGSTREAM_HPP
|
---|