1 /*
2  * IceWM
3  *
4  * Copyright (C) 1998-2001 Marko Macek
5  */
6 #include "config.h"
7 #include "ytimer.h"
8 #include "yapp.h"
9 #include "yprefs.h"
10 
YTimer(long ms)11 YTimer::YTimer(long ms) :
12     fListener(nullptr),
13     fTimeout(zerotime()),
14     fInterval(0L),
15     fFuzziness(0L),
16     fRunning(false),
17     fFixed(false)
18 {
19     setInterval(ms);
20 }
21 
YTimer(long ms,YTimerListener * listener,bool start,bool fixed)22 YTimer::YTimer(long ms, YTimerListener* listener, bool start, bool fixed) :
23     fListener(listener),
24     fTimeout(zerotime()),
25     fInterval(max(0L, ms)),
26     fFuzziness(0L),
27     fRunning(false),
28     fFixed(fixed)
29 {
30     if (start)
31         startTimer();
32 }
33 
~YTimer()34 YTimer::~YTimer() {
35     stopTimer();
36 }
37 
setFixed()38 void YTimer::setFixed() {
39     // Fixed here means: not fuzzy, but exact.
40     fFixed = true;
41     fFuzziness = 0L;
42 }
43 
isFixed() const44 bool YTimer::isFixed() const {
45     return fFixed || !fFuzziness;
46 }
47 
setInterval(long ms)48 void YTimer::setInterval(long ms) {
49     fInterval = max(0L, ms);
50 }
51 
startTimer(long ms)52 void YTimer::startTimer(long ms) {
53     setInterval(ms);
54     startTimer();
55 }
56 
startTimer()57 void YTimer::startTimer() {
58     fTimeout = monotime() + millitime(fInterval);
59     fuzzTimer();
60     enlist(true);
61 }
62 
fuzzTimer()63 void YTimer::fuzzTimer() {
64     if (false == fFixed && inrange(DelayFuzziness, 1, 100)) {
65         // non-fixed timer: configure fuzzy timeout range
66         // to allow for merging of several timers
67         fFuzziness = (fInterval * DelayFuzziness) / 100L;
68     } else {
69         fFuzziness = 0L;
70     }
71 }
72 
runTimer()73 void YTimer::runTimer() {
74     fTimeout = monotime();
75     fuzzTimer();
76     enlist(true);
77 }
78 
stopTimer()79 void YTimer::stopTimer() {
80     enlist(false);
81 }
82 
enlist(bool enable)83 void YTimer::enlist(bool enable) {
84     if (fRunning != enable) {
85         fRunning = enable;
86         if (enable) {
87             mainLoop->registerTimer(this);
88         } else {
89             mainLoop->unregisterTimer(this);
90         }
91     }
92 }
93 
disableTimerListener(YTimerListener * listener)94 void YTimer::disableTimerListener(YTimerListener *listener) {
95     // a global timer may be in use by several listeners.
96     // here one of those listeners asks to be deregistered.
97     // if it was the active listener then also stop the timer.
98     YTimer* nonNull(this);
99     if (nonNull && fListener == listener) {
100         fListener = nullptr;
101         stopTimer();
102     }
103 }
104 
setTimer(long interval,YTimerListener * listener,bool start)105 void YTimer::setTimer(long interval, YTimerListener *listener, bool start) {
106     stopTimer();
107     setInterval(interval);
108     setTimerListener(listener);
109     if (start)
110         startTimer();
111 }
112 
113 // vim: set sw=4 ts=4 et:
114