drishti 0.2.0

Rust frontend orchestration framework: design publication plus deterministic reference cores for the Logical Works ink lab, the GPU residency model and the Logic OS Canvas protocol, motion, scene and native host broker; no qualified GPU backend yet.
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
//! Single-owner presentation reducer with a bounded inbox.
//!
//! Absorbed from `primitives/canvas-native/crates/canvas/src/scene.rs`
//! (kernel#850 row 15). Acknowledgement is present-after-success: the adapter
//! calls [`Canvas::acknowledge_present`] only after actual presentation.
//! Headless acknowledgement is not native-display evidence. The read-only
//! accessors live in `query`; the ordering envelope and counters in `delta`.

use std::{collections::VecDeque, sync::Arc};

pub use super::delta::{Delta, Statistics};
use super::frame::{Frame, FrameToken};
use super::model::{Action, Artifact, CommitStatus, Error, Limits, PresentationLease, View};
use crate::canvas_protocol::SessionInvariant;
use crate::motion::node::critical::CriticalSpring;

mod query;

/// Single-owner presentation instance.
///
/// # Examples
///
/// ```
/// use drishti::canvas_protocol::SessionInvariant;
/// use drishti::canvas_scene::{Artifact, Canvas, Limits};
///
/// let id = "11111111-1111-1111-1111-111111111111";
/// let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
/// let limits = Limits::default();
/// let mut canvas = Canvas::new(session, 1, Artifact::new(id, 1, "one\ntwo", None, None, limits)?, limits)?;
/// let frame = canvas.prepare(0.0, 900, 600, false)?.ok_or("a new canvas owes a frame")?;
/// canvas.acknowledge_present(frame.token())?;
/// assert!(canvas.presented_token().is_some());
/// assert_eq!(canvas.stats().presented(), 1);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Canvas {
    /// Bound session.
    session: SessionInvariant,
    /// Bound lease, if any.
    lease: Option<PresentationLease>,
    /// Instance identity for token scoping.
    instance: Arc<()>,
    /// Instance generation.
    generation: u64,
    /// Scene revision: increments per drained action and per denial.
    revision: u64,
    /// Resource envelope.
    limits: Limits,
    /// Presented artifact.
    artifact: Arc<Artifact>,
    /// Confirmed domain status.
    commit_status: CommitStatus,
    /// Optimistic overlay, if any.
    optimistic_status: Option<CommitStatus>,
    /// Bounded inbox.
    inbox: VecDeque<Action>,
    /// View-axis spring.
    motion: CriticalSpring,
    /// Navigation target.
    target: View,
    /// Scroll offsets in view-index order.
    scroll: [usize; 3],
    /// Reduced-motion mode.
    reduced: bool,
    /// Whether a frame is owed.
    dirty: bool,
    /// Whether the instance was revoked.
    revoked: bool,
    /// Last prepared token, if any.
    prepared: Option<FrameToken>,
    /// Last presented token, if any.
    presented: Option<FrameToken>,
    /// Frame serial.
    serial: u64,
    /// Reducer counters.
    stats: Statistics,
}

