rs-rich-embed 0.0.7

A terminal pane and a web view for intuiTUIve apps, over swappable PTY and browser backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! The web view: a web page in a pane, over a [`WebEngine`].
//!
//! The view keeps the page's state in signals (its address, title, whether
//! it is loading, and whether it can go back or forward), draws a small
//! address bar over the page, forwards keys and the mouse, and tells the
//! engine the page's size. Engines hand back frames of cells (a text
//! browser) or of pixels (a graphical one); pixels are drawn as coloured
//! half blocks.

use std::cell::RefCell;
use std::io;
use std::rc::{Rc, Weak};

use rich::{Segment, Style};
use rich_intuituive::interact::{Button, Key, KeyCode, Mouse, MouseKind};
use rich_intuituive::widget::{Canvas, DrawCx, EventCx, Used, Widget, WidgetEvent, widget};
use rich_intuituive::{Ctx, Node, Signal, signal, watch};

use crate::host::Notify;
use crate::pixels::{Pixels, half_blocks};
use crate::program::ProgramEngine;
use crate::wake::{Fed, connect};

/// Input for the page, in the page's own cells.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WebInput {
    Key(Key),
    /// The mouse, at a cell of the page (the address bar is not counted).
    Mouse(Mouse),
    Paste(String),
}

/// What an engine draws.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WebFrame {
    /// Text: one line of rich segments per row, and the text cursor.
    Cells {
        lines: Vec<Vec<Segment>>,
        cursor: Option<(u16, u16)>,
    },
    /// An image of the page, scaled into the pane.
    Pixels(Pixels),
}

/// Where the page is and what it is doing.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PageState {
    pub url: String,
    pub title: String,
    pub loading: bool,
    pub can_go_back: bool,
    pub can_go_forward: bool,
    /// Why the page could not be shown, if it could not.
    pub error: Option<String>,
}

/// A browser behind a [`web_view`]: opens pages, takes input, and hands
/// back frames. Every method is called on the app's thread; work that takes
/// time happens on the engine's own threads, which call the [`Notify`]
/// when there is a new frame or a new state.
///
/// The view calls [`resize`](Self::resize) before the first
/// [`open`](Self::open), and again whenever the page's area changes.
pub trait WebEngine {
    /// Go to `url`.
    fn open(&mut self, url: &str) -> io::Result<()>;
    /// The page's area is now `columns` x `rows` cells.
    fn resize(&mut self, columns: u16, rows: u16) -> io::Result<()>;
    fn input(&mut self, input: WebInput) -> io::Result<()>;
    fn back(&mut self) -> io::Result<()>;
    fn forward(&mut self) -> io::Result<()>;
    fn reload(&mut self) -> io::Result<()>;
    /// The newest frame since the last call, if there is one.
    fn poll(&mut self) -> Option<WebFrame>;
    /// Where the page is and what it is doing now.
    fn state(&self) -> PageState;
    /// Call `notify` when there is a new frame or state. Given once.
    fn set_notify(&mut self, notify: Notify);
}

/// The page's state as signals, and what the app can ask of it. `Copy`,
/// like a signal: move it into handlers.
pub struct WebHandle {
    address: Signal<String>,
    title: Signal<String>,
    loading: Signal<bool>,
    can_go_back: Signal<bool>,
    can_go_forward: Signal<bool>,
    error: Signal<Option<String>>,
    view: Signal<Weak<RefCell<ViewState>>>,
}

impl Clone for WebHandle {
    fn clone(&self) -> Self {
        *self
    }
}

impl Copy for WebHandle {}

impl WebHandle {
    /// The page's address. Setting it opens that address.
    pub fn address(&self) -> Signal<String> {
        self.address
    }

    pub fn title(&self) -> Signal<String> {
        self.title
    }

    pub fn loading(&self) -> Signal<bool> {
        self.loading
    }

    pub fn can_go_back(&self) -> Signal<bool> {
        self.can_go_back
    }

    pub fn can_go_forward(&self) -> Signal<bool> {
        self.can_go_forward
    }

