prismsdk-linux 0.1.0

Prism backend for Linux desktops (GTK 4 native widgets).
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
//! Rich inputs (#115): a text area's `GtkTextView` showing the runs of a
//! [`rich_input`](prism_core::rich_input) as text tags, each chip and
//! inline icon a widget at a child anchor (one character, U+FFFC, that the
//! caret, the selection and Backspace treat as one).
//!
//! Edits reach the app as the plain text (`UiEvent::Input`, chips
//! included): prism-core gives the typed text the style of the run around
//! it and keeps the other runs. The app's runs come back on a later turn:
//! when they hold the text the view shows (the echo of the typing, or the
//! app restyling it), their tags replace the old ones in place, caret and
//! undo untouched; when the user typed further meanwhile, they wait for the
//! next echo. New text from the app comes first through `set_text` (#73),
//! its chips as plain U+FFFC characters that become anchors here. Without
//! the app's hooks, a copy is plain text with each chip's label, and a
//! paste is plain text without chips.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use gtk::prelude::*;
use gtk::{gdk, glib, pango};
use prism_core::{Color, NodeId, OBJECT_CHAR, Style, TextRun, TextTransform, UiEvent, decode_runs};
use prism_native::text::{StyledRun, StyledText};

thread_local! {
    static RICH: RefCell<HashMap<NodeId, Rich>> = RefCell::new(HashMap::new());
}

/// A rich input: its view, the app's runs and style, and what shows them.
struct Rich {
    view: gtk::TextView,
    runs: String,
    style: Option<Style>,
    /// The tags of the runs shown (anonymous, in the buffer's table).
    tags: Vec<gtk::TextTag>,
    chips: Vec<Chip>,
}

/// A chip (or inline icon) at its anchor: a box with its symbol and label.
struct Chip {
    anchor: gtk::TextChildAnchor,
    widget: gtk::Box,
    icon: gtk::Label,
    label: gtk::Label,
    css: gtk::CssProvider,
    link: Rc<Cell<Option<u64>>>,
    /// What a copy writes for it: a chip's label, nothing for an icon.
    copied: String,
}

/// Makes text area `view` of node `id` a rich input.
pub(crate) fn setup(id: NodeId, view: &gtk::TextView) {
    RICH.with(|r| {
        r.borrow_mut().insert(
            id,
            Rich {
                view: view.clone(),
                runs: String::new(),
                style: None,
                tags: Vec::new(),
                chips: Vec::new(),
            },
        )
    });
}

pub(crate) fn forget(id: NodeId) {
    RICH.with(|r| r.borrow_mut().remove(&id));
}

pub(crate) fn is_rich(id: NodeId) -> bool {
    RICH.with(|r| r.borrow().contains_key(&id))
}

/// The runs to show (`Widgets::set_rich_value`).
pub(crate) fn set_runs(id: NodeId, runs: &str) {
    RICH.with(|r| {
        if let Some(rich) = r.borrow_mut().get_mut(&id) {
            rich.runs = runs.to_string();
            show(rich);
        }
    });
}

/// The field's style (its font, size and color): the base of the runs.
pub(crate) fn set_style(id: NodeId, style: &Style) {
    RICH.with(|r| {
        if let Some(rich) = r.borrow_mut().get_mut(&id) {
            rich.style = Some(style.clone());
            show(rich);
        }
    });
}

/// The appearance changed: colors take their light or dark variant.
pub(crate) fn restyle_all() {
    RICH.with(|r| r.borrow_mut().values_mut().for_each(show));
}

/// The buffer's characters, a chip as its U+FFFC (unlike `text()`).
pub(crate) fn slice(b: &gtk::TextBuffer) -> String {
    b.slice(&b.start_iter(), &b.end_iter(), false).to_string()
}

