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