    /// Why the page could not be shown, if it could not.
    pub fn error(&self) -> Signal<Option<String>> {
        self.error
    }

    fn with_view(&self, f: impl FnOnce(&mut ViewState)) {
        if let Some(view) = self.view.with_untracked(Weak::upgrade) {
            let mut view = view.borrow_mut();
            f(&mut view);
            view.sync();
        }
    }

    /// Open `url`.
    pub fn open(&self, url: impl Into<String>) {
        self.address.set(url.into());
    }

    pub fn back(&self) {
        self.with_view(|view| view.act(|engine| engine.back()));
    }

    pub fn forward(&self) {
        self.with_view(|view| view.act(|engine| engine.forward()));
    }

    pub fn reload(&self) {
        self.with_view(|view| view.act(|engine| engine.reload()));
    }
}

struct ViewState {
    engine: Box<dyn WebEngine>,
    handle: Option<WebHandle>,
    /// Bumped when there is something new to draw.
    wake: Signal<u64>,
    frame: Option<WebFrame>,
    /// The page's area it was last given; `None` before the first.
    size: Option<(u16, u16)>,
    /// The address to open once the page has a size.
    first: Option<String>,
    /// The address the engine was last asked for, or reported.
    current: String,
    /// The last call to the engine that failed, and why.
    failure: Option<String>,
    /// The engine's wake-up, kept to bring a failure to the signals.
    notify: Option<Notify>,
}

impl ViewState {
    /// Ask the engine for something; a failure is kept for the next
    /// [`sync`](Self::sync) (this may run while the view draws, which
    /// writes no signals).
    fn act(&mut self, f: impl FnOnce(&mut dyn WebEngine) -> io::Result<()>) {
        if self.size.is_none() {
            return;
        }
        self.failure = f(self.engine.as_mut()).err().map(|e| e.to_string());
        // An engine that failed at once may never call `notify`; call it
        // here, so the next turn copies the failure into the signals (this
        // may run while the view draws, where signals are not written).
        if self.failure.is_some()
            && let Some(notify) = &self.notify
        {
            notify();
        }
    }

    /// Copy the engine's state into the signals.
    fn sync(&mut self) {
        let Some(handle) = self.handle else {
            return;
        };
        let state = self.engine.state();
        if !state.url.is_empty() {
            self.current = state.url.clone();
            handle.address.set(state.url);
        }
        handle.title.set(state.title);
        handle.loading.set(state.loading);
        handle.can_go_back.set(state.can_go_back);
        handle.can_go_forward.set(state.can_go_forward);
        handle
            .error
            .set(state.error.or_else(|| self.failure.clone()));
    }

    /// The page's area changed to `columns` x `rows`: tell the engine, and
    /// open the first page once there is one.
    fn fit(&mut self, columns: u16, rows: u16) {
        if columns == 0 || rows == 0 || self.size == Some((columns, rows)) {
            return;
        }
        self.size = Some((columns, rows));
        self.act(|engine| engine.resize(columns, rows));
        if let Some(url) = self.first.take() {
            self.current = url.clone();
            self.act(|engine| engine.open(&url));
        }
    }
}

impl Fed for ViewState {
    fn install(&mut self, notify: Notify) {
        self.notify = Some(notify.clone());
        self.engine.set_notify(notify);
    }

    fn pump(this: &Rc<RefCell<Self>>, _cx: &mut Ctx) {
        let mut view = this.borrow_mut();
        if let Some(frame) = view.engine.poll() {
            view.frame = Some(frame);
            view.wake.update(|n| *n = n.wrapping_add(1));
        }
        view.sync();
    }
}

/// A web view being built: [`web_view`] or [`web_view_with`], then
/// [`node`](Self::node) to place it; [`handle`](Self::handle) for its
/// signals and navigation.
///
/// The top row is an address bar: `←` back, `→` forward, `↻` reload, the
/// address, and `…` while the page loads. Click the address or press
/// Ctrl+L to type one (Enter opens it, Esc gives up); Alt+Left, Alt+Right
/// and F5 go back, forward and reload. Every other key, the mouse and
/// pastes go to the page while the view has the focus, except the keys
/// [`release_keys`](Self::release_keys) names.
pub struct WebView {
    state: Rc<RefCell<ViewState>>,
    handle: WebHandle,
    bar: bool,
    release: Vec<Key>,
}

