1// Signals, the bindings reading them and the owners everything made2// belongs to.3//4// A binding is an effect: a function run with the reads it makes5// recorded, each read subscribing it to the signal, stamped with the run6// that made it. A change marks the subscribers whose stamp is their last7// run's and drops the rest, so a run forgets what it no longer reads8// without unsubscribing. Marked effects run once the handler returns,9// owners nearer the root first.1011import std::string;12import std::vector;13import std::option;14import std::map;15import std::hash as hash;16import std::sync;17import std::math;18import std::equal;1920import ui;21import tree;22import timers;23import transitions;24import motion;25import extensions;2627// A signal's value behind an object, downcast to its type when read.28pub interface Stored {}2930pub type Held<T> : Stored = struct {31 pub value: T,32};3334exp type Reader = struct {35 exp effect: u32,36 exp run: u32,37};3839exp type SignalSlot = struct {40 exp generation: u32,41 pub value: Option<*var Stored>, // None once its owner went42 exp readers: Vector<Reader>,43 pub limit: u64, // the readers' length at which they are compacted44};4546// The effect running, if any, and the signals read since it started; a47// nested run reads from its own mark on.48pub type Tracking = struct {49 pub effect: Option<u32>,50 pub reads: Vector<u32>,51};5253// Where a run started recording: the effect recording before it, and54// how many reads there were.55type Mark = struct {56 effect: Option<u32>,57 reads: u64,58};5960exp type Effect = struct {61 exp alive: bool,62 exp generation: u32,63 exp run: Option<|=| (&var Ui)>,64 pub owner: u32,65 pub depth: u32,66 exp runs: u32,67 pub queued: bool,68 exp node: Option<u32> = ::None, // the element it makes or fills69};7071// What a view made: freed together, with the owners made under it.72exp type OwnerSlot = struct {73 pub alive: bool,74 exp generation: u32 = 0, // of the Owner handles naming it75 pub parent: Option<u32>, // None for the root's76 pub depth: u32,77 pub signals: Vector<u32>,78 pub nodes: Vector<u32>,79 pub effects: Vector<u32>,80 pub owners: Vector<u32>,81 pub timers: Vector<u32>,82 // a hidden view's (screens.alloy): the bindings under it marked83 // meanwhile wait here, still queued, until it shows84 pub hidden: bool = false,85 pub deferred: Vector<u32> = Vector<u32>::empty(),86};8788pub fn OwnerSlot::create(parent: Option<u32>, depth: u32) -> OwnerSlot => OwnerSlot {89 .alive = true,90 .parent = parent,91 .depth = depth,92 .signals = Vector<u32>::empty(),93 .nodes = Vector<u32>::empty(),94 .effects = Vector<u32>::empty(),95 .owners = Vector<u32>::empty(),96 .timers = Vector<u32>::empty()97};9899/* --- Signals --- */100101pub fn new_signal(self ui: &var Ui, value: *var Stored) -> u32 {102 var index: u32 = 0;103 if (ui.free_signals.pop() is ::Some |k|) {104 index = k;105 const slot = &var ui.signals.get_var(k to u64);106 slot.value = ::Some(move value);107 slot.readers.clear();108 slot.limit = READERS_KEPT;109 } else {110 index = ui.signals.length() to u32;111 ui.signals.push(SignalSlot {112 .generation = 0,113 .value = ::Some(move value),114 .readers = Vector<Reader>::empty(),115 .limit = READERS_KEPT116 });117 }118 ui.owners.get_var(ui.owner to u64).signals.push(index);119 return index;120}121122pub fn check_signal(self ui: &Ui, index: u32, generation: u32) {123 const slot = &ui.signals.get(index to u64);124 if (slot.generation != generation || slot.value is ::None) {125 panic "pkg::alloy::ui: a signal used after its owner went";126 }127}128129// Records the read for the effect running, if any.130pub fn read_signal(self ui: &Ui, index: u32, generation: u32) {131 ui.check_signal(index, generation);132 var guard = ui.tracking.lock();133 const tracking = &var guard.value();134 if (tracking.effect is ::Some) {135 tracking.reads.push(index);136 }137 guard.dispose();138}139140// Marks the effects that read the signal in their last run.141exp fn changed_signal(self ui: &var Ui, index: u32) {142 const count = ui.signals.get(index to u64).readers.length();143 for ([..count]) |k| {144 const reader = ui.signals.get(index to u64).readers.get(k);145 ui.mark_effect(reader);146 }147 ui.signals.get_var(index to u64).readers.clear();148}149150// The value with no read recorded nor change marked: the framework's own151// state kept in signals.152exp fn peek<T>(self signal: &Signal<T>, ui: &Ui) -> &T {153 ui.check_signal(signal.index, signal.generation);154 if (ui.signals.get(signal.index to u64).value is ::Some |&held|) {155 if (held is Held<T> |&h|) {156 return &h.value;157 }158 }159 panic "pkg::alloy::ui: a signal of another type";160}161162exp fn peek_var<T>(self signal: &Signal<T>, ui: &var Ui) -> &var T {163 ui.check_signal(signal.index, signal.generation);164 if (ui.signals.get_var(signal.index to u64).value is ::Some |&var held|) {165 if (held is Held<T> |&var h|) {166 return &var h.value;167 }168 }169 panic "pkg::alloy::ui: a signal of another type";170}171172/* --- Effects --- */173174exp fn new_effect(self ui: &var Ui) -> u32 {175 const owner = ui.owner;176 const depth = ui.owners.get(owner to u64).depth;177 var index: u32 = 0;178 if (ui.free_effects.pop() is ::Some |k|) {179 index = k;180 const effect = &var ui.effects.get_var(k to u64);181 effect.alive = true;182 effect.owner = owner;183 effect.depth = depth;184 // past the old effect's runs, so its readers left in signals never185 // match the new one186 effect.runs += 1;187 effect.queued = false;188 } else {189 index = ui.effects.length() to u32;190 ui.effects.push(Effect {191 .alive = true,192 .generation = 0,193 .run = ::None,194 .owner = owner,195 .depth = depth,196 .runs = 0,197 .queued = false198 });199 }200 ui.owners.get_var(owner to u64).effects.push(index);201 return index;202}203204// Gives the effect what it runs, and the element it makes or fills, if205// any: what is busy while it shows a resource loading.206exp fn set_effect(self ui: &var Ui, effect: u32, node: Option<u32>, run: |=| (&var Ui)) {207 const e = &var ui.effects.get_var(effect to u64);208 e.run = ::Some(move run);209 e.node = node;210}211212// Queues the reader's effect, when the read is from its last run.213fn mark_effect(self ui: &var Ui, reader: Reader) {214 const e = &var ui.effects.get_var(reader.effect to u64);215 if (e.alive && e.runs == reader.run && !e.queued) {216 e.queued = true;217 ui.queue_effect(reader.effect);218 }219}220221// The dirty effects are a binary heap of their owner's depth and their222// index, the one nearest the root, then of the lowest index, first: the223// key is kept, so an effect freed and made again while queued leaves the224// heap in order, its old entry skipped when taken.225fn queue_effect(self ui: &var Ui, effect: u32) {226 const depth = ui.effects.get(effect to u64).depth to u64;227 ui.dirty.push(depth << 32 | effect to u64);228 var k = ui.dirty.length() - 1;229 while (k > 0) {230 const parent = (k - 1) / 2;231 const item = ui.dirty.get(k);232 const above = ui.dirty.get(parent);233 if (above <= item) {234 break;235 }236 ui.dirty.get_var(k) = above;237 ui.dirty.get_var(parent) = item;238 k = parent;239 }240}241242fn next_effect(self ui: &var Ui) -> u32 {243 const first = ui.dirty.get(0);244 const last = if (ui.dirty.pop() is ::Some |e|) e else first;245 const n = ui.dirty.length();246 if (n > 0) {247 ui.dirty.get_var(0) = last;248 var k: u64 = 0;249 while (2 * k + 1 < n) {250 var child = 2 * k + 1;251 if (child + 1 < n && ui.dirty.get(child + 1) < ui.dirty.get(child)) {252 child += 1;253 }254 const item = ui.dirty.get(k);255 const below = ui.dirty.get(child);256 if (item <= below) {257 break;258 }259 ui.dirty.get_var(k) = below;260 ui.dirty.get_var(child) = item;261 k = child;262 }263 }264 return (first & 0xFFFFFFFF) to u32;265}266267// Starts recording reads for the effect, or for none; gives the mark268// `end_tracking` takes.269fn begin_tracking(self ui: &Ui, effect: Option<u32>) -> Mark {270 var guard = ui.tracking.lock();271 const tracking = &var guard.value();272 const saved = Mark { .effect = tracking.effect, .reads = tracking.reads.length() };273 tracking.effect = effect;274 guard.dispose();275 return saved;276}277278// Subscribes the effect recording to what it read since the mark, and279// goes back to recording for the effect before.280fn end_tracking(self ui: &var Ui, saved: Mark) {281 var guard = ui.tracking.lock();282 const tracking = &var guard.value();283 const recording = tracking.effect;284 const reads = Vector<u32>::from(&tracking.reads.view()[saved.reads..]);285 tracking.reads.truncate(saved.reads);286 tracking.effect = saved.effect;287 guard.dispose();288 const effect = if (recording is ::Some |e| && ui.effects.get(e to u64).alive) e else {289 return;290 };291 const run = ui.effects.get(effect to u64).runs;292 for (reads.view()) |&index| {293 const slot = &var ui.signals.get_var(index to u64);294 const fresh = if (slot.readers.try_last() is ::Some |&r|) r.effect != effect295 || r.run != run else true;296 if (fresh) {297 slot.readers.push(Reader { .effect = effect, .run = run });298 if (slot.readers.length() >= slot.limit) {299 ui.compact_readers(index);300 }301 }302 }303}304305// Drops the readers whose effect ran again or went, which a signal that306// rarely changes would otherwise keep gathering, and sets the length at307// which it is done again to twice what is left.308fn compact_readers(self ui: &var Ui, index: u32) {309 var kept = Vector<Reader>::empty();310 for (ui.signals.get(index to u64).readers.view()) |r| {311 const e = &ui.effects.get(r.effect to u64);312 if (e.alive && e.runs == r.run) {313 kept.push(r);314 }315 }316 const slot = &var ui.signals.get_var(index to u64);317 slot.limit = max(READERS_KEPT, kept.length() * 2);318 slot.readers = move kept;319}320321const READERS_KEPT: u64 = 16;322323// The function's result, its reads subscribing the effect.324exp fn tracked<R>(self ui: &var Ui, effect: u32, f: &|&| (&Ui) -> R) -> R {325 ui.effects.get_var(effect to u64).runs += 1;326 const saved = ui.begin_tracking(::Some(effect));327 var result = f(&ui);328 ui.end_tracking(saved);329 return move result;330}331332// Runs the function recording no reads, as views are made.333pub fn untracked<R>(self ui: &var Ui, f: &|&| (&var Ui) -> R) -> R {334 const saved = ui.begin_tracking(::None);335 var result = f(&var ui);336 ui.end_tracking(saved);337 return move result;338}339340// Runs the effect, what it makes belonging to its owner.341exp fn run_effect(self ui: &var Ui, effect: u32) {342 if (!ui.effects.get(effect to u64).alive) {343 return;344 }345 const generation = ui.effects.get(effect to u64).generation;346 var run = ui.take_run(effect);347 if (run is ::Some |&f|) {348 const owner = ui.owner;349 ui.owner = ui.effects.get(effect to u64).owner;350 ui.effects.get_var(effect to u64).runs += 1;351 const saved = ui.begin_tracking(::Some(effect));352 f(&var ui);353 ui.end_tracking(saved);354 ui.owner = owner;355 }356 const slot = &var ui.effects.get_var(effect to u64);357 if (slot.alive && slot.generation == generation) {358 slot.run = move run;359 }360}361362fn take_run(self ui: &var Ui, effect: u32) -> Option<|=| (&var Ui)> {363 const slot = &var ui.effects.get_var(effect to u64);364 var taken = move slot.run;365 slot.run = ::None;366 return move taken;367}368369// Runs the marked effects, those of owners nearer the root first, then370// those of lower index; effects they mark run in the same pass. Those of371// a hidden view wait for it to show.372exp fn flush(self ui: &var Ui) {373 while (ui.dirty.length() > 0) {374 const effect = ui.next_effect();375 if (ui.effects.get(effect to u64).alive && ui.effects.get(effect to u64).queued) {376 if (377 ui.hidden_owners > 0378 && ui.hidden_above(ui.effects.get(effect to u64).owner) is ::Some |h|379 ) {380 ui.owners.get_var(h to u64).deferred.push(effect);381 continue;382 }383 ui.effects.get_var(effect to u64).queued = false;384 ui.run_effect(effect);385 }386 }387}388389// The hidden owner the owner is or is under, if any.390fn hidden_above(self ui: &Ui, owner: u32) -> Option<u32> {391 var at: Option<u32> = ::Some(owner);392 while (at is ::Some |k|) {393 const o = &ui.owners.get(k to u64);394 if (o.hidden) {395 return at;396 }397 at = o.parent;398 }399 return ::None;400}401402// Hides what the owner made from its bindings' runs, or shows it again,403// queueing those marked meanwhile.404pub fn set_owner_hidden(self ui: &var Ui, owner: u32, hidden: bool) {405 const o = &var ui.owners.get_var(owner to u64);406 if (o.hidden == hidden) {407 return;408 }409 o.hidden = hidden;410 if (hidden) {411 ui.hidden_owners += 1;412 return;413 }414 ui.hidden_owners -= 1;415 var waiting = move o.deferred;416 o.deferred = Vector<u32>::empty();417 for (waiting.view()) |effect| {418 const e = &ui.effects.get(effect to u64);419 if (e.alive && e.queued) {420 ui.queue_effect(effect);421 }422 }423}424425// Whether a binding shown reads the signal: one whose last run read it,426// not in a hidden view.427exp fn read_shown(self ui: &Ui, index: u32) -> bool {428 for (ui.signals.get(index to u64).readers.view()) |r| {429 const e = &ui.effects.get(r.effect to u64);430 if (431 e.alive432 && e.runs == r.run433 && (ui.hidden_owners == 0 || ui.hidden_above(e.owner) is ::None)434 ) {435 return true;436 }437 }438 return false;439}440441// Whether the signal is still there.442exp fn signal_alive(self ui: &Ui, index: u32, generation: u32) -> bool {443 const slot = &ui.signals.get(index to u64);444 return slot.generation == generation && slot.value is ::Some;445}446447/* --- Owners --- */448449exp fn new_owner(self ui: &var Ui, parent: u32) -> u32 {450 const depth = ui.owners.get(parent to u64).depth + 1;451 var index: u32 = 0;452 if (ui.free_owners.pop() is ::Some |k|) {453 index = k;454 const generation = ui.owners.get(k to u64).generation;455 ui.owners.set(k to u64, OwnerSlot::create(::Some(parent), depth));456 ui.owners.get_var(k to u64).generation = generation;457 } else {458 index = ui.owners.length() to u32;459 ui.owners.push(OwnerSlot::create(::Some(parent), depth));460 }461 ui.owners.get_var(parent to u64).owners.push(index);462 return index;463}464465// Frees what the owner made, and the owners made under it.466exp fn free_owner(self ui: &var Ui, owner: u32) {467 if (!ui.owners.get(owner to u64).alive) {468 return;469 }470 // what it made with a transition plays it as it goes, its requests471 // cancelled472 ui.extensions_owner_going(owner);473 while (ui.owners.get_var(owner to u64).owners.pop() is ::Some |child|) {474 ui.free_owner(child);475 }476 ui.drop_owned_timers(owner);477 while (ui.owners.get_var(owner to u64).effects.pop() is ::Some |e|) {478 const effect = &var ui.effects.get_var(e to u64);479 effect.alive = false;480 effect.generation += 1;481 effect.run = ::None;482 effect.queued = false;483 ui.free_effects.push(e);484 }485 while (ui.owners.get_var(owner to u64).nodes.pop() is ::Some |n|) {486 ui.free_node(n);487 }488 while (ui.owners.get_var(owner to u64).signals.pop() is ::Some |s|) {489 const slot = &var ui.signals.get_var(s to u64);490 slot.value = ::None;491 slot.generation += 1;492 slot.readers.clear();493 ui.free_signals.push(s);494 }495 const o = &var ui.owners.get_var(owner to u64);496 o.alive = false;497 o.generation += 1;498 if (o.hidden) {499 o.hidden = false;500 o.deferred.clear();501 ui.hidden_owners -= 1;502 }503 if (o.parent is ::Some |parent|) {504 const siblings = &var ui.owners.get_var(parent to u64).owners;505 for ([..siblings.length()]) |k| {506 if (siblings.get(k) == owner) {507 siblings.swap_remove(k);508 break;509 }510 }511 }512 ui.free_owners.push(owner);513}514515// The owner the handle names, faulting once it went.516exp fn owner_index(self ui: &Ui, owner: Owner) -> u32 {517 if (518 ui.owners.try_get(owner.index to u64) is ::Some |&slot|519 && slot.alive520 && slot.generation == owner.generation521 ) {522 return owner.index;523 }524 panic "pkg::alloy::ui: an owner used after it went";525}526527// The owner given, else what is being made now belongs to.528exp fn owner_given(self ui: &Ui, owner: Option<Owner>) -> u32 {529 return if (owner is ::Some |o|) ui.owner_index(o) else ui.owner;530}531532// Runs the function as a new owner under the one now.533exp fn owned<R>(self ui: &var Ui, owner: u32, f: &|&| (&var Ui) -> R) -> R {534 const saved = ui.owner;535 ui.owner = owner;536 var result = ui.untracked(&f);537 ui.owner = saved;538 return move result;539}540541/* --- show and each --- */542543pub type RowOf<T> = struct {544 pub owner: u32,545 pub item: Signal<T>,546 pub element: u32,547};548549pub type Rows<T, K: hash::Key> = struct {550 pub rows: Map<K, RowOf<T>>,551};552553// Shows or hides the view as the condition says; `state` holds the554// owner of what the view made while it shows.555pub fn run_show(556 self ui: &var Ui,557 element: Element,558 state: Signal<Option<u32>>,559 condition: &|&| (&Ui) -> bool,560 view: &|&| (&var Ui) -> Element561) {562 const visible = condition(&ui);563 const shown: Option<u32> = state.peek(&ui);564 if (visible == (shown is ::Some)) {565 return;566 }567 if (shown is ::Some |owner|) {568 // freed first, so a view leaving with a reveal leaves its room569 ui.free_owner(owner);570 ui.disown_children_but_rooms(element.index);571 state.peek_var(&var ui) = ::None;572 } else {573 const made = ui.new_owner(ui.owner);574 const root = ui.owned(made, &view);575 ui.adopt(element.index, root);576 state.peek_var(&var ui) = ::Some(made);577 }578 ui.mark_layout(element.index);579}580581pub fn run_each<T, K: hash::Key>(582 self ui: &var Ui,583 element: Element,584 items: Signal<Vector<T>>,585 state: Signal<Rows<T, K>>,586 key: &|&| (&T) -> K,587 row: &|&| (&var Ui, Signal<T>) -> Element588) {589 const list = copy items.get(&ui);590 var seen = Map<K, bool>::empty();591 var order = Vector<u32>::empty();592 for (list.view()) |&item| {593 var k = key(&item);594 if (seen.insert(copy k, true) is ::Some) {595 panic "pkg::alloy::ui: two items of an each with one key";596 }597 if (state.peek(&ui).rows.try_get(&k) is ::Some |&r|) {598 const signal = r.item;599 order.push(r.element);600 // a row's item set again only when it changed, where its601 // type says what changing is602 var same = false;603 if (T: Equal) {604 same = signal.peek(&ui) == item;605 }606 if (!same) {607 signal.set(&var ui, copy item);608 }609 } else {610 const made = ui.new_owner(ui.owner);611 const saved = ui.owner;612 ui.owner = made;613 const signal = ui.signal(copy item);614 ui.owner = saved;615 const built = ui.owned(made, &|&row, signal| (ui: &var Ui) -> Element {616 return row(&var ui, signal);617 });618 order.push(built.index);619 state.peek_var(&var ui).rows.insert(move k, RowOf<T> {620 .owner = made,621 .item = signal,622 .element = built.index623 });624 }625 }626 // the rows whose keys went, freed first, so one leaving with a reveal627 // leaves its room among the rows628 var gone = Vector<K>::empty();629 for (state.peek(&ui).rows.entries()) |&entry| {630 if (!seen.contains(&entry.key)) {631 gone.push(copy entry.key);632 }633 }634 for (gone.view()) |&k| {635 if (state.peek_var(&var ui).rows.remove(&k) is ::Some |&r|) {636 ui.free_owner(r.owner);637 }638 }639 const before = copy ui.node(element.index).children;640 ui.disown_children(element.index);641 if (ui.extension<Visuals>() is ::Some) {642 order = rooms_kept(&ui, &before.view(), &order.view());643 }644 for (order.view()) |&child| {645 ui.adopt_index(element.index, child);646 }647 ui.mark_layout(element.index);648}649650// The rows in their new order, with the rooms rows leaving left after651// the row that was before each, or first.652fn rooms_kept(ui: &Ui, before: &[u32], order: &[u32]) -> Vector<u32> {653 var out = Vector<u32>::empty();654 var after = Map<u32, Vector<u32>>::empty();655 var last = Option<u32>::None;656 for (before) |&child| {657 if (!ui.is_room(child)) {658 last = ::Some(child);659 } else if (last is ::Some |row|) {660 if (after.try_get_var(&row) is ::Some |&var rooms|) {661 rooms.push(child);662 } else {663 after.insert(row, Vector<u32>::from(&[child]));664 }665 } else {666 out.push(child);667 }668 }669 for (order) |&row| {670 out.push(row);671 if (after.try_get(&row) is ::Some |&rooms|) {672 out.append(&rooms.view());673 }674 }675 return move out;676}677678// Takes from the node its children but the rooms of views leaving.679fn disown_children_but_rooms(self ui: &var Ui, parent: u32) {680 if (ui.extension<Visuals>() is ::None) {681 ui.disown_children(parent);682 return;683 }684 var kept = Vector<u32>::empty();685 for (ui.node(parent).children.view()) |&child| {686 if (ui.is_room(child)) {687 kept.push(child);688 } else {689 ui.node_var(child).parent = ::None;690 }691 }692 ui.node_var(parent).children = move kept;693}