]> git.lyx.org Git - lyx.git/blob - src/support/Timeout.cpp
infrastructure for 'graceful asserts'
[lyx.git] / src / support / Timeout.cpp
1 /**
2  * \file Timeout.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/Timeout.h"
14 #include "support/debug.h"
15
16 #include <QObject>
17 #include <QTimerEvent>
18
19 using namespace std;
20
21 namespace lyx {
22
23 /**
24  * This class executes the callback when the timeout expires
25  * using Qt mechanisms
26  */
27 class Timeout::Impl : QObject {
28 public:
29         ///
30         Impl(Timeout & owner) : owner_(owner), timeout_id(-1) {}
31         ///
32         bool running() const { return timeout_id != -1; } 
33         /// start the timer
34         void start();
35         /// stop the timer
36         void stop();
37         /// reset
38         void reset();
39         ///
40         unsigned int timeout_ms() const { return owner_.timeout_ms; }
41
42 protected:
43         /// 
44         void timerEvent(QTimerEvent *) { owner_.emit(); }
45
46 private:
47         ///
48         Timeout & owner_;
49         /// timout id
50         int timeout_id;
51 };
52
53
54 void Timeout::Impl::reset()
55 {
56         if (timeout_id != -1)
57                 killTimer(timeout_id);
58         timeout_id = -1;
59 }
60
61
62 void Timeout::Impl::start()
63 {
64         if (running())
65                 lyxerr << "Timeout::start: already running!" << endl;
66         timeout_id = startTimer(timeout_ms());
67 }
68
69
70 void Timeout::Impl::stop()
71 {
72         if (running())
73                 reset();
74 }
75
76
77 //
78 // Timeout
79 //
80
81 Timeout::Timeout(unsigned int msec, Type t)
82         : pimpl_(new Impl(*this)), type(t), timeout_ms(msec)
83 {}
84
85
86 Timeout::~Timeout()
87 {
88         pimpl_->stop();
89         delete pimpl_;
90 }
91
92
93 bool Timeout::running() const
94 {
95         return pimpl_->running();
96 }
97
98
99 void Timeout::start()
100 {
101         pimpl_->start();
102 }
103
104
105 void Timeout::stop()
106 {
107         pimpl_->stop();
108 }
109
110
111 void Timeout::restart()
112 {
113         pimpl_->stop();
114         pimpl_->start();
115 }
116
117
118 void Timeout::emit()
119 {
120         pimpl_->reset();
121         timeout();
122         if (type == CONTINUOUS)
123                 pimpl_->start();
124 }
125
126
127 Timeout & Timeout::setType(Type t)
128 {
129         type = t;
130         return *this;
131 }
132
133
134 Timeout & Timeout::setTimeout(unsigned int msec)
135 {
136         // Can't have a timeout of zero!
137         LASSERT(msec, /**/);
138
139         timeout_ms = msec;
140         return *this;
141 }
142
143
144 } // namespace lyx