/// A web page at `url`, shown by a terminal browser named by the
/// environment or found on `PATH` ([`ProgramEngine::detect`]). Name one
/// with [`web_view_with`] and [`ProgramEngine::new`].
///
/// # Panics
/// Outside a running or building app, like [`signal`].
pub fn web_view(url: impl Into<String>) -> WebView {
    web_view_with(ProgramEngine::detect(), url)
}

/// A web page at `url`, shown by `engine`.
///
/// ```no_run
/// # extern crate rich_intuituive as intuituive;
/// use intuituive::prelude::*;
/// use rich_embed::{web_view_with, ProgramEngine};
///
/// App::new(|| {
///     let page = web_view_with(ProgramEngine::new("w3m"), "https://example.com");
///     let address = page.handle().address();
///     column([page.node(), text!("{address}").fixed(1)])
/// })
/// .run()
/// # ; Ok::<(), std::io::Error>(())
/// ```
///
/// # Panics
/// Outside a running or building app, like [`signal`].
pub fn web_view_with(engine: impl WebEngine + 'static, url: impl Into<String>) -> WebView {
    let url = url.into();
    let state = Rc::new(RefCell::new(ViewState {
        engine: Box::new(engine),
        handle: None,
        wake: signal(0),
        frame: None,
        size: None,
        first: Some(url.clone()),
        current: url.clone(),
        failure: None,
        notify: None,
    }));
    let handle = WebHandle {
        address: signal(url),
        title: signal(String::new()),
        loading: signal(false),
        can_go_back: signal(false),
        can_go_forward: signal(false),
        error: signal(None),
        view: signal(Rc::downgrade(&state)),
    };
    state.borrow_mut().handle = Some(handle);
    connect(&state);
    // The app setting the address opens it; the engine reporting a new one
    // (a link followed, a redirect) changes nothing.
    let weak = Rc::downgrade(&state);
    watch(
        move || handle.address.get(),
        move |url, _| {
            let Some(view) = weak.upgrade() else {
                return;
            };
            let mut view = view.borrow_mut();
            if url == view.current {
                return;
            }
            view.current = url.clone();
            if view.size.is_none() {
                view.first = Some(url);
                return;
            }
            view.act(|engine| engine.open(&url));
        },
    );
    WebView {
        state,
        handle,
        bar: true,
        release: Vec::new(),
    }
}

impl WebView {
    /// The page's signals, and back, forward, reload and open.
    pub fn handle(&self) -> WebHandle {
        self.handle
    }

    /// Show the address bar (default) or not: an app may draw its own from
    /// the [handle](Self::handle)'s signals.
    #[must_use]
    pub fn address_bar(mut self, on: bool) -> WebView {
        self.bar = on;
        self
    }

    /// Keys (space-separated names, as [`Node::on_key`] takes them) that
    /// are not sent to the page but go on to the app's bindings.
    #[must_use]
    pub fn release_keys(mut self, keys: &str) -> WebView {
        self.release
            .extend(keys.split_whitespace().filter_map(Key::parse));
        self
    }

    /// The view as a node: focusable, and flexible until sized.
    pub fn node(self) -> Node {
        widget(ViewWidget {
            state: self.state,
            handle: self.handle,
            bar: self.bar,
            release: self.release,
            editing: None,
            caret: None,
        })
    }
}

impl From<WebView> for Node {
    fn from(view: WebView) -> Node {
        view.node()
    }
}

/// Where the address bar's parts are.
const BACK: u16 = 1;
const FORWARD: u16 = 3;
const RELOAD: u16 = 5;
const ADDRESS: u16 = 7;

struct ViewWidget {
    state: Rc<RefCell<ViewState>>,
    handle: WebHandle,
    bar: bool,
    release: Vec<Key>,
    /// The address being typed, while it is.
    editing: Option<String>,
    caret: Option<(u16, u16)>,
}

