File: ftimer.h

package info (click to toggle)
finalcut 0.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,832 kB
  • sloc: cpp: 90,264; makefile: 546; sh: 412
file content (399 lines) | stat: -rw-r--r-- 11,052 bytes parent folder | download
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/***********************************************************************
* ftimer.h - Timer for executing recurring tasks                       *
*                                                                      *
* This file is part of the FINAL CUT widget toolkit                    *
*                                                                      *
* Copyright 2022-2023 Markus Gans                                      *
*                                                                      *
* FINAL CUT is free software; you can redistribute it and/or modify    *
* it under the terms of the GNU Lesser General Public License as       *
* published by the Free Software Foundation; either version 3 of       *
* the License, or (at your option) any later version.                  *
*                                                                      *
* FINAL CUT is distributed in the hope that it will be useful, but     *
* WITHOUT ANY WARRANTY; without even the implied warranty of           *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
* GNU Lesser General Public License for more details.                  *
*                                                                      *
* You should have received a copy of the GNU Lesser General Public     *
* License along with this program.  If not, see                        *
* <http://www.gnu.org/licenses/>.                                      *
***********************************************************************/

/*  Base class
 *  ══════════
 *
 * ▕▔▔▔▔▔▔▔▔▏
 * ▕ FTimer ▏
 * ▕▁▁▁▁▁▁▁▁▏
 */

#ifndef FTIMER_H
#define FTIMER_H

#if !defined (USE_FINAL_H) && !defined (COMPILE_FINAL_CUT)
  #error "Only <final/final.h> can be included directly."
#endif

#include <algorithm>
#include <chrono>
#include <memory>
#include <mutex>
#include <vector>

#include "final/fevent.h"
#include "final/util/fstring.h"

namespace finalcut
{

namespace internal
{

struct timer_var
{
  static std::mutex mutex;
};

}  // namespace internal

using std::chrono::duration_cast;
using std::chrono::seconds;
using std::chrono::milliseconds;
using std::chrono::microseconds;
using std::chrono::system_clock;
using std::chrono::time_point;

// class forward declaration
class FEvent;

//----------------------------------------------------------------------
// class FTimer
//----------------------------------------------------------------------

template <typename ObjectT>
class FTimer
{
  public:
    // Destructor
    virtual ~FTimer() = default;

    // Accessors
    inline virtual auto getClassName() const -> FString
    {
      return "FTimer";
    }

    inline auto getCurrentTime() const -> TimeValue
    {
      return system_clock::now();  // Get the current time
    }

    // Inquiries
    auto  isTimeout (const TimeValue&, uInt64) -> bool;

    // Methods
    auto  addTimer (ObjectT*, int) & -> int;
    auto  delTimer (int) const & -> bool;
    auto  delOwnTimers(const ObjectT*) const & -> bool;
    auto  delAllTimers() const & -> bool;

  protected:
    struct FTimerData
    {
      int          id;
      milliseconds interval;
      TimeValue    timeout;
      ObjectT*     object;
    };

    // Using-declaration
    using FTimerList = std::vector<FTimerData>;
    using FTimerListUniquePtr = std::unique_ptr<FTimerList>;

    // Accessor
    auto getTimerList() const -> FTimerList*
    {
      return globalTimerList().get();
    }

    // Method
    template <typename CallbackT>
    auto processTimerEvent (CallbackT) -> uInt;

  private:
    // Method
    static auto globalTimerList() -> const FTimerListUniquePtr&;

