Skip to main content

tilo_actions/
selection.rs

1//! What a person has selected, carried to whoever is asked to act on it.
2//!
3//! A person selects a sentence in a document, a range of cells or a row in a
4//! list, and asks an agent about it. The agent must act at exactly that place
5//! through the actions the resource publishes, so the selection travels in
6//! the resource's own terms: a [`SelectionPlace`] is the same value an action
7//! takes as its place argument (`{"item": id, "start": n, "end": n}`, in
8//! characters), an [`InteractionAnchor`] names selections that are not text
9//! (cells, objects, rows), and a short excerpt lets a reader see what was
10//! selected without opening the resource. None of it grants authority: the
11//! agent still reaches the resource only through permission-filtered actions.
12
13use serde::{Deserialize, Serialize};
14
15use crate::InteractionAnchor;
16
17/// What a resource id starts with when a window publishes it under the
18/// toolkit's transport alias: `<prefix><host>:<publication>:<hex of the
19/// app's own id>`. The window's actions are addressed by the alias; the app
20/// names the resource by its own id (a selection's subject does), so a
21/// reader matching the two decodes the alias ([`logical_resource_id`]).
22pub const BOUND_RESOURCE_PREFIX: &str = "tilo-ui-bound:v1:";
23
24/// The app's own id for the published resource `id`: the id inside a
25/// [`BOUND_RESOURCE_PREFIX`] alias, or `id` itself when it is no alias (or a
26/// malformed one).
27#[must_use]
28pub fn logical_resource_id(id: &str) -> std::borrow::Cow<'_, str> {
29    let decoded = id.strip_prefix(BOUND_RESOURCE_PREFIX).and_then(|rest| {
30        let hex = rest.rsplit(':').next()?;
31        if hex.is_empty() || hex.len() % 2 != 0 {
32            return None;
33        }
34        let bytes = (0..hex.len())
35            .step_by(2)
36            .map(|at| u8::from_str_radix(hex.get(at..at.checked_add(2)?)?, 16).ok())
37            .collect::<Option<Vec<u8>>>()?;
38        String::from_utf8(bytes)
39            .ok()
40            .filter(|key| !key.is_empty() && !key.chars().any(char::is_control))
41    });
42    decoded.map_or(std::borrow::Cow::Borrowed(id), std::borrow::Cow::Owned)
43}
44
45/// The most characters an excerpt keeps. A selection is context for a
46/// request, not its payload: a longer one is cut and ends in `…`.
47pub const MAX_EXCERPT_CHARS: usize = 1000;
48/// The most bytes an excerpt may take at a trust boundary.
49pub const MAX_EXCERPT_BYTES: usize = 4 * 1024;
50/// The most bytes a place's item id may take.
51pub const MAX_PLACE_ITEM_BYTES: usize = 512;
52/// The most bytes an interaction anchor may take, encoded.
53pub const MAX_SELECTION_ANCHOR_BYTES: usize = 8 * 1024;
54/// The most items a selection of several items (files, rows, cards) names
55/// one by one; the excerpt counts the rest.
56pub const MAX_SELECTED_ITEMS: usize = 64;
57
58/// Where a selection is inside a resource: an item, a caret or a character
59/// range inside one item. Its JSON form is exactly what an action's place
60/// parameter takes (`tilo_resource::Place`), so an agent hands it back
61/// unchanged.
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct SelectionPlace {
65    pub item: String,
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub at: Option<usize>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub start: Option<usize>,
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub end: Option<usize>,
72}
73
74/// The validated position inside a [`SelectionPlace`]'s item.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum SelectionSpan {
77    Item,
78    Caret(usize),
79    Range { start: usize, end: usize },
80}
81
82impl SelectionPlace {
83    /// The whole of `item`.
84    #[must_use]
85    pub fn item(item: impl Into<String>) -> Self {
86        Self {
87            item: item.into(),
88            at: None,
89            start: None,
90            end: None,
91        }
92    }
93
94    #[must_use]
95    pub fn caret(item: impl Into<String>, at: usize) -> Self {
96        Self {
97            at: Some(at),
98            ..Self::item(item)
99        }
100    }
101
102    /// Characters `start..end` of `item`; the bounds are put in order.
103    #[must_use]
104    pub fn range(item: impl Into<String>, start: usize, end: usize) -> Self {
105        Self {
106            start: Some(start.min(end)),
107            end: Some(start.max(end)),
108            ..Self::item(item)
109        }
110    }
111
112    /// Validate this place and return its position inside [`Self::item`]:
113    /// a whole item, a caret `at`, or an ordered range `start..end`.
114    ///
115    /// # Errors
116    /// Returns a reason when `item` is empty, oversized, or holds control
117    /// characters, or when `at`, `start`, and `end` do not name one item,
118    /// caret, or ordered range.
119    pub fn validated_span(&self) -> Result<SelectionSpan, String> {
120        if self.item.is_empty() || self.item.len() > MAX_PLACE_ITEM_BYTES {
121            return Err("a selection place names one item of bounded length".into());
122        }
123        if self.item.chars().any(char::is_control) {
124            return Err("a selection place item contains control characters".into());
125        }
126        match (self.at, self.start, self.end) {
127            (None, None, None) => Ok(SelectionSpan::Item),
128            (Some(at), None, None) => Ok(SelectionSpan::Caret(at)),
129            (None, Some(start), Some(end)) if start <= end => {
130                Ok(SelectionSpan::Range { start, end })
131            }
132            _ => Err(
133                "a place is an item, a caret `at` in it, or an ordered range `start..end` of it"
134                    .into(),
135            ),
136        }
137    }
138
139    /// Whether this is a well-formed place, the shape an action's place
140    /// parameter accepts.
141    pub fn validate(&self) -> Result<(), String> {
142        self.validated_span().map(|_| ())
143    }
144}
145
146/// What was selected: where (a place, an app-native anchor, or both) and a
147/// short excerpt of it. Every part is optional; an empty anchor says
148/// nothing and is dropped by [`Self::non_empty`].
149///
150/// Encoded as a JSON object in JSON, and as that object's JSON text in a
151/// binary format, because an [`InteractionAnchor`] reads only from JSON.
152#[derive(Clone, Debug, Default, PartialEq, Eq)]
153pub struct SelectionAnchor {
154    pub place: Option<SelectionPlace>,
155    /// Every item of a selection of several (files in a folder, rows of a
156    /// list), each the whole of one item, in the order shown. Empty for a
157    /// selection inside one item, which [`Self::place`] names.
158    pub items: Vec<SelectionPlace>,
159    pub interaction: Option<InteractionAnchor>,
160    pub excerpt: Option<String>,
161}
162
163#[derive(Serialize, Deserialize)]
164#[serde(deny_unknown_fields)]
165struct SelectionAnchorWire {
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    place: Option<SelectionPlace>,
168    #[serde(default, skip_serializing_if = "Vec::is_empty")]
169    items: Vec<SelectionPlace>,
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    interaction: Option<InteractionAnchor>,
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    excerpt: Option<String>,
174}
175
176impl Serialize for SelectionAnchor {
177    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
178        let wire = SelectionAnchorWire {
179            place: self.place.clone(),
180            items: self.items.clone(),
181            interaction: self.interaction.clone(),
182            excerpt: self.excerpt.clone(),
183        };
184        if serializer.is_human_readable() {
185            wire.serialize(serializer)
186        } else {
187            serde_json::to_string(&wire)
188                .map_err(serde::ser::Error::custom)?
189                .serialize(serializer)
190        }
191    }
192}
193
194impl<'de> Deserialize<'de> for SelectionAnchor {
195    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
196        let wire = if deserializer.is_human_readable() {
197            SelectionAnchorWire::deserialize(deserializer)?
198        } else {
199            let text = String::deserialize(deserializer)?;
200            serde_json::from_str(&text).map_err(serde::de::Error::custom)?
201        };
202        Ok(Self {
203            place: wire.place,
204            items: wire.items,
205            interaction: wire.interaction,
206            excerpt: wire.excerpt,
207        })
208    }
209}
210
211impl SelectionAnchor {
212    /// An anchor of `excerpt` alone: what is known of a selection in an app
213    /// that publishes no resources, read from the primary selection.
214    #[must_use]
215    pub fn of_text(excerpt: &str) -> Self {
216        Self {
217            excerpt: excerpt_of(excerpt),
218            ..Self::default()
219        }
220    }
221
222    /// A selection of several whole items, each `(id, label)` in the order
223    /// shown: every item named as a place (at most [`MAX_SELECTED_ITEMS`]),
224    /// and an excerpt listing their labels, counting any beyond that.
225    #[must_use]
226    pub fn of_items<I, L>(items: impl IntoIterator<Item = (I, L)>) -> Self
227    where
228        I: Into<String>,
229        L: AsRef<str>,
230    {
231        let mut places = Vec::new();
232        let mut labels = Vec::new();
233        let mut total = 0_usize;
234        for (id, label) in items {
235            total = total.saturating_add(1);
236            if places.len() == MAX_SELECTED_ITEMS {
237                continue;
238            }
239            let id = id.into();
240            let label = label.as_ref().trim();
241            labels.push(if label.is_empty() {
242                id.clone()
243            } else {
244                label.to_owned()
245            });
246            places.push(SelectionPlace::item(id));
247        }
248        // List names while they fit the excerpt, leaving room to count the
249        // rest, so the excerpt never ends cut mid-name.
250        let budget = MAX_EXCERPT_CHARS.saturating_sub(32);
251        let mut listed = String::new();
252        let mut shown = 0_usize;
253        for label in &labels {
254            let line = format!("- {label}");
255            let used = listed
256                .chars()
257                .count()
258                .saturating_add(line.chars().count())
259                .saturating_add(1);
260            if used > budget {
261                break;
262            }
263            if !listed.is_empty() {
264                listed.push('\n');
265            }
266            listed.push_str(&line);
267            shown = shown.saturating_add(1);
268        }
269        let more = total.saturating_sub(shown);
270        if more > 0 {
271            if !listed.is_empty() {
272                listed.push('\n');
273            }
274            listed.push_str("- and ");
275            listed.push_str(&more.to_string());
276            listed.push_str(" more");
277        }
278        Self {
279            items: places,
280            excerpt: excerpt_of(&listed),
281            ..Self::default()
282        }
283    }
284
285    #[must_use]
286    pub fn with_excerpt(mut self, excerpt: &str) -> Self {
287        self.excerpt = excerpt_of(excerpt);
288        self
289    }
290
291    #[must_use]
292    pub fn at(mut self, place: SelectionPlace) -> Self {
293        self.place = Some(place);
294        self
295    }
296
297    /// The same anchor noting the whole of a selection that spans several
298    /// blocks of a text, `ranges` in document order, of which [`Self::place`]
299    /// is one block's part (an action's place names one block). One range
300    /// says nothing more than the place, so it is left out; a long
301    /// selection keeps its first [`crate::interaction::MAX_ANCHOR_ITEMS`].
302    #[must_use]
303    pub fn spanning(mut self, region: &str, mut ranges: Vec<crate::InteractionTextRange>) -> Self {
304        if ranges.len() > 1 {
305            ranges.truncate(crate::interaction::MAX_ANCHOR_ITEMS);
306            self.interaction = Some(InteractionAnchor::Text {
307                region: region.to_owned(),
308                ranges,
309            });
310        }
311        self
312    }
313
314    /// The block ranges of a selection spanning several blocks
315    /// ([`Self::spanning`]).
316    #[must_use]
317    pub fn spanned_ranges(&self) -> Option<&[crate::InteractionTextRange]> {
318        match &self.interaction {
319            Some(InteractionAnchor::Text { ranges, .. }) if ranges.len() > 1 => Some(ranges),
320            _ => None,
321        }
322    }
323
324    /// Whether the anchor says nothing at all.
325    #[must_use]
326    pub fn is_empty(&self) -> bool {
327        self.place.is_none()
328            && self.items.is_empty()
329            && self.interaction.is_none()
330            && self.excerpt.is_none()
331    }
332
333    /// The anchor, unless it says nothing.
334    #[must_use]
335    pub fn non_empty(self) -> Option<Self> {
336        (!self.is_empty()).then_some(self)
337    }
338
339    /// Whether the anchor is within bounds, so a receiver may keep it.
340    pub fn validate(&self) -> Result<(), String> {
341        if let Some(place) = &self.place {
342            place.validate()?;
343        }
344        if self.items.len() > MAX_SELECTED_ITEMS {
345            return Err("a selection names too many items".into());
346        }
347        for item in &self.items {
348            item.validate()?;
349        }
350        if let Some(excerpt) = &self.excerpt
351            && (excerpt.len() > MAX_EXCERPT_BYTES
352                || excerpt.chars().count() > MAX_EXCERPT_CHARS + 1
353                || excerpt
354                    .chars()
355                    .any(|c| c.is_control() && !matches!(c, '\n' | '\t')))
356        {
357            return Err("a selection excerpt is oversized or contains control characters".into());
358        }
359        if let Some(interaction) = &self.interaction {
360            let encoded = serde_json::to_vec(interaction).map_err(|error| error.to_string())?;
361            if encoded.len() > MAX_SELECTION_ANCHOR_BYTES {
362                return Err("a selection's interaction anchor is oversized".into());
363            }
364        }
365        Ok(())
366    }
367}
368
369/// What a request is about: the resource a person had selected something in,
370/// and the selection. Only the subject of the request: it carries no
371/// authority, so a run about a selection may act anywhere its starter and
372/// its agent may (other resources, other apps), as any task may.
373#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
374#[serde(deny_unknown_fields)]
375pub struct SelectionSubject {
376    /// The application the resource is in, by package id.
377    pub app_id: String,
378    pub app_label: String,
379    pub resource: crate::ActionResource,
380    pub anchor: SelectionAnchor,
381}
382
383impl SelectionSubject {
384    /// Whether the subject is within bounds, so a receiver may keep it.
385    pub fn validate(&self) -> Result<(), String> {
386        for (value, maximum, name) in [
387            (self.app_id.as_str(), 256, "app"),
388            (self.app_label.as_str(), 512, "app label"),
389            (self.resource.id.as_str(), 2048, "resource id"),
390            (self.resource.kind.as_str(), 128, "resource kind"),
391            (self.resource.label.as_str(), 512, "resource label"),
392        ] {
393            if value.len() > maximum || value.chars().any(char::is_control) {
394                return Err(format!("a selection's {name} is oversized or malformed"));
395            }
396        }
397        if self.resource.id.trim().is_empty() || self.app_id.trim().is_empty() {
398            return Err("a selection names its application and resource".into());
399        }
400        if self.anchor.is_empty() {
401            return Err("a selection says what was selected".into());
402        }
403        self.anchor.validate()
404    }
405
406    /// Whether the published resource `id` is the one this selection is in:
407    /// the same id, or a window's transport alias of it
408    /// ([`logical_resource_id`]).
409    #[must_use]
410    pub fn is_in(&self, id: &str) -> bool {
411        id == self.resource.id || logical_resource_id(id) == self.resource.id
412    }
413}
414
415/// `text` as a selection excerpt: trimmed, at most [`MAX_EXCERPT_CHARS`]
416/// characters (a longer one is cut and ends in `…`), without control
417/// characters other than line breaks and tabs. `None` when nothing is left.
418#[must_use]
419pub fn excerpt_of(text: &str) -> Option<String> {
420    let text = text.trim();
421    if text.is_empty() {
422        return None;
423    }
424    let mut kept = text
425        .chars()
426        .filter(|c| !c.is_control() || matches!(c, '\n' | '\t'));
427    let mut excerpt: String = kept.by_ref().take(MAX_EXCERPT_CHARS).collect();
428    let mut cut = kept.next().is_some();
429    while excerpt.len() > MAX_EXCERPT_BYTES.saturating_sub('…'.len_utf8()) {
430        excerpt.pop();
431        cut = true;
432    }
433    if cut {
434        excerpt.push('…');
435    }
436    Some(excerpt)
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442
443    fn anchor() -> SelectionAnchor {
444        SelectionAnchor {
445            place: Some(SelectionPlace::range("block-1", 4, 9)),
446            items: Vec::new(),
447            interaction: Some(InteractionAnchor::Objects {
448                ids: vec!["block-1".into()],
449            }),
450            excerpt: Some("quick".into()),
451        }
452    }
453
454    tilo_test_env::scenario! {
455        fn a_selection_names_its_place_and_travels_bounded;
456
457        phase a_selection_is_in_its_resource_under_a_window_alias_too;
458        {
459            let body = "notes.notebook/pages/p1/body";
460            let alias = format!(
461                "{BOUND_RESOURCE_PREFIX}2a4120d7-2f63-4578-aed8-11cb91ed3628:\
462             c0fe4ad7-b7d0-46c3-ab7e-78d12d5d86f4:6e6f7465732e6e6f7465626f6f6b2f70616765732f70312f626f6479"
463            );
464            assert_eq!(logical_resource_id(&alias), body);
465            assert_eq!(logical_resource_id(body), body);
466            assert_eq!(
467                logical_resource_id(&format!("{BOUND_RESOURCE_PREFIX}a:b:zz")),
468                format!("{BOUND_RESOURCE_PREFIX}a:b:zz"),
469                "a malformed alias is its own id"
470            );
471            let subject = SelectionSubject {
472                app_id: "so.tilo.notes".into(),
473                app_label: "Notes".into(),
474                resource: crate::ActionResource {
475                    id: body.into(),
476                    kind: "tilo.rich-text".into(),
477                    label: "Links".into(),
478                },
479                anchor: anchor(),
480            };
481            assert!(subject.is_in(body));
482            assert!(subject.is_in(&alias));
483            assert!(!subject.is_in("notes.notebook/pages/p2/body"));
484        }
485
486        phase a_selection_of_several_items_names_each_and_lists_them;
487        {
488            let anchor = SelectionAnchor::of_items(
489                (0..MAX_SELECTED_ITEMS + 2).map(|n| (format!("file:{n}"), format!("report-{n}.pdf"))),
490            );
491            assert_eq!(anchor.items.len(), MAX_SELECTED_ITEMS);
492            assert_eq!(anchor.items[1], SelectionPlace::item("file:1"));
493            let excerpt = anchor.excerpt.as_deref().unwrap();
494            assert!(excerpt.starts_with("- report-0.pdf\n- report-1.pdf\n"));
495            assert!(excerpt.ends_with(" more"), "{excerpt}");
496            assert!(!excerpt.contains('…'), "the list is never cut mid-name");
497            let listed = excerpt
498                .lines()
499                .filter(|line| line.starts_with("- report-"))
500                .count();
501            assert!(
502                excerpt.ends_with(&format!("- and {} more", MAX_SELECTED_ITEMS + 2 - listed)),
503                "{excerpt}"
504            );
505            assert!(anchor.validate().is_ok());
506            let json = serde_json::to_value(&anchor).unwrap();
507            assert_eq!(json["items"][0], serde_json::json!({"item": "file:0"}));
508            assert_eq!(
509                serde_json::from_value::<SelectionAnchor>(json).unwrap(),
510                anchor
511            );
512            let encoded = postcard::to_allocvec(&anchor).unwrap();
513            assert_eq!(
514                postcard::from_bytes::<SelectionAnchor>(&encoded).unwrap(),
515                anchor
516            );
517            assert!(
518                serde_json::to_value(SelectionAnchor::of_text("x"))
519                    .unwrap()
520                    .get("items")
521                    .is_none(),
522                "a selection inside one item writes what it wrote before"
523            );
524            let too_many = SelectionAnchor {
525                items: vec![SelectionPlace::item("f"); MAX_SELECTED_ITEMS + 1],
526                ..SelectionAnchor::default()
527            };
528            assert!(too_many.validate().is_err());
529        }
530
531        phase place_travels_as_the_action_place_parameter_does;
532        {
533            let place = SelectionPlace::range("block-1", 9, 4);
534            assert_eq!(
535                serde_json::to_value(&place).unwrap(),
536                serde_json::json!({"item": "block-1", "start": 4, "end": 9})
537            );
538            assert_eq!(
539                serde_json::to_value(SelectionPlace::caret("b", 2)).unwrap(),
540                serde_json::json!({"item": "b", "at": 2})
541            );
542            assert!(
543                crate::validate_json_schema(
544                    &serde_json::to_value(&place).unwrap(),
545                    &crate::place_schema()
546                )
547                .is_ok()
548            );
549        }
550
551        phase malformed_places_are_refused;
552        {
553            assert!(SelectionPlace::item("").validate().is_err());
554            let both = SelectionPlace {
555                at: Some(1),
556                ..SelectionPlace::range("b", 1, 2)
557            };
558            assert!(both.validate().is_err());
559            let open = SelectionPlace {
560                start: Some(3),
561                ..SelectionPlace::item("b")
562            };
563            assert!(open.validate().is_err());
564            let backwards = SelectionPlace {
565                start: Some(3),
566                end: Some(1),
567                ..SelectionPlace::item("b")
568            };
569            assert!(backwards.validate().is_err());
570            assert!(
571                serde_json::from_value::<SelectionPlace>(serde_json::json!({"item":"b","x":1}))
572                    .is_err()
573            );
574        }
575
576        phase anchor_round_trips_through_json_and_postcard;
577        {
578            let anchor = anchor();
579            let json = serde_json::to_value(&anchor).unwrap();
580            assert_eq!(json["place"]["start"], 4);
581            assert_eq!(json["interaction"]["kind"], "objects");
582            assert_eq!(
583                serde_json::from_value::<SelectionAnchor>(json).unwrap(),
584                anchor
585            );
586            let bytes = postcard::to_allocvec(&anchor).unwrap();
587            assert_eq!(
588                postcard::from_bytes::<SelectionAnchor>(&bytes).unwrap(),
589                anchor
590            );
591        }
592
593        phase absent_parts_are_omitted_and_older_readers_default_them;
594        {
595            let only_text = SelectionAnchor::of_text("  hello  ");
596            assert_eq!(
597                serde_json::to_value(&only_text).unwrap(),
598                serde_json::json!({"excerpt": "hello"})
599            );
600            assert_eq!(
601                serde_json::from_value::<SelectionAnchor>(serde_json::json!({})).unwrap(),
602                SelectionAnchor::default()
603            );
604            assert!(SelectionAnchor::of_text("   ").non_empty().is_none());
605        }
606
607        phase excerpts_are_bounded_and_cut_visibly;
608        {
609            let long = "word ".repeat(400);
610            let excerpt = excerpt_of(&long).unwrap();
611            assert_eq!(excerpt.chars().count(), MAX_EXCERPT_CHARS + 1);
612            assert!(excerpt.ends_with('…'));
613            assert!(SelectionAnchor::of_text(&long).validate().is_ok());
614            let wide = "界".repeat(MAX_EXCERPT_CHARS * 2);
615            let excerpt = excerpt_of(&wide).unwrap();
616            assert!(excerpt.len() <= MAX_EXCERPT_BYTES);
617            assert!(excerpt.ends_with('…'));
618            assert_eq!(excerpt_of("a\u{7}b\nc").as_deref(), Some("ab\nc"));
619            let forged = SelectionAnchor {
620                excerpt: Some("x".repeat(MAX_EXCERPT_BYTES + 1)),
621                ..SelectionAnchor::default()
622            };
623            assert!(forged.validate().is_err());
624        }
625    }
626}