impl ViewWidget {
    fn top(&self) -> u16 {
        self.bar as u16
    }

    fn draw_bar(&mut self, cx: &mut DrawCx, canvas: &mut Canvas) {
        let width = canvas.width();
        let bar = cx.style("web.bar", "on grey15");
        let off = bar.combine(&Style::parse("dim").unwrap_or_default());
        canvas.fill(0, 0, width, 1, Some(&bar));
        let back = self.handle.can_go_back.get();
        let forward = self.handle.can_go_forward.get();
        canvas.print(BACK, 0, "←", Some(if back { &bar } else { &off }));
        canvas.print(FORWARD, 0, "→", Some(if forward { &bar } else { &off }));
        canvas.print(RELOAD, 0, "↻", Some(&bar));
        let loading = self.handle.loading.get();
        let room = width.saturating_sub(ADDRESS + 2 * loading as u16);
        match &self.editing {
            Some(text) => {
                let field = cx.style("web.address.edit", "on grey30");
                canvas.fill(ADDRESS, 0, room, 1, Some(&field));
                // The end of what is typed stays in view.
                let shown = tail(text, room.saturating_sub(1));
                canvas.print(ADDRESS, 0, &shown, Some(&field));
                let at = ADDRESS + rich::cells::cell_len(&shown) as u16;
                self.caret = Some((at.min(width.saturating_sub(1)), 0));
            }
            None => {
                let address = self.handle.address.get();
                let line = crate::web::fit(&address, room);
                canvas.print(ADDRESS, 0, &line, Some(&bar));
            }
        }
        if loading {
            canvas.print(width.saturating_sub(2), 0, "…", Some(&bar));
        }
    }

    fn input(&self, input: WebInput) {
        let mut view = self.state.borrow_mut();
        view.act(|engine| engine.input(input));
    }

    fn edit(&mut self, cx: &mut EventCx, key: Key) -> Used {
        let Some(text) = &mut self.editing else {
            return Used::No;
        };
        match key.code {
            KeyCode::Enter => {
                let url = std::mem::take(text).trim().to_string();
                self.editing = None;
                if !url.is_empty() {
                    self.handle.open(with_scheme(&url));
                }
            }
            KeyCode::Escape => self.editing = None,
            KeyCode::Backspace => {
                text.pop();
            }
            KeyCode::Char(c) if !key.modifiers.ctrl && !key.modifiers.alt => text.push(c),
            _ => {}
        }
        cx.redraw();
        Used::Yes
    }
}