impl Canvas {
    /// Read-only host context. Creates a default diagnostic presentation
    /// lease from the session, generation, and envelope.
    ///
    /// # Errors
    ///
    /// Returns the lease or scope failure when the session cannot present
    /// the artifact.
    ///
    /// # Examples
    ///
    /// ```
    /// use drishti::canvas_protocol::SessionInvariant;
    /// use drishti::canvas_scene::{Artifact, Canvas, Error, Limits};
    ///
    /// let id = "11111111-1111-1111-1111-111111111111";
    /// let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// let limits = Limits::default();
    /// let canvas = Canvas::new(session.clone(), 1, Artifact::new(id, 1, "src", None, None, limits)?, limits)?;
    /// assert!(canvas.lease().is_some() && canvas.needs_frame());
    /// let foreign = Artifact::new("other-work", 1, "src", None, None, limits)?;
    /// assert_eq!(Canvas::new(session, 1, foreign, limits).err(), Some(Error::WrongScope));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn new(
        session: SessionInvariant,
        generation: u64,
        artifact: Artifact,
        limits: Limits,
    ) -> Result<Self, Error> {
        let lease = PresentationLease::new(
            "diagnostic-lease",
            "primary-surface",
            session,
            generation,
            limits,
        )?;
        Self::with_lease(lease, artifact)
    }

    /// Construct a presentation instance bound to an explicit versioned lease.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidInput`] for an invalid lease,
    /// [`Error::WrongScope`] when the artifact key differs from the session
    /// work object id, or [`Error::BudgetExceeded`] for an over-envelope
    /// payload.
    ///
    /// # Examples
    ///
    /// ```
    /// use drishti::canvas_protocol::SessionInvariant;
    /// use drishti::canvas_scene::{Artifact, Canvas, Limits, PresentationLease};
    ///
    /// let id = "11111111-1111-1111-1111-111111111111";
    /// let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// let limits = Limits::default();
    /// let lease = PresentationLease::new("lease-1", "surface-1", session, 3, limits)?;
    /// let canvas = Canvas::with_lease(lease, Artifact::new(id, 1, "src", None, None, limits)?)?;
    /// assert_eq!(canvas.generation(), 3);
    /// assert_eq!(canvas.lease().map(|lease| lease.lease_id()), Some("lease-1"));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn with_lease(lease: PresentationLease, artifact: Artifact) -> Result<Self, Error> {
        lease.validate()?;
        let limits = lease.limits();
        let session = lease.session().clone();
        let generation = lease.generation();
        // Presentation data belongs to the session work object.
        Error::require(
            artifact.key() == session.work_object_id(),
            Error::WrongScope,
        )?;
        Error::require(
            artifact.payload_bytes() <= limits.text_bytes(),
            Error::BudgetExceeded,
        )?;
        let commit_status = artifact.commit_status();
        let motion = CriticalSpring::new(0.0, 0.45).map_err(Error::from)?;
        Ok(Self {
            session,
            lease: Some(lease),
            instance: Arc::new(()),
            generation,
            revision: 0,
            limits,
            artifact: Arc::new(artifact),
            commit_status,
            optimistic_status: None,
            inbox: VecDeque::with_capacity(limits.queued_commands()),
            motion,
            target: View::Source,
            scroll: [0; 3],
            reduced: false,
            dirty: true,
            revoked: false,
            prepared: None,
            presented: None,
            serial: 0,
            stats: Statistics::default(),
        })
    }

    /// Cancel active and queued optimistic overlays, advancing the revision
    /// past both so no accepted revision is ever reused.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Revoked`] on a revoked instance.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Action, Artifact, Canvas, CommitStatus, Delta, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session.clone(), 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let base = canvas.next_base_revision()?;
    /// canvas.enqueue(Delta::new(session, 1, base, Action::OptimisticTransition(CommitStatus::Committed)))?;
    /// canvas.prepare(0.0, 900, 600, false)?;
    /// assert!(canvas.is_optimistic());
    /// canvas.deny_optimistic()?;
    /// assert!(!canvas.is_optimistic());
    /// assert_eq!(canvas.commit_status(), CommitStatus::Proposed);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn deny_optimistic(&mut self) -> Result<(), Error> {
        Error::require(!self.revoked, Error::Revoked)?;
        let cancelled = self
            .inbox
            .iter()
            .filter(|action| matches!(action, Action::OptimisticTransition(_)))
            .count();
        let cancelled_count = u64::try_from(cancelled)?;
        let overlay_count = u64::from(self.optimistic_status.is_some());
        let advance = cancelled_count
            .checked_add(overlay_count)
            .ok_or(Error::InvalidInput)?;
        if advance > 0 {
            let inbox_count = u64::try_from(self.inbox.len())?;
            let live_count = inbox_count
                .checked_sub(cancelled_count)
                .ok_or(Error::InvalidInput)?;
            let revision = self
                .revision
                .checked_add(advance)
                .ok_or(Error::InvalidInput)?;
            revision
                .checked_add(live_count)
                .ok_or(Error::InvalidInput)?;
            self.inbox
                .retain(|action| !matches!(action, Action::OptimisticTransition(_)));
            self.optimistic_status = None;
            self.revision = revision;
            self.dirty = true;
            self.presented = None;
            self.prepared = None;
        }
        Ok(())
    }

    /// Enqueue one ordering envelope after scope, freshness, and capacity
    /// checks. Rejections consume nothing: no revision, no inbox slot.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Revoked`], [`Error::WrongScope`], [`Error::Stale`],
    /// [`Error::QueueFull`], or [`Error::InvalidInput`] on overflow.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Action, Artifact, Canvas, Delta, Error, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session.clone(), 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let delta = Delta::new(session, 1, 0, Action::Step(1));
    /// canvas.enqueue(delta.clone())?;
    /// assert_eq!(canvas.next_base_revision()?, 1);
    /// assert_eq!(canvas.enqueue(delta), Err(Error::Stale));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn enqueue(&mut self, delta: Delta) -> Result<(), Error> {
        Error::require(!self.revoked, Error::Revoked)?;
        Error::require(delta.session == self.session, Error::WrongScope)?;
        Error::require(
            delta.generation == self.generation
                && delta.base_revision == self.next_base_revision()?,
            Error::Stale,
        )?;
        Error::require(
            self.inbox.len() != self.limits.queued_commands(),
            Error::QueueFull,
        )?;
        delta
            .base_revision
            .checked_add(1)
            .ok_or(Error::InvalidInput)?;
        self.inbox.push_back(delta.action);
        self.stats.accepted = self.stats.accepted.saturating_add(1);
        Ok(())
    }

    /// Enqueue a local interaction against a presented token. A frame token
    /// authorizes local interaction, never a domain-status claim: transition
    /// actions are rejected here.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Revoked`], [`Error::Stale`], or [`Error::WrongScope`]
    /// for transition-family actions.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Action, Artifact, Canvas, CommitStatus, Error, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session, 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let frame = canvas.prepare(0.0, 900, 600, false)?.ok_or("frame owed")?;
    /// canvas.acknowledge_present(frame.token())?;
    /// canvas.input(frame.token(), Action::Step(1))?;
    /// let claim = canvas.input(frame.token(), Action::Transition(CommitStatus::Committed));
    /// assert_eq!(claim, Err(Error::WrongScope));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn input(&mut self, token: FrameToken, action: Action) -> Result<(), Error> {
        Error::require(!self.revoked, Error::Revoked)?;
        Error::require(self.presented.as_ref() == Some(&token), Error::Stale)?;
        Error::require(
            !matches!(
                action,
                Action::Transition(_) | Action::OptimisticTransition(_) | Action::RevertOptimistic
            ),
            Error::WrongScope,
        )?;
        self.enqueue(Delta::new(
            self.session.clone(),
            self.generation,
            self.next_base_revision()?,
            action,
        ))
    }

    /// Drain the inbox in order. Upper bound is the fixed inbox limit: no
    /// actor, thread, or durable event per widget.
    fn drain(&mut self) -> Result<(), Error> {
        while let Some(action) = self.inbox.pop_front() {
            match action {
                Action::Navigate(view) => {
                    self.motion
                        .retarget(view_position(view))
                        .map_err(Error::from)?;
                    self.target = view;
                }
                Action::Step(amount) => {
                    let target = step_target(self.target, amount);
                    self.motion
                        .retarget(view_position(target))
                        .map_err(Error::from)?;
                    self.target = target;
                }
                Action::ToggleReducedMotion => self.reduced = !self.reduced,
                Action::ReducedMotion(reduced) => self.reduced = reduced,
                Action::Scroll { view, lines } => {
                    let max = self.artifact.text(view).lines().count().saturating_sub(1);
                    let max_line = i64::try_from(max)?;
                    let current = i64::try_from(self.scroll[view.index()])?;
                    let scrolled = current
                        .checked_add(i64::from(lines))
                        .ok_or(Error::InvalidInput)?;
                    let clamped = scrolled.clamp(0, max_line);
                    self.scroll[view.index()] = usize::try_from(clamped)?;
                }
                Action::Transition(status) => {
                    self.commit_status = status;
                    self.optimistic_status = None;
                }
                Action::OptimisticTransition(status) => {
                    self.optimistic_status = Some(status);
                }
                Action::RevertOptimistic => {
                    self.optimistic_status = None;
                }
            }
            if self.reduced {
                self.motion.snap();
            }
            self.revision = self.revision.checked_add(1).ok_or(Error::InvalidInput)?;
            self.stats.drained = self.stats.drained.saturating_add(1);
            self.dirty = true;
            self.presented = None;
        }
        Ok(())
    }

    /// Validate time and viewport BEFORE draining. A rejected frame cannot
    /// consume queued actions.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Revoked`] on a revoked instance or
    /// [`Error::InvalidInput`] for non-finite or over-60s time, or an
    /// over-budget viewport.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Artifact, Canvas, Error, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session, 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let frame = canvas.prepare(0.0, 900, 600, false)?.ok_or("frame owed")?;
    /// assert_eq!((frame.width(), frame.height()), (900, 600));
    /// assert_eq!(canvas.prepare(f64::NAN, 900, 600, false).err(), Some(Error::InvalidInput));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn prepare(
        &mut self,
        seconds: f64,
        width: u32,
        height: u32,
        force: bool,
    ) -> Result<Option<Frame>, Error> {
        Error::require(!self.revoked, Error::Revoked)?;
        Error::require(
            seconds.is_finite() && (0.0..=60.0).contains(&seconds),
            Error::InvalidInput,
        )?;
        self.limits.pixel_count(width, height)?;
        if !force && !self.needs_frame() {
            return Ok(None);
        }
        let serial = self.serial.checked_add(1).ok_or(Error::InvalidInput)?;
        self.drain()?;
        if !self.motion.is_settled() {
            self.motion.advance(seconds).map_err(Error::from)?;
            self.stats.sampled = self.stats.sampled.saturating_add(1);
        }
        if self.motion.is_settled() {
            self.motion.snap();
        }
        self.serial = serial;
        let token = FrameToken {
            instance: Arc::clone(&self.instance),
            generation: self.generation,
            serial,
            revision: self.revision,
        };
        self.prepared = Some(token.clone());
        self.stats.prepared = self.stats.prepared.saturating_add(1);
        let mut frame = Frame::new(
            token,
            Arc::clone(&self.artifact),
            self.commit_status(),
            self.commit_status,
            self.is_optimistic(),
            self.motion.velocity(),
            self.motion.position(),
        );
        frame.set_target(self.target);
        frame.set_scroll(self.scroll);
        frame.set_viewport(width, height);
        frame.set_reduced_motion(self.reduced);
        frame.set_animating(!self.motion.is_settled());
        Ok(Some(frame))
    }

    /// Record successful presentation of a prepared token. The adapter calls
    /// this only AFTER actual presentation succeeds.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Revoked`] on a revoked instance or [`Error::Stale`]
    /// for a superseded or mismatched token.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Artifact, Canvas, Error, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session, 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let token = canvas.prepare(0.0, 900, 600, false)?.ok_or("frame owed")?.token();
    /// canvas.acknowledge_present(token.clone())?;
    /// assert_eq!(canvas.presented_token(), Some(token.clone()));
    /// assert_eq!(canvas.acknowledge_present(token), Err(Error::Stale));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn acknowledge_present(&mut self, token: FrameToken) -> Result<(), Error> {
        Error::require(!self.revoked, Error::Revoked)?;
        Error::require(
            self.prepared.as_ref() == Some(&token) && token.revision == self.revision,
            Error::Stale,
        )?;
        self.presented = Some(token);
        self.prepared = None;
        self.dirty = false;
        self.stats.presented = self.stats.presented.saturating_add(1);
        Ok(())
    }

    /// Drop presented/prepared tokens and owe a fresh frame (surface lost).
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Artifact, Canvas, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session, 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let token = canvas.prepare(0.0, 900, 600, false)?.ok_or("frame owed")?.token();
    /// canvas.acknowledge_present(token)?;
    /// canvas.invalidate_surface();
    /// assert!(canvas.presented_token().is_none());
    /// assert!(canvas.needs_frame());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn invalidate_surface(&mut self) {
        self.presented = None;
        self.prepared = None;
        self.dirty = true;
    }

    /// Snap motion and invalidate the surface: recover from a long idle sleep
    /// without replaying events.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Artifact, Canvas, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session, 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// let token = canvas.prepare(0.0, 900, 600, false)?.ok_or("frame owed")?.token();
    /// canvas.acknowledge_present(token)?;
    /// canvas.resume_without_replay();
    /// assert!(canvas.presented_token().is_none() && canvas.needs_frame());
    /// assert_eq!(canvas.revision(), 0);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn resume_without_replay(&mut self) {
        self.motion.snap();
        self.invalidate_surface();
    }

    /// Revoke the instance: clear the inbox and refuse everything after.
    ///
    /// # Examples
    ///
    /// ```
    /// # use drishti::canvas_protocol::SessionInvariant;
    /// # use drishti::canvas_scene::{Action, Artifact, Canvas, Delta, Error, Limits};
    /// # let id = "11111111-1111-1111-1111-111111111111";
    /// # let session = SessionInvariant::new(id.into(), id.into(), id.into(), "t".into(), id.into())?;
    /// # let mut canvas = Canvas::new(session.clone(), 1, Artifact::new(id, 1, "one\ntwo", None, None, Limits::default())?, Limits::default())?;
    /// canvas.revoke();
    /// let late = Delta::new(session, 1, 0, Action::Step(1));
    /// assert_eq!(canvas.enqueue(late), Err(Error::Revoked));
    /// assert!(!canvas.needs_frame());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn revoke(&mut self) {
        self.revoked = true;
        self.inbox.clear();
        self.presented = None;
        self.prepared = None;
    }
}