    // Friend classes
    friend class FObjectTimer;
};

// non-member function forward declarations
//----------------------------------------------------------------------
auto getNextId() -> int;

// public methods of FTimer
//----------------------------------------------------------------------
template <typename ObjectT>
inline auto FTimer<ObjectT>::isTimeout (const TimeValue& time, uInt64 timeout) -> bool
{
  // Checks whether the specified time span (timeout in µs) has elapsed

  const auto& now = getCurrentTime();

  if ( now < time )
    return false;

  const auto diff = now - time;
  const auto& diff_usec = uInt64(duration_cast<microseconds>(diff).count());
  return diff_usec > timeout;
}

//----------------------------------------------------------------------
template <typename ObjectT>
auto FTimer<ObjectT>::addTimer (ObjectT* object, int interval) & -> int
{
  // Create a timer and returns the timer identifier number
  // (interval in ms)

  std::lock_guard<std::mutex> lock_guard(internal::timer_var::mutex);
  auto& timer_list = globalTimerList();
  int id = getNextId();
  const auto time_interval = milliseconds(interval);
  const auto timeout = getCurrentTime() + time_interval;
  FTimerData timedata{ id, time_interval, timeout, object };

  // Insert in list sorted by timeout
  timer_list->insert( std::lower_bound( timer_list->cbegin()
                                      , timer_list->cend()
                                      , timedata
                                      , [] (const auto& a, const auto& b)
                                        {
                                          return a.timeout < b.timeout;
                                        }
                                      )
                    , timedata);
  return id;
}

//----------------------------------------------------------------------
template <typename ObjectT>
auto FTimer<ObjectT>::delTimer (int id) const & -> bool
{
  // Deletes a timer by using the timer identifier number

  if ( id <= 0 )
    return false;

  std::lock_guard<std::mutex> lock_guard(internal::timer_var::mutex);
  auto& timer_list = globalTimerList();

  if ( ! timer_list || timer_list->empty() )
    return false;

  auto iter = std::find_if ( timer_list->cbegin()
                           , timer_list->cend()
                           , [id] (const auto& timer)
                             {
                               return timer.id == id;
                             }
                           );

  if ( iter == timer_list->cend() )
    return false;

  timer_list->erase(iter);
  return true;
}

//----------------------------------------------------------------------
template <typename ObjectT>
auto FTimer<ObjectT>::delOwnTimers(const ObjectT* object) const & -> bool
{
  // Deletes all timers of this object

  std::lock_guard<std::mutex> lock_guard(internal::timer_var::mutex);
  auto& timer_list = globalTimerList();

  if ( ! timer_list || timer_list->empty() )
    return false;

  timer_list->erase ( std::remove_if( timer_list->begin()
                                    , timer_list->end()
                                    , [&object] (const auto& timer)
                                      {
                                        return timer.object == object;
                                      }
                                    ), timer_list->end() );
  return true;
}

//----------------------------------------------------------------------
template <typename ObjectT>
auto FTimer<ObjectT>::delAllTimers() const & -> bool
{
  // Deletes all timers of all objects

  std::lock_guard<std::mutex> lock_guard(internal::timer_var::mutex);
  auto& timer_list = globalTimerList();

  if ( ! timer_list || timer_list->empty() )
    return false;

  timer_list->clear();
  timer_list->shrink_to_fit();
  return true;
}

// protected methods of FTimer
//----------------------------------------------------------------------
template <typename ObjectT>
template <typename CallbackT>
auto FTimer<ObjectT>::processTimerEvent (CallbackT callback) -> uInt
{
  uInt activated{0};
  std::unique_lock<std::mutex> lock ( internal::timer_var::mutex
                                    , std::defer_lock );

  if ( ! lock.try_lock() )
    return 0;

  auto& timer_list = globalTimerList();

  if ( ! timer_list || timer_list->empty() )
    return 0;

  const auto& currentTime = getCurrentTime();

  for (auto&& timer : *timer_list)
  {
    if ( ! timer.id
      || ! timer.object
      || currentTime < timer.timeout )  // Timer not expired
      continue;

    timer.timeout += timer.interval;

    if ( timer.timeout < currentTime )
      timer.timeout = currentTime + timer.interval;

    if ( timer.interval > microseconds(0) )
      ++activated;

    lock.unlock();
    FTimerEvent t_ev(Event::Timer, timer.id);
    callback (timer.object, &t_ev);
    lock.lock();
  }

  return activated;
}

// private methods of FTimer
//----------------------------------------------------------------------
template <typename ObjectT>
auto FTimer<ObjectT>::globalTimerList() -> const FTimerListUniquePtr&
{
  static const auto& timer_list = std::make_unique<FTimerList>();
  return timer_list;
}

// class forward declaration
class FObject;

// Specialization for FObject
template <>
auto FTimer<FObject>::globalTimerList() -> const FTimerListUniquePtr&;


//----------------------------------------------------------------------
// class FObjectTimer
//----------------------------------------------------------------------
class FObjectTimer
{
  public:
    FObjectTimer();

    // Destructor
    virtual ~FObjectTimer() = default;

    // Accessors
    inline virtual auto getClassName() const -> FString
    {
      return "FObjectTimer";
    }

    static inline auto getCurrentTime() -> TimeValue
    {
      return timer->getCurrentTime();
    }

    // Inquiries
    static auto isTimeout (const TimeValue& time, uInt64 timeout) -> bool
    {
      return timer->isTimeout(time, timeout);
    }

    // Methods
    auto addTimer (int interval) -> int
    {
      return timer->addTimer(selfPointer<FObject*>(), interval);
    }

    auto delTimer (int id) const -> bool
    {
      return timer->delTimer(id);
    }

    auto delOwnTimers() const -> bool
    {
      return timer->delOwnTimers(selfPointer<const FObject*>());
    }

    auto delAllTimers() const -> bool
    {
      return timer->delAllTimers();
    }

  protected:
    auto getTimerList() const -> FTimer<FObject>::FTimerList*
    {
      return timer->globalTimerList().get();
    }

    // Method
    auto processTimerEvent() -> uInt
    {
      return timer->processTimerEvent ( [this] (FObject* receiver, FEvent* event)
                                        {
                                          performTimerAction(receiver, event);
                                        }
                                      );
    }

  private:
    // Method
    virtual void performTimerAction (FObject*, FEvent*);

    template <typename T>
    inline auto selfPointer() -> T
    {
      return T(this);
    }

    template <typename T>
    inline auto selfPointer() const -> T
    {
      return T(this);
    }

    // Data members
    static FTimer<FObject>* timer;
};


}  // namespace finalcut

#endif  // FTIMER_H