1// Timers: functions run as handlers once a clock reaches their time,2// kept in a heap by time for each clock, the window's and the wall's;3// the app asks the window to wake it at the earliest (`wake_at`), at4// most 5 seconds ahead while one waits for the wall clock. A timer5// belongs to the owner making it and goes with it. The clocks `ui.clock`6// gives are signals of the wall clock, set at each event and ticking7// through a wall timer only while a binding shown reads them. The wall8// clock's heap and the clocks are an extension installed by the first9// `at` or clock, so a program using neither carries none of their code.1011import std::string;12import std::vector;13import std::option;14import std::math;15import std::time;16import pkg::alloy::window;1718import ui;19import store;20import layers;21import extensions;2223// A timer's slot: what it runs, how often, and whose it is; `then` is24// None once it ran or was cancelled, and while a repeating one runs.25pub type TimerSlot = struct {26 pub generation: u32,27 pub then: Option<|=| (&var Ui)>,28 pub owner: u32,29 pub period: u64 = 0, // a repeating timer's, in nanoseconds; 0 runs once30};3132// An entry of a heap: the time, then the slot and its generation, an33// entry whose generation is past its slot's left there and skipped.34pub type Due = struct {35 // nanoseconds on the window's clock, or on the wall clock since 197036 pub at: u64,37 pub index: u32,38 pub generation: u32,39};4041// A signal of the wall clock at a step (`ui.clock`), with its next tick42// while a binding shown reads it.43pub type WallClock = struct {44 pub step: u64, // in nanoseconds45 pub signal: Signal<i64>,46 pub tick: Option<Timer> = ::None,47};4849// The longest the window waits while a timer waits for the wall clock,50// which may jump or have gone on while the machine slept.51const WALL_CHECK: u64 = 5000000000;5253// What the Ui calls of the wall clock's timers and the clocks once the54// first is made: the clocks set as an event comes, the wall's timers run55// after the window clock's, and when to look at the wall clock again.56pub type WallTimers : Extension = struct {};5758pub fn clock(self w: &var WallTimers, ui: &var Ui) {59 ui.refresh_clocks();60}6162pub fn timers(self w: &var WallTimers, ui: &var Ui) {63 ui.run_wall_timers();64}6566pub fn deadline(self w: &var WallTimers, ui: &var Ui) -> Option<u64> {67 ui.arm_clocks();68 return ui.next_wall();69}7071fn use_wall(self ui: &var Ui) {72 if (ui.extension<WallTimers>() is ::None) {73 ui.install(new WallTimers {});74 }75}7677fn before(self a: &Due, b: &Due) -> bool {78 return a.at < b.at || (a.at == b.at && a.index < b.index);79}8081// A slot running the function, belonging to what is made now.82fn new_slot(self ui: &var Ui, then: |=| (&var Ui), period: u64) -> Timer {83 var index: u32 = 0;84 if (ui.free_timers.pop() is ::Some |k|) {85 index = k;86 const slot = &var ui.timers.get_var(k to u64);87 slot.then = ::Some(move then);88 slot.owner = ui.owner;89 slot.period = period;90 } else {91 index = ui.timers.length() to u32;92 ui.timers.push(TimerSlot {93 .generation = 0,94 .then = ::Some(move then),95 .owner = ui.owner,96 .period = period97 });98 }99 ui.owners.get_var(ui.owner to u64).timers.push(index);100 return Timer { .index = index, .generation = ui.timers.get(index to u64).generation };101}102103// A timer due at the time on the window's clock, repeating at the period104// when not 0.105exp fn new_timer(self ui: &var Ui, at: u64, period: u64, then: |=| (&var Ui)) -> Timer {106 const timer = ui.new_slot(move then, period);107 push_due(&var ui.due, Due { .at = at, .index = timer.index, .generation = timer.generation });108 return timer;109}110111// A timer due once the wall clock reaches the moment.112pub fn new_wall_timer(self ui: &var Ui, moment: i64, then: |=| (&var Ui)) -> Timer {113 ui.use_wall();114 const timer = ui.new_slot(move then, 0);115 push_due(116 &var ui.wall_due,117 Due { .at = wall_at(moment), .index = timer.index, .generation = timer.generation }118 );119 return timer;120}121122// A moment as a heap's time, those before 1970 due already.123fn wall_at(moment: i64) -> u64 => if (moment < 0) 0 else moment to u64;124125// Forgets the timer, which then names nothing; whether it was set.126exp fn drop_timer(self ui: &var Ui, timer: Timer) -> bool {127 if (128 ui.timers.try_get(timer.index to u64) is ::Some |&slot|129 && slot.generation == timer.generation130 ) {131 ui.release_timer(timer.index);132 return true;133 }134 return false;135}136137// Frees the slot, taking it off its owner's list.138fn release_timer(self ui: &var Ui, index: u32) {139 const slot = &var ui.timers.get_var(index to u64);140 slot.then = ::None;141 slot.generation += 1;142 const owner = slot.owner;143 ui.free_timers.push(index);144 const listed = &var ui.owners.get_var(owner to u64).timers;145 for ([..listed.length()]) |k| {146 if (listed.get(k) == index) {147 listed.swap_remove(k);148 break;149 }150 }151}152153// Forgets the timers of an owner going, its list emptied.154pub fn drop_owned_timers(self ui: &var Ui, owner: u32) {155 while (ui.owners.get_var(owner to u64).timers.pop() is ::Some |index|) {156 const slot = &var ui.timers.get_var(index to u64);157 slot.then = ::None;158 slot.generation += 1;159 ui.free_timers.push(index);160 }161}162163// Sets the clocks' signals to the wall clock, then runs the timers164// whose time has come on the window's clock, then those on the wall's,165// each heap's earliest first, as handlers; those they set for now or166// before run too. A repeating one is then due a period after it was,167// past the runs missed.168exp fn run_timers(self ui: &var Ui) {169 ui.extensions_clock();170 const now = ui.time.nanoseconds;171 while (ui.due.try_get(0) is ::Some |&first| && first.at <= now) {172 const due = copy first;173 pop_due(&var ui.due);174 ui.run_due(due);175 }176 ui.extensions_timers();177}178179// Runs the entry's timer when it is still set.180fn run_due(self ui: &var Ui, due: Due) {181 const slot = &var ui.timers.get_var(due.index to u64);182 if (slot.generation != due.generation || slot.then is ::None) {183 return;184 }185 var then = move slot.then;186 slot.then = ::None;187 if (slot.period > 0) {188 if (then is ::Some |move f|) {189 ui.repeat_timer(due, move f);190 }191 return;192 }193 ui.release_timer(due.index);194 if (then is ::Some |&f|) {195 f(&var ui);196 }197}198199// Runs a repeating timer, then sets it due a period after it was, past200// the runs missed, unless it was cancelled meanwhile.201fn repeat_timer(self ui: &var Ui, due: Due, then: |=| (&var Ui)) {202 then(&var ui);203 const now = ui.time.nanoseconds;204 const kept = &var ui.timers.get_var(due.index to u64);205 if (kept.generation == due.generation) {206 const period = kept.period;207 kept.then = ::Some(move then);208 push_due(&var ui.due, Due {209 .at = due.at + period * ((now - due.at) / period + 1),210 .index = due.index,211 .generation = due.generation212 });213 }214}215216// Runs the timers whose moment the wall clock reached.217fn run_wall_timers(self ui: &var Ui) {218 const wall = wall_at(ui.wall);219 while (ui.wall_due.try_get(0) is ::Some |&first| && first.at <= wall) {220 const due = copy first;221 pop_due(&var ui.wall_due);222 ui.run_due(due);223 }224}225226// When on the window's clock to look at the wall clock again for the227// first wall timer still set: at its moment, 5 seconds ahead at most.228fn next_wall(self ui: &var Ui) -> Option<u64> {229 if (first_live(&var ui.wall_due, &ui.timers) is ::Some |moment|) {230 const wall = wall_at(ui.wall);231 return ::Some(232 ui.time.nanoseconds + min(if (moment > wall) moment - wall else 0, WALL_CHECK)233 );234 }235 return ::None;236}237238// The earliest time on the window's clock a timer waits for, the clocks239// read asking for their next tick first; a wait for the wall clock is240// at most 5 seconds.241exp fn next_due(self ui: &var Ui) -> Option<Duration> {242 // the extensions' first, which may set timers of the window's clock243 const asked = ui.extensions_deadline();244 var next = first_live(&var ui.due, &ui.timers);245 if (asked is ::Some |at|) {246 const sooner = if (next is ::Some |n|) at < n else true;247 if (sooner) {248 next = ::Some(at);249 }250 }251 if (next is ::Some |at|) {252 return ::Some(Duration::from_nanoseconds(at));253 }254 return ::None;255}256257// The time of the heap's first entry still set, the entries of those258// gone taken off on the way.259fn first_live(heap: &var Vector<Due>, timers: &Vector<TimerSlot>) -> Option<u64> {260 while (heap.try_get(0) is ::Some |&first|) {261 const slot = &timers.get(first.index to u64);262 if (slot.generation == first.generation && slot.then is ::Some) {263 return ::Some(first.at);264 }265 pop_due(&var heap);266 }267 return ::None;268}269270/* --- Clocks --- */271272// The clock of the step, made at the wall clock's step the first time.273pub fn wall_clock_signal(self ui: &var Ui, step: u64) -> Signal<i64> {274 for (ui.clocks.view()) |&c| {275 if (c.step == step) {276 return c.signal;277 }278 }279 // the Ui's own, whoever asks first; a program making none carries280 // none of their code281 ui.use_wall();282 const owner = ui.owner;283 ui.owner = 0;284 const signal = ui.signal(at_step(ui.wall, step));285 ui.owner = owner;286 ui.clocks.push(WallClock { .step = step, .signal = signal });287 return signal;288}289290// The moment at the start of the step it is in.291fn at_step(moment: i64, step: u64) -> i64 {292 const s = step to i64;293 return moment - (moment % s + s) % s;294}295296// Sets each clock's signal to the step the wall clock is at; one moved297// ticks next from there.298fn refresh_clocks(self ui: &var Ui) {299 for ([..ui.clocks.length()]) |k| {300 const c = copy ui.clocks.get(k);301 const value = at_step(ui.wall, c.step);302 if (copy c.signal.peek(&ui) != value) {303 c.signal.set(&var ui, value);304 if (c.tick is ::Some |tick|) {305 ui.drop_timer(tick);306 ui.clocks.get_var(k).tick = ::None;307 }308 }309 }310}311312// Sets the next tick of each clock a binding shown reads, and cancels313// those of the clocks none reads.314fn arm_clocks(self ui: &var Ui) {315 for ([..ui.clocks.length()]) |k| {316 const c = copy ui.clocks.get(k);317 const read = ui.read_shown(c.signal.index);318 if (read && c.tick is ::None) {319 const owner = ui.owner;320 ui.owner = 0;321 // the tick only wakes the loop: `refresh_clocks` sets the signal322 const shown = copy c.signal.peek(&ui);323 const tick = ui.new_wall_timer(shown + c.step to i64, (ui) {});324 ui.owner = owner;325 ui.clocks.get_var(k).tick = ::Some(tick);326 } else if (!read && c.tick is ::Some |tick|) {327 ui.drop_timer(tick);328 ui.clocks.get_var(k).tick = ::None;329 }330 }331}332333/* --- The heaps --- */334335fn push_due(heap: &var Vector<Due>, due: Due) {336 heap.push(due);337 var k = heap.length() - 1;338 while (k > 0) {339 const parent = (k - 1) / 2;340 const item = heap.get(k);341 const above = heap.get(parent);342 if (!item.before(&above)) {343 break;344 }345 heap.set(k, above);346 heap.set(parent, item);347 k = parent;348 }349}350351fn pop_due(heap: &var Vector<Due>) {352 const last = if (heap.pop() is ::Some |d|) d else {353 return;354 };355 const n = heap.length();356 if (n == 0) {357 return;358 }359 heap.set(0, last);360 var k: u64 = 0;361 while (2 * k + 1 < n) {362 var child = 2 * k + 1;363 if (child + 1 < n && heap.get(child + 1).before(&heap.get(child))) {364 child += 1;365 }366 const item = heap.get(k);367 const below = heap.get(child);368 if (!below.before(&item)) {369 break;370 }371 heap.set(k, below);372 heap.set(child, item);373 k = child;374 }375}