Numworks Epsilon  1.4.1
Graphing Calculator Operating System
run_loop.cpp
Go to the documentation of this file.
1 #include <escher/run_loop.h>
2 #include <assert.h>
3 #ifdef __EMSCRIPTEN__
4 #include <emscripten.h>
5 #endif
6 
8  m_time(0) {
9 }
10 
12  return 0;
13 }
14 
16  assert(false);
17  return nullptr;
18 }
19 
20 void RunLoop::run() {
21  runWhile(nullptr, nullptr);
22 }
23 
24 void RunLoop::runWhile(bool (*callback)(void * ctx), void * ctx) {
25  while ((callback == nullptr || callback(ctx)) && step()) {
26  }
27 }
28 
29 bool RunLoop::step() {
30  // Fetch the event, if any
31  int eventDuration = Timer::TickDuration;
32  int timeout = eventDuration;
33 
34  Ion::Events::Event event = Ion::Events::getEvent(&timeout);
35  assert(event.isDefined());
36 
37  eventDuration -= timeout;
38  assert(eventDuration >= 0);
39  assert(eventDuration <= Timer::TickDuration);
40 
41  /* At this point, eventDuration contains the time it took to retrieve the
42  * event. It can be zero, and is at most equal to the timeout value, Timer::
43  * TickDuration. The event returned can be None if nothing worth taking care
44  * of happened. In other words, getEvent is a blocking call with a timeout. */
45 
46  m_time += eventDuration;
47 
48  if (m_time >= Timer::TickDuration) {
49  m_time -= Timer::TickDuration;
50  for (int i=0; i<numberOfTimers(); i++) {
51  Timer * timer = timerAtIndex(i);
52  if (timer->tick()) {
54  }
55  }
56  }
57 
58 #if ESCHER_LOG_EVENTS_BINARY
59  Ion::Console::writeChar((char)event.id());
60 #endif
61 #if ESCHER_LOG_EVENTS_NAME
62  const char * name = event.name();
63  if (name == nullptr) {
64  name = "UNDEFINED";
65  }
67 #endif
68 
69  if (event != Ion::Events::None) {
70  dispatchEvent(event);
71  }
72 
73  return event != Ion::Events::Termination;
74 }
Event getEvent(int *timeout)
Definition: events.cpp:12
static constexpr int TickDuration
Definition: timer.h:17
Definition: timer.h:15
#define assert(e)
Definition: assert.h:9
virtual int numberOfTimers()
Definition: run_loop.cpp:11
void run()
Definition: run_loop.cpp:20
RunLoop()
Definition: run_loop.cpp:7
bool tick()
Definition: timer.cpp:9
constexpr Event None
Definition: events.h:215
virtual Timer * timerAtIndex(int i)
Definition: run_loop.cpp:15
void writeLine(const char *line)
Definition: console_line.cpp:9
virtual bool dispatchEvent(Ion::Events::Event e)=0
constexpr Event TimerFire
Definition: events.h:217
void runWhile(bool(*callback)(void *ctx), void *ctx)
Definition: run_loop.cpp:24
void writeChar(char c)
Definition: console.cpp:16
constexpr Event Termination
Definition: events.h:216