Skip to main content

nsh_core/element/
services.rs

1//! The platform's services for components, modules and tasks beyond
2//! dialogs and the keyboard: screen reader announcements, the
3//! clipboard, image information, display frames and the layout direction
4//! ([`super`]'s free functions, [`super::ModuleCx`]). Each is an
5//! [`Action`] the core applies in order with the component's other changes.
6
7use std::{
8    future::Future,
9    pin::Pin,
10    task::{Context as TaskContext, Poll},
11};
12
13use super::{
14    Answer, ImageSize,
15    task::{
16        Action, AnswerSlot, ClipboardImage, ClipboardItem, ClipboardRead, ClipboardWrite,
17        FileAnswer,
18    },
19};
20use crate::{
21    Command, ROOT_ID,
22    platform::{HttpHead, HttpRequest},
23    time::Instant,
24};
25
26/// Whether an image loaded ahead ([`super::prefetch_image`]): `Ok`
27/// once its bytes are in memory, else the error.
28#[must_use = "an answer does nothing unless awaited"]
29#[derive(Debug)]
30pub struct Prefetch(Answer<Result<ImageSize, String>>);
31
32impl Future for Prefetch {
33    type Output = Result<(), String>;
34
35    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
36        Pin::new(&mut self.0).poll(cx).map(|size| size.map(|_| ()))
37    }
38}
39
40/// The response to a [`super::fetch`]: its status line, headers
41/// and whole body.
42#[derive(Debug, Clone, PartialEq, Eq, Default)]
43pub struct HttpResponse {
44    /// The status, final URL and headers.
45    pub head: HttpHead,
46    /// The body.
47    pub body: Vec<u8>,
48}
49
50impl HttpResponse {
51    /// The status code.
52    pub fn status(&self) -> u16 {
53        self.head.status
54    }
55
56    /// Whether the status is a success (200–299).
57    pub fn ok(&self) -> bool {
58        (200..300).contains(&self.head.status)
59    }
60
61    /// The first header named `name` (case-insensitively).
62    pub fn header(&self, name: &str) -> Option<&str> {
63        self.head
64            .headers
65            .iter()
66            .find(|(n, _)| n.eq_ignore_ascii_case(name))
67            .map(|(_, v)| v.as_str())
68    }
69
70    /// The body as text (UTF-8; invalid sequences become U+FFFD).
71    pub fn text(&self) -> String {
72        String::from_utf8_lossy(&self.body).into_owned()
73    }
74}
75
76/// A request in flight ([`super::fetch`]): awaited, its response,
77/// or why there is none (the network failed, or the app's capabilities do
78/// not grant the host).
79#[must_use = "a request does nothing unless awaited"]
80#[derive(Debug)]
81pub struct Fetch(pub(crate) Answer<Result<HttpResponse, FetchFailure>>);
82
83impl Fetch {
84    /// The response, or why there is none with a refusal kept apart from a
85    /// failure: what the runtime's module functions reject with, a refusal
86    /// as `ERR_ACCESS_DENIED` (`registerFont`).
87    pub(crate) async fn detailed(self) -> Result<HttpResponse, FetchFailure> {
88        self.0.await
89    }
90}
91
92impl Future for Fetch {
93    type Output = Result<HttpResponse, String>;
94
95    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
96        Pin::new(&mut self.0)
97            .poll(cx)
98            .map(|response| response.map_err(FetchFailure::into_message))
99    }
100}
101
102/// Why a task's request has no response ([`Fetch::detailed`]).
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub(crate) enum FetchFailure {
105    /// The network failed (no response, or the body broke off): why.
106    Failed(String),
107    /// The app's capabilities do not grant `url`, the request's or a
108    /// redirect's (the engine checks every hop): why, and that URL
109    /// ([`Core::fetch_refused`](crate::Core::fetch_refused)).
110    Refused { message: String, url: String },
111}
112
113impl FetchFailure {
114    /// Why, for people.
115    fn into_message(self) -> String {
116        match self {
117            Self::Failed(message) | Self::Refused { message, .. } => message,
118        }
119    }
120}
121
122/// Makes `request` through the engine's network stack.
123pub(crate) fn fetch(request: HttpRequest) -> (Fetch, Action) {
124    let (answer, slot) = Answer::new();
125    (Fetch(answer), Action::Fetch(Box::new(request), slot))
126}
127
128/// The screen reader reads `message`.
129pub(crate) fn announce(message: String) -> Action {
130    Action::Command(ROOT_ID, Command::Announce(message))
131}
132
133/// The device plays `haptic`.
134pub(crate) fn haptic(haptic: crate::Haptic) -> Action {
135    Action::Command(ROOT_ID, Command::Haptic(haptic))
136}
137
138/// Turns the performance monitor on or off.
139pub(crate) fn perf_monitor(enabled: bool) -> Action {
140    Action::Command(ROOT_ID, Command::PerfMonitor(enabled))
141}
142
143/// How the performance monitor shows.
144pub(crate) fn perf_monitor_mode(mode: crate::FpsMode) -> Action {
145    Action::Command(ROOT_ID, Command::PerfMonitorMode(mode))
146}
147
148/// Puts `text` on the system clipboard; the answer is what became of it.
149pub(crate) fn set_clipboard(text: String) -> (Answer<ClipboardWrite>, Action) {
150    let (answer, slot) = Answer::new();
151    (
152        answer,
153        Action::WriteClipboard(Command::SetClipboard(text), slot),
154    )
155}
156
157/// Puts `item` on the system clipboard, each of its formats in one write;
158/// the answer is what became of it.
159pub(crate) fn set_clipboard_item(item: ClipboardItem) -> (Answer<ClipboardWrite>, Action) {
160    let (answer, slot) = Answer::new();
161    (
162        answer,
163        Action::WriteClipboard(Command::SetClipboardItem(item), slot),
164    )
165}
166
167/// The text on the system clipboard (`""` when it holds none).
168pub(crate) fn clipboard_string() -> (Answer<String>, Action) {
169    let (answer, slot) = Answer::new();
170    (answer, Action::ReadClipboard(ClipboardRead::Text(slot)))
171}
172
173/// The text on the system clipboard for `Clipboard.readText` (`""` when
174/// it holds none; `None` when the person refused the read).
175pub(crate) fn clipboard_checked_string() -> (Answer<Option<String>>, Action) {
176    let (answer, slot) = Answer::new();
177    (
178        answer,
179        Action::ReadClipboard(ClipboardRead::CheckedText(slot)),
180    )
181}
182
183/// Whether the system clipboard holds text (without reading it).
184pub(crate) fn clipboard_has_string() -> (Answer<bool>, Action) {
185    let (answer, slot) = Answer::new();
186    (answer, Action::ReadClipboard(ClipboardRead::Has(slot)))
187}
188
189/// Puts the image of the `data:` URI `uri` on the system clipboard.
190pub(crate) fn set_clipboard_image(uri: String) -> Action {
191    Action::Command(ROOT_ID, Command::SetClipboardImage(uri))
192}
193
194/// The image on the system clipboard (`None` when it holds none).
195pub(crate) fn clipboard_image() -> (Answer<Option<ClipboardImage>>, Action) {
196    let (answer, slot) = Answer::new();
197    (answer, Action::ReadClipboard(ClipboardRead::Image(slot)))
198}
199
200/// The image on the system clipboard for `Clipboard.readImage` (`None`
201/// when it holds none; `Err` with the size in bytes of one over the limit).
202pub(crate) fn clipboard_checked_image() -> (Answer<Result<Option<ClipboardImage>, usize>>, Action) {
203    let (answer, slot) = Answer::new();
204    (
205        answer,
206        Action::ReadClipboard(ClipboardRead::CheckedImage(slot)),
207    )
208}
209
210/// Whether the system clipboard holds an image (without reading it).
211pub(crate) fn clipboard_has_image() -> (Answer<bool>, Action) {
212    let (answer, slot) = Answer::new();
213    (answer, Action::ReadClipboard(ClipboardRead::HasImage(slot)))
214}
215
216/// The `file:` URLs of the local files on the system clipboard.
217pub(crate) fn clipboard_files() -> (Answer<Vec<String>>, Action) {
218    let (answer, slot) = Answer::new();
219    (answer, Action::ReadClipboard(ClipboardRead::Files(slot)))
220}
221
222/// Registers the font in `data`.
223pub(crate) fn register_font(data: Vec<u8>) -> (Answer<Result<String, String>>, Action) {
224    let (answer, slot) = Answer::new();
225    (answer, Action::RegisterFont(data, slot))
226}
227
228/// The images the user picks in the system's picker (none when cancelled).
229pub(crate) fn pick_images(
230    request: crate::picker::PickRequest,
231) -> (Answer<Vec<crate::picker::PickedFile>>, Action) {
232    let (answer, slot) = Answer::new();
233    (answer, Action::PickImages(request, slot))
234}
235
236/// The files the user picks in the system's picker (none when cancelled).
237pub(crate) fn pick_files(
238    request: crate::picker::FilePickRequest,
239) -> (Answer<Vec<crate::picker::PickedFile>>, Action) {
240    let (answer, slot) = Answer::new();
241    (answer, Action::PickFiles(request, slot))
242}
243
244/// Calls function `name` of the embedding app with `args` (`nsh/host`).
245pub(crate) fn host_call(
246    name: String,
247    args: crate::JsonValue,
248) -> (
249    Answer<Result<crate::JsonValue, crate::host_channel::HostError>>,
250    Action,
251) {
252    let (answer, slot) = Answer::new();
253    (
254        answer,
255        Action::HostCall {
256            name,
257            args,
258            answer: slot,
259        },
260    )
261}
262
263/// Opens `url` outside the app; the answer is whether it opened.
264pub(crate) fn open_url(url: String) -> (Answer<bool>, Action) {
265    let (answer, slot) = Answer::new();
266    (answer, Action::OpenUrl(url, slot))
267}
268
269/// Carries out `request` on local paths; `answer` takes the platform's
270/// answer.
271pub(crate) fn file_request<T>(
272    request: crate::file_dialog::FileRequest,
273    answer: impl FnOnce(AnswerSlot<T>) -> FileAnswer,
274) -> (Answer<T>, Action) {
275    let (result, slot) = Answer::new();
276    (result, Action::FileRequest(request, answer(slot)))
277}
278
279/// Renders `request` offscreen into an image ([`crate::canvas::render`]).
280pub(crate) fn render_canvas(
281    request: crate::canvas::render::RenderRequest,
282) -> (Answer<Result<Vec<u8>, super::JsError>>, Action) {
283    let (answer, slot) = Answer::new();
284    (answer, Action::RenderCanvas(Box::new(request), slot))
285}
286
287/// The color the user picks on the screen (none when cancelled).
288pub(crate) fn pick_screen_color() -> (Answer<Option<crate::Hsla>>, Action) {
289    let (answer, slot) = Answer::new();
290    (answer, Action::PickScreenColor(slot))
291}
292
293/// The size of the image at `uri`, its bytes loaded.
294pub(crate) fn image_size(uri: String) -> (Answer<Result<ImageSize, String>>, Action) {
295    let (answer, slot) = Answer::new();
296    (answer, Action::ImageInfo(uri, slot))
297}
298
299/// Loads the image at `uri` ahead.
300pub(crate) fn prefetch(uri: String) -> (Prefetch, Action) {
301    let (answer, action) = image_size(uri);
302    (Prefetch(answer), action)
303}
304
305/// The start of the next display frame.
306pub(crate) fn frame() -> (Answer<Instant>, Action) {
307    let (answer, slot): (_, AnswerSlot<Instant>) = Answer::new();
308    (answer, Action::Frame(slot))
309}