/// Shows the runs: in place when the view holds their text.
fn show(rich: &mut Rich) {
    let Some(style) = rich.style.clone() else {
        return;
    };
    // The text the user edits is the value: no case transform.
    let style = Style {
        text_transform: TextTransform::None,
        ..style
    };
    let runs = decode_runs(&rich.runs);
    let text: String = runs.iter().map(|r| r.text.as_str()).collect();
    let b = rich.view.buffer();
    if slice(&b) != text {
        // The user typed since: the next echo restyles it.
        return;
    }
    let styled = StyledText::from_runs(&text, &runs, &style);
    let dark = crate::imp::dark();
    let table = b.tag_table();
    for tag in rich.tags.drain(..) {
        table.remove(&tag);
    }
    let mut at = 0;
    for (s, run) in styled.runs.iter().zip(&runs) {
        let (start, len) = (at, run.text.chars().count() as i32);
        at += len;
        if len == 0 {
            continue;
        }
        if run.is_object() && len == 1 && b.iter_at_offset(start).char() == OBJECT_CHAR {
            chip_at(rich, &b, start, run, s, &style, dark);
            continue;
        }
        if let Some(tag) = tag(s, &style, dark) {
            table.add(&tag);
            b.apply_tag(&tag, &b.iter_at_offset(start), &b.iter_at_offset(at));
            rich.tags.push(tag);
        }
    }
    // Chips deleted with their text (Backspace, a new value).
    rich.chips.retain(|c| !c.anchor.is_deleted());
}

/// The tag of a text run: what differs from the field's own font and color
/// (its CSS rule), `None` when nothing does.
fn tag(s: &StyledRun, style: &Style, dark: bool) -> Option<gtk::TextTag> {
    let tag = gtk::TextTag::new(None);
    let mut any = false;
    if s.font.family != style.font_family
        && let Some(name) = crate::text::family_name(&s.font.family)
    {
        tag.set_family(Some(&name));
        any = true;
    }
    if s.font.weight != style.font_weight {
        tag.set_weight(s.font.weight.css() as i32);
        any = true;
    }
    if s.font.italic && !style.italic {
        tag.set_style(pango::Style::Italic);
        any = true;
    }
    if s.font.size != style.font_size && style.font_size > 0. {
        tag.set_scale((s.font.size / style.font_size) as f64);
        any = true;
    }
    if let Some(c) = s
        .color
        .filter(|_| s.color != style.text_color || s.link.is_some())
    {
        tag.set_foreground_rgba(Some(&rgba(c, dark)));
        any = true;
    }
    if let Some(c) = s.background {
        tag.set_background_rgba(Some(&rgba(c, dark)));
        any = true;
    }
    if s.underline {
        tag.set_underline(crate::text::underline(s.underline_style));
        if let Some(c) = s.underline_color {
            tag.set_underline_rgba(Some(&rgba(c, dark)));
        }
        any = true;
    }
    if s.strikethrough {
        tag.set_strikethrough(true);
        any = true;
    }
    any.then_some(tag)
}

fn rgba(c: Color, dark: bool) -> gdk::RGBA {
    let c = if dark {
        c.dark_variant()
    } else {
        c.light_variant()
    };
    gdk::RGBA::new(c.r, c.g, c.b, c.a)
}

/// The chip of `run` at character `at`: its anchor (a plain U+FFFC becomes
/// one) and its widget, updated in place.
fn chip_at(
    rich: &mut Rich,
    b: &gtk::TextBuffer,
    at: i32,
    run: &TextRun,
    s: &StyledRun,
    style: &Style,
    dark: bool,
) {
    let anchor = match b.iter_at_offset(at).child_anchor() {
        Some(a) => a,
        None => {
            // Not an edit to undo: the app's value.
            b.begin_irreversible_action();
            let (mut from, mut to) = (b.iter_at_offset(at), b.iter_at_offset(at + 1));
            b.delete(&mut from, &mut to);
            let a = b.create_child_anchor(&mut b.iter_at_offset(at));
            b.end_irreversible_action();
            a
        }
    };
    let i = match rich.chips.iter().position(|c| c.anchor == anchor) {
        Some(i) => i,
        None => {
            let c = new_chip(anchor);
            rich.view.add_child_at_anchor(&c.widget, &c.anchor);
            rich.chips.push(c);
            rich.chips.len() - 1
        }
    };
    configure(&rich.chips[i], run, s, style, dark);
    rich.chips[i].copied = copied(run).to_string();
}

/// What a chip run shows: its symbol's glyph, its label, and whether it is
/// boxed (a chip) or alone (an inline icon, its glyph as the label).
fn parts(run: &TextRun) -> (Option<&'static str>, &str, bool) {
    match &run.chip {
        Some(_) => (
            run.chip_icon.as_deref().map(prism_core::glyphs::glyph),
            run.chip_label.as_deref().unwrap_or(""),
            true,
        ),
        None => (
            None,
            run.icon.as_deref().map_or("", prism_core::glyphs::glyph),
            false,
        ),
    }
}