/// Spring position for a navigation target on the 0/1/2 view axis.
fn view_position(view: View) -> f64 {
    match view {
        View::Source => 0.0,
        View::Proposal => 1.0,
        View::Evidence => 2.0,
    }
}

/// Step the target by a signed amount with wraparound, using only
/// wrapping arithmetic (no remainder operator): `wrapping_rem` keeps the
/// dividend's sign, so a negative remainder is lifted back into range.
fn step_target(current: View, amount: i32) -> View {
    let base = match current {
        View::Source => 0_i64,
        View::Proposal => 1_i64,
        View::Evidence => 2_i64,
    };
    let shifted = base.wrapping_add(i64::from(amount));
    let reduced = shifted.wrapping_rem(3);
    let index = if reduced < 0 {
        reduced.wrapping_add(3)
    } else {
        reduced
    };
    match index {
        0 => View::Source,
        1 => View::Proposal,
        _ => View::Evidence,
    }
}

#[cfg(test)]
mod tests {
    use super::{View, step_target};

    /// Assert one step lands on the expected view.
    fn assert_step(current: View, amount: i32, want: View) -> Result<(), String> {
        let got = step_target(current, amount);
        if got != want {
            return Err(format!(
                "step {current:?} by {amount}: got {got:?}, want {want:?}"
            ));
        }
        Ok(())
    }

    /// Step arithmetic wraps exactly, forward and backward, for small and
    /// extreme amounts.
    #[test]
    fn step_target_wraps_like_euclidean_modulo_three() -> Result<(), String> {
        assert_step(View::Source, 1, View::Proposal)?;
        assert_step(View::Proposal, 1, View::Evidence)?;
        assert_step(View::Evidence, 1, View::Source)?;
        assert_step(View::Source, -1, View::Evidence)?;
        assert_step(View::Evidence, -1, View::Proposal)?;
        assert_step(View::Source, 3, View::Source)?;
        assert_step(View::Source, -3, View::Source)?;
        assert_step(View::Proposal, 4, View::Evidence)?;
        assert_step(View::Evidence, -4, View::Proposal)?;
        assert_step(View::Source, 0, View::Source)?;
        assert_step(View::Source, i32::MAX, View::Proposal)?;
        assert_step(View::Source, i32::MIN, View::Proposal)?;
        assert_step(View::Evidence, i32::MAX, View::Source)?;
        Ok(())
    }
}