impl Widget for ViewWidget {
    fn name(&self) -> &'static str {
        "web view"
    }

    fn describe(&self) -> Option<String> {
        Some(self.state.borrow().current.clone())
    }

    fn draw(&mut self, cx: &mut DrawCx, canvas: &mut Canvas) {
        let wake = self.state.borrow().wake;
        wake.get();
        self.caret = None;
        let (width, height) = (canvas.width(), canvas.height());
        let top = self.top();
        if self.bar && height > 0 {
            self.draw_bar(cx, canvas);
        }
        let rows = height.saturating_sub(top);
        let mut view = self.state.borrow_mut();
        view.fit(width, rows);
        if rows == 0 {
            return;
        }
        let error = self.handle.error.get().or_else(|| view.failure.clone());
        match &view.frame {
            Some(WebFrame::Cells { lines, cursor }) => {
                canvas.lines_at(0, top, width, rows, lines);
                if self.editing.is_none() {
                    self.caret = cursor.map(|(x, y)| (x, y + top));
                }
            }
            Some(WebFrame::Pixels(pixels)) => {
                canvas.lines_at(0, top, width, rows, &half_blocks(pixels, width, rows));
            }
            None => {
                canvas.clear(0, top, width, rows);
                let note = match &error {
                    Some(error) => format!("[red]{}", error.replace('[', "\\[")),
                    None => "[dim]loading…".to_string(),
                };
                canvas.markup(cx.console(), 1, top, width.saturating_sub(1), &note, None);
            }
        }
        if let (Some(error), Some(_)) = (error, &view.frame) {
            let line = format!("[reverse red] {} ", error.replace('[', "\\["));
            canvas.markup(cx.console(), 0, height - 1, width, &line, None);
        }
    }

    fn event(&mut self, cx: &mut EventCx, event: &WidgetEvent) -> Used {
        let top = self.top();
        match event {
            WidgetEvent::Key(key) if self.release.contains(key) && self.editing.is_none() => {
                Used::No
            }
            WidgetEvent::Key(key) => {
                if self.editing.is_some() {
                    return self.edit(cx, *key);
                }
                let alt = key.modifiers.alt && !key.modifiers.ctrl;
                match key.code {
                    KeyCode::Char('l') if key.modifiers.ctrl && self.bar => {
                        self.editing = Some(self.handle.address.get_untracked());
                    }
                    KeyCode::Left if alt => self.handle.back(),
                    KeyCode::Right if alt => self.handle.forward(),
                    KeyCode::F(5) => self.handle.reload(),
                    _ => self.input(WebInput::Key(*key)),
                }
                cx.redraw();
                Used::Yes
            }
            WidgetEvent::Paste(text) => {
                match &mut self.editing {
                    Some(editing) => editing.push_str(text.trim()),
                    None => self.input(WebInput::Paste(text.clone())),
                }
                cx.redraw();
                Used::Yes
            }
            WidgetEvent::Mouse(mouse) if self.bar && mouse.row == 0 => {
                if mouse.kind != MouseKind::Down(Button::Left) {
                    return Used::Yes;
                }
                match mouse.column {
                    c if c == BACK => self.handle.back(),
                    c if c == FORWARD => self.handle.forward(),
                    c if c == RELOAD => self.handle.reload(),
                    c if c >= ADDRESS && self.editing.is_none() => {
                        self.editing = Some(self.handle.address.get_untracked());
                    }
                    _ => {}
                }
                cx.redraw();
                Used::Yes
            }
            WidgetEvent::Mouse(mouse) => {
                let mut page = *mouse;
                page.row -= top;
                self.input(WebInput::Mouse(page));
                Used::Yes
            }
            WidgetEvent::Focus(false) if self.editing.is_some() => {
                self.editing = None;
                cx.redraw();
                Used::Yes
            }
            _ => Used::No,
        }
    }

    fn focusable(&self) -> bool {
        true
    }

    fn caret(&self) -> Option<(u16, u16)> {
        self.caret
    }
}

/// `text` cut to `width` cells, with an ellipsis where it was cut.
pub(crate) fn fit(text: &str, width: u16) -> String {
    let width = width as usize;
    if rich::cells::cell_len(text) <= width {
        return text.to_string();
    }
    if width == 0 {
        return String::new();
    }
    let mut out = String::new();
    let mut used = 0;
    for c in text.chars() {
        let w = rich::cells::cell_len(c.encode_utf8(&mut [0u8; 4]));
        if used + w + 1 > width {
            break;
        }
        out.push(c);
        used += w;
    }
    out.push('…');
    out
}

/// The last `width` cells of `text`.
fn tail(text: &str, width: u16) -> String {
    let mut out: Vec<char> = Vec::new();
    let mut used = 0;
    for c in text.chars().rev() {
        let w = rich::cells::cell_len(c.encode_utf8(&mut [0u8; 4]));
        if used + w > width as usize {
            break;
        }
        out.push(c);
        used += w;
    }
    out.into_iter().rev().collect()
}

/// An address as typed, with `https://` when it names no scheme.
fn with_scheme(url: &str) -> String {
    if url.contains("://") || url.starts_with("about:") || url.starts_with("file:") {
        url.to_string()
    } else {
        format!("https://{url}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn addresses_fit_and_get_a_scheme() {
        assert_eq!(fit("https://example.com", 10), "https://e…");
        assert_eq!(fit("short", 10), "short");
        assert_eq!(tail("abcdef", 3), "def");
        assert_eq!(with_scheme("example.com"), "https://example.com");
        assert_eq!(with_scheme("http://x"), "http://x");
        assert_eq!(with_scheme("about:blank"), "about:blank");
    }
}