/// What a copy writes for a chip run: its label (an icon: nothing).
fn copied(run: &TextRun) -> &str {
    match (&run.chip, &run.chip_label) {
        (Some(_), Some(label)) => label,
        _ => "",
    }
}

fn new_chip(anchor: gtk::TextChildAnchor) -> Chip {
    let widget = gtk::Box::new(gtk::Orientation::Horizontal, 0);
    widget.add_css_class("prism-chip");
    widget.set_focusable(false);
    widget.set_can_focus(false);
    let icon = gtk::Label::new(None);
    let label = gtk::Label::new(None);
    widget.append(&icon);
    widget.append(&label);
    let css = gtk::CssProvider::new();
    #[allow(deprecated)]
    widget
        .style_context()
        .add_provider(&css, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION + 2);
    let link = Rc::new(Cell::new(None));
    // A click on a chip with `on_click`.
    let click = gtk::GestureClick::new();
    let l = link.clone();
    click.connect_released(move |g, _, _, _| {
        if let Some(link) = l.get() {
            g.set_state(gtk::EventSequenceState::Claimed);
            crate::imp::dispatch(UiEvent::MenuSelect(link));
        }
    });
    widget.add_controller(click);
    Chip {
        anchor,
        widget,
        icon,
        label,
        css,
        link,
        copied: String::new(),
    }
}

/// Shows `run` in `chip`: a rounded box with its symbol and label in the
/// run's font, on the system's gray at 18% unless it sets a background;
/// an inline icon is its glyph alone.
fn configure(chip: &Chip, run: &TextRun, s: &StyledRun, style: &Style, dark: bool) {
    let (icon, label, boxed) = parts(run);
    let attrs = pango::AttrList::new();
    if let Some(name) = crate::text::family_name(&s.font.family) {
        attrs.insert(pango::AttrString::new_family(&name));
    }
    let w: pango::Weight = unsafe { glib::translate::from_glib(s.font.weight.css() as i32) };
    attrs.insert(pango::AttrInt::new_weight(w));
    if s.font.italic {
        attrs.insert(pango::AttrInt::new_style(pango::Style::Italic));
    }
    attrs.insert(pango::AttrSize::new_size_absolute(
        crate::text::pango_units(s.font.size),
    ));
    for l in [&chip.icon, &chip.label] {
        l.set_attributes(Some(&attrs));
    }
    chip.icon.set_text(icon.unwrap_or(""));
    chip.icon.set_visible(icon.is_some());
    chip.label.set_text(label);
    chip.label.set_visible(!label.is_empty());
    let em = s.font.size.max(1.);
    let gap = if icon.is_some() && !label.is_empty() {
        (em * 0.25).round()
    } else {
        0.
    };
    chip.widget.set_spacing(gap as i32);
    // GTK sets an anchored widget on the baseline: the box hangs below it
    // by its text's descent, so its text sits on the line's baseline.
    let probe = if label.is_empty() {
        &chip.icon
    } else {
        &chip.label
    };
    let (_, height, _, baseline) = probe.measure(gtk::Orientation::Vertical, -1);
    let descent = if baseline >= 0 { height - baseline } else { 0 };
    let mut css = format!("box{{margin-bottom:-{descent}px;");
    if boxed {
        let bg = s.background.map_or_else(
            || "alpha(#8e8e93,0.18)".to_string(),
            |c| crate::decor::color(c, dark),
        );
        css += &format!(
            "padding:0 {}px;border-radius:4px;background-color:{bg};",
            (em * 0.35).round()
        );
    }
    if let Some(c) = s.color.filter(|_| s.color != style.text_color) {
        css += &format!("color:{};", crate::decor::color(c, dark));
    }
    css.push('}');
    #[allow(deprecated)]
    chip.css.load_from_data(&css);
    chip.link.set(run.link);
    chip.widget
        .set_cursor_from_name(run.link.map(|_| "pointer"));
}

