ui_app

source of network

1// Waiting in the Ui (decisions/F12.md, "Waiting in ui"): the2// requests `send` sends and the resources `load` keeps, each request an3// exchange belonging to an owner, cancelled when it goes. Where one runs4// depends on where the Ui is: natively on the app's network tasks, which5// wait in std::http and give back through the background work's channel;6// on the web through `fetch`, its callback waking the loop; in a replay7// from its script; and in a Ui made on its own at once. What came back is8// handled as a handler at the next update. While a binding shown reads9// an exchange's progress, the Ui looks at it every 100 ms. None of it is10// in a program sending nothing: the Ui's state for it is an extension11// installed as the first request goes, the tasks' a service of the app's.1213import std::string;14import std::vector;15import std::option;16import std::result;17import std::sync;18import std::time;19import std::ffi;20import std::format;21import std::process;22import std::http;23import pkg::alloy::window;2425import pkg::alloy::ui;26import pkg::alloy::ui::store;27import pkg::alloy::ui::tree;28import pkg::alloy::ui::layout;29import pkg::alloy::ui::painting;30import pkg::alloy::ui::events;31import pkg::alloy::ui::widgets;32import pkg::alloy::ui::fields;33import pkg::alloy::ui::scrolling;34import pkg::alloy::ui::running;35import pkg::alloy::ui::timers;36import pkg::alloy::ui::layers;37import pkg::alloy::ui::motion;38import pkg::alloy::ui::transitions;39import pkg::alloy::ui::languages;40import pkg::alloy::ui::extensions;41import pkg::alloy::ui::views;42import ui_app;4344/* --- The app's network tasks --- */4546// What the app's network and worker tasks share with the UI thread, the47// app's service (`Workers.service`), set as the first request goes or48// the store first writes: the requests sent to the network's tasks, each49// given the app's client, a local of theirs (`serve`); the exchanges50// under way, which the UI thread cancels and follows through their51// controls; whether the network's tasks were started, by the first52// request, so an app sending none has no network tasks nor their code;53// and whether a worker is writing the app's store (persisted.alloy),54// which the last write as the app ends waits for, so the older never55// lands over the newer.56pub type Network : Service + Shared = struct {57    pub requests: Channel<|=| (&Network, &Client) -> |=| (&var Ui)>,58    lines: Mutex<Lines>,59    pub started: Atomic<bool>,60    pub store_writing: Atomic<bool>,61};6263// The network tasks an app runs once it sends a request.64const NETWORK_TASKS: u64 = 8;6566// The exchanges the tasks are running, by the Ui's ids, and those67// cancelled before a task took them.68type Lines = struct {69    running: Vector<Line>,70    cancelled: Vector<u64>,71    closed: bool, // the app is ending: nothing more starts72};7374type Line = struct {75    id: u64,76    control: &Control,77};7879pub fn Network::create() -> Network {80    return Network {81        .requests = Channel<|=| (&Network, &Client) -> |=| (&var Ui)>::empty(),82        .lines = Mutex<Lines>::from(Lines {83            .running = Vector<Line>::empty(),84            .cancelled = Vector<u64>::empty(),85            .closed = false86        }),87        .started = Atomic<bool>::from(false),88        .store_writing = Atomic<bool>::from(false)89    };90}9192// The network's tasks, from the first request on: eight taking the93// requests in turn, all through the app's client, whose kept connections94// close as the app ends.95pub fn serve(self network: &Network, workers: &Workers) {96    var client = Client {};97    scope {98        for ([..NETWORK_TASKS]) {99            spawn {100                while (network.requests.receive() is ::Some |move job|) {101                    workers.finish(job(&network, &client));102                }103            }104        }105    }106    client.dispose();107}108109// The app ends: the network's tasks end with what they are doing.110pub fn end(self network: &Network) {111    network.requests.close();112}113114// The app's network service, made the first time it is asked for; none115// with no workers, and none on the web, whose page has no tasks.116pub fn network_of(self ui: &Ui) -> Option<&Network> {117    if (target() != "web-wasm32") {118        if (ui.workers is ::Some |&workers|) {119            if (workers.service is ::None) {120                workers.service = ::Some(new Network::create());121            }122            if (workers.service is ::Some |&service| && service is Network |&network|) {123                return ::Some(&network);124            }125        }126    }127    return ::None;128}129130// What the app's tasks share, as a job given it finds the network.131pub fn network_in(workers: &Workers) -> Option<&Network> {132    if (workers.service is ::Some |&service| && service is Network |&network|) {133        return ::Some(&network);134    }135    return ::None;136}137138// Ends the exchanges under way and refuses those to come, as the app139// closes its window, so its tasks end soon.140fn close_lines(self network: &Network) {141    var guard = network.lines.lock();142    const lines = &var guard.value();143    lines.closed = true;144    for (lines.running.view()) |&line| {145        line.control.cancel();146    }147    guard.dispose();148}149150// Follows the exchange through the control while it runs; false when it151// was cancelled before, or the app is ending.152fn open(self network: &Network, id: u64, control: &Control) -> bool {153    var guard = network.lines.lock();154    const lines = &var guard.value();155    var going = !lines.closed;156    for ([..lines.cancelled.length()]) |k| {157        if (lines.cancelled.get(k) == id) {158            lines.cancelled.swap_remove(k);159            going = false;160            break;161        }162    }163    if (going) {164        lines.running.push(Line { .id = id, .control = &control });165    }166    guard.dispose();167    return going;168}169170fn finish(self network: &Network, id: u64) {171    var guard = network.lines.lock();172    const running = &var guard.value().running;173    for ([..running.length()]) |k| {174        if (running.get(k).id == id) {175            running.swap_remove(k);176            break;177        }178    }179    guard.dispose();180}181182// Cancels the exchange, now or as a task takes it.183fn cancel_line(self network: &Network, id: u64) {184    var guard = network.lines.lock();185    const lines = &var guard.value();186    var found = false;187    for (lines.running.view()) |&line| {188        if (line.id == id) {189            line.control.cancel();190            found = true;191        }192    }193    if (!found) {194        lines.cancelled.push(id);195    }196    guard.dispose();197}198199// What came back for an exchange cancelled before a task took it no200// longer needs its mark.201fn forget(self network: &Network, id: u64) {202    var guard = network.lines.lock();203    const cancelled = &var guard.value().cancelled;204    for ([..cancelled.length()]) |k| {205        if (cancelled.get(k) == id) {206            cancelled.swap_remove(k);207            break;208        }209    }210    guard.dispose();211}212213fn line_progress(self network: &Network, id: u64) -> Option<Progress> {214    var guard = network.lines.lock();215    var found: Option<Progress> = ::None;216    for (guard.value().running.view()) |&line| {217        if (line.id == id) {218            found = ::Some(line.control.progress());219        }220    }221    guard.dispose();222    return found;223}224225// The request for a network task: sent through a control the Ui follows,226// then given to `complete`, natively off the UI thread.227fn network_job(228    id: u64,229    request: Request,230    complete: |=| (Result<Response, HttpError>) -> |=| (&var Ui)231) -> |=| (&Network, &Client) -> |=| (&var Ui) {232    return |move request, move complete, id| (network: &Network, client: &Client) -> |=| (&var Ui) {233        const control = Control::create();234        var result: Result<Response, HttpError> = ::Err(::Cancelled);235        if (network.open(id, &control)) {236            result = client.send_with(&request, &control);237            network.finish(id);238        }239        return complete(move result);240    };241}242243/* --- The Ui's exchanges --- */244245// What a resource holds: now, and the last Done while the next loads.246pub type Loaded<T> = struct {247    pub now: Loading<T>,248    pub kept: Option<T>,249};250251pub type NetState = struct {252    pub exchanges: Vector<ExchangeSlot> = Vector<ExchangeSlot>::empty(),253    pub free: Vector<u32> = Vector<u32>::empty(),254    pub serial: u64 = 0,255    pub resources: Vector<ResourceSlot> = Vector<ResourceSlot>::empty(),256    // a replay's responses, and the URLs asked for, in order257    pub script: Option<Vector<Scripted>> = ::None,258    pub asked: Vector<String> = Vector<String>::empty(),259    // on the web, what the page's callbacks gave, taken as it wakes260    pub inbox: c_pointer = 0,261    pub poll: Option<Timer> = ::None, // the next look at the progress read262    pub busy: Vector<u32> = Vector<u32>::empty(), // the elements marked busy263};264265pub type Scripted = struct {266    pub response: ScriptedResponse,267    pub used: bool,268};269270pub type ExchangeSlot = struct {271    pub generation: u32,272    pub live: bool,273    pub id: u64,274    pub owner: u32,275    pub resource: Option<u32>, // the resource it loads for276    pub progress: Option<Signal<Option<Progress>>>, // a request's `send` sent277    pub shown: Progress, // as last given278    pub announce: bool, // a failure is said279    pub page: Option<Exchange>, // on the web280    // in a replay: the answer's timer, when the request went and the281    // answer comes, and its body's length282    pub answer: Option<Timer>,283    pub started: u64,284    pub due: u64,285    pub length: u64,286};287288pub type ResourceSlot = struct {289    pub generation: u32,290    pub alive: bool,291    pub owner: u32,292    pub signal: u32, // its state's293    pub delay: Duration,294    pub runs: u32, // of its request binding295    pub asked: Option<Request>, // what it asked for last296    pub exchange: Option<u32>, // the exchange under way297    pub timer: Option<Timer>, // the delay's298    pub waiting: bool,299    // the completion of an exchange (its slot and generation) for it, and300    // the state set waiting, at the progress301    pub make: Option<|=| (u32, u32) -> |=| (Result<Response, HttpError>) -> |=| (&var Ui)>,302    pub wait: Option<|=| (&var Ui, Progress)>,303};304305// The progress of nothing yet.306pub fn no_progress() -> Progress => Progress {307    .sent = 0,308    .to_send = 0,309    .received = 0,310    .total = ::None311};312313// The requests' and resources' state, an extension installed as the314// first request goes: an owner going cancels its exchanges, the progress315// read is looked at before the window's deadline, the elements waiting316// are marked busy before the tree is sent, the page's answers taken as it317// wakes the loop, and every exchange cancelled as the app ends.318pub type Requests : Extension = struct {319    pub net: NetState = NetState {},320};321322pub fn owner_going(self r: &var Requests, ui: &var Ui, owner: u32) {323    ui.requests_gone(owner);324}325326pub fn deadline(self r: &var Requests, ui: &var Ui) -> Option<u64> {327    ui.arm_network();328    return ::None;329}330331pub fn describing(self r: &var Requests, ui: &var Ui) {332    ui.mark_busy();333}334335pub fn event(self r: &var Requests, ui: &var Ui, event: &Event) {336    // what the page's callbacks gave337    if (event is ::Woken && target() == "web-wasm32") {338        ui.take_inbox();339    }340}341342pub fn closing(self r: &var Requests, ui: &var Ui) {343    ui.requests_end();344}345346pub fn net_state(self ui: &var Ui) -> &var NetState {347    if (ui.extension<Requests>() is ::None) {348        var made = Requests {};349        // a replay's requests are answered from its script, none by the350        // network351        if (ui.replaying) {352            made.net.script = ::Some(Vector<Scripted>::empty());353        }354        ui.install(new made);355    }356    if (ui.extension_var<Requests>() is ::Some |&var r|) {357        return &var r.net;358    }359    panic "pkg::alloy::ui: no network state";360}361362fn net_peek(self ui: &Ui) -> &NetState {363    if (ui.extension<Requests>() is ::Some |&r|) {364        return &r.net;365    }366    panic "pkg::alloy::ui: no network state";367}368369// Whether a request went yet.370fn has_requests(self ui: &Ui) -> bool => ui.extension<Requests>() is ::Some;371372// Answers requests from the responses from now on, as a replay given373// them does.374pub fn use_script(self ui: &var Ui, responses: Vector<ScriptedResponse>) {375    var script = Vector<Scripted>::empty();376    var given = move responses;377    for (given.items()) |&var r| {378        script.push(Scripted { .response = move r, .used = false });379    }380    ui.net_state().script = ::Some(move script);381}382383// A slot for an exchange belonging to the owner.384fn new_exchange(self ui: &var Ui, owner: u32, resource: Option<u32>, announce: bool) -> [u32 : 2] {385    const started = ui.time.nanoseconds;386    const net = &var ui.net_state();387    net.serial += 1;388    var slot = ExchangeSlot {389        .generation = 0,390        .live = true,391        .id = net.serial,392        .owner = owner,393        .resource = resource,394        .progress = ::None,395        .shown = no_progress(),396        .announce = announce,397        .page = ::None,398        .answer = ::None,399        .started = started,400        .due = started,401        .length = 0402    };403    if (net.free.pop() is ::Some |k|) {404        slot.generation = net.exchanges.get(k to u64).generation;405        net.exchanges.set(k to u64, move slot);406        return [k, net.exchanges.get(k to u64).generation];407    }408    net.exchanges.push(move slot);409    return [(net.exchanges.length() - 1) to u32, 0];410}411412// Starts the exchange in the slot where this Ui sends requests.413fn start_exchange(414    self ui: &var Ui,415    index: u32,416    request: Request,417    complete: |=| (Result<Response, HttpError>) -> |=| (&var Ui)418) {419    const id = ui.net_peek().exchanges.get(index to u64).id;420    if (ui.net_peek().script is ::Some) {421        ui.start_scripted(index, move request, move complete);422    } else if (target() == "web-wasm32") {423        const inbox = ui.page_inbox();424        const waker = ui.waker;425        const exchange = start(move request, |move complete, inbox, waker| (result) {426            var finish = complete(move result);427            inbox.as_var<Vector<|=| (&var Ui)>>().push(move finish);428            waker.wake();429        });430        ui.net_state().exchanges.get_var(index to u64).page = ::Some(exchange);431    } else if (ui.network_of() is ::Some |&network|) {432        // the first request starts the network's tasks433        if (!network.started.load()) {434            network.started.store(true);435            if (ui.workers is ::Some |&workers|) {436                workers.starting.send(true);437            }438        }439        network.requests.send(network_job(id, move request, move complete));440    } else {441        // a Ui on its own waits here442        ui.finished.push(complete(send(&request)));443    }444}445446// The script's answer to the request, at its time, or a failure at once447// when it has none.448fn start_scripted(449    self ui: &var Ui,450    index: u32,451    request: Request,452    complete: |=| (Result<Response, HttpError>) -> |=| (&var Ui)453) {454    const now = ui.time.nanoseconds;455    const owner = ui.net_peek().exchanges.get(index to u64).owner;456    const net = &var ui.net_state();457    net.asked.push(copy request.url);458    var answer: Result<Response, HttpError> = ::Err(::Unsupported);459    var due = now;460    var found = false;461    if (net.script is ::Some |&var script|) {462        for (script.items()) |&var s| {463            if (!s.used && s.response.url == request.url) {464                s.used = true;465                found = true;466                answer = copy s.response.answer;467                due = if (s.response.at.nanoseconds > now) s.response.at.nanoseconds else now;468                break;469            }470        }471    }472    if (!found) {473        ui.finished.push(complete(move answer));474        return;475    }476    const slot = &var net.exchanges.get_var(index to u64);477    slot.due = due;478    slot.length = if (answer is ::Ok |&r|) r.body.length() else 0;479    const saved = ui.owner;480    ui.owner = owner;481    const timer = ui.new_timer(due, 0, |move complete, move answer| (ui: &var Ui) {482        var finish = complete(move answer);483        finish(&var ui);484    });485    ui.owner = saved;486    ui.net_state().exchanges.get_var(index to u64).answer = ::Some(timer);487}488489// The page's inbox, made on the heap the first time: the page's callbacks490// reach it through its address.491fn page_inbox(self ui: &var Ui) -> c_pointer {492    const net = &var ui.net_state();493    if (net.inbox == 0) {494        var inbox: *var Vector<|=| (&var Ui)> = new Vector<|=| (&var Ui)>::empty();495        net.inbox = c_pointer::keep(move inbox);496    }497    return net.inbox;498}499500// What the page's callbacks gave, to run at the next update.501fn take_inbox(self ui: &var Ui) {502    const inbox = ui.net_peek().inbox;503    if (inbox != 0) {504        const items = &var inbox.as_var<Vector<|=| (&var Ui)>>();505        for (items.items()) |&var done| {506            ui.finished.push(move done);507        }508        items.clear();509    }510}511512// Ends the exchange as what came back is handled, saying a failure the513// user asked for; false when it was cancelled meanwhile.514fn end_exchange(self ui: &var Ui, index: u32, generation: u32, failed: Option<String>) -> bool {515    const slot = &ui.net_peek().exchanges.get(index to u64);516    if (slot.generation != generation || !slot.live) {517        if (ui.network_of() is ::Some |&network|) {518            network.forget(slot.id);519        }520        return false;521    }522    const announce = slot.announce;523    ui.release_exchange(index);524    if (announce && failed is ::Some |move why|) {525        ui.announce(move why, true);526    }527    return true;528}529530// Frees the slot: its progress read as none, its resource no longer531// waiting on it.532fn release_exchange(self ui: &var Ui, index: u32) {533    const net = &var ui.net_state();534    const slot = &var net.exchanges.get_var(index to u64);535    slot.live = false;536    slot.generation += 1;537    const progress = slot.progress;538    const resource = slot.resource;539    net.free.push(index);540    if (resource is ::Some |r|) {541        const held = &var net.resources.get_var(r to u64);542        if (held.exchange == ::Some(index)) {543            held.exchange = ::None;544            held.waiting = false;545        }546    }547    if (progress is ::Some |signal| && ui.signal_alive(signal.index, signal.generation)) {548        signal.set(&var ui, ::None);549    }550}551552// Stops the exchange where it runs and frees its slot.553fn cancel_exchange(self ui: &var Ui, index: u32) {554    const slot = copy ui.net_peek().exchanges.get(index to u64);555    if (!slot.live) {556        return;557    }558    if (slot.page is ::Some |&exchange|) {559        exchange.cancel();560    } else if (slot.answer is ::Some |timer|) {561        ui.drop_timer(timer);562    } else if (ui.network_of() is ::Some |&network|) {563        network.cancel_line(slot.id);564    }565    ui.release_exchange(index);566}567568/* --- Requests --- */569570pub fn send_request(571    self ui: &var Ui,572    request: Request,573    then: |=| (&var Ui, Result<Response, HttpError>),574    given: Option<u32>575) -> Pending {576    ui.net_state();577    const owner = if (given is ::Some |o|) o else if (578        ui.handling is ::Some |h|579    ) ui.owner_of(h) else ui.owner;580    const made = ui.new_exchange(owner, ::None, true);581    const saved = ui.owner;582    ui.owner = owner;583    const progress = ui.signal(Option<Progress>::Some(no_progress()));584    ui.owner = saved;585    ui.net_state().exchanges.get_var(made[0] to u64).progress = ::Some(progress);586    const index = made[0];587    const generation = made[1];588    var complete = |move then, index, generation| (589        result: Result<Response, HttpError>590    ) -> |=| (&var Ui) {591        var failed: Option<String> = ::None;592        if (result is ::Err |&e|) {593            failed = ::Some(f"The request failed: {e}");594        } else if (result is ::Ok |&r| && !r.ok()) {595            failed = ::Some(f"The request failed: the server answered {r.status}");596        }597        return |move then, move result, move failed, index, generation| (ui: &var Ui) {598            if (ui.end_exchange(index, generation, move failed)) {599                then(&var ui, move result);600            }601        };602    };603    ui.start_exchange(index, move request, move complete);604    return Pending { .index = index, .generation = generation };605}606607pub fn cancel_pending(self ui: &var Ui, pending: Pending) {608    if (!ui.has_requests()) {609        return;610    }611    const net = &ui.net_peek();612    if (613        net.exchanges.try_get(pending.index to u64) is ::Some |&slot|614        && slot.generation == pending.generation615    ) {616        ui.cancel_exchange(pending.index);617    }618}619620pub fn pending_progress(self ui: &Ui, pending: Pending) -> Option<Progress> {621    if (!ui.has_requests()) {622        return ::None;623    }624    const net = &ui.net_peek();625    if (626        net.exchanges.try_get(pending.index to u64) is ::Some |&slot|627        && slot.generation == pending.generation628        && slot.progress is ::Some |signal|629    ) {630        return copy signal.get(&ui);631    }632    return ::None;633}634635/* --- Resources --- */636637pub fn new_resource<T>(638    self ui: &var Ui,639    request: |=| (&Ui) -> Option<Request>,640    read: |=| (&Response) -> Result<T, String>,641    options: LoadOptions642) -> Resource<T> {643    const state = ui.signal(Loaded<T> {644        .now = Loading<T>::Waiting(no_progress()),645        .kept = ::None646    });647    var make = |move read, state| (648        index: u32,649        generation: u32650    ) -> |=| (Result<Response, HttpError>) -> |=| (&var Ui) {651        return |copy read, state, index, generation| (652            result: Result<Response, HttpError>653        ) -> |=| (&var Ui) {654            var now = loading_from(&read, move result);655            var failed: Option<String> = ::None;656            if (now is ::Failed |&f|) {657                failed = ::Some(f"Loading failed: {f}");658            }659            return |move now, move failed, state, index, generation| (ui: &var Ui) {660                if (ui.end_exchange(index, generation, move failed)) {661                    var given = move now;662                    state.update(&var ui, |move given| (l: &var Loaded<T>) {663                        if (given is ::Done) {664                            l.kept = ::None;665                        }666                        l.now = move given;667                    });668                }669            };670        };671    };672    const keep = options.keep;673    var wait = |state, keep| (ui: &var Ui, progress: Progress) {674        state.update(&var ui, |progress, keep| (l: &var Loaded<T>) {675            var was = move l.now;676            l.now = Loading<T>::Waiting(progress);677            if (was is ::Done |move value|) {678                l.kept = if (keep) ::Some(move value) else ::None;679            }680        });681    };682    const slot = ui.add_resource(state.index, options.delay, move make, move wait);683    const effect = ui.new_effect();684    ui.set_effect(effect, ::None, |move request, slot| (ui: &var Ui) {685        var asked = request(&ui);686        ui.resource_asked(slot[0], slot[1], move asked);687    });688    ui.run_effect(effect);689    return Resource<T> { .state = state, .slot = slot[0], .generation = slot[1] };690}691692// What the request gave as the resource holds it: read when the server693// answered with 2xx.694fn loading_from<T>(695    read: &|=| (&Response) -> Result<T, String>,696    result: Result<Response, HttpError>697) -> Loading<T> {698    var given = move result;699    match (given) {700        ::Err |move e| {701            return ::Failed(::Network(move e));702        }703        ::Ok |move response| {704            if (!response.ok()) {705                return ::Failed(::Status(move response));706            }707            var got = read(&response);708            match (got) {709                ::Err |move why| {710                    return ::Failed(::Unreadable(move why));711                }712                ::Ok |move value| {713                    return ::Done(move value);714                }715            }716        }717    }718}719720fn add_resource(721    self ui: &var Ui,722    signal: u32,723    delay: Duration,724    make: |=| (u32, u32) -> |=| (Result<Response, HttpError>) -> |=| (&var Ui),725    wait: |=| (&var Ui, Progress)726) -> [u32 : 2] {727    const owner = ui.owner;728    const net = &var ui.net_state();729    var slot = ResourceSlot {730        .generation = 0,731        .alive = true,732        .owner = owner,733        .signal = signal,734        .delay = delay,735        .runs = 0,736        .asked = ::None,737        .exchange = ::None,738        .timer = ::None,739        .waiting = true,740        .make = ::Some(move make),741        .wait = ::Some(move wait)742    };743    // the slots of resources gone, kept apart from the live ones' by744    // their generation745    for ([..net.resources.length()]) |k| {746        if (!net.resources.get(k).alive) {747            slot.generation = net.resources.get(k).generation;748            net.resources.set(k, move slot);749            return [k to u32, net.resources.get(k).generation];750        }751    }752    net.resources.push(move slot);753    return [(net.resources.length() - 1) to u32, 0];754}755756fn resource_alive(self ui: &Ui, slot: u32, generation: u32) -> bool {757    if (!ui.has_requests()) {758        return false;759    }760    const r = &ui.net_peek().resources.get(slot to u64);761    return r.alive && r.generation == generation;762}763764// The request binding gave another request, or none.765fn resource_asked(self ui: &var Ui, slot: u32, generation: u32, asked: Option<Request>) {766    if (!ui.resource_alive(slot, generation)) {767        return;768    }769    ui.stop_resource(slot);770    const net = &var ui.net_state();771    const r = &var net.resources.get_var(slot to u64);772    const first = r.runs == 0;773    r.runs += 1;774    const delay = r.delay;775    const owner = r.owner;776    const has = asked is ::Some;777    r.asked = move asked;778    ui.set_waiting(slot, no_progress());779    if (!has) {780        ui.net_state().resources.get_var(slot to u64).waiting = false;781        return;782    }783    if (!first && delay.nanoseconds > 0) {784        const saved = ui.owner;785        ui.owner = owner;786        const timer = ui.after(delay, |slot, generation| (ui: &var Ui) {787            if (ui.resource_alive(slot, generation)) {788                ui.net_state().resources.get_var(slot to u64).timer = ::None;789                ui.start_resource(slot, false);790            }791        });792        ui.owner = saved;793        ui.net_state().resources.get_var(slot to u64).timer = ::Some(timer);794    } else {795        ui.start_resource(slot, false);796    }797}798799pub fn reload_resource(self ui: &var Ui, slot: u32, generation: u32) {800    if (!ui.resource_alive(slot, generation)) {801        return;802    }803    if (ui.net_peek().resources.get(slot to u64).asked is ::None) {804        return;805    }806    ui.stop_resource(slot);807    ui.set_waiting(slot, no_progress());808    ui.start_resource(slot, true);809}810811// Cancels the exchange under way and the delay's timer.812fn stop_resource(self ui: &var Ui, slot: u32) {813    const r = &var ui.net_state().resources.get_var(slot to u64);814    const exchange = r.exchange;815    const timer = r.timer;816    r.exchange = ::None;817    r.timer = ::None;818    if (timer is ::Some |t|) {819        ui.drop_timer(t);820    }821    if (exchange is ::Some |index|) {822        ui.cancel_exchange(index);823    }824}825826// Starts an exchange for what the resource asked for last.827fn start_resource(self ui: &var Ui, slot: u32, announce: bool) {828    const owner = ui.net_peek().resources.get(slot to u64).owner;829    const made = ui.new_exchange(owner, ::Some(slot), announce);830    const r = &var ui.net_state().resources.get_var(slot to u64);831    var request = if (r.asked is ::Some |&asked|) copy asked else {832        return;833    };834    r.exchange = ::Some(made[0]);835    r.waiting = true;836    var complete = if (r.make is ::Some |&make|) make(made[0], made[1]) else {837        return;838    };839    ui.start_exchange(made[0], move request, move complete);840}841842// Sets the resource's state waiting at the progress.843fn set_waiting(self ui: &var Ui, slot: u32, progress: Progress) {844    var wait = move ui.net_state().resources.get_var(slot to u64).wait;845    ui.net_state().resources.get_var(slot to u64).wait = ::None;846    if (wait is ::Some |&f|) {847        f(&var ui, progress);848    }849    ui.net_state().resources.get_var(slot to u64).wait = move wait;850}851852/* --- What the Ui calls --- */853854// Cancels the exchanges of an owner going, and forgets its resources.855fn requests_gone(self ui: &var Ui, owner: u32) {856    const count = ui.net_peek().exchanges.length();857    for ([..count]) |k| {858        const slot = &ui.net_peek().exchanges.get(k);859        if (slot.live && slot.owner == owner) {860            ui.cancel_exchange(k to u32);861        }862    }863    const net = &var ui.net_state();864    for (net.resources.items()) |&var r| {865        if (r.alive && r.owner == owner) {866            r.alive = false;867            r.generation += 1;868            r.make = ::None;869            r.wait = ::None;870            r.asked = ::None;871        }872    }873}874875// Cancels every exchange as the app closes its window.876fn requests_end(self ui: &var Ui) {877    for ([..ui.net_peek().exchanges.length()]) |k| {878        ui.cancel_exchange(k to u32);879    }880    if (ui.network_of() is ::Some |&network|) {881        network.close_lines();882    }883}884885// Looks at the progress again in 100 ms while a binding shown reads that886// of an exchange under way.887fn arm_network(self ui: &var Ui) {888    var read = false;889    const net = &ui.net_peek();890    for (net.exchanges.view()) |&slot| {891        if (slot.live) {892            if (slot.progress is ::Some |signal|) {893                read = read || ui.read_shown(signal.index);894            }895            if (slot.resource is ::Some |r|) {896                read = read || ui.read_shown(net.resources.get(r to u64).signal);897            }898        }899    }900    const poll = net.poll;901    if (read && poll is ::None) {902        const owner = ui.owner;903        ui.owner = 0;904        const timer = ui.after(905            Duration::from_nanoseconds(POLL_NANOSECONDS),906            (ui) => ui.poll_progress()907        );908        ui.owner = owner;909        ui.net_state().poll = ::Some(timer);910    } else if (!read && poll is ::Some |timer|) {911        ui.drop_timer(timer);912        ui.net_state().poll = ::None;913    }914}915916const POLL_NANOSECONDS: u64 = 100000000;917918// Gives each exchange's progress to what reads it, when it moved.919fn poll_progress(self ui: &var Ui) {920    ui.net_state().poll = ::None;921    const now = ui.time.nanoseconds;922    const count = ui.net_peek().exchanges.length();923    for ([..count]) |k| {924        const slot = copy ui.net_peek().exchanges.get(k);925        if (!slot.live) {926            continue;927        }928        var progress = no_progress();929        if (slot.page is ::Some |&exchange|) {930            progress = exchange.progress();931        } else if (slot.answer is ::Some) {932            // a scripted answer arrives evenly until its time933            const span = slot.due - slot.started;934            const gone = if (now > slot.started) now - slot.started else 0;935            progress.received = if (span == 0 || gone >= span) slot.length else (936                slot.length to f64 * gone to f64 / span to f64937            ) to u64;938            progress.total = ::Some(slot.length);939        } else if (940            ui.network_of() is ::Some |&network|941            && network.line_progress(slot.id) is ::Some |p|942        ) {943            progress = p;944        }945        if (progress == slot.shown) {946            continue;947        }948        ui.net_state().exchanges.get_var(k).shown = progress;949        if (slot.progress is ::Some |signal|) {950            signal.set(&var ui, ::Some(progress));951        }952        if (slot.resource is ::Some |r|) {953            ui.set_waiting(r, progress);954        }955    }956}957958// Marks busy the elements whose bindings read a resource waiting, or959// the nearest above them a screen reader is told of, and no longer those960// marked before.961fn mark_busy(self ui: &var Ui) {962    var before = move ui.net_state().busy;963    ui.net_state().busy = Vector<u32>::empty();964    for (before.view()) |index| {965        ui.node_var(index).busy = false;966    }967    var marked = Vector<u32>::empty();968    for (ui.net_peek().resources.view()) |&r| {969        if (!r.alive || !r.waiting) {970            continue;971        }972        for (ui.signals.get(r.signal to u64).readers.view()) |reader| {973            const e = &ui.effects.get(reader.effect to u64);974            if (e.alive && e.runs == reader.run && e.node is ::Some |n|) {975                marked.push(ui.described_at(n));976            }977        }978    }979    for (marked.view()) |index| {980        ui.node_var(index).busy = true;981    }982    ui.net_state().busy = move marked;983}984985// The element or the nearest above it with a role; the root, which986// stands for the window, when none has.987fn described_at(self ui: &Ui, index: u32) -> u32 {988    var at = index;989    while (true) {990        const node = &ui.node(at);991        if (!node.transparent && node.widget is ::Some |&w| && !(w.semantics().role is ::Unknown)) {992            return at;993        }994        if (node.parent is ::Some |up|) {995            at = up;996        } else {997            return at;998        }999    }1000}10011002/* --- Failures --- */10031004pub fn write_failure(failure: &Failure, out: &var String) {1005    match (failure) {1006        ::Network |&e| {1007            out.write(&e);1008        }1009        ::Status |&r| {1010            out.append(&f"the server answered {r.status}".view());1011        }1012        ::Unreadable |&why| {1013            out.append(&f"what came back is not as expected: {why}".view());1014        }1015    }1016}