/// Characters `start..end` of rich input `id` as copied text: each chip as
/// its label, icons and other objects dropped.
pub(crate) fn labelled(id: NodeId, b: &gtk::TextBuffer, start: i32, end: i32) -> String {
    RICH.with(|r| {
        let r = r.borrow();
        let chips = r.get(&id).map(|r| &r.chips[..]).unwrap_or_default();
        let mut out = String::new();
        let mut it = b.iter_at_offset(start);
        while it.offset() < end && !it.is_end() {
            match it.child_anchor() {
                Some(a) => {
                    if let Some(c) = chips.iter().find(|c| c.anchor == a) {
                        out += &c.copied;
                    }
                }
                None if it.char() == OBJECT_CHAR => {}
                None => out.push(it.char()),
            }
            it.forward_char();
        }
        out
    })
}

/// Pango attributes of rich input `id`'s text (as `slice` gives it), to
/// measure its height: the runs' fonts and sizes, each chip its box.
pub(crate) fn attributes(id: NodeId) -> Option<pango::AttrList> {
    RICH.with(|r| {
        let r = r.borrow();
        let rich = r.get(&id)?;
        let style = rich.style.clone()?;
        let style = Style {
            text_transform: TextTransform::None,
            ..style
        };
        let runs = decode_runs(&rich.runs);
        let text: String = runs.iter().map(|r| r.text.as_str()).collect();
        let b = rich.view.buffer();
        if slice(&b) != text {
            return None;
        }
        let styled = StyledText::from_runs(&text, &runs, &style);
        let attrs = pango::AttrList::new();
        for s in &styled.runs {
            let (start, end) = (s.byte_start as u32, (s.byte_start + s.text.len()) as u32);
            let add = |mut a: pango::Attribute| {
                a.set_start_index(start);
                a.set_end_index(end);
                attrs.insert(a);
            };
            let char_at = text[..s.byte_start].chars().count() as i32;
            let anchor = b.iter_at_offset(char_at).child_anchor();
            if let Some(chip) = anchor.and_then(|a| rich.chips.iter().find(|c| c.anchor == a)) {
                // As GTK lays it out: its minimum size, on the baseline.
                let (w, _, _, _) = chip.widget.measure(gtk::Orientation::Horizontal, -1);
                let (h, _, _, _) = chip.widget.measure(gtk::Orientation::Vertical, w);
                let rect =
                    pango::Rectangle::new(0, -h * pango::SCALE, w * pango::SCALE, h * pango::SCALE);
                add(pango::AttrShape::new(&rect, &rect).upcast());
                continue;
            }
            if let Some(name) = crate::text::family_name(&s.font.family) {
                add(pango::AttrString::new_family(&name).upcast());
            }
            if s.font.size != style.font_size && style.font_size > 0. {
                add(pango::AttrFloat::new_scale((s.font.size / style.font_size) as f64).upcast());
            }
            if s.font.weight != style.font_weight {
                let w: pango::Weight =
                    unsafe { glib::translate::from_glib(s.font.weight.css() as i32) };
                add(pango::AttrInt::new_weight(w).upcast());
            }
        }
        Some(attrs)
    })
}

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

    #[test]
    fn a_chip_shows_its_symbol_and_label_and_copies_its_label() {
        let runs = decode_runs(&prism_core::encode_runs(&[
            TextRun {
                text: "See ".into(),
                ..TextRun::default()
            },
            TextRun {
                text: OBJECT_CHAR.to_string(),
                chip: Some("page:1".into()),
                chip_label: Some("Roadmap".into()),
                chip_icon: Some("doc.text".into()),
                link: Some(7),
                ..TextRun::default()
            },
            TextRun {
                text: OBJECT_CHAR.to_string(),
                icon: Some("star.fill".into()),
                ..TextRun::default()
            },
        ]));
        let (icon, label, boxed) = parts(&runs[1]);
        assert!(boxed);
        assert_eq!(label, "Roadmap");
        assert_eq!(icon, Some(prism_core::glyphs::glyph("doc.text")));
        assert_eq!(copied(&runs[1]), "Roadmap");
        assert_eq!(runs[1].link, Some(7));
        // An inline icon: its glyph, unboxed, copied as nothing.
        let (icon, label, boxed) = parts(&runs[2]);
        assert!(!boxed);
        assert_eq!(icon, None);
        assert_eq!(label, prism_core::glyphs::glyph("star.fill"));
        assert_eq!(copied(&runs[2]), "");
        // One character each, like the buffer's anchors.
        let text: String = runs.iter().map(|r| r.text.as_str()).collect();
        assert_eq!(text.chars().count(), 6);
    }
}