Compare commits

..
23 changed files with 52 additions and 4797 deletions
-21
View File
@@ -11,7 +11,6 @@ mod reference_authoring;
#[cfg(test)]
mod review_navigation_tests;
mod scenario_diagram;
mod scenario_spacing;
pub(crate) mod source_rename;
mod source_symbols;
#[cfg(test)]
@@ -1272,9 +1271,6 @@ impl App {
])
}
pub fn update(&mut self, message: Message) -> Task<Message> {
if let Message::ScenarioCanvas(behavior::scenario::CanvasEvent::Spacing(event)) = &message {
return self.scenario_spacing(*event);
}
// Reject stale rename intents before camera/reveal reconciliation or
// source interaction can disturb a newer navigation destination.
if let Message::SourceRename(event) = &message
@@ -1334,7 +1330,6 @@ impl App {
| Message::TopologyCanvas(crate::behavior::topology::CanvasEvent::Camera(..))
);
let before = self.camera_boundary();
let spacing_selected = self.selected;
let task = self.update_inner(message);
if window_resized && let Some((_, _, epoch)) = &mut self.pending_diagram_reveal {
*epoch = self.canvas_epoch;
@@ -1349,13 +1344,6 @@ impl App {
{
self.diagram_navigation_focus = None;
}
if (self.camera_boundary() != before
|| self.selected != spacing_selected
|| !self.spacing_enabled())
&& self.behavior.scenario.cancel_spacing()
{
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
if !camera && self.camera_boundary() != before {
self.camera_epoch = self.camera_epoch.wrapping_add(1);
self.camera_boundary_epoch = self.canvas_epoch;
@@ -1390,9 +1378,6 @@ impl App {
Message::ScenarioCanvas(Scenario::Camera(c, lifetime, Camera::Focus))
if valid_scenario(*c) && *lifetime == scope.epoch =>
{
if self.behavior.scenario.cancel_spacing() {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
return canvas_workspace::focus_task(scope, Camera::Focus);
}
Message::TopologyCanvas(Process::Camera(c, lifetime, Camera::Focus))
@@ -1418,9 +1403,6 @@ impl App {
_ => return Task::none(),
}
let task = self.update(message);
if self.behavior.scenario.cancel_spacing() {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
// Reapplying Fit or a tool also ends a held gesture. Focus is stamped
// after the action, for Iced's final-view ordering.
if self.camera_epoch == scope.epoch {
@@ -1990,9 +1972,6 @@ impl App {
{
return Task::none();
}
if self.behavior.scenario.cancel_spacing() {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
match input {
Event::Focus
| Event::Traverse(_)
@@ -1,88 +0,0 @@
//! Admit spacing packets before ordinary navigation can retire a newer reveal.
use super::*;
use behavior::scenario::spacing::{Event, controller::Finish};
#[cfg(test)]
mod tests;
impl App {
pub(super) fn spacing_enabled(&self) -> bool {
self.pending_diagram_reveal.is_none()
&& !self.behavior.has_pending()
&& !self.draft_dirty()
&& !self.source_dirty()
&& !self.source_rename.open()
&& behavior::canvas_workspace::keyboard_enabled(self)
}
pub(super) fn scenario_spacing(&mut self, event: Event) -> Task<Message> {
let stamp = event.stamp();
if self.scenario_context() != Some(stamp.context) || self.camera_epoch != stamp.camera_epoch
{
return Task::none();
}
let state = &self.behavior.scenario;
let matches =
state.spacing_token() == Some(event.token()) && state.spacing_stamp() == Some(stamp);
if match event {
Event::Begin { token, .. } => token.is_nil() || state.spacing_token().is_some(),
_ => !matches,
} {
return Task::none();
}
if matches!(event, Event::Cancel { .. }) || !self.spacing_enabled() {
if self.behavior.scenario.cancel_spacing() {
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
return Task::none();
}
match event {
Event::Begin { .. } => {
let mut state = std::mem::take(&mut self.behavior.scenario);
let result = state.begin_spacing(self.project(), event);
self.behavior.scenario = state;
if result.is_err() {
self.status = "The drag could not start in this view. Try again.".into();
}
}
Event::Move { screen, .. } => self.behavior.scenario.move_spacing(screen),
Event::Finish { screen, .. } => {
let finished = self.behavior.scenario.finish_spacing(screen);
// Retire queued packets even for zero motion or a refused finish.
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
match finished {
Ok(Finish::Click(target)) => self.select(target),
Ok(Finish::Noop) => {}
Ok(Finish::Commit {
command,
selected,
scale,
pan,
}) => {
// Document prepares and writes the source candidate before
// committing its snapshot. Failure leaves camera/selection
// and source/history at their accepted values.
match self.document.execute(command) {
Ok(_) => {
self.selected = selected;
self.selected_node = None;
self.diagram_navigation_focus = None;
self.behavior.scenario.accept_spacing_camera(scale, pan);
self.sync();
self.status = "Scenario spacing updated.".into();
}
Err(error) => self.status = format!("Spacing was not applied: {error}"),
}
}
Err(_) => {
self.status =
"That position cannot be applied. The saved arrangement is unchanged."
.into()
}
}
}
Event::Cancel { .. } => unreachable!(),
}
Task::none()
}
}
@@ -1,272 +0,0 @@
use super::*;
use behavior::scenario::{
CanvasEvent,
spacing::{
Target,
controller::tests::{fixture, packet},
},
};
use iced::{Point, Size, Vector};
fn setup() -> (App, Id, Id) {
let (document, owner, diagram, lane, message) = fixture();
let mut app = App::with_project(document.project().clone());
let _ = app.update(Message::Select(owner));
let _ = app.update(Message::Diagram(Choice {
id: diagram,
label: "Saved".into(),
}));
let c = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Viewport(
c,
Size::new(900., 600.),
)));
assert!(app.spacing_enabled());
(app, lane, message)
}
fn begin(app: &mut App, target: Target) -> (Event, Point, f32) {
let event = packet(
app.project(),
&app.behavior.scenario,
app.scenario_context().unwrap(),
app.camera_epoch,
target,
);
let Event::Begin {
press_screen,
scale,
..
} = event
else {
unreachable!()
};
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(event)));
assert_eq!(app.behavior.scenario.spacing_token(), Some(event.token()));
(event, press_screen, scale)
}
fn send(app: &mut App, event: Event) {
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(event)));
}
fn move_to(app: &mut App, begin: Event, screen: Point) {
send(
app,
Event::Move {
stamp: begin.stamp(),
token: begin.token(),
screen,
},
);
}
fn finish(app: &mut App, begin: Event, screen: Point) {
send(
app,
Event::Finish {
stamp: begin.stamp(),
token: begin.token(),
screen,
},
);
}
#[test]
fn same_batch_preview_is_immutable_and_one_commit_undo_redo_has_exact_source_parity() {
let (mut app, lane, _) = setup();
let original = app.document.snapshot();
let source = app.source_workspace.bundle();
let selected = app.selected;
let epoch = app.canvas_epoch;
let (event, start, scale) = begin(&mut app, Target::Lane(lane));
move_to(&mut app, event, start + Vector::new(40., 300.));
assert_eq!(app.selected, selected);
assert_eq!(app.canvas_epoch, epoch);
assert_eq!(app.project(), &original.decoded.project);
assert_eq!(app.source_workspace.bundle(), source);
assert!(!app.document.can_undo() && !app.document.can_redo());
finish(&mut app, event, start + Vector::new(40., 300.));
assert_eq!(app.selected, lane);
assert!(app.document.can_undo() && !app.document.can_redo());
let accepted = app.document.snapshot();
assert_ne!(accepted.bundle, original.bundle);
let expected = behavior::scenario::spacing::controller::tests::expected(
&original.decoded.project,
match event.stamp().context.representation {
behavior::scenario_layout::Representation::Saved { diagram } => diagram,
_ => unreachable!(),
},
Target::Lane(lane),
40. / scale,
);
assert_eq!(app.project(), &expected);
let _ = app.update(Message::ShortcutUndo(false));
assert_eq!(app.project(), &original.decoded.project);
assert_eq!(app.document.bundle(), &original.bundle);
assert!(!app.document.can_undo() && app.document.can_redo());
let _ = app.update(Message::ShortcutUndo(true));
assert_eq!(app.project(), &accepted.decoded.project);
assert_eq!(app.document.bundle(), &accepted.bundle);
}
#[test]
fn click_selects_but_crossed_return_and_cancel_preserve_selection_camera_and_history() {
let (mut app, lane, message) = setup();
let original = app.document.snapshot();
let camera = app.behavior.scenario.camera_boundary();
let (event, start, _) = begin(&mut app, Target::Message(message));
finish(&mut app, event, start + Vector::new(30., 2.));
assert_eq!(app.selected, message);
assert!(camera == app.behavior.scenario.camera_boundary());
for cancel in [false, true] {
let (event, start, _) = begin(&mut app, Target::Lane(lane));
move_to(&mut app, event, start + Vector::new(30., 0.));
if cancel {
send(
&mut app,
Event::Cancel {
stamp: event.stamp(),
token: event.token(),
},
);
} else {
finish(&mut app, event, start);
}
assert_eq!(app.selected, message);
assert!(camera == app.behavior.scenario.camera_boundary());
assert_eq!(app.document.bundle(), &original.bundle);
assert_eq!(app.project(), &original.decoded.project);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
}
#[test]
fn stale_finish_after_new_view_and_forged_token_are_inert_before_reveal_reconciliation() {
let (mut app, lane, _) = setup();
let (event, start, _) = begin(&mut app, Target::Lane(lane));
let held_epoch = app.canvas_epoch;
send(
&mut app,
Event::Finish {
stamp: event.stamp(),
token: Id::new_v4(),
screen: start + Vector::new(30., 0.),
},
);
assert_eq!(app.canvas_epoch, held_epoch);
assert_eq!(app.behavior.scenario.spacing_token(), Some(event.token()));
let owner = event.stamp().context.scenario;
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Representation(
event.stamp().context,
behavior::scenario_layout::Representation::Derived { owner },
)));
let current = app.scenario_context();
let epoch = app.canvas_epoch;
let original = app.document.snapshot();
finish(&mut app, event, start + Vector::new(50., 0.));
assert_eq!(app.scenario_context(), current);
assert_eq!(app.canvas_epoch, epoch);
assert!(app.behavior.scenario.spacing_token().is_none());
assert_eq!(app.document.bundle(), &original.bundle);
}
#[test]
fn source_write_failure_cannot_commit_candidate_or_materialize_camera() {
let (mut app, lane, _) = setup();
let bundle = app.document.bundle().clone();
let mut limits = oa_core::source_project::ProjectLimits::default();
limits.model.max_source_bytes = bundle.files.values().map(String::len).sum();
app.document = Document::from_bundle(bundle, limits).unwrap();
app.sync();
let original = app.document.snapshot();
let selected = app.selected;
let camera = app.behavior.scenario.camera_boundary();
let (event, start, _) = begin(&mut app, Target::Lane(lane));
move_to(&mut app, event, start + Vector::new(40., 0.));
finish(&mut app, event, start + Vector::new(40., 0.));
assert!(
app.status.starts_with("Spacing was not applied:"),
"{}",
app.status
);
assert_eq!(app.selected, selected);
assert!(camera == app.behavior.scenario.camera_boundary());
assert_eq!(app.project(), &original.decoded.project);
assert_eq!(app.document.bundle(), &original.bundle);
assert!(!app.document.can_undo() && !app.document.can_redo());
assert!(app.behavior.scenario.spacing_token().is_none());
}
#[test]
fn pending_semantic_draft_and_source_edit_cancel_and_reject_held_finish() {
for source in [false, true] {
let (mut app, lane, _) = setup();
let original = app.document.snapshot();
let selected = app.selected;
let (event, start, _) = begin(&mut app, Target::Lane(lane));
move_to(&mut app, event, start + Vector::new(30., 0.));
if source {
let _ = app.update(Message::SourceEdit(text_editor::Action::Edit(
text_editor::Edit::Insert(' '),
)));
assert!(app.source_dirty());
} else {
let _ = app.update(Message::Behavior(behavior::Event::Scenario(
behavior::scenario::Event::Start(
event.stamp().context.scenario,
behavior::scenario::Tool::Lifeline,
),
)));
assert!(app.behavior.has_pending());
}
let draft = app.source_workspace.bundle();
assert!(app.behavior.scenario.spacing_token().is_none());
finish(&mut app, event, start + Vector::new(30., 0.));
assert_eq!(app.project(), &original.decoded.project);
assert_eq!(app.document.bundle(), &original.bundle);
assert_eq!(app.source_workspace.bundle(), draft);
assert_eq!(app.selected, selected);
assert!(!app.document.can_undo());
}
}
#[test]
fn stale_finish_cannot_remove_new_same_view_deferred_reveal() {
let (mut app, lane, message) = setup();
let (event, start, _) = begin(&mut app, Target::Lane(lane));
let behavior::scenario_layout::Representation::Saved { diagram } =
event.stamp().context.representation
else {
unreachable!()
};
let _ = app.update(Message::RevealInDiagram(diagram, message));
assert!(app.pending_diagram_reveal.is_some());
let epoch = app.canvas_epoch;
let selected = app.selected;
let visit = app.pending_scenario_reveal_visit;
let original = app.document.snapshot();
finish(&mut app, event, start + Vector::new(50., 0.));
assert_eq!(app.canvas_epoch, epoch);
assert_eq!(app.pending_scenario_reveal_visit, visit);
assert!(app.pending_diagram_reveal.is_some());
assert_eq!(app.selected, selected);
assert_eq!(app.document.bundle(), &original.bundle);
assert!(!app.document.can_undo());
}
#[test]
fn modal_open_cancels_preview_and_captured_begin_stays_retired_after_close() {
let (mut app, lane, _) = setup();
let original = app.document.snapshot();
let camera = app.behavior.scenario.camera_boundary();
let (event, start, _) = begin(&mut app, Target::Lane(lane));
move_to(&mut app, event, start + Vector::new(30., 0.));
let _ = app.update(Message::Delete);
assert!(app.delete_pending);
assert!(app.behavior.scenario.spacing_token().is_none());
finish(&mut app, event, start + Vector::new(30., 0.));
let _ = app.update(Message::CancelDelete);
send(&mut app, event);
assert!(app.behavior.scenario.spacing_token().is_none());
assert_eq!(app.project(), &original.decoded.project);
assert_eq!(app.document.bundle(), &original.bundle);
assert!(camera == app.behavior.scenario.camera_boundary());
assert!(!app.document.can_undo());
}
+30 -224
View File
@@ -21,8 +21,6 @@ pub(crate) mod creation;
mod form_session;
pub(crate) mod scenario;
mod scenario_activation;
#[cfg(test)]
mod scenario_hit_tests;
// Pure saved-geometry bridge; workspace integration is a separate checkpoint.
#[allow(dead_code)]
pub(crate) mod scenario_layout;
@@ -1163,27 +1161,8 @@ fn in_machine(p: &Project, id: Id, machine: Id) -> bool {
false
}
/// Identifies the drawn primitive that won selection, not an authoring permission.
/// In particular an activation and its message can share an occurrence UUID.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SceneHitRole {
LifelineHeader,
MessageBody,
MessageLabel,
Activation,
LifecycleMarker,
LifelineGuide,
Box,
OtherLine,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SceneHit {
id: Id,
role: SceneHitRole,
}
struct BoxItem {
id: Id,
role: SceneHitRole,
rect: Rectangle,
title: String,
detail: String,
@@ -1216,7 +1195,6 @@ fn box_text_clip(
struct Line {
id: Id,
role: SceneHitRole,
points: Vec<Point>,
label: String,
label_at: Point,
@@ -1242,7 +1220,6 @@ struct Scene {
scale: f32,
camera_pan: iced::Vector,
interaction: Option<(scenario::Context, scenario::CanvasTool, bool)>,
spacing_stamp: Option<scenario::spacing::Stamp>,
coordinate_input: bool,
pending_placement: Option<(scenario::Slot, Option<Id>)>,
lanes: BTreeMap<Id, f32>,
@@ -1271,10 +1248,6 @@ struct SequenceInput {
}
#[derive(Clone, Copy)]
enum SequencePress {
Spacing {
stamp: scenario::spacing::Stamp,
token: Id,
},
Occurrence {
tool: scenario::Tool,
slot: scenario::Slot,
@@ -1295,19 +1268,6 @@ enum SequencePress {
},
}
impl SequenceInput {
fn cancel_spacing(&mut self) -> Option<Action<Message>> {
let cancel = match self.press {
Some(SequencePress::Spacing { stamp, token }) => Some(
Action::publish(Message::ScenarioCanvas(scenario::CanvasEvent::Spacing(
scenario::spacing::Event::Cancel { stamp, token },
)))
.and_capture(),
),
_ => None,
};
self.cancel();
cancel
}
fn cancel(&mut self) {
self.source = None;
self.press = None;
@@ -1333,7 +1293,6 @@ impl Scene {
layout_origin: Point::ORIGIN,
selected,
interaction: None,
spacing_stamp: None,
coordinate_input: true,
pending_placement: None,
lanes: BTreeMap::new(),
@@ -1491,7 +1450,6 @@ impl Scene {
0,
Line {
id,
role: SceneHitRole::LifelineGuide,
points: vec![Point::new(x, 85.), Point::new(x, scene.size.height - 20.)],
label: String::new(),
label_at: Point::ORIGIN,
@@ -1501,11 +1459,6 @@ impl Scene {
}
scene.boxes.push(BoxItem {
id,
role: if scenario {
SceneHitRole::LifelineHeader
} else {
SceneHitRole::Box
},
rect: Rectangle::new(Point::new(x - 102., 15.), Size::new(204., 70.)),
title: if scenario {
format!("Lane · {name}")
@@ -1599,7 +1552,6 @@ impl Scene {
0,
BoxItem {
id: *id,
role: SceneHitRole::Box,
rect,
title: format!("{operator:?} · {}", e.name),
detail: String::new(),
@@ -1611,7 +1563,6 @@ impl Scene {
OccurrenceBody::Branch { guard, .. } => {
self.boxes.push(BoxItem {
id: *id,
role: SceneHitRole::Box,
rect: Rectangle::new(
Point::new(36. + depth as f32 * 10., *y),
Size::new(self.size.width - 85. - depth as f32 * 20., 43.),
@@ -1695,7 +1646,6 @@ impl Scene {
}
self.lines.push(Line {
id: *id,
role: SceneHitRole::MessageBody,
points,
label: format!("{}. {kind}{}", index + 1, message_label),
label_at: Point::new(a.min(*b) + 12., *y - 26.),
@@ -1704,7 +1654,6 @@ impl Scene {
} else {
self.boxes.push(BoxItem {
id: *id,
role: SceneHitRole::Box,
rect: Rectangle::new(
Point::new(65., *y - 20.),
Size::new(self.size.width - 130., 65.),
@@ -1727,7 +1676,6 @@ impl Scene {
.unwrap_or(180.);
self.boxes.push(BoxItem {
id: *id,
role: SceneHitRole::Box,
rect: Rectangle::new(Point::new(x - 110., *y - 20.), Size::new(220., 70.)),
title: e.name.clone(),
detail: action
@@ -1740,7 +1688,6 @@ impl Scene {
OccurrenceBody::Control { kind } => {
self.boxes.push(BoxItem {
id: *id,
role: SceneHitRole::Box,
rect: Rectangle::new(Point::new(65., *y - 20.), Size::new(240., 70.)),
title: format!("{kind:?} · {}", e.name),
detail: "Contextual process control".into(),
@@ -1751,7 +1698,6 @@ impl Scene {
OccurrenceBody::SequenceReference { sequence } => {
self.boxes.push(BoxItem {
id: *id,
role: SceneHitRole::Box,
rect: Rectangle::new(Point::new(65., *y - 20.), Size::new(280., 70.)),
title: e.name.clone(),
detail: sequence
@@ -1764,7 +1710,6 @@ impl Scene {
OccurrenceBody::ScenarioUse { scenario, bindings } => {
self.boxes.push(BoxItem {
id: *id,
role: SceneHitRole::Box,
rect: Rectangle::new(
Point::new(65., *y - 20.),
Size::new(self.size.width - 130., 70.),
@@ -1830,21 +1775,11 @@ impl Scene {
))
}
fn hit(&self, point: Point) -> Option<Id> {
self.hit_item(point).map(|hit| hit.id)
}
/// Preserve the semantic selection order and tolerance while retaining the
/// primitive's identity. Future spacing admission must also validate the
/// saved view, owner and core occurrence kind; a hit alone grants no edit.
fn hit_item(&self, point: Point) -> Option<SceneHit> {
if !point.x.is_finite() || !point.y.is_finite() {
return None;
}
if let Some(id) = self.lifecycle.marker_at(point) {
return Some(SceneHit {
id,
role: SceneHitRole::LifecycleMarker,
});
return Some(id);
}
self.boxes
.iter()
@@ -1854,10 +1789,7 @@ impl Scene {
&& b.rect.contains(point)
&& (b.marker != Some(Kind::Occurrence) || point.y < b.rect.y + 38.)
})
.map(|b| SceneHit {
id: b.id,
role: b.role,
})
.map(|b| b.id)
.or_else(|| {
self.lines
.iter()
@@ -1867,51 +1799,36 @@ impl Scene {
crate::diagram::distance_to_segment(point, p[0], p[1]) < 1.5
})
})
.map(|line| SceneHit {
id: line.id,
role: line.role,
})
.map(|line| line.id)
})
.or_else(|| {
self.activations
.iter()
.rev()
.find(|b| b.rect.contains(point))
.map(|b| SceneHit {
id: b.call,
role: SceneHitRole::Activation,
})
.map(|b| b.call)
})
.or_else(|| {
self.lines
.iter()
.find(|line| !line.label.is_empty() && line.label_bounds().contains(point))
.map(|line| SceneHit {
id: line.id,
role: if line.role == SceneHitRole::MessageBody {
SceneHitRole::MessageLabel
} else {
SceneHitRole::OtherLine
},
.find(|line| {
!line.label.is_empty()
&& Rectangle::new(
line.label_at,
Size::new(
(line.label.chars().count() as f32 * 6.8 + 8.).min(225.),
25.,
),
)
.contains(point)
})
.map(|line| line.id)
})
// The generous message tolerance must not steal the exposed
// shoulder of another call's execution when the view is zoomed out.
.or_else(|| self.near_sequence_item(point))
.or_else(|| {
self.lifecycle
.lane_at(point, self.scale)
.map(|id| SceneHit {
id,
role: SceneHitRole::LifelineGuide,
})
})
.or_else(|| {
self.lane_at(point).map(|id| SceneHit {
id,
role: SceneHitRole::LifelineGuide,
})
})
.or_else(|| self.lifecycle.lane_at(point, self.scale))
.or_else(|| self.lane_at(point))
.or_else(|| {
self.lines
.iter()
@@ -1922,14 +1839,11 @@ impl Scene {
< 8. / self.scale
})
})
.map(|line| SceneHit {
id: line.id,
role: line.role,
})
.map(|line| line.id)
})
}
fn near_sequence_item(&self, point: Point) -> Option<SceneHit> {
fn near_sequence_item(&self, point: Point) -> Option<Id> {
if !self.scale.is_finite() || self.scale <= 0. {
return None;
}
@@ -1943,32 +1857,17 @@ impl Scene {
.windows(2)
.map(|p| crate::diagram::distance_to_segment(point, p[0], p[1]))
.fold(f32::INFINITY, f32::min);
(
SceneHit {
id: line.id,
role: line.role,
},
distance,
)
(line.id, distance)
});
// Compare broad message and lifecycle-marker tolerance together after
// exact shapes, so dense minimum-Fit rows choose the nearer item.
self.lifecycle
.nearest_marker(point)
.map(|(id, distance)| {
(
SceneHit {
id,
role: SceneHitRole::LifecycleMarker,
},
distance,
)
})
.into_iter()
.chain(messages)
.filter(|(_, distance)| *distance <= 8. / self.scale)
.min_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.id.cmp(&b.0.id)))
.map(|(hit, _)| hit)
.min_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)))
.map(|(id, _)| id)
}
}
impl canvas::Program<Message> for Scene {
@@ -1996,33 +1895,15 @@ impl canvas::Program<Message> for Scene {
// captured insertion slot belongs to the previous view, even if the
// pointer itself did not move and the semantic context is unchanged.
if state.bounds.is_some_and(|previous| previous != bounds) {
let cancelled = state.cancel_spacing();
state.cancel();
state.pointer = None;
state.bounds = Some(bounds);
if cancelled.is_some() {
return cancelled;
}
}
state.bounds = Some(bounds);
if (!editable || !self.coordinate_input)
&& let Some(cancelled) = state.cancel_spacing()
{
return Some(cancelled);
if !editable || !self.coordinate_input {
state.cancel();
}
// The viewport masks input outside its visible canvas bounds.
let visible = cursor.position().is_some();
if !visible
&& matches!(state.press, Some(SequencePress::Spacing { .. }))
&& matches!(
event,
canvas::Event::Mouse(
mouse::Event::CursorMoved { .. }
| mouse::Event::ButtonReleased(mouse::Button::Left)
)
)
{
return state.cancel_spacing();
}
if !visible
&& matches!(
event,
@@ -2041,7 +1922,7 @@ impl canvas::Program<Message> for Scene {
| SequencePress::Reorder { start, moved, .. } => {
*moved |= position.distance(*start) >= 3.
}
SequencePress::Occurrence { .. } | SequencePress::Spacing { .. } => {}
SequencePress::Occurrence { .. } => {}
}
}
mouse::Cursor::Available(*position)
@@ -2050,9 +1931,9 @@ impl canvas::Program<Message> for Scene {
| canvas::Event::Window(iced::window::Event::Resized(_))
| canvas::Event::Mouse(mouse::Event::CursorLeft)
| canvas::Event::Window(iced::window::Event::Unfocused) => {
let cancelled = state.cancel_spacing();
state.cancel();
state.pointer = None;
return cancelled.or_else(|| Some(Action::request_redraw()));
return Some(Action::request_redraw());
}
canvas::Event::Mouse(
mouse::Event::ButtonPressed(_) | mouse::Event::ButtonReleased(_),
@@ -2065,9 +1946,8 @@ impl canvas::Program<Message> for Scene {
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
..
}) if state.source.is_some() || state.press.is_some() => {
return state
.cancel_spacing()
.or_else(|| Some(Action::request_redraw().and_capture()));
state.cancel();
return Some(Action::request_redraw().and_capture());
}
_ => cursor,
};
@@ -2121,48 +2001,6 @@ impl canvas::Program<Message> for Scene {
});
return Some(Action::request_redraw().and_capture());
}
if matches!(
context.representation,
scenario_layout::Representation::Saved { .. }
) {
let hit = self.hit_item(point)?;
let target = match hit.role {
SceneHitRole::LifelineHeader => {
Some(scenario::spacing::Target::Lane(hit.id))
}
SceneHitRole::MessageBody | SceneHitRole::MessageLabel => {
Some(scenario::spacing::Target::Message(hit.id))
}
_ => None,
};
if let Some((target, stamp)) = target.zip(self.spacing_stamp)
&& stamp.context == context
{
let token = Id::new_v4();
state.press = Some(SequencePress::Spacing { stamp, token });
return Some(
Action::publish(Message::ScenarioCanvas(CanvasEvent::Spacing(
scenario::spacing::Event::Begin {
stamp,
token,
target,
press_screen: cursor.position()?,
canvas_bounds: bounds,
scale: self.scale,
pan: self.camera_pan,
},
)))
.and_capture(),
);
}
// Saved spacing never silently changes the shared Scenario order.
return Some(
Action::publish(Message::ScenarioCanvas(CanvasEvent::Select(
context, hit.id,
)))
.and_capture(),
);
}
if let Some(occurrence) = self
.hit(point)
.filter(|id| self.rows.contains_key(id))
@@ -2192,22 +2030,6 @@ impl canvas::Program<Message> for Scene {
let press = state.press.take()?;
let context = context?;
match press {
SequencePress::Spacing { stamp, token } => {
state.source = None;
let event = if world.is_some() {
scenario::spacing::Event::Finish {
stamp,
token,
screen: cursor.position()?,
}
} else {
scenario::spacing::Event::Cancel { stamp, token }
};
return Some(
Action::publish(Message::ScenarioCanvas(CanvasEvent::Spacing(event)))
.and_capture(),
);
}
SequencePress::Occurrence {
tool: captured,
slot,
@@ -2299,18 +2121,6 @@ impl canvas::Program<Message> for Scene {
Some(Action::request_redraw().and_capture())
}
canvas::Event::Mouse(mouse::Event::CursorMoved { .. }) if context.is_some() => {
if let Some(SequencePress::Spacing { stamp, token }) = state.press {
return Some(
Action::publish(Message::ScenarioCanvas(CanvasEvent::Spacing(
scenario::spacing::Event::Move {
stamp,
token,
screen: cursor.position()?,
},
)))
.and_capture(),
);
}
Some(Action::request_redraw())
}
_ => None,
@@ -2513,10 +2323,6 @@ impl canvas::Program<Message> for Scene {
if editable
&& self.coordinate_input
&& tool == scenario::CanvasTool::Select
&& matches!(
context.representation,
scenario_layout::Representation::Derived { .. }
)
&& let Some(handle) = self.reorder_handle()
{
f.fill_rectangle(handle.position(), handle.size(), style::TEAL);
@@ -6,7 +6,6 @@ use iced::widget::{Column, column, text_input};
use std::{cell::RefCell, collections::BTreeSet};
mod camera;
pub(crate) mod focus;
pub(crate) mod spacing;
use super::scenario_layout::{
Representation,
presentation::{self, ScenarioPresentation},
@@ -107,7 +106,6 @@ impl std::fmt::Display for CanvasTool {
}
#[derive(Debug, Clone)]
pub enum CanvasEvent {
Spacing(spacing::Event),
Scrolled(Context, ScrollArea, iced::Vector),
Restored(Context, Id, ScrollArea, iced::Vector),
Viewport(Context, Size),
@@ -148,7 +146,6 @@ pub enum ScrollArea {
impl CanvasEvent {
pub fn context(&self) -> Context {
match self {
Self::Spacing(event) => event.stamp().context,
Self::Scrolled(context, _, _)
| Self::Restored(context, ..)
| Self::Viewport(context, _)
@@ -217,7 +214,6 @@ pub enum ValueSection {
const VALUE_PAGE_SIZE: usize = 24;
#[derive(Default)]
pub struct State {
spacing: Option<spacing::controller::Session>,
draft: Option<Draft>,
form_session: Id,
form_mount: Id,
@@ -374,7 +370,6 @@ impl State {
self.canvas_tool = Some((owner, CanvasTool::Select));
}
if changed || self.presentation.visit.is_nil() {
self.spacing = None;
self.presentation.visit = Id::new_v4();
self.restore = None;
return true;
@@ -383,12 +378,10 @@ impl State {
}
/// Suspend captured events while preserving this destination's camera state.
pub(crate) fn leave(&mut self) {
self.spacing = None;
self.presentation.visit = Id::nil();
self.restore = None;
}
pub(crate) fn forget_view(&mut self) {
self.spacing = None;
self.presentation.identity = None;
self.presentation.representation = None;
self.presentation.visit = Id::nil();
@@ -1,160 +0,0 @@
//! Pure Saved-only spacing preparation. Delta is measured from the original
//! pointer in the captured camera's world coordinates, never from the last
//! preview. The controller must own document/revision/visit, camera and hit-role
//! admission; this module neither dispatches commands nor changes selection.
use crate::behavior::scenario_layout::{
GeometryIssue, Representation, ResolvedScenarioPlan, presentation::checked_owner, resolve,
};
use oa_core::{
Command, Id, Kind, OccurrenceBody, OccurrenceEndpoint, Project, ScenarioLanePosition,
ScenarioMessagePosition, SharedBody, execute_batch,
};
pub(crate) mod controller;
#[cfg(test)]
mod tests;
pub(crate) use controller::{Event, Stamp};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Target {
Lane(Id),
Message(Id),
}
impl Target {
pub(crate) fn id(self) -> Id {
match self {
Self::Lane(id) | Self::Message(id) => id,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Refusal {
InvalidSavedView(Id),
TargetNotRendered(Target),
InvalidDelta,
InvalidGesture,
CameraChanged,
TargetNotHit(Target),
Command(String),
Geometry(Vec<GeometryIssue>),
}
pub(super) struct Drag {
original: Project,
diagram: Id,
target: Target,
origin: f32,
original_geometry: ResolvedScenarioPlan,
}
pub(super) struct Preview {
pub(super) command: Command,
#[cfg(test)]
pub(super) project: Project,
pub(super) geometry: ResolvedScenarioPlan,
}
/// Capture an accepted, actually drawn target. A Saved view displaying automatic
/// fallback is not an editable original, even if the target appears in fallback.
pub(super) fn capture(project: &Project, diagram: Id, target: Target) -> Result<Drag, Refusal> {
let representation = Representation::Saved { diagram };
let owner = checked_owner(project, representation).ok_or(Refusal::InvalidSavedView(diagram))?;
let geometry = resolve(project, representation, target.id()).map_err(Refusal::Geometry)?;
let element = project.elements.get(&target.id());
let origin = match target {
Target::Lane(id)
if element.is_some_and(|e| e.kind() == Kind::Lifeline && e.parent == Some(owner)) =>
{
// Unassigned lifelines still have drawn headers. `scene.lanes`
// excludes them only from semantic message-endpoint hit testing.
geometry.scene.render_lanes.get(&id).copied()
}
Target::Message(id)
if element.is_some_and(|e| {
matches!(
e.shared(),
Some(SharedBody::Occurrence {
body: OccurrenceBody::Exchange { .. },
..
})
)
}) =>
{
// A lifecycle row can denote receive y; the public position means
// send y. Read the actual outgoing endpoint, including self calls.
geometry
.scene
.lines
.iter()
.find(|line| line.id == id)
.and_then(|line| line.points.first())
.map(|point| point.y)
}
_ => None,
}
.ok_or(Refusal::TargetNotRendered(target))?;
if !origin.is_finite() {
return Err(Refusal::TargetNotRendered(target));
}
Ok(Drag {
original: project.clone(),
diagram,
target,
origin,
original_geometry: geometry,
})
}
impl Drag {
/// None means there is no command to commit. In particular +0/-0, return to
/// start, and sub-precision motion never materialize a missing override or
/// normalize an existing explicit value. Document/redo are never touched.
pub(super) fn prepare(&self, original_delta: f32) -> Result<Option<Preview>, Refusal> {
if !original_delta.is_finite() {
return Err(Refusal::InvalidDelta);
}
if original_delta == 0. {
return Ok(None);
}
let position = (f64::from(self.origin) + f64::from(original_delta)) as f32;
if position == self.origin {
return Ok(None);
}
let command = match self.target {
Target::Lane(lifeline) => Command::SetScenarioLanePosition {
diagram: self.diagram,
position: ScenarioLanePosition {
lifeline,
x: position,
},
},
Target::Message(occurrence) => Command::SetScenarioMessagePosition {
diagram: self.diagram,
position: ScenarioMessagePosition {
address: OccurrenceEndpoint {
references: vec![],
occurrence,
},
send_y: position,
},
},
};
let project = execute_batch(&self.original, std::slice::from_ref(&command))
.map_err(|error| Refusal::Command(error.to_string()))?;
let geometry = resolve(
&project,
Representation::Saved {
diagram: self.diagram,
},
self.target.id(),
)
.map_err(Refusal::Geometry)?;
Ok(Some(Preview {
command,
#[cfg(test)]
project,
geometry,
}))
}
}
@@ -1,300 +0,0 @@
//! One press owns one immutable accepted Project and one frozen display camera.
use super::*;
use crate::behavior::{
Scene, SceneHitRole,
scenario::{CanvasTool, Context, State},
scenario_layout::Diagnostic,
};
use iced::{Point, Rectangle, Vector};
#[cfg(test)]
pub(crate) mod tests;
#[cfg(test)]
mod timing_tests;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Stamp {
pub(crate) context: Context,
pub(crate) camera_epoch: u64,
}
#[derive(Clone, Copy, Debug)]
pub enum Event {
Begin {
stamp: Stamp,
token: Id,
target: Target,
press_screen: Point,
canvas_bounds: Rectangle,
scale: f32,
pan: Vector,
},
Move {
stamp: Stamp,
token: Id,
screen: Point,
},
Finish {
stamp: Stamp,
token: Id,
screen: Point,
},
Cancel {
stamp: Stamp,
token: Id,
},
}
impl Event {
pub(crate) fn stamp(self) -> Stamp {
match self {
Self::Begin { stamp, .. }
| Self::Move { stamp, .. }
| Self::Finish { stamp, .. }
| Self::Cancel { stamp, .. } => stamp,
}
}
pub(crate) fn token(self) -> Id {
match self {
Self::Begin { token, .. }
| Self::Move { token, .. }
| Self::Finish { token, .. }
| Self::Cancel { token, .. } => token,
}
}
}
pub(crate) struct Session {
stamp: Stamp,
token: Id,
press_screen: Point,
scale: f32,
pan: Vector,
drag: Drag,
preview: Option<Preview>,
refusal: Option<Refusal>,
ever_crossed: bool,
}
pub(in crate::behavior) struct Paint<'a> {
pub(in crate::behavior) scene: &'a Scene,
#[cfg(test)]
pub(in crate::behavior) bounds: Rectangle,
pub(in crate::behavior) refusal: Option<&'a Refusal>,
pub(in crate::behavior) original_diagnostics: &'a [Diagnostic],
pub(in crate::behavior) original_latent: &'a [Id],
pub(in crate::behavior) diagnostics: &'a [Diagnostic],
}
pub(crate) enum Finish {
Click(Id),
Noop,
Commit {
command: Command,
selected: Id,
scale: f32,
pan: Vector,
},
}
impl Session {
fn configure(&self, scene: &mut Scene) {
scene.selected = self.drag.target.id();
scene.scale = self.scale;
scene.camera_pan = self.pan;
scene.interaction = Some((self.stamp.context, CanvasTool::Select, true));
scene.spacing_stamp = Some(self.stamp);
scene.coordinate_input = true;
scene.pending_placement = None;
}
fn update(&mut self, screen: Point) {
self.preview = None;
self.refusal = None;
if !screen.x.is_finite() || !screen.y.is_finite() {
self.refusal = Some(Refusal::InvalidDelta);
return;
}
let distance = match self.drag.target {
Target::Lane(_) => screen.x - self.press_screen.x,
Target::Message(_) => screen.y - self.press_screen.y,
};
self.ever_crossed |= distance.abs() >= 3.;
if !self.ever_crossed {
return;
}
match self.drag.prepare(distance / self.scale) {
Ok(Some(mut preview)) => {
self.configure(&mut preview.geometry.scene);
self.preview = Some(preview);
}
Ok(None) => {}
Err(error) => self.refusal = Some(error),
}
}
}
impl State {
pub(crate) fn spacing_token(&self) -> Option<Id> {
self.spacing.as_ref().map(|s| s.token)
}
pub(crate) fn spacing_stamp(&self) -> Option<Stamp> {
self.spacing.as_ref().map(|s| s.stamp)
}
pub(crate) fn cancel_spacing(&mut self) -> bool {
self.spacing.take().is_some()
}
pub(in crate::behavior) fn spacing_paint(
&self,
context: Context,
camera_epoch: u64,
) -> Option<Paint<'_>> {
let session = self.spacing.as_ref()?;
if session.stamp
!= (Stamp {
context,
camera_epoch,
})
{
return None;
}
let original = &session.drag.original_geometry;
let shown = session.preview.as_ref().map_or(original, |p| &p.geometry);
Some(Paint {
scene: &shown.scene,
#[cfg(test)]
bounds: shown.bounds,
refusal: session.refusal.as_ref(),
original_diagnostics: &original.plan.diagnostics,
original_latent: &original.latent_messages,
diagnostics: &shown.plan.diagnostics,
})
}
pub(crate) fn begin_spacing(&mut self, project: &Project, event: Event) -> Result<(), Refusal> {
let Event::Begin {
stamp,
token,
target,
press_screen,
canvas_bounds,
scale,
pan,
} = event
else {
return Err(Refusal::InvalidGesture);
};
let context = stamp.context;
if self.spacing.is_some()
|| token.is_nil()
|| self.context(
context.document,
context.scenario,
context.revision,
context.epoch,
) != Some(context)
|| self.canvas_tool(context.scenario) != CanvasTool::Select
|| ![
press_screen.x,
press_screen.y,
canvas_bounds.x,
canvas_bounds.y,
canvas_bounds.width,
canvas_bounds.height,
scale,
pan.x,
pan.y,
]
.into_iter()
.all(f32::is_finite)
|| scale <= 0.
|| canvas_bounds.width <= 0.
|| canvas_bounds.height <= 0.
|| !canvas_bounds.contains(press_screen)
{
return Err(Refusal::InvalidGesture);
}
let Representation::Saved { diagram } = context.representation else {
return Err(Refusal::InvalidGesture);
};
let mut drag = capture(project, diagram, target)?;
let camera = self.presentation.camera(drag.original_geometry.bounds);
if self.presentation.viewport != Some(canvas_bounds.size())
|| camera.scale != scale
|| camera.pan != pan
{
return Err(Refusal::CameraChanged);
}
let world = Point::new(
(press_screen.x - canvas_bounds.x - pan.x) / scale,
(press_screen.y - canvas_bounds.y - pan.y) / scale,
);
// Hit tolerance is measured in displayed pixels, just like the widget.
drag.original_geometry.scene.scale = scale;
drag.original_geometry.scene.camera_pan = pan;
let hit = drag.original_geometry.scene.hit_item(world);
if !hit.is_some_and(|hit| {
hit.id == target.id()
&& match target {
Target::Lane(_) => hit.role == SceneHitRole::LifelineHeader,
Target::Message(_) => matches!(
hit.role,
SceneHitRole::MessageBody | SceneHitRole::MessageLabel
),
}
}) {
return Err(Refusal::TargetNotHit(target));
}
// Configure baseline without changing the persistent camera or selection.
let scene = &mut drag.original_geometry.scene;
scene.selected = target.id();
scene.scale = scale;
scene.camera_pan = pan;
scene.interaction = Some((context, CanvasTool::Select, true));
scene.spacing_stamp = Some(stamp);
scene.coordinate_input = true;
scene.pending_placement = None;
self.spacing = Some(Session {
stamp,
token,
press_screen,
scale,
pan,
drag,
preview: None,
refusal: None,
ever_crossed: false,
});
Ok(())
}
pub(crate) fn move_spacing(&mut self, screen: Point) {
if let Some(session) = &mut self.spacing {
session.update(screen);
}
}
pub(crate) fn finish_spacing(&mut self, screen: Point) -> Result<Finish, Refusal> {
let Some(mut session) = self.spacing.take() else {
return Err(Refusal::InvalidGesture);
};
session.update(screen);
if let Some(error) = session.refusal {
return Err(error);
}
if !session.ever_crossed {
return Ok(Finish::Click(session.drag.target.id()));
}
Ok(match session.preview {
None => Finish::Noop,
Some(preview) => Finish::Commit {
command: preview.command,
selected: session.drag.target.id(),
scale: session.scale,
pan: session.pan,
},
})
}
pub(crate) fn accept_spacing_camera(&mut self, scale: f32, pan: Vector) {
self.presentation.zoom = Some(scale);
self.presentation.pan = pan;
self.presentation.fit = false;
}
}
@@ -1,330 +0,0 @@
use super::*;
use crate::document::Document;
use iced::Size;
use oa_core::{Diagram, Layer, ProjectionKind, language, source_project::ProjectLimits};
pub(crate) fn fixture() -> (Document, Id, Id, Id, Id) {
let mut p = language::parse(r#"arcadia 7;
project spacing "Spacing" {
oa_activity work "Work" {}
oa_activity response "Response" {}
oa_scenario incident "Incident" { viewpoint OperationalActivity; steps [@first, @second]; }
oa_lifeline reporter "Reporter" { parent @incident; represented @work; }
oa_lifeline operator "Operator" { parent @incident; represented @response; }
oa_occurrence first "First" { parent @incident; body { Exchange { exchange none; sender @reporter; receiver @operator; message_kind Asynchronous; }; }; }
oa_occurrence second "Second" { parent @incident; body { Exchange { exchange none; sender @operator; receiver @reporter; message_kind Asynchronous; }; }; }
}"#).unwrap();
let id = |name: &str| {
p.identities()
.into_iter()
.find(|(_, alias)| *alias == name)
.unwrap()
.0
};
let (owner, lane, message) = (id("incident"), id("reporter"), id("first"));
let diagram = Id::new_v4();
p.diagrams.insert(
diagram,
Diagram {
id: diagram,
alias: "saved".into(),
name: "Saved".into(),
description: String::new(),
layer: Layer::Oa,
projection: ProjectionKind::Scenario { scenario: owner },
nodes: Default::default(),
routes: vec![],
view_options: Default::default(),
layout: None,
},
);
(
Document::from_project(p, ProjectLimits::default()).unwrap(),
owner,
diagram,
lane,
message,
)
}
pub(crate) fn expected(p: &Project, diagram: Id, target: Target, delta: f32) -> Project {
capture(p, diagram, target)
.unwrap()
.prepare(delta)
.unwrap()
.unwrap()
.project
}
pub(crate) fn packet(
p: &Project,
state: &State,
context: Context,
camera_epoch: u64,
target: Target,
) -> Event {
let geometry = resolve(p, context.representation, target.id()).unwrap();
let world = match target {
Target::Lane(id) => geometry
.scene
.boxes
.iter()
.find(|item| item.id == id && item.role == SceneHitRole::LifelineHeader)
.unwrap()
.rect
.center(),
Target::Message(id) => {
let line = geometry
.scene
.lines
.iter()
.find(|line| line.id == id)
.unwrap();
Point::new((line.points[0].x + line.points[1].x) / 2., line.points[0].y)
}
};
assert!(
geometry
.scene
.hit_item(world)
.is_some_and(|hit| hit.id == target.id())
);
let camera = state.presentation.camera(geometry.bounds);
let canvas_bounds = Rectangle::new(Point::new(17., 23.), state.presentation.viewport.unwrap());
Event::Begin {
stamp: Stamp {
context,
camera_epoch,
},
token: Id::new_v4(),
target,
press_screen: Point::new(
canvas_bounds.x + world.x * camera.scale + camera.pan.x,
canvas_bounds.y + world.y * camera.scale + camera.pan.y,
),
canvas_bounds,
scale: camera.scale,
pan: camera.pan,
}
}
fn setup(target_message: bool) -> (Document, State, Event) {
let (doc, owner, diagram, lane, message) = fixture();
let mut state = State::default();
state.enter_representation(Id::new_v4(), owner, Representation::Saved { diagram });
state.presentation.viewport = Some(Size::new(900., 600.));
let context = state
.context(
state.presentation.identity.unwrap().0,
owner,
doc.revision(),
4,
)
.unwrap();
let target = if target_message {
Target::Message(message)
} else {
Target::Lane(lane)
};
let event = packet(doc.project(), &state, context, 9, target);
(doc, state, event)
}
fn press(event: Event) -> Point {
let Event::Begin { press_screen, .. } = event else {
unreachable!()
};
press_screen
}
#[test]
fn real_preview_moves_only_active_axis_from_original_and_never_changes_document() {
for message in [false, true] {
let (doc, mut state, begin) = setup(message);
let original = doc.snapshot();
let camera = state.camera_boundary();
let start = press(begin);
state.begin_spacing(doc.project(), begin).unwrap();
let first = if message {
Vector::new(500., 30.)
} else {
Vector::new(30., 500.)
};
state.move_spacing(start + first);
let session = state.spacing.as_ref().unwrap();
let candidate = session.preview.as_ref().unwrap();
let delta = 30. / session.scale;
let actual_anchor = match session.drag.target {
Target::Lane(id) => candidate.geometry.scene.render_lanes[&id],
Target::Message(id) => {
candidate
.geometry
.scene
.lines
.iter()
.find(|line| line.id == id)
.unwrap()
.points[0]
.y
}
};
let wanted = (f64::from(session.drag.origin) + f64::from(delta)) as f32;
assert_eq!(actual_anchor.to_bits(), wanted.to_bits());
let expected = session.drag.prepare(delta).unwrap().unwrap();
assert_eq!(candidate.project, expected.project);
assert_eq!(candidate.geometry.scene.rows, expected.geometry.scene.rows);
assert_eq!(
candidate.geometry.scene.render_lanes,
expected.geometry.scene.render_lanes
);
state.move_spacing(start + first * 2.);
let session = state.spacing.as_ref().unwrap();
assert_eq!(
session.preview.as_ref().unwrap().project,
session.drag.prepare(delta * 2.).unwrap().unwrap().project
);
assert_eq!(doc.project(), &original.decoded.project);
assert_eq!(doc.compiled().bundle, original.bundle);
assert!(!doc.dirty() && !doc.can_undo() && !doc.can_redo());
assert!(camera == state.camera_boundary());
}
}
#[test]
fn click_threshold_is_active_axis_and_return_to_zero_is_not_a_click() {
let (doc, mut state, begin) = setup(false);
let start = press(begin);
state.begin_spacing(doc.project(), begin).unwrap();
state.move_spacing(start + Vector::new(2., 100.));
assert!(matches!(
state.finish_spacing(start).unwrap(),
Finish::Click(_)
));
state.begin_spacing(doc.project(), begin).unwrap();
state.move_spacing(start + Vector::new(4., 0.));
assert!(matches!(state.finish_spacing(start).unwrap(), Finish::Noop));
assert!(!doc.can_undo());
}
#[test]
fn invalid_move_discards_prior_candidate_and_finish_rechecks_final_pointer() {
let (doc, mut state, begin) = setup(false);
let start = press(begin);
state.begin_spacing(doc.project(), begin).unwrap();
state.move_spacing(start + Vector::new(20., 0.));
state.move_spacing(Point::new(f32::NAN, start.y));
let paint = state.spacing_paint(begin.stamp().context, 9).unwrap();
assert!(matches!(paint.refusal, Some(Refusal::InvalidDelta)));
assert_eq!(
paint.scene.render_lanes,
state
.spacing
.as_ref()
.unwrap()
.drag
.original_geometry
.scene
.render_lanes
);
assert!(matches!(
state.finish_spacing(Point::new(f32::NAN, start.y)),
Err(Refusal::InvalidDelta)
));
assert!(state.spacing_token().is_none());
}
#[test]
fn forged_camera_hit_role_and_retired_visit_cannot_capture() {
let (doc, mut state, begin) = setup(false);
let Event::Begin {
stamp,
token,
target,
press_screen,
canvas_bounds,
scale,
pan,
} = begin
else {
unreachable!()
};
assert!(matches!(
state.begin_spacing(
doc.project(),
Event::Begin {
stamp,
token,
target,
press_screen,
canvas_bounds,
scale: scale * 2.,
pan
}
),
Err(Refusal::CameraChanged)
));
assert!(matches!(
state.begin_spacing(
doc.project(),
Event::Begin {
stamp,
token,
target,
press_screen: canvas_bounds.center(),
canvas_bounds,
scale,
pan
}
),
Err(Refusal::TargetNotHit(_))
));
state.leave();
assert!(matches!(
state.begin_spacing(doc.project(), begin),
Err(Refusal::InvalidGesture)
));
}
#[test]
fn zoomed_out_message_tolerance_matches_actual_canvas_hit() {
let (doc, mut state, _) = setup(true);
state.presentation.fit = false;
state.presentation.zoom = Some(0.25);
state.presentation.pan = Vector::ZERO;
let context = state
.context(
state.presentation.identity.unwrap().0,
state.owner().unwrap(),
doc.revision(),
4,
)
.unwrap();
let message = doc
.project()
.identities()
.into_iter()
.find(|(_, alias)| *alias == "first")
.map(|(id, _)| id)
.unwrap();
let Event::Begin {
stamp,
token,
target,
press_screen,
canvas_bounds,
scale,
pan,
} = packet(doc.project(), &state, context, 9, Target::Message(message))
else {
unreachable!()
};
let event = Event::Begin {
stamp,
token,
target,
press_screen: press_screen + Vector::new(0., 3.),
canvas_bounds,
scale,
pan,
};
state.begin_spacing(doc.project(), event).unwrap();
assert_eq!(state.spacing_token(), Some(token));
}
@@ -1,304 +0,0 @@
//! Diagnostic only: production capture/prepare, excluding fixture construction,
//! oracle work, App source writes, widget rebuilds, text shaping and GPU paint.
use super::*;
use crate::document::Document;
use oa_core::{
DiagramLayout, Layer, MessageKind, RelationKind, ScenarioLayout, source_project::ProjectLimits,
};
use serde_json::{Value, json};
use std::{collections::BTreeSet, sync::Arc, time::Instant};
const MESSAGE_COUNT: usize = 1000;
const TARGET_INDEX: usize = 500;
fn large_fixture() -> (Document, Id, [Id; 3], Vec<Id>, Vec<Id>) {
let (seed, owner, a, reporter, first) = super::tests::fixture();
let mut p = seed.project().clone();
let old_steps = p.elements[&owner].steps().unwrap().clone();
let template = p.elements[&first].clone();
let work = |alias: &str| {
p.identities()
.into_iter()
.find(|(_, name)| *name == alias)
.unwrap()
.0
};
let (source, target) = (work("work"), work("response"));
let operator = work("operator");
let relation = p.relate(
RelationKind::Interaction,
"Repeated incident report",
source,
target,
);
let mut lanes = vec![];
for index in 0..20 {
let original = if index < 10 { reporter } else { operator };
let mut lane = p.elements[&original].clone();
lane.id = Id::new_v4();
lane.alias = format!("timing_lane_{index:02}");
lane.name = format!("Review participant {index:02}");
lanes.push(lane.id);
p.elements.insert(lane.id, lane);
}
p.elements.remove(&reporter);
p.elements.remove(&operator);
for id in old_steps {
p.elements.remove(&id);
}
let mut messages = vec![];
for index in 0..MESSAGE_COUNT {
let mut occurrence = template.clone();
occurrence.id = Id::new_v4();
occurrence.alias = format!("timing_message_{index:04}");
occurrence.name = format!("Validate incident report {index:04}");
*occurrence.shared_mut().unwrap() = SharedBody::Occurrence {
body: OccurrenceBody::Exchange {
exchange: Some(relation),
sender: Some(lanes[index % 10]),
receiver: Some(lanes[10 + index % 10]),
message_kind: MessageKind::Asynchronous,
operation: None,
reply_to: None,
values: vec![],
},
precondition: String::new(),
postcondition: String::new(),
};
messages.push(occurrence.id);
p.elements.insert(occurrence.id, occurrence);
}
*p.elements.get_mut(&owner).unwrap().steps_mut().unwrap() = messages.clone();
p.diagrams.get_mut(&a).unwrap().layout = Some(DiagramLayout::Scenario(ScenarioLayout {
lanes: lanes
.iter()
.enumerate()
.map(|(i, &lifeline)| ScenarioLanePosition {
lifeline,
x: 160. + i as f32 * 240.,
})
.collect(),
messages: vec![],
}));
let mut views = [a, Id::nil(), Id::nil()];
for (index, x, offset) in [(1, -500., 12.), (2, 6500., -12.)] {
let mut view = p.diagrams[&a].clone();
view.id = Id::new_v4();
view.alias = format!("timing_saved_{index}");
view.name = format!("Review arrangement {index}");
view.layout = Some(DiagramLayout::Scenario(ScenarioLayout {
lanes: vec![ScenarioLanePosition {
lifeline: lanes[0],
x,
}],
messages: vec![ScenarioMessagePosition {
address: OccurrenceEndpoint {
references: vec![],
occurrence: messages[TARGET_INDEX],
},
send_y: 148. + TARGET_INDEX as f32 * 92. + offset,
}],
}));
views[index] = view.id;
p.diagrams.insert(view.id, view);
}
let document = Document::from_project(p, ProjectLimits::default()).unwrap();
assert_eq!(
document
.project()
.children(owner)
.filter(|e| e.kind() == Kind::Lifeline)
.count(),
20
);
assert_eq!(document.project().elements[&owner].layer(), Layer::Oa);
assert_eq!(document.project().diagrams.len(), 3);
(document, owner, views, lanes, messages)
}
fn assert_scene(
scene: &Scene,
lanes: &[Id],
messages: &[Id],
moved_message: Option<(Id, f32)>,
moved_lane: Option<(Id, f32)>,
) {
assert_eq!(scene.render_lanes.len(), 20);
assert_eq!(
scene
.boxes
.iter()
.filter(|b| b.role == SceneHitRole::LifelineHeader)
.count(),
20
);
assert_eq!(scene.lines.len(), MESSAGE_COUNT);
assert_eq!(
scene
.lines
.iter()
.map(|line| line.id)
.collect::<BTreeSet<_>>(),
messages.iter().copied().collect::<BTreeSet<_>>()
);
assert!(scene.activations.is_empty() && scene.open_calls.is_empty());
let x = |index: usize| {
160. + index as f32 * 240.
+ moved_lane
.filter(|(id, _)| *id == lanes[index])
.map_or(0., |(_, delta)| delta)
};
for (index, &lane) in lanes.iter().enumerate() {
assert_eq!(scene.render_lanes[&lane], x(index));
}
for (index, (line, &id)) in scene.lines.iter().zip(messages).enumerate() {
let y = 148.
+ index as f32 * 92.
+ moved_message
.filter(|(target, _)| *target == id)
.map_or(0., |(_, delta)| delta);
assert_eq!(line.id, id);
assert_eq!(
line.points,
vec![
Point::new(x(index % 10), y),
Point::new(x(10 + index % 10), y)
]
);
}
}
fn summary(samples: &[Value], phase: &str) -> Value {
let mut times: Vec<u64> = samples
.iter()
.filter(|sample| sample["phase"] == phase)
.map(|sample| sample["elapsed_ns"].as_u64().unwrap())
.collect();
times.sort_unstable();
let n = times.len();
let median = if n.is_multiple_of(2) {
((u128::from(times[n / 2 - 1]) + u128::from(times[n / 2])) / 2) as u64
} else {
times[n / 2]
};
json!({"samples": n, "min_ns": times[0], "median_ns": median, "max_ns": times[n-1]})
}
#[test]
#[ignore = "Diagnostic timing only; run alone with --exact --ignored --nocapture after correctness gates; no latency acceptance threshold"]
fn saved_spacing_capture_prepare_20_lanes_1000_messages_3_views() {
let (document, owner, views, lanes, messages) = large_fixture();
let original = document.snapshot();
let target = messages[TARGET_INDEX];
let mut samples = vec![];
let mut retained = None;
for iteration in 0..4 {
let start = Instant::now();
let result = capture(document.project(), views[0], Target::Message(target));
let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap();
let drag = result.expect("complete asynchronous fixture must resolve");
samples.push(json!({"phase":"capture_message", "iteration":iteration,
"first_in_probe":iteration==0, "elapsed_ns":elapsed_ns, "outcome":"captured"}));
assert_scene(&drag.original_geometry.scene, &lanes, &messages, None, None);
if iteration == 0 {
retained = Some(drag);
}
}
let drag = retained.unwrap();
// Every sample is relative to the original press, including duplicate,
// reverse and return-to-start samples. Oracle work is outside each timer.
let deltas = [
4., 8., 12., 16., 20., 24., 28., 32., 32., 28., 24., 20., 16., 12., 8., 4., -4., -8., -4.,
0.,
];
for (iteration, delta) in deltas.into_iter().enumerate() {
let start = Instant::now();
let result = drag.prepare(delta);
let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap();
let candidate = result.expect("these isolated asynchronous offsets are feasible");
samples.push(json!({"phase":"prepare_message", "iteration":iteration,
"delta_world":delta, "elapsed_ns":elapsed_ns, "outcome":if candidate.is_some(){"preview"}else{"noop"}}));
if delta == 0. {
assert!(candidate.is_none());
} else {
let candidate = candidate.unwrap();
let mut expected = original.decoded.project.clone();
let Some(DiagramLayout::Scenario(layout)) =
&mut expected.diagrams.get_mut(&views[0]).unwrap().layout
else {
panic!()
};
layout.messages.push(ScenarioMessagePosition {
address: OccurrenceEndpoint {
references: vec![],
occurrence: target,
},
send_y: 148. + TARGET_INDEX as f32 * 92. + delta,
});
assert_eq!(candidate.project, expected);
assert_scene(
&candidate.geometry.scene,
&lanes,
&messages,
Some((target, delta)),
None,
);
}
assert_eq!(
document.project().elements[&owner].steps().unwrap(),
&messages
);
assert_eq!(document.project(), &original.decoded.project);
assert!(Arc::ptr_eq(&original, &document.snapshot()));
}
let lane = lanes[10];
let start = Instant::now();
let result = capture(document.project(), views[0], Target::Lane(lane));
let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap();
let drag = result.unwrap();
samples.push(json!({"phase":"capture_lane", "iteration":0, "elapsed_ns":elapsed_ns, "outcome":"captured"}));
for (iteration, delta) in [20., 40., -20.].into_iter().enumerate() {
let start = Instant::now();
let result = drag.prepare(delta);
let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap();
let candidate = result.unwrap().unwrap();
samples.push(json!({"phase":"prepare_lane", "iteration":iteration,
"delta_world":delta, "elapsed_ns":elapsed_ns, "outcome":"preview"}));
let mut expected = original.decoded.project.clone();
let Some(DiagramLayout::Scenario(layout)) =
&mut expected.diagrams.get_mut(&views[0]).unwrap().layout
else {
panic!()
};
layout.lanes[10].x = 2560. + delta;
assert_eq!(candidate.project, expected);
assert_scene(
&candidate.geometry.scene,
&lanes,
&messages,
None,
Some((lane, delta)),
);
}
assert_eq!(document.project(), &original.decoded.project);
assert_eq!(document.bundle(), &original.bundle);
for view in views {
assert_eq!(
document.project().diagrams[&view],
original.decoded.project.diagrams[&view]
);
}
assert_eq!(document.revision(), 0);
assert!(!document.dirty() && !document.can_undo() && !document.can_redo());
let report = json!({
"schema":"scenario_spacing_timing_v1",
"fixture":{"lanes":20,"messages":MESSAGE_COUNT,"saved_views":3,"target_index":TARGET_INDEX,"distinct_message_ids":messages.iter().copied().collect::<BTreeSet<_>>().len()},
"profile_context":{"debug_assertions":cfg!(debug_assertions),"os":std::env::consts::OS,"arch":std::env::consts::ARCH,
"source_pin_from_runner":std::env::var("SCENARIO_SPACING_SOURCE_PIN").ok(),"source_binary_toolchain_binding":"external gate receipt required"},
"summaries":{"capture_message":summary(&samples,"capture_message"),"prepare_message":summary(&samples,"prepare_message"),"capture_lane":summary(&samples,"capture_lane"),"prepare_lane":summary(&samples,"prepare_lane")},
"samples":samples,
"invariant_status":"passed",
"limits":"First capture is first in this probe, not cold OS caches. Timers exclude construction/oracles, prior-preview disposal, source write/history, widget rebuild, label shaping, GPU paint and queued input; no responsiveness acceptance or latency threshold. All messages asynchronous; no nested frame/lifecycle stress."
});
println!("SPACING_TIMING_JSON={report}");
}
@@ -1,522 +0,0 @@
use super::*;
use crate::behavior::scenario_layout::Diagnostic;
use crate::document::Document;
use oa_core::{
Diagram, DiagramLayout, ProjectionKind, ScenarioLayout, language, source_project::ProjectLimits,
};
fn id(project: &Project, alias: &str) -> Id {
project
.identities()
.into_iter()
.find(|(_, name)| *name == alias)
.unwrap()
.0
}
fn fixture(layout: Option<ScenarioLayout>) -> (Document, Id, Id) {
let mut project = language::parse(FIXTURE).unwrap();
let owner = id(&project, "conversation");
let mut add = |alias: &str, layout: Option<ScenarioLayout>| {
let diagram = Id::new_v4();
project.diagrams.insert(
diagram,
Diagram {
id: diagram,
alias: alias.into(),
name: alias.into(),
description: String::new(),
layer: oa_core::Layer::Oa,
projection: ProjectionKind::Scenario { scenario: owner },
nodes: Default::default(),
routes: vec![],
view_options: Default::default(),
layout: layout.map(DiagramLayout::Scenario),
},
);
diagram
};
let a = add("saved_a", layout);
let b = add("saved_b", Some(ScenarioLayout::default()));
let document = Document::from_project(project, ProjectLimits::default()).unwrap();
(document, a, b)
}
fn resolved(project: &Project, diagram: Id, selected: Id) -> ResolvedScenarioPlan {
resolve(project, Representation::Saved { diagram }, selected).unwrap()
}
fn same_geometry(a: &ResolvedScenarioPlan, b: &ResolvedScenarioPlan) {
assert_eq!(a.bounds, b.bounds);
assert_eq!(a.lanes, b.lanes);
assert_eq!(a.plan.frames, b.plan.frames);
assert_eq!(a.plan.scopes, b.plan.scopes);
let (a, b) = (&a.scene, &b.scene);
assert_eq!(a.rows, b.rows);
assert_eq!(a.sequence_bounds, b.sequence_bounds);
assert_eq!(a.size, b.size);
assert_eq!(a.layout_origin, b.layout_origin);
assert_eq!(a.lanes, b.lanes);
assert_eq!(a.render_lanes, b.render_lanes);
assert_eq!(a.activations, b.activations);
assert_eq!(a.lifecycle, b.lifecycle);
assert_eq!(a.open_calls, b.open_calls);
let slots = |scene: &crate::behavior::Scene| {
scene
.slots
.iter()
.map(|item| {
(
item.slot.parent,
item.slot.before,
item.y,
item.label.clone(),
)
})
.collect::<Vec<_>>()
};
assert_eq!(slots(a), slots(b));
let lines = |scene: &crate::behavior::Scene| {
scene
.lines
.iter()
.map(|line| {
(
line.id,
line.points.clone(),
line.label_at,
line.label.clone(),
line.dashed,
)
})
.collect::<Vec<_>>()
};
let boxes = |scene: &crate::behavior::Scene| {
scene
.boxes
.iter()
.map(|item| {
(
item.id,
item.rect,
item.title.clone(),
item.detail.clone(),
item.marker,
)
})
.collect::<Vec<_>>()
};
assert_eq!(lines(a), lines(b));
assert_eq!(boxes(a), boxes(b));
}
fn expected_message(project: &Project, diagram: Id, occurrence: Id, y: f32) -> Project {
// Independent expected mutation: tests begin with no message overrides.
let mut expected = project.clone();
expected.diagrams.get_mut(&diagram).unwrap().layout =
Some(DiagramLayout::Scenario(ScenarioLayout {
lanes: vec![],
messages: vec![ScenarioMessagePosition {
address: OccurrenceEndpoint {
references: vec![],
occurrence,
},
send_y: y,
}],
}));
expected
}
#[test]
fn one_repeated_message_moves_in_one_view_with_exact_document_undo_redo_and_reopen() {
let (mut document, a, b) = fixture(None);
let original = document.snapshot();
let before = document.project().clone();
let first = id(&before, "first");
let second = id(&before, "second");
let baseline = resolved(&before, a, second);
assert_eq!(baseline.scene.rows[&first].1, 148.);
assert_eq!(baseline.scene.rows[&second].1, 240.);
let untouched = resolved(&before, b, second);
let drag = capture(&before, a, Target::Message(second)).unwrap();
let preview = drag.prepare(-40.).unwrap().unwrap();
let expected = expected_message(&before, a, second, 200.);
assert_eq!(preview.project, expected);
assert_eq!(preview.geometry.scene.rows[&first].1, 148.);
assert_eq!(preview.geometry.scene.rows[&second].1, 200.);
let line = preview
.geometry
.scene
.lines
.iter()
.find(|line| line.id == second)
.unwrap();
assert_eq!(line.points.first().unwrap().y, 200.);
assert_eq!(line.points.last().unwrap().y, 200.);
assert_eq!(
preview.geometry.scene.activations,
baseline.scene.activations
);
assert_eq!(preview.geometry.scene.lifecycle, baseline.scene.lifecycle);
same_geometry(&resolved(&preview.project, b, second), &untouched);
assert_eq!(drag.original, before);
assert!(std::sync::Arc::ptr_eq(&original, &document.snapshot()));
assert!(!document.can_undo());
let returned_selection = document.execute(preview.command).unwrap();
assert_eq!(
returned_selection,
Some(a),
"controller must preserve the dragged semantic selection separately"
);
assert_eq!(document.project(), &expected);
assert_eq!(document.revision(), 1);
let accepted = document.bundle().clone();
same_geometry(&resolved(document.project(), a, second), &preview.geometry);
assert!(document.undo());
assert_eq!(document.project(), &before);
assert_eq!(document.bundle(), &original.bundle);
assert!(!document.can_undo());
assert!(document.redo());
assert_eq!(document.project(), &expected);
assert_eq!(document.bundle(), &accepted);
let reopened = Document::from_bundle(accepted, ProjectLimits::default()).unwrap();
assert_eq!(reopened.project(), &expected);
same_geometry(&resolved(reopened.project(), a, second), &preview.geometry);
assert!(!reopened.dirty() && !reopened.can_undo());
}
#[test]
fn horizontal_lane_move_changes_actual_header_and_attached_endpoints_only_in_selected_view() {
let (document, a, b) = fixture(None);
let before = document.project();
let right = id(before, "right");
let first = id(before, "first");
let other = resolved(before, b, right);
let preview = capture(before, a, Target::Lane(right))
.unwrap()
.prepare(100.)
.unwrap()
.unwrap();
let mut expected = before.clone();
expected.diagrams.get_mut(&a).unwrap().layout = Some(DiagramLayout::Scenario(ScenarioLayout {
lanes: vec![ScenarioLanePosition {
lifeline: right,
x: 500.,
}],
messages: vec![],
}));
assert_eq!(preview.project, expected);
assert_eq!(preview.geometry.scene.lanes[&right], 500.);
let header = preview
.geometry
.scene
.boxes
.iter()
.find(|item| item.id == right)
.unwrap();
assert_eq!(header.rect.center_x(), 500.);
let line = preview
.geometry
.scene
.lines
.iter()
.find(|line| line.id == first)
.unwrap();
assert_eq!(line.points.first().unwrap().x, 160.);
assert_eq!(line.points.last().unwrap().x, 500.);
assert!(line.points.iter().all(|point| point.y == 148.));
same_geometry(&resolved(&preview.project, b, right), &other);
assert_eq!(document.project(), before);
assert!(!document.dirty() && !document.can_undo());
}
#[test]
fn drawn_unassigned_lifeline_can_move_without_assigning_a_semantic_participant() {
let (document, a, _) = fixture(None);
let mut project = document.project().clone();
let owner = id(&project, "conversation");
let lane = project
.add_element(
Kind::Lifeline,
oa_core::Layer::Oa,
"Unassigned header",
Some(owner),
)
.unwrap();
let document = Document::from_project(project, ProjectLimits::default()).unwrap();
let baseline = resolved(document.project(), a, lane);
assert!(!baseline.scene.lanes.contains_key(&lane));
let before_header = baseline
.scene
.boxes
.iter()
.find(|item| item.id == lane)
.unwrap()
.rect;
let preview = capture(document.project(), a, Target::Lane(lane))
.unwrap()
.prepare(70.)
.unwrap()
.unwrap();
let after_header = preview
.geometry
.scene
.boxes
.iter()
.find(|item| item.id == lane)
.unwrap()
.rect;
assert_eq!(after_header.x, before_header.x + 70.);
assert_eq!(after_header.y, before_header.y);
assert_eq!(after_header.size(), before_header.size());
assert_eq!(preview.project.elements, document.project().elements);
assert_eq!(preview.project.relations, document.project().relations);
assert!(!document.can_undo());
}
#[test]
fn self_call_spacing_uses_send_y_and_preserves_reply_and_actual_activation_finish() {
let (document, a, _) = fixture(None);
let before = document.project();
let call = id(before, "call");
let reply = id(before, "reply");
let baseline = resolved(before, a, call);
let preview = capture(before, a, Target::Message(call))
.unwrap()
.prepare(-22.)
.unwrap()
.unwrap();
assert_eq!(preview.project, expected_message(before, a, call, 310.));
let line = preview
.geometry
.scene
.lines
.iter()
.find(|line| line.id == call)
.unwrap();
assert_eq!(line.points.first().unwrap().y, 310.);
assert_eq!(line.points.last().unwrap().y, 334.);
assert_eq!(preview.geometry.scene.rows[&reply].1, 424.);
assert_eq!(preview.geometry.scene.activations.len(), 1);
let mut expected_activation = baseline.scene.activations.clone();
expected_activation[0].rect.y = 334.;
expected_activation[0].rect.height = 90.;
assert_eq!(preview.geometry.scene.activations, expected_activation);
assert_eq!(preview.geometry.scene.lifecycle, baseline.scene.lifecycle);
}
#[test]
fn feasible_spacing_crossing_remains_authored_with_diagnostic_and_unchanged_steps() {
let (document, a, _) = fixture(None);
let before = document.project();
let first = id(before, "first");
let second = id(before, "second");
let owner = id(before, "conversation");
let preview = capture(before, a, Target::Message(second))
.unwrap()
.prepare(-120.)
.unwrap()
.unwrap();
assert_eq!(preview.project, expected_message(before, a, second, 120.));
assert_eq!(preview.geometry.scene.rows[&second].1, 120.);
assert_eq!(preview.geometry.scene.rows[&first].1, 148.);
assert_eq!(
preview.project.elements[&owner].steps(),
before.elements[&owner].steps()
);
let shown = crate::behavior::scenario_layout::presentation::present(
&preview.project,
Representation::Saved { diagram: a },
second,
);
assert!(shown.capabilities().coordinate_input);
assert!(
shown
.diagnostics()
.contains(&Diagnostic::SourceOrderCrossing {
scope: owner,
before: first,
after: second
})
);
}
#[test]
fn unsupported_self_call_move_is_refused_and_automatic_fallback_is_not_editable_capture() {
let (document, a, _) = fixture(None);
let before = document.project();
let call = id(before, "call");
let drag = capture(before, a, Target::Message(call)).unwrap();
let Err(Refusal::Geometry(issues)) = drag.prepare(118.) else {
panic!("send450 / receive474 after reply424 must be refused")
};
assert!(issues.iter().any(|issue| matches!(issue, GeometryIssue::TypedActivationCrossingNotSupported { call: id, .. } if *id == call)));
assert_eq!(&drag.original, before);
let invalid_geometry = expected_message(before, a, call, 450.);
let shown = crate::behavior::scenario_layout::presentation::present(
&invalid_geometry,
Representation::Saved { diagram: a },
call,
);
assert!(shown.capabilities().geometry_navigation && !shown.capabilities().coordinate_input);
assert!(matches!(
capture(&invalid_geometry, a, Target::Message(call)),
Err(Refusal::Geometry(_))
));
assert!(!document.dirty() && !document.can_undo());
}
#[test]
fn invalid_view_foreign_identity_and_latent_message_are_not_spacing_targets() {
let (document, a, b) = fixture(None);
let p = document.project();
let unfinished = id(p, "unfinished");
let source = id(p, "source");
assert!(matches!(
capture(p, Id::nil(), Target::Lane(source)),
Err(Refusal::InvalidSavedView(_))
));
for target in [
Target::Lane(source),
Target::Lane(b),
Target::Message(source),
Target::Message(unfinished),
] {
assert!(
matches!(capture(p, a, target), Err(Refusal::TargetNotRendered(found)) if found == target)
);
}
// A stored latent coordinate is not permission to fabricate a painted arrow.
let mut latent = expected_message(p, a, unfinished, 2000.);
let foreign_owner = latent
.add_element(Kind::Scenario, oa_core::Layer::Oa, "Foreign", None)
.unwrap();
let foreign_lane = latent
.add_element(
Kind::Lifeline,
oa_core::Layer::Oa,
"Foreign lane",
Some(foreign_owner),
)
.unwrap();
*latent
.elements
.get_mut(&foreign_lane)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Lifeline {
represented: Some(source),
};
let latent_document = Document::from_project(latent, ProjectLimits::default()).unwrap();
assert!(matches!(
capture(latent_document.project(), a, Target::Message(unfinished)),
Err(Refusal::TargetNotRendered(_))
));
assert!(matches!(
capture(latent_document.project(), a, Target::Lane(foreign_lane)),
Err(Refusal::TargetNotRendered(_))
));
}
#[test]
fn zero_motion_return_to_start_and_subprecision_preserve_sparse_intent_and_real_redo() {
let parsed = language::parse(FIXTURE).unwrap();
let left = id(&parsed, "left");
let second = id(&parsed, "second");
let layouts = [
None,
Some(ScenarioLayout::default()),
Some(ScenarioLayout {
lanes: vec![],
messages: vec![ScenarioMessagePosition {
address: OccurrenceEndpoint {
references: vec![],
occurrence: second,
},
send_y: 240.,
}],
}),
Some(ScenarioLayout {
lanes: vec![ScenarioLanePosition {
lifeline: left,
x: -0.,
}],
messages: vec![],
}),
];
for (index, layout) in layouts.into_iter().enumerate() {
let (mut document, a, _) = fixture(layout);
let owner = id(document.project(), "conversation");
document
.execute(Command::Rename(owner, "A real redo entry".into()))
.unwrap();
let redo = document.snapshot();
assert!(document.undo());
let before = document.snapshot();
let revision = document.revision();
let target = if index == 3 {
Target::Lane(left)
} else {
Target::Message(second)
};
let drag = capture(document.project(), a, target).unwrap();
if index == 3 {
let Some(DiagramLayout::Scenario(layout)) = &drag.original.diagrams[&a].layout else {
panic!()
};
assert_eq!(layout.lanes[0].x.to_bits(), (-0_f32).to_bits());
}
assert!(drag.prepare(10.).unwrap().is_some());
for delta in [0., -0.] {
assert!(drag.prepare(delta).unwrap().is_none());
}
if index != 3 {
assert!(drag.prepare(f32::from_bits(1)).unwrap().is_none());
}
assert_eq!(
serde_json::to_vec(&drag.original).unwrap(),
serde_json::to_vec(document.project()).unwrap()
);
assert!(std::sync::Arc::ptr_eq(&before, &document.snapshot()));
assert_eq!(document.bundle(), &before.bundle);
assert_eq!(document.revision(), revision);
assert!(document.can_redo());
assert!(document.redo());
assert_eq!(document.project(), &redo.decoded.project);
assert_eq!(document.bundle(), &redo.bundle);
}
}
#[test]
fn malformed_or_out_of_range_motion_cannot_mutate_original() {
let (document, a, _) = fixture(None);
let drag = capture(
document.project(),
a,
Target::Message(id(document.project(), "second")),
)
.unwrap();
for delta in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
assert!(matches!(drag.prepare(delta), Err(Refusal::InvalidDelta)));
}
assert!(matches!(drag.prepare(f32::MAX), Err(Refusal::Command(_))));
assert_eq!(&drag.original, document.project());
assert!(!document.dirty() && !document.can_undo());
}
const FIXTURE: &str = r#"arcadia 7;
project spacing_probe "Saved spacing probe" id "71000000-0000-4000-8000-000000000001" {
oa_activity source "Source" id "71000000-0000-4000-8000-000000000002" {}
oa_activity target "Target" id "71000000-0000-4000-8000-000000000003" {}
interaction exchange "Repeated exchange" id "71000000-0000-4000-8000-000000000004" { source @source; target @target; }
oa_scenario conversation "Conversation" id "71000000-0000-4000-8000-000000000005" { viewpoint OperationalActivity; steps [@first, @second, @call, @reply, @unfinished]; }
oa_lifeline left "Left" id "71000000-0000-4000-8000-000000000006" { parent @conversation; represented @source; }
oa_lifeline right "Right" id "71000000-0000-4000-8000-000000000007" { parent @conversation; represented @target; }
oa_occurrence first "First" id "71000000-0000-4000-8000-000000000008" { parent @conversation; body { Exchange { exchange @exchange; sender @left; receiver @right; message_kind Asynchronous; }; }; }
oa_occurrence second "Second" id "71000000-0000-4000-8000-000000000009" { parent @conversation; body { Exchange { exchange @exchange; sender @left; receiver @right; message_kind Asynchronous; }; }; }
oa_occurrence call "Call" id "71000000-0000-4000-8000-00000000000a" { parent @conversation; body { Exchange { exchange none; sender @right; receiver @right; message_kind Call; }; }; }
oa_occurrence reply "Reply" id "71000000-0000-4000-8000-00000000000b" { parent @conversation; body { Exchange { exchange none; sender @right; receiver @right; message_kind Reply; reply_to @call; }; }; }
oa_occurrence unfinished "Unfinished" id "71000000-0000-4000-8000-00000000000c" { parent @conversation; body { Exchange { exchange @exchange; sender @left; receiver none; message_kind Asynchronous; }; }; }
}
"#;
@@ -78,43 +78,11 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
};
let tool = state.canvas_tool(owner);
let clean = !app.behavior.has_pending() && !app.draft_dirty() && !app.source_dirty();
// Resolve once per accepted view. An active spacing session owns its exact
// prepared geometry; borrowing it also retains the canvas input state.
let preview = state.spacing_paint(context, app.camera_epoch);
let shown = preview
.is_none()
.then(|| presentation::present(p, context.representation, app.selected));
let capabilities = shown.as_ref().map_or(
presentation::PresentationCapabilities {
geometry_navigation: true,
coordinate_input: true,
},
ScenarioPresentation::capabilities,
);
let shown = presentation::present(p, context.representation, app.selected);
let capabilities = shown.capabilities();
let coordinate_input = clean && capabilities.coordinate_input;
let notice = if let Some(paint) = &preview {
display_notice_parts(
p,
context.representation,
&presentation::PresentationStatus::Ready,
paint.original_diagnostics,
paint.original_latent,
)
} else {
display_notice(p, shown.as_ref().expect("normal presentation"))
};
let camera_state = preview
.as_ref()
.map(|paint| camera::Camera {
scale: paint.scene.scale,
pan: paint.scene.camera_pan,
})
.or_else(|| {
shown
.as_ref()
.and_then(ScenarioPresentation::bounds)
.map(|bounds| presentation.camera(bounds))
});
let notice = display_notice(p, &shown);
let camera_state = shown.bounds().map(|bounds| presentation.camera(bounds));
let scale = camera_state.map_or(1., |camera| camera.scale);
let scope = super::super::canvas_workspace::Scope {
document: context.document,
@@ -127,56 +95,23 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
&& capabilities.geometry_navigation
&& super::super::canvas_workspace::keyboard_enabled(app);
let camera = move |e| Message::ScenarioCanvas(CanvasEvent::Camera(context, scope.epoch, e));
let raw_canvas: Option<Element<'a, Message>> = if let Some(paint) = &preview {
Some(
canvas::Canvas::new(paint.scene)
.width(Fill)
.height(Fill)
.into(),
)
} else if let Some(mut scene) = shown.and_then(ScenarioPresentation::into_scene) {
let canvas: Element<'a, Message> = if let Some(mut scene) = shown.into_scene() {
let camera_state = camera_state.expect("displayed Scene has complete bounds");
scene.scale = camera_state.scale;
scene.camera_pan = camera_state.pan;
scene.interaction = Some((context, tool, clean));
scene.spacing_stamp = (coordinate_input
&& !app.source_rename.open()
&& keyboard
&& matches!(context.representation, Representation::Saved { .. }))
.then_some(spacing::Stamp {
context,
camera_epoch: app.camera_epoch,
});
scene.coordinate_input = capabilities.coordinate_input;
scene.pending_placement = coordinate_input
.then(|| state.pending_placement(owner))
.flatten();
Some(canvas::Canvas::new(scene).width(Fill).height(Fill).into())
} else {
None
};
let canvas: Element<'a, Message> = if let Some(raw_canvas) = raw_canvas {
// Keep this Stack in both branches: replacing the Canvas with a wrapper
// on Begin would discard its pointer capture before Move/Finish.
let mut layers = iced::widget::stack![raw_canvas];
if let Some(paint) = &preview {
let feedback = spacing_feedback(p, paint.refusal, paint.diagnostics);
layers = layers.push(
container(
container(text(feedback).size(12))
.padding(6)
.width(Fill)
.style(style::card),
)
.width(Fill)
.align_bottom(Fill)
.padding(8),
);
}
container(
sensor(
super::super::canvas_workspace::Viewport::new(
layers, scope, scale, keyboard, camera,
canvas::Canvas::new(scene).width(Fill).height(Fill),
scope,
scale,
keyboard,
camera,
)
.pan_background(tool == CanvasTool::Select || !capabilities.coordinate_input),
)
@@ -287,15 +222,7 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
));
}
let entries = [
(
"S",
if matches!(context.representation, Representation::Saved { .. }) {
"Select / move messages and lifelines"
} else {
"Select / reorder occurrences"
},
CanvasTool::Select,
),
("S", "Select / reorder occurrences", CanvasTool::Select),
(
"L",
"Lifeline: click to choose represented work or participant",
@@ -383,10 +310,6 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
))),
));
}
details = details.push(text("Scenario order").size(13));
if matches!(context.representation, Representation::Saved { .. }) {
details = details.push(text("↑ and ↓ change the shared Scenario order. Saved message positions are retained; automatically placed items may move.").size(11));
}
let details = details_pane(
context,
state.scroll_restore(context, ScrollArea::Page),
@@ -717,24 +640,8 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
}
fn display_notice<'a>(p: &Project, shown: &ScenarioPresentation) -> Element<'a, Message> {
display_notice_parts(
p,
shown.requested(),
shown.status(),
shown.diagnostics(),
shown.latent_messages(),
)
}
fn display_notice_parts<'a>(
p: &Project,
requested: Representation,
status: &presentation::PresentationStatus,
diagnostics: &[super::super::scenario_layout::Diagnostic],
latent_messages: &[Id],
) -> Element<'a, Message> {
use super::super::scenario_layout::{Diagnostic, presentation::PresentationStatus};
let title = match requested {
let title = match shown.requested() {
Representation::Saved { diagram } => p.diagrams.get(&diagram).map_or_else(
|| "Unavailable saved Scenario view".into(),
|view| format!("Saved view · {}", view.name),
@@ -742,9 +649,9 @@ fn display_notice_parts<'a>(
Representation::Derived { owner } => format!("Automatic view · {}", p.named(owner)),
};
let mut notice = column![text(title).size(14)].spacing(4);
match status {
match shown.status() {
PresentationStatus::Ready => {
for diagnostic in diagnostics.iter().take(3) {
for diagnostic in shown.diagnostics().iter().take(3) {
let explanation = match diagnostic {
Diagnostic::SourceOrderCrossing { before, after, .. } => format!(
"Saved spacing places '{}' below '{}'. The Scenario order is unchanged.",
@@ -759,11 +666,11 @@ fn display_notice_parts<'a>(
};
notice = notice.push(text(explanation).size(12));
}
if diagnostics.len() > 3 {
if shown.diagnostics().len() > 3 {
notice = notice.push(
text(format!(
"{} additional spacing notices are retained.",
diagnostics.len() - 3
shown.diagnostics().len() - 3
))
.size(12),
);
@@ -780,8 +687,8 @@ fn display_notice_parts<'a>(
notice = notice.push(text("This view is unavailable. Its identity or automatic geometry cannot be resolved; the model and source remain available for inspection and repair.").size(12));
}
}
if !latent_messages.is_empty() {
notice = notice.push(text(format!("{} unfinished message position(s) are retained until their endpoints are complete.", latent_messages.len())).size(12));
if !shown.latent_messages().is_empty() {
notice = notice.push(text(format!("{} unfinished message position(s) are retained until their endpoints are complete.", shown.latent_messages().len())).size(12));
}
notice = notice.push(button("Open selected source").on_press(Message::SourceForSelection));
container(notice)
@@ -791,43 +698,6 @@ fn display_notice_parts<'a>(
.into()
}
fn spacing_feedback(
p: &Project,
refusal: Option<&spacing::Refusal>,
diagnostics: &[super::super::scenario_layout::Diagnostic],
) -> String {
if let Some(refusal) = refusal {
let reason = match refusal {
spacing::Refusal::Geometry(issues) => issues
.first()
.map(|issue| geometry_problem(p, issue))
.unwrap_or_else(|| "This position cannot be displayed.".into()),
spacing::Refusal::Command(error) => error.clone(),
_ => "This position is unavailable in the current view.".into(),
};
return format!(
"Position unavailable · {reason} Move back to a supported position, or release to cancel."
);
}
let explanation = match diagnostics.first() {
Some(super::super::scenario_layout::Diagnostic::SourceOrderCrossing {
before,
after,
..
}) => format!(
" '{}' is below '{}'; Scenario order stays unchanged.",
p.named(*before),
p.named(*after)
),
Some(super::super::scenario_layout::Diagnostic::FrameExtendsPastFollowingAnchor {
frame,
following,
}) => format!(" '{}' overlaps '{}'.", p.named(*frame), p.named(*following)),
None => " Scenario order stays unchanged.".into(),
};
format!("Spacing preview · Release to finish; Escape cancels.{explanation}")
}
fn geometry_problem(p: &Project, issue: &super::super::scenario_layout::GeometryIssue) -> String {
use super::super::scenario_layout::GeometryIssue;
match issue {
@@ -919,9 +789,6 @@ fn editor_panel<'a, R: iced::advanced::text::Renderer + 'a>(
#[cfg(all(test, debug_assertions))]
mod tests;
#[cfg(all(test, debug_assertions))]
mod spacing_tests;
fn sequence_rows<'a>(
p: &'a Project,
context: Context,
@@ -1,420 +0,0 @@
//! Real mounted widgets dispatch the gesture; expectations name authored fields
//! and actual displayed anchors independently of controller command results.
use super::*;
use crate::behavior::canvas_workspace::tests::{Mounted, key};
use crate::behavior::scenario_layout::{ResolvedScenarioPlan, resolve};
use crate::document::Document;
use iced::Vector;
use std::sync::Arc;
const FIXTURE: &str = include_str!("../../../app/diagram_usages/tests/saved_scenario.arcadia");
fn id(app: &App, alias: &str) -> Id {
app.project()
.identities()
.into_iter()
.find(|(_, name)| *name == alias)
.unwrap()
.0
}
async fn setup(fit: bool) -> (App, Mounted, Id) {
let mut app = App::with_project(oa_core::language::parse(FIXTURE).unwrap());
let owner = id(&app, "incident_response");
let diagram = id(&app, "incident_readable");
let _ = app.update(Message::Select(owner));
let _ = app.update(Message::Diagram(crate::app::Choice {
id: diagram,
label: "A - Incident review readable".into(),
}));
app.window_size = Size::new(1440., 900.);
let mut mounted = Mounted::new(&mut app).await;
if !fit {
let context = app.scenario_context().unwrap();
let task = app.update(Message::ScenarioCanvas(CanvasEvent::Zoom(
context,
Some(0.5),
)));
mounted.perform(&mut app, task).await;
mounted.settle(&mut app).await;
}
assert_eq!(
app.scenario_context().unwrap().representation,
Representation::Saved { diagram }
);
assert!(!app.document.can_undo() && !app.document.can_redo());
(app, mounted, diagram)
}
fn resolved(app: &App) -> ResolvedScenarioPlan {
resolve(
app.project(),
app.scenario_context().unwrap().representation,
app.selected,
)
.unwrap()
}
fn stored_camera(app: &App) -> (Vector, Option<f32>, bool) {
let p = &app.behavior.scenario.presentation;
(p.pan, p.zoom, p.fit)
}
fn screen(mounted: &mut Mounted, app: &App, world: Point) -> Point {
let bounds = mounted.geometry(app).bounds("scenario-viewport");
let geometry = resolved(app);
let camera = app.behavior.scenario.presentation.camera(geometry.bounds);
let point = bounds.position() + camera.pan + Vector::new(world.x, world.y) * camera.scale;
assert!(
bounds.contains(point),
"actual visible world {world:?}: {point:?} in {bounds:?}"
);
point
}
fn mouse_event(event: mouse::Event) -> iced::Event {
iced::Event::Mouse(event)
}
async fn press(mounted: &mut Mounted, app: &mut App, point: Point) -> Vec<Message> {
mounted
.batch(
app,
&[
mouse_event(mouse::Event::CursorMoved { position: point }),
mouse_event(mouse::Event::ButtonPressed(mouse::Button::Left)),
],
mouse::Cursor::Available(point),
)
.await
}
async fn move_to(mounted: &mut Mounted, app: &mut App, point: Point) -> Vec<Message> {
mounted
.batch(
app,
&[mouse_event(mouse::Event::CursorMoved { position: point })],
mouse::Cursor::Available(point),
)
.await
}
async fn release(mounted: &mut Mounted, app: &mut App, point: Point) -> Vec<Message> {
mounted
.batch(
app,
&[mouse_event(mouse::Event::ButtonReleased(
mouse::Button::Left,
))],
mouse::Cursor::Available(point),
)
.await
}
fn set_expected_message(project: &mut oa_core::Project, diagram: Id, occurrence: Id, y: f32) {
let Some(oa_core::DiagramLayout::Scenario(layout)) =
&mut project.diagrams.get_mut(&diagram).unwrap().layout
else {
panic!()
};
layout
.messages
.iter_mut()
.find(|m| m.address.occurrence == occurrence)
.unwrap()
.send_y = y;
}
fn set_expected_lane(project: &mut oa_core::Project, diagram: Id, lifeline: Id, x: f32) {
let Some(oa_core::DiagramLayout::Scenario(layout)) =
&mut project.diagrams.get_mut(&diagram).unwrap().layout
else {
panic!()
};
layout
.lanes
.iter_mut()
.find(|lane| lane.lifeline == lifeline)
.unwrap()
.x = x;
}
fn assert_reopens_exactly(app: &App) {
let reopened = Document::from_bundle(
app.document.bundle().clone(),
oa_core::source_project::ProjectLimits::default(),
)
.unwrap();
assert_eq!(reopened.project(), app.project());
assert_eq!(reopened.bundle(), app.document.bundle());
}
#[tokio::test]
async fn saved_message_same_batch_pointer_events_commit_once_and_one_undo_redo_restores_exact_source()
{
let (mut app, mut mounted, diagram) = setup(false).await;
let target = id(&app, "updated_report");
let before = app.document.snapshot();
let revision = app.document.revision();
let start = screen(&mut mounted, &app, Point::new(400., 252.));
let end = start + Vector::new(0., 10.); // .5 display scale: +20 authored y.
let messages = mounted
.batch(
&mut app,
&[
mouse_event(mouse::Event::CursorMoved { position: start }),
mouse_event(mouse::Event::ButtonPressed(mouse::Button::Left)),
mouse_event(mouse::Event::CursorMoved { position: end }),
mouse_event(mouse::Event::ButtonReleased(mouse::Button::Left)),
],
mouse::Cursor::Available(end),
)
.await;
assert_eq!(
messages
.iter()
.filter(|m| matches!(
m,
Message::ScenarioCanvas(CanvasEvent::Spacing(spacing::Event::Begin { .. }))
))
.count(),
1
);
assert_eq!(
messages
.iter()
.filter(|m| matches!(
m,
Message::ScenarioCanvas(CanvasEvent::Spacing(spacing::Event::Finish { .. }))
))
.count(),
1
);
let mut expected = before.decoded.project.clone();
set_expected_message(&mut expected, diagram, target, 272.);
assert_eq!(
app.project(),
&expected,
"Only Saved A's addressed y changes; steps, other occurrences and B/C are exact"
);
assert_eq!(app.document.revision(), revision + 1);
assert_eq!(app.selected, target);
assert!(app.behavior.scenario.spacing_token().is_none());
assert_reopens_exactly(&app);
let after = app.document.snapshot();
let task = app.update(Message::Undo);
mounted.perform(&mut app, task).await;
assert_eq!(app.project(), &before.decoded.project);
assert_eq!(app.document.bundle(), &before.bundle);
assert!(!app.document.can_undo() && app.document.can_redo());
let task = app.update(Message::Redo);
mounted.perform(&mut app, task).await;
assert_eq!(app.project(), &after.decoded.project);
assert_eq!(app.document.bundle(), &after.bundle);
}
#[tokio::test]
async fn saved_header_preview_survives_frames_and_freezes_fit_while_actual_bounds_expand() {
let (mut app, mut mounted, diagram) = setup(true).await;
let assessor = id(&app, "assessor");
let before = app.document.snapshot();
let original = resolved(&app);
let original_camera = app.behavior.scenario.presentation.camera(original.bounds);
let stored = stored_camera(&app);
assert!(stored.2, "test must exercise original Fit");
let start = screen(&mut mounted, &app, Point::new(640., 45.));
press(&mut mounted, &mut app, start).await;
let token = app
.behavior
.scenario
.spacing_token()
.expect("actual header press begins");
for x in [670., 700.] {
let end = start + Vector::new((x - 640.) * original_camera.scale, 0.);
move_to(&mut mounted, &mut app, end).await;
mounted.settle(&mut app).await; // Actual borrowed Scene/Stack tree is rebuilt.
assert_eq!(app.behavior.scenario.spacing_token(), Some(token));
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
assert_eq!(stored_camera(&app), stored);
let paint = app
.behavior
.scenario
.spacing_paint(app.scenario_context().unwrap(), app.camera_epoch)
.unwrap();
assert!(paint.refusal.is_none());
assert!((paint.scene.render_lanes[&assessor] - x).abs() < 0.001);
assert!(paint.bounds.width > original.bounds.width);
assert_eq!(paint.scene.scale, original_camera.scale);
assert_eq!(paint.scene.camera_pan, original_camera.pan);
let header = paint.scene.boxes.iter().find(|b| b.id == assessor).unwrap();
let displayed = Vector::new(header.rect.center().x, header.rect.center().y)
* paint.scene.scale
+ paint.scene.camera_pan;
let baseline = Vector::new(640., 50.) * original_camera.scale + original_camera.pan;
assert!((displayed.x - baseline.x - (x - 640.) * original_camera.scale).abs() < 0.001);
assert_eq!(displayed.y, baseline.y);
}
let end = start + Vector::new(60. * original_camera.scale, 0.);
release(&mut mounted, &mut app, end).await;
let final_geometry = resolved(&app);
let actual_x = final_geometry.scene.render_lanes[&assessor];
assert!((actual_x - 700.).abs() < 0.001);
let mut expected = before.decoded.project.clone();
set_expected_lane(&mut expected, diagram, assessor, actual_x);
assert_eq!(app.project(), &expected);
let final_camera = app
.behavior
.scenario
.presentation
.camera(final_geometry.bounds);
assert_eq!(
final_camera, original_camera,
"commit must not refit underneath pointer"
);
assert!(!app.behavior.scenario.presentation.fit);
assert_eq!(app.selected, assessor);
assert_reopens_exactly(&app);
}
#[tokio::test]
async fn saved_body_and_header_clicks_select_without_materializing_spacing() {
let (mut app, mut mounted, _) = setup(false).await;
let before = app.document.snapshot();
let original_camera = stored_camera(&app);
for (alias, world) in [
("updated_report", Point::new(400., 252.)),
("assessor", Point::new(640., 45.)),
] {
let target = id(&app, alias);
let point = screen(&mut mounted, &app, world);
mounted.click(&mut app, point).await;
assert_eq!(app.selected, target);
assert!(app.behavior.scenario.spacing_token().is_none());
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
assert_eq!(stored_camera(&app), original_camera);
}
assert!(!app.document.can_undo() && !app.document.can_redo());
}
#[tokio::test]
async fn saved_valid_preview_then_refused_self_call_never_commits_last_valid_candidate() {
let (mut app, mut mounted, _) = setup(false).await;
let target = id(&app, "assess_call");
let before = app.document.snapshot();
let camera = stored_camera(&app);
let start = screen(&mut mounted, &app, Point::new(680., 344.));
press(&mut mounted, &mut app, start).await;
let valid = start + Vector::new(0., -10.); // send324, receive348, reply436 unchanged.
move_to(&mut mounted, &mut app, valid).await;
mounted.settle(&mut app).await;
let paint = app
.behavior
.scenario
.spacing_paint(app.scenario_context().unwrap(), app.camera_epoch)
.unwrap();
assert!(paint.refusal.is_none());
let line = paint.scene.lines.iter().find(|l| l.id == target).unwrap();
assert_eq!(line.points[0].y, 324.);
assert_eq!(line.points.last().unwrap().y, 348.);
let refused = start + Vector::new(0., 53.); // send450, receive474 would follow reply436.
move_to(&mut mounted, &mut app, refused).await;
mounted.settle(&mut app).await;
let paint = app
.behavior
.scenario
.spacing_paint(app.scenario_context().unwrap(), app.camera_epoch)
.unwrap();
assert!(paint.refusal.is_some());
assert_eq!(
paint
.scene
.lines
.iter()
.find(|l| l.id == target)
.unwrap()
.points[0]
.y,
344.
);
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
release(&mut mounted, &mut app, refused).await;
assert!(app.behavior.scenario.spacing_token().is_none());
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
assert_eq!(stored_camera(&app), camera);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
#[tokio::test]
async fn saved_escape_and_outside_pointer_cancel_actual_held_preview() {
for escape in [true, false] {
let (mut app, mut mounted, _) = setup(false).await;
let before = app.document.snapshot();
let camera = stored_camera(&app);
let start = screen(&mut mounted, &app, Point::new(400., 252.));
let end = start + Vector::new(0., 10.);
press(&mut mounted, &mut app, start).await;
move_to(&mut mounted, &mut app, end).await;
mounted.settle(&mut app).await;
assert!(app.behavior.scenario.spacing_token().is_some());
let release_at = if escape {
mounted
.batch(
&mut app,
&[key(iced::keyboard::key::Named::Escape)],
mouse::Cursor::Available(end),
)
.await;
end
} else {
let bounds = mounted.geometry(&app).bounds("scenario-viewport");
let outside = Point::new(bounds.x - 5., bounds.y + 100.);
move_to(&mut mounted, &mut app, outside).await;
outside
};
assert!(app.behavior.scenario.spacing_token().is_none());
release(&mut mounted, &mut app, release_at).await;
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
assert_eq!(stored_camera(&app), camera);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
}
#[tokio::test]
async fn saved_drag_return_to_origin_preserves_redo_selection_and_original_fit_camera() {
let (mut app, mut mounted, _) = setup(true).await;
let owner = id(&app, "incident_response");
app.document
.execute(oa_core::Command::Rename(
owner,
"Previously edited owner".into(),
))
.unwrap();
let redo = app.document.snapshot();
let task = app.update(Message::Undo);
mounted.perform(&mut app, task).await;
mounted.settle(&mut app).await;
assert!(app.document.can_redo());
let before = app.document.snapshot();
let camera = stored_camera(&app);
let selected = app.selected;
let revision = app.document.revision();
let start = screen(&mut mounted, &app, Point::new(400., 252.));
press(&mut mounted, &mut app, start).await;
move_to(&mut mounted, &mut app, start + Vector::new(0., 12.)).await;
mounted.settle(&mut app).await;
assert!(app.behavior.scenario.spacing_token().is_some());
move_to(&mut mounted, &mut app, start).await;
mounted.settle(&mut app).await;
release(&mut mounted, &mut app, start).await;
assert!(app.behavior.scenario.spacing_token().is_none());
assert!(Arc::ptr_eq(&before, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &before.bundle);
assert_eq!(app.document.revision(), revision);
assert_eq!(stored_camera(&app), camera);
assert_eq!(app.selected, selected);
assert!(app.document.can_redo());
let task = app.update(Message::Redo);
mounted.perform(&mut app, task).await;
assert_eq!(app.project(), &redo.decoded.project);
assert_eq!(app.document.bundle(), &redo.bundle);
}
@@ -1,386 +0,0 @@
//! Actual Scene primitives, with independently chosen points and semantic IDs.
//! These preserve the existing label hit band; they do not establish ink bounds
//! or authoring eligibility, and do not dispatch a spacing gesture.
use super::*;
use crate::document::Document;
struct Fixture {
project: Project,
owner: Id,
sender: Id,
receiver: Id,
call: Id,
reply: Id,
exchange: Id,
}
fn fixture() -> Fixture {
let project = language::parse(r#"arcadia 7;
project hits "Hit roles" {
oa_activity source "Source" {}
oa_activity target "Target" {}
interaction exchange "Contract" { source @source; target @target; }
oa_scenario conversation "Conversation" { viewpoint OperationalActivity; steps [@call, @reply]; }
oa_lifeline left "Left" { parent @conversation; represented @source; }
oa_lifeline right "Right" { parent @conversation; represented @target; }
oa_occurrence call "Call" { parent @conversation; body { Exchange { exchange @exchange; sender @left; receiver @right; message_kind Call; }; }; }
oa_occurrence reply "Reply" { parent @conversation; body { Exchange { exchange @exchange; sender @right; receiver @left; message_kind Reply; reply_to @call; }; }; }
}
"#).unwrap();
let id = |alias: &str| {
project
.identities()
.into_iter()
.find(|(_, name)| *name == alias)
.unwrap()
.0
};
Fixture {
owner: id("conversation"),
sender: id("left"),
receiver: id("right"),
call: id("call"),
reply: id("reply"),
exchange: id("exchange"),
project,
}
}
fn scene(f: &Fixture) -> Scene {
let document =
Document::from_project(f.project.clone(), source_project::ProjectLimits::default())
.unwrap();
let before = document.snapshot();
let result = Scene::sequence_geometry(
document.project(),
f.owner,
f.call,
Some(&BTreeMap::from([(f.sender, 160.), (f.receiver, 400.)])),
None,
);
assert_eq!(document.project(), &before.decoded.project);
assert_eq!(document.bundle(), &before.bundle);
assert_eq!(document.revision(), 0);
assert!(!document.can_undo() && !document.can_redo() && !document.dirty());
result
}
fn hit(scene: &Scene, point: Point, id: Id, role: SceneHitRole) {
assert_eq!(scene.hit_item(point), Some(SceneHit { id, role }));
assert_eq!(scene.hit(point), Some(id));
}
fn occurrence(p: &mut Project, parent: Id, body: OccurrenceBody) -> Id {
let mut element = p
.make_element(Kind::Occurrence, Layer::Oa, "Hit target", Some(parent))
.unwrap();
let id = element.id;
*element.shared_mut().unwrap() = SharedBody::Occurrence {
body,
precondition: String::new(),
postcondition: String::new(),
};
p.elements.insert(id, element);
p.elements
.get_mut(&parent)
.unwrap()
.steps_mut()
.unwrap()
.push(id);
id
}
fn exchange_mut(p: &mut Project, id: Id) -> &mut OccurrenceBody {
let SharedBody::Occurrence { body, .. } =
p.elements.get_mut(&id).unwrap().shared_mut().unwrap()
else {
panic!("expected occurrence")
};
body
}
#[test]
fn exact_headers_include_unassigned_lifelines_but_guides_are_not_headers() {
let mut f = fixture();
*f.project
.elements
.get_mut(&f.receiver)
.unwrap()
.shared_mut()
.unwrap() = SharedBody::Lifeline { represented: None };
let s = scene(&f);
assert!(!s.lanes.contains_key(&f.receiver));
assert_eq!(s.render_lanes[&f.receiver], 400.);
for (id, x) in [(f.sender, 160.), (f.receiver, 400.)] {
// The actual header is x-102..x+102, y15..85, including its padding.
for point in [Point::new(x - 101., 16.), Point::new(x + 101., 84.)] {
hit(&s, point, id, SceneHitRole::LifelineHeader);
}
hit(&s, Point::new(x, 95.), id, SceneHitRole::LifelineGuide);
}
}
#[test]
fn repeated_exchange_occurrences_keep_distinct_message_body_and_label_hits() {
let f = fixture();
let s = scene(&f);
assert_eq!(s.rows[&f.call].1, 148.);
assert_eq!(s.rows[&f.reply].1, 240.);
for (id, y) in [(f.call, 148.), (f.reply, 240.)] {
hit(&s, Point::new(280., y), id, SceneHitRole::MessageBody);
hit(
&s,
Point::new(180., y - 16.),
id,
SceneHitRole::MessageLabel,
);
assert_ne!(id, f.exchange);
}
}
#[test]
fn self_call_elbow_and_receive_endpoint_are_messages_not_execution_hits() {
let mut f = fixture();
for id in [f.call, f.reply] {
let OccurrenceBody::Exchange {
sender,
receiver,
exchange,
..
} = exchange_mut(&mut f.project, id)
else {
unreachable!()
};
*sender = Some(f.sender);
*receiver = Some(f.sender);
*exchange = None;
}
let s = scene(&f);
let call = s.lines.iter().find(|l| l.id == f.call).unwrap();
assert_eq!(call.points.len(), 4);
assert_eq!(call.points[0].y, 148.);
assert_eq!(call.points[3].y, 172.);
hit(
&s,
Point::new(call.points[1].x, 160.),
f.call,
SceneHitRole::MessageBody,
);
hit(&s, call.points[3], f.call, SceneHitRole::MessageBody);
hit(
&s,
Point::new(180., 132.),
f.call,
SceneHitRole::MessageLabel,
);
let bar = s.activations.iter().find(|a| a.call == f.call).unwrap();
hit(
&s,
Point::new(bar.rect.x + 2., 190.),
f.call,
SceneHitRole::Activation,
);
}
#[test]
fn activation_shoulder_beats_another_calls_label_and_broad_message_tolerance() {
let mut f = fixture();
let mut inner = f.project.elements[&f.call].clone();
inner.id = Id::new_v4();
inner.alias = "inner_call_hit".into();
inner.name = "Pressure verification with a descriptive operation label".into();
let inner_id = inner.id;
f.project.elements.insert(inner_id, inner);
let mut inner_reply = f.project.elements[&f.reply].clone();
inner_reply.id = Id::new_v4();
inner_reply.alias = "inner_reply_hit".into();
let reply_id = inner_reply.id;
f.project.elements.insert(reply_id, inner_reply);
let OccurrenceBody::Exchange { reply_to, .. } = exchange_mut(&mut f.project, reply_id) else {
unreachable!()
};
*reply_to = Some(inner_id);
*f.project
.elements
.get_mut(&f.owner)
.unwrap()
.steps_mut()
.unwrap() = vec![f.call, inner_id, reply_id, f.reply];
let mut s = scene(&f);
let inner = s.lines.iter().find(|l| l.id == inner_id).unwrap();
let outer = s.activations.iter().find(|a| a.call == f.call).unwrap();
let shoulder = Point::new(outer.rect.x + 1., 225.);
assert!(outer.rect.contains(shoulder));
assert!(inner.label_bounds().contains(shoulder));
let endpoint = *inner.points.last().unwrap();
for scale in [1., 0.05, 0.0003] {
s.scale = scale;
hit(&s, shoulder, f.call, SceneHitRole::Activation);
hit(&s, endpoint, inner_id, SceneHitRole::MessageBody);
hit(
&s,
Point::new(180., 225.),
inner_id,
SceneHitRole::MessageLabel,
);
}
}
#[test]
fn create_delete_markers_are_distinct_from_their_own_message_body_and_label() {
let mut f = fixture();
for (id, kind) in [
(f.call, MessageKind::Create),
(f.reply, MessageKind::Delete),
] {
let OccurrenceBody::Exchange {
sender,
receiver,
message_kind,
reply_to,
..
} = exchange_mut(&mut f.project, id)
else {
unreachable!()
};
*sender = Some(f.sender);
*receiver = Some(f.receiver);
*message_kind = kind;
*reply_to = None;
}
let s = scene(&f);
for (id, y, label_y) in [(f.call, 148., 118.), (f.reply, 240., 224.)] {
hit(&s, Point::new(400., y), id, SceneHitRole::LifecycleMarker);
hit(&s, Point::new(280., y), id, SceneHitRole::MessageBody);
hit(
&s,
Point::new(180., label_y),
id,
SceneHitRole::MessageLabel,
);
}
// Capsule boundary owns its contact with the incoming Create arrow.
hit(
&s,
Point::new(330., 148.),
f.call,
SceneHitRole::LifecycleMarker,
);
}
#[test]
fn tiny_scale_nearest_hit_retains_the_winning_marker_or_message_role() {
let mut f = fixture();
let OccurrenceBody::Exchange {
sender,
receiver,
message_kind,
reply_to,
..
} = exchange_mut(&mut f.project, f.reply)
else {
unreachable!()
};
*sender = Some(f.sender);
*receiver = Some(f.receiver);
*message_kind = MessageKind::Delete;
*reply_to = None;
let mut s = scene(&f);
s.scale = 0.0003;
// Both are outside exact strokes/labels. Comparing all broad candidates
// chooses the actual nearer shape, even when their UUID is identical.
hit(
&s,
Point::new(280., 246.),
f.reply,
SceneHitRole::MessageBody,
);
hit(
&s,
Point::new(400., 265.),
f.reply,
SceneHitRole::LifecycleMarker,
);
hit(
&s,
Point::new(280., 154.),
f.call,
SceneHitRole::MessageBody,
);
}
#[test]
fn action_frame_and_use_boxes_do_not_advertise_message_or_header_roles() {
for body in [
OccurrenceBody::Action {
action: None,
lifeline: None,
},
OccurrenceBody::Fragment {
operator: FragmentOperator::Alternative,
branches: vec![],
},
OccurrenceBody::ScenarioUse {
scenario: None,
bindings: vec![],
},
OccurrenceBody::Exchange {
exchange: None,
sender: None,
receiver: None,
message_kind: MessageKind::Asynchronous,
operation: None,
reply_to: None,
values: vec![],
},
] {
let mut f = fixture();
let id = occurrence(&mut f.project, f.owner, body);
let s = scene(&f);
let item = s.boxes.iter().find(|b| b.id == id).unwrap();
hit(
&s,
item.rect.position() + iced::Vector::new(15., 15.),
id,
SceneHitRole::Box,
);
}
}
#[test]
fn winning_primitive_role_does_not_come_from_its_shared_uuid() {
let f = fixture();
let mut s = scene(&f);
// A controlled overlapping primitive verifies reverse box order without
// inventing a core alias. Its ID intentionally equals a real header's ID.
s.boxes.push(BoxItem {
id: f.sender,
role: SceneHitRole::Box,
rect: Rectangle::new(Point::new(150., 20.), Size::new(20., 20.)),
title: "Overlay control".into(),
detail: String::new(),
marker: None,
});
hit(&s, Point::new(160., 30.), f.sender, SceneHitRole::Box);
hit(
&s,
Point::new(180., 30.),
f.sender,
SceneHitRole::LifelineHeader,
);
}
#[test]
fn invalid_points_never_produce_a_semantic_or_spacing_hit() {
let f = fixture();
let s = scene(&f);
for point in [
Point::new(f32::NAN, 148.),
Point::new(280., f32::NAN),
Point::new(f32::INFINITY, 148.),
Point::new(280., f32::NEG_INFINITY),
] {
assert_eq!(s.hit_item(point), None);
assert_eq!(s.hit(point), None);
}
}
@@ -18,19 +18,12 @@
//! It measures layout advances, not raster ink; overhang/clip/activation-border
//! acceptance still requires the real WGPU evaluator. The old 32-grapheme/225px
//! renderer is deliberately untouched for a later baseline comparison.
//! Field geometry is a second unwired experiment: exact retained source spans
//! and winning-buffer cluster boxes, with unresolved glyph coverage distinct
//! from truncation. It does not adopt a production navigation policy.
use iced::advanced::{
graphics::text as graphics_text,
text::{Alignment, LineHeight, Shaping},
};
use iced::{Color, Font, Pixels, Point, Rectangle, Size, widget::canvas::Text};
use std::{
collections::{HashSet, VecDeque},
ops::Range,
sync::Arc,
};
use std::{collections::VecDeque, ops::Range, sync::Arc};
use unicode_segmentation::UnicodeSegmentation;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
@@ -101,207 +94,9 @@ pub(super) struct Label {
style: Style,
measured_session: RenderSession,
measured_zoom: f32,
// Snapshot of the final displayed Cache entry, after alignment. These are
// cluster advance boxes, never glyph ink or inferred character cells.
clusters: Vec<FieldCluster>,
source_spans: Vec<SourceSpan>,
retained_normalized: usize,
field_index: FieldIndex,
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct FieldLayout {
pub rectangles: Vec<Rectangle>,
pub covered: Vec<Range<usize>>,
pub truncated: Vec<Range<usize>>,
pub unresolved: Vec<UnresolvedField>,
pub partially_retained: bool,
pub shared_cluster: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum FieldIssue {
MissingGlyph,
NoAdvanceGeometry,
NonPaintingScalar,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct UnresolvedField {
pub source: Range<usize>,
pub reason: FieldIssue,
}
#[derive(Clone, Debug)]
struct SourceSpan {
source: Range<usize>,
normalized: Range<usize>,
whitespace: bool,
non_painting: bool,
}
#[derive(Clone, Debug)]
struct FieldCluster {
normalized: Range<usize>,
rectangles: Vec<Rectangle>,
missing: bool,
}
/// Immutable overlap membership, built from Normalized's ordered, disjoint
/// scalar/separator spans. Clusters may overlap and need not be in visual order.
/// Construction costs O(C log S + I), storage O(S + C + I), where I is the
/// number of actual span/cluster overlaps, rather than the full S*C product.
#[derive(Clone, Debug)]
struct FieldIndex {
clusters_by_span: Vec<Vec<usize>>,
source_extents: Vec<Option<SourceExtents>>,
}
#[derive(Clone, Copy, Debug)]
struct SourceExtents {
minimum_end: usize,
maximum_start: usize,
}
impl FieldIndex {
fn new(spans: &[SourceSpan], clusters: &[FieldCluster]) -> Self {
debug_assert!(
spans
.iter()
.all(|span| span.normalized.start < span.normalized.end)
);
debug_assert!(
spans
.windows(2)
.all(|pair| pair[0].normalized.end <= pair[1].normalized.start)
);
let mut result = Self {
clusters_by_span: vec![vec![]; spans.len()],
source_extents: vec![None; clusters.len()],
};
for (index, cluster) in clusters.iter().enumerate() {
if cluster.normalized.start >= cluster.normalized.end {
continue;
}
let first =
spans.partition_point(|span| span.normalized.end <= cluster.normalized.start);
for (offset, span) in spans[first..].iter().enumerate() {
if span.normalized.start >= cluster.normalized.end {
break;
}
result.clusters_by_span[first + offset].push(index);
let extents = result.source_extents[index].get_or_insert(SourceExtents {
minimum_end: span.source.end,
maximum_start: span.source.start,
});
extents.minimum_end = extents.minimum_end.min(span.source.end);
extents.maximum_start = extents.maximum_start.max(span.source.start);
}
}
result
}
}
// Translation rejects nonfinite rectangle components before deduplication.
// For finite f32 values, bit equality differs from `==` only at signed zero.
// Normalize only the key: preserve the first rectangle and its original bits.
fn rectangle_key(bounds: Rectangle) -> [u32; 4] {
[bounds.x, bounds.y, bounds.width, bounds.height]
.map(|value| if value == 0. { 0 } else { value.to_bits() })
}
impl Label {
/// Geometry and coverage are separate: truncation is not missing-font
/// coverage, and a positive .notdef advance is not represented field text.
/// Shared ligatures use whole cluster boxes; no sub-cluster fraction is
/// invented. Returned ranges refer only to the requested original source.
pub fn field_layout(
&self,
session: &RenderSession,
zoom: f32,
position: Point,
field: Range<usize>,
) -> Result<FieldLayout, Error> {
self.check(session, zoom)?;
translated_bounds(position, Size::ZERO)?;
if field.start > field.end || self.source.get(field.clone()).is_none() {
return Err(Error::InvalidFieldRange);
}
let mut result = FieldLayout {
rectangles: vec![],
covered: vec![],
truncated: vec![],
unresolved: vec![],
partially_retained: false,
shared_cluster: false,
};
let mut selected = vec![false; self.clusters.len()];
for (span_index, span) in self.source_spans.iter().enumerate() {
if span.whitespace || !overlaps(&span.source, &field) {
continue;
}
// Source spans for text are exact UTF-8 scalars, not intervals
// between ends (which could assign trimmed whitespace to text).
if span.normalized.end > self.retained_normalized {
append_range(&mut result.truncated, span.source.clone());
continue;
}
let matching = &self.field_index.clusters_by_span[span_index];
result.shared_cluster |= matching.iter().any(|&index| {
let cluster = &self.clusters[index];
cluster.normalized.end > self.retained_normalized
|| self.field_index.source_extents[index].is_some_and(|extents| {
// Any overlapping source span outside the requested
// field is exactly either a too-small end or too-large
// start. Include whitespace/nonpainting spans, as before.
extents.minimum_end <= field.start || extents.maximum_start >= field.end
})
});
let issue = if span.non_painting {
Some(FieldIssue::NonPaintingScalar)
} else if matching.iter().any(|&index| self.clusters[index].missing) {
Some(FieldIssue::MissingGlyph)
} else if matching.is_empty()
|| matching
.iter()
.all(|&index| self.clusters[index].rectangles.is_empty())
{
Some(FieldIssue::NoAdvanceGeometry)
} else {
None
};
if let Some(reason) = issue {
result.unresolved.push(UnresolvedField {
source: span.source.clone(),
reason,
});
continue;
}
append_range(&mut result.covered, span.source.clone());
for &index in matching {
selected[index] = true;
}
}
let mut seen = HashSet::new();
for (cluster, selected) in self.clusters.iter().zip(selected) {
if !selected {
continue;
}
for bounds in &cluster.rectangles {
let translated = translated_bounds(
Point::new(position.x + bounds.x, position.y + bounds.y),
bounds.size(),
)?;
if seen.insert(rectangle_key(translated)) {
result.rectangles.push(translated);
}
}
}
result.partially_retained = !result.truncated.is_empty()
&& (!result.covered.is_empty() || !result.unresolved.is_empty());
Ok(result)
}
fn check(&self, session: &RenderSession, zoom: f32) -> Result<(), Error> {
if !Arc::ptr_eq(&self.measured_session.identity, &session.identity) {
return Err(Error::StaleRenderSession);
@@ -399,7 +194,6 @@ pub(super) enum Error {
StaleZoom,
StaleRenderSession,
FontSetChanged,
InvalidFieldRange,
}
struct Entry {
@@ -492,8 +286,8 @@ impl Cache {
if cuts.len().saturating_sub(1) > MAX_GRAPHEMES {
return Err(Error::GraphemeBudget);
}
// Candidate buffers are temporary. The winning strings, metrics, source
// spans and cluster boxes survive; renderer caching remains independent.
// Candidate buffers are temporary. Only the resolved strings/metrics
// survive, bounded by MAX_ENTRIES; renderer caching remains independent.
let mut shapes = graphics_text::Cache::new();
let mut measure = |content: &str| -> Result<Size, Error> {
if content.is_empty() {
@@ -551,25 +345,6 @@ impl Cache {
best
}
};
let clusters = if displayed.is_empty() {
// measure("") deliberately creates no cache entry.
vec![]
} else {
let (_, entry) = shapes.allocate(
fonts.raw(),
graphics_text::cache::Key {
content: &displayed,
size,
line_height,
font: style.font,
bounds: Size::INFINITE,
shaping: style.shaping,
align_x: Alignment::Default,
},
);
field_clusters(entry, zoom)?
};
let field_index = FieldIndex::new(&normalized.spans, &clusters);
let label = Arc::new(Label {
source: source.into(),
displayed,
@@ -578,10 +353,6 @@ impl Cache {
style,
measured_session: session.clone(),
measured_zoom: zoom,
clusters,
source_spans: normalized.spans,
retained_normalized: retained,
field_index,
});
if self.entries.len() == MAX_ENTRIES {
self.entries.pop_front();
@@ -623,14 +394,12 @@ fn translated_bounds(position: Point, size: Size) -> Result<Rectangle, Error> {
struct Normalized {
text: String,
ends: Vec<(usize, usize)>,
spans: Vec<SourceSpan>,
}
impl Normalized {
fn new(source: &str) -> Self {
let mut result = Self {
text: String::new(),
ends: vec![(0, 0)],
spans: vec![],
};
let mut separator = false;
for (start, c) in source.char_indices() {
@@ -639,25 +408,11 @@ impl Normalized {
continue;
}
if separator {
let normalized_start = result.text.len();
result.text.push(' ');
result.spans.push(SourceSpan {
source: result.ends.last().expect("initial boundary").1..start,
normalized: normalized_start..result.text.len(),
whitespace: true,
non_painting: false,
});
result.ends.push((result.text.len(), start));
separator = false;
}
let normalized_start = result.text.len();
result.text.push(c);
result.spans.push(SourceSpan {
source: start..start + c.len_utf8(),
normalized: normalized_start..result.text.len(),
whitespace: false,
non_painting: non_painting_scalar(c),
});
result.ends.push((result.text.len(), start + c.len_utf8()));
}
result
@@ -670,90 +425,6 @@ impl Normalized {
}
}
fn overlaps(a: &Range<usize>, b: &Range<usize>) -> bool {
a.start < a.end && b.start < b.end && a.start < b.end && b.start < a.end
}
fn append_range(ranges: &mut Vec<Range<usize>>, next: Range<usize>) {
if let Some(last) = ranges.last_mut()
&& last.end == next.start
{
last.end = next.end;
return;
}
ranges.push(next);
}
// Conservative non-membership for controls/default-ignorables, even when a
// shaper assigns them a neighbor's positive-width cluster. Unicode 14 ranges
// documented in pinned harfrust 0.3.2 src/hb/unicode.rs:615–650. Include its
// spacing-filler exceptions conservatively; this is not an ink classifier.
fn non_painting_scalar(c: char) -> bool {
c.is_control()
|| matches!(c as u32,
0x00ad | 0x034f | 0x061c | 0x115f..=0x1160 | 0x17b4..=0x17b5 |
0x180b..=0x180f | 0x200b..=0x200f | 0x202a..=0x202e | 0x2060..=0x206f |
0x3164 | 0xfe00..=0xfe0f | 0xfeff | 0xffa0 | 0xfff0..=0xfff8 |
0x1bca0..=0x1bca3 | 0x1d173..=0x1d17a | 0xe0000..=0xe0fff)
}
fn field_clusters(
entry: &graphics_text::cache::Entry,
zoom: f32,
) -> Result<Vec<FieldCluster>, Error> {
let mut clusters: std::collections::BTreeMap<(usize, usize), FieldCluster> = Default::default();
for run in entry.buffer.layout_runs() {
for glyph in run.glyphs {
if glyph.start >= glyph.end || run.text.get(glyph.start..glyph.end).is_none() {
return Err(Error::InvalidMeasurement);
}
let cluster =
clusters
.entry((glyph.start, glyph.end))
.or_insert_with(|| FieldCluster {
normalized: glyph.start..glyph.end,
rectangles: vec![],
missing: false,
});
cluster.missing |= glyph.glyph_id == 0;
let x1 = glyph.x / zoom;
let x2 = (glyph.x + glyph.w) / zoom;
let y = (run.line_top + glyph.y) / zoom;
let height = glyph.line_height_opt.unwrap_or(run.line_height) / zoom;
if !x1.is_finite()
|| !x2.is_finite()
|| !y.is_finite()
|| !height.is_finite()
|| height < 0.
|| !(y + height).is_finite()
{
return Err(Error::InvalidMeasurement);
}
if x1 != x2 && height > 0. {
let bounds = Rectangle::new(
Point::new(x1.min(x2), y),
Size::new((x2 - x1).abs(), height),
);
if !bounds.width.is_finite() {
return Err(Error::InvalidMeasurement);
}
if !cluster.rectangles.contains(&bounds) {
cluster.rectangles.push(bounds);
}
}
}
}
Ok(clusters.into_values().collect())
}
#[cfg(test)]
#[path = "scenario_label/tests.rs"]
mod tests;
#[cfg(test)]
#[path = "scenario_label/field_tests.rs"]
mod field_tests;
#[cfg(test)]
#[path = "scenario_label/lookup_tests.rs"]
mod lookup_tests;
@@ -1,732 +0,0 @@
//! Unwired field-layout falsifiers. Execution evidence is recorded in the harness.
//! Paragraph is an independent
//! shaping oracle; it never invokes the candidate normalization/extraction.
use super::*;
use iced::advanced::{
graphics::text::Paragraph,
text::{Paragraph as _, Text as ParagraphText, Wrapping},
};
// The two ligature tests run alone in fresh processes. Clearing host faces is
// deliberate: a system-installed Noto Sans with another version must not win.
const LIGATURE_FONT: &[u8] = include_bytes!("fixtures/NotoSans-Regular.ttf");
fn isolated_ligature_style(shaping: Shaping) -> Style {
let mut fonts = graphics_text::font_system().write().unwrap();
let ids: Vec<_> = fonts.raw().db().faces().map(|face| face.id).collect();
for id in ids {
fonts.raw().db_mut().remove_face(id);
}
fonts.load_font(std::borrow::Cow::Borrowed(LIGATURE_FONT));
assert_eq!(fonts.raw().db().len(), 1);
Style {
font: Font::with_name("Noto Sans"),
shaping,
..Style::default()
}
}
fn assert_ligature_fixture_face(oracle: &Paragraph) {
let mut fonts = graphics_text::font_system().write().unwrap();
let mut count = 0;
for glyph in oracle.buffer().layout_runs().flat_map(|run| run.glyphs) {
assert_eq!(
fonts
.raw()
.db()
.with_face_data(glyph.font_id, |bytes, index| {
index == 0 && bytes == LIGATURE_FONT
}),
Some(true),
"the actual shaped face must be the byte-pinned fixture"
);
count += 1;
}
assert!(count > 0, "font identity cannot pass on an empty paragraph");
}
fn paragraph(text: &str, zoom: f32, style: Style) -> Paragraph {
Paragraph::with_text(ParagraphText {
content: text,
bounds: Size::INFINITE,
size: Pixels(style.size.0 * zoom),
line_height: match style.line_height {
LineHeight::Relative(value) => LineHeight::Relative(value),
LineHeight::Absolute(value) => LineHeight::Absolute(Pixels(value.0 * zoom)),
},
font: style.font,
align_x: Alignment::Default,
align_y: iced::alignment::Vertical::Top,
shaping: style.shaping,
wrapping: Wrapping::default(),
})
}
fn resolve(text: &str, width: f32, zoom: f32, style: Style) -> (RenderSession, Arc<Label>) {
let session = RenderSession::after_fonts_settled_and_renderer_reset().unwrap();
let label = Cache::default()
.resolve(&session, text, width, zoom, style)
.unwrap();
(session, label)
}
// The oracle walks an independently built Paragraph, never Label's retained
// spans, cluster snapshot, or field_layout. Test callers supply explicit ranges
// in the already displayed string; synthetic ellipsis is deliberately excluded.
fn paragraph_boxes(oracle: &Paragraph, ranges: &[Range<usize>], zoom: f32) -> Vec<Rectangle> {
let mut boxes = vec![];
for run in oracle.buffer().layout_runs() {
for glyph in run.glyphs {
if !ranges
.iter()
.any(|range| range.start < glyph.end && glyph.start < range.end)
{
continue;
}
assert_ne!(glyph.glyph_id, 0, "oracle requires actual font coverage");
if glyph.w == 0. {
continue;
}
assert!(
glyph.w > 0.,
"these fixtures require positive glyph advances"
);
let left = glyph.x / zoom;
let right = (glyph.x + glyph.w) / zoom;
boxes.push(Rectangle::new(
Point::new(left, (run.line_top + glyph.y) / zoom),
Size::new(
right - left,
glyph.line_height_opt.unwrap_or(run.line_height) / zoom,
),
));
}
}
canonical_boxes(boxes)
}
fn canonical_boxes(mut boxes: Vec<Rectangle>) -> Vec<Rectangle> {
boxes.sort_by(|a, b| {
a.x.total_cmp(&b.x)
.then(a.y.total_cmp(&b.y))
.then(a.width.total_cmp(&b.width))
.then(a.height.total_cmp(&b.height))
});
boxes.dedup();
boxes
}
fn assert_complete_boxes(actual: &[Rectangle], expected: Vec<Rectangle>) {
let canonical = canonical_boxes(actual.to_vec());
assert_eq!(
actual.len(),
canonical.len(),
"duplicate returned boxes are extraneous"
);
assert!(
!expected.is_empty(),
"the geometric oracle must be nonempty"
);
assert_eq!(
canonical, expected,
"every selected rectangle and only selected rectangles"
);
}
fn resolved_fonts(oracle: &Paragraph) -> Vec<String> {
let mut identities = vec![];
let mut fonts = graphics_text::font_system().write().unwrap();
for glyph in oracle.buffer().layout_runs().flat_map(|run| run.glyphs) {
let face = fonts.raw().db().face(glyph.font_id).unwrap();
let identity = format!(
"{:?}: {} {:?}",
glyph.font_id, face.post_script_name, face.families
);
if !identities.contains(&identity) {
identities.push(identity);
}
}
identities
}
#[test]
fn empty_and_ellipsis_only_have_no_field_coverage() {
for text in ["", " \t\n", "Operation: assess"] {
let (session, label) = resolve(text, 0., 1., Style::default());
assert!(label.displayed.is_empty());
let field = label
.field_layout(&session, 1., Point::ORIGIN, 0..text.len())
.unwrap();
assert!(field.rectangles.is_empty());
assert!(field.covered.is_empty());
assert!(field.unresolved.is_empty());
}
let style = Style::default();
let width = paragraph("…", 1., style).min_width();
let text = "Operation: assess";
let (session, label) = resolve(text, width, 1., style);
assert_eq!(
label.displayed, "…",
"must exercise synthetic-only displayed content"
);
let field = label
.field_layout(&session, 1., Point::ORIGIN, 0..text.len())
.unwrap();
assert!(field.covered.is_empty());
assert!(field.rectangles.is_empty());
assert!(!field.truncated.is_empty());
}
#[test]
fn exact_scalar_mapping_does_not_assign_trimmed_or_collapsed_whitespace_to_text() {
let source = " send\t\n assess ";
let (session, label) = resolve(source, 900., 1., Style::default());
assert_eq!(label.displayed, "send assess");
for range in [0..2, 6..10, 16..18] {
let result = label
.field_layout(&session, 1., Point::ORIGIN, range)
.unwrap();
assert!(result.covered.is_empty());
assert!(result.rectangles.is_empty());
assert!(result.unresolved.is_empty());
}
let result = label
.field_layout(&session, 1., Point::ORIGIN, 10..16)
.unwrap();
assert_eq!(result.covered, vec![10..16]);
assert!(!result.rectangles.is_empty());
assert!(result.truncated.is_empty());
assert!(result.unresolved.is_empty());
}
#[test]
fn late_operation_reports_hidden_partial_and_complete_without_ellipsis_membership() {
let source = "1. call - Incident report - assess_pressure";
let start = source.find("assess_pressure").unwrap();
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let (session, full) = resolve(source, 900., 1., style);
let complete = full
.field_layout(&session, 1., Point::ORIGIN, start..source.len())
.unwrap();
assert_eq!(complete.covered, vec![start..source.len()]);
assert!(!complete.partially_retained);
let (_, hidden) = resolve(
source,
paragraph("1. call…", 1., style).min_width(),
1.,
style,
);
let hidden_result = hidden
.field_layout(
&hidden.measured_session,
1.,
Point::ORIGIN,
start..source.len(),
)
.unwrap();
assert!(hidden.retained_source.end <= start);
assert!(hidden_result.covered.is_empty());
assert_eq!(hidden_result.truncated, vec![start..source.len()]);
assert!(!hidden_result.partially_retained);
let desired = format!("{}assess…", &source[..start]);
let (_, partial) = resolve(
source,
paragraph(&desired, 1., style).min_width(),
1.,
style,
);
assert!(
partial.retained_source.end > start && partial.retained_source.end < source.len(),
"actual fitting result must retain a strict operation prefix"
);
let result = partial
.field_layout(
&partial.measured_session,
1.,
Point::ORIGIN,
start..source.len(),
)
.unwrap();
assert_eq!(result.covered, vec![start..partial.retained_source.end]);
assert_eq!(
result.truncated,
vec![partial.retained_source.end..source.len()]
);
assert!(result.partially_retained);
assert!(result.unresolved.is_empty());
}
#[test]
fn positive_notdef_advance_is_unresolved_not_covered_or_truncated() {
let source = "A\u{10ffff}B";
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let oracle = paragraph(source, 1., style);
assert!(
oracle
.buffer()
.layout_runs()
.flat_map(|run| run.glyphs)
.any(|glyph| glyph.start == 1 && glyph.end == 5 && glyph.glyph_id == 0 && glyph.w > 0.),
"font precondition: actual positive-width .notdef for the noncharacter"
);
let (session, label) = resolve(source, 900., 1., style);
let missing = label
.field_layout(&session, 1., Point::ORIGIN, 1..5)
.unwrap();
assert!(missing.covered.is_empty());
assert!(missing.rectangles.is_empty());
assert!(missing.truncated.is_empty());
assert_eq!(
missing.unresolved,
vec![UnresolvedField {
source: 1..5,
reason: FieldIssue::MissingGlyph
}]
);
let mixed = label
.field_layout(&session, 1., Point::ORIGIN, 0..source.len())
.unwrap();
assert_eq!(mixed.covered, vec![0..1, 5..6]);
assert_eq!(mixed.unresolved, missing.unresolved);
assert!(!mixed.rectangles.is_empty());
}
#[test]
#[ignore = "replaces global fonts; run only this exact test in a fresh process"]
fn advanced_ligature_partial_field_uses_whole_shared_cluster_not_fraction() {
let source = "ffi";
let style = isolated_ligature_style(Shaping::Advanced);
let oracle = paragraph(source, 1., style);
assert_ligature_fixture_face(&oracle);
let run = oracle.buffer().layout_runs().next().unwrap();
let glyph = run
.glyphs
.iter()
.find(|glyph| glyph.start == 0 && glyph.end == 3 && glyph.w > 0. && glyph.glyph_id != 0)
.expect("font precondition: Advanced must produce the ffi ligature cluster");
let expected = Rectangle::new(
Point::new(glyph.x, run.line_top + glyph.y),
Size::new(glyph.w, glyph.line_height_opt.unwrap_or(run.line_height)),
);
let (session, label) = resolve(source, 900., 1., style);
let field = label
.field_layout(&session, 1., Point::ORIGIN, 1..2)
.unwrap();
assert_eq!(field.covered, vec![1..2]);
assert!(field.shared_cluster);
assert!(field.rectangles.contains(&expected));
assert_eq!(
field.rectangles.iter().map(|rect| rect.width).sum::<f32>(),
expected.width
);
assert_complete_boxes(&field.rectangles, vec![expected]);
assert!(field.unresolved.is_empty());
}
#[test]
fn shared_default_ignorable_does_not_inherit_neighbor_coverage() {
let source = "a\u{fe0f}";
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let oracle = paragraph(source, 1., style);
assert!(
oracle
.buffer()
.layout_runs()
.flat_map(|run| run.glyphs)
.any(|glyph| glyph.start == 0
&& glyph.end == source.len()
&& glyph.w > 0.
&& glyph.glyph_id != 0),
"precondition: variation selector shares a real positive-width base cluster"
);
let (session, label) = resolve(source, 900., 1., style);
let field = label
.field_layout(&session, 1., Point::ORIGIN, 1..source.len())
.unwrap();
assert!(field.covered.is_empty());
assert!(field.rectangles.is_empty());
assert!(field.truncated.is_empty());
assert!(field.shared_cluster);
assert_eq!(
field.unresolved,
vec![UnresolvedField {
source: 1..source.len(),
reason: FieldIssue::NonPaintingScalar
}]
);
}
#[test]
fn combining_mark_field_retains_cluster_geometry_without_splitting_the_grapheme() {
let source = "e\u{301} next";
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let oracle = paragraph(source, 1., style);
let run = oracle.buffer().layout_runs().next().unwrap();
let cluster = run
.glyphs
.iter()
.find(|glyph| glyph.start == 0 && glyph.end == 3 && glyph.w > 0. && glyph.glyph_id != 0)
.expect("precondition: composed accent and base share the grapheme cluster");
let (session, label) = resolve(source, 900., 1., style);
let field = label
.field_layout(&session, 1., Point::ORIGIN, 1..3)
.unwrap();
assert_eq!(field.covered, vec![1..3]);
assert!(field.shared_cluster);
assert!(
field
.rectangles
.iter()
.any(|rect| rect.x == cluster.x && rect.width == cluster.w)
);
assert!(field.unresolved.is_empty());
assert_eq!(
label.field_layout(&session, 1., Point::ORIGIN, 2..3),
Err(Error::InvalidFieldRange)
);
let (_, short) = resolve(
source,
paragraph("e\u{301}…", 1., style).min_width(),
1.,
style,
);
assert_ne!(
short.retained_source.end, 1,
"the chosen prefix must never split the combining grapheme"
);
}
#[test]
fn bidi_logical_field_keeps_visual_pieces_without_enclosing_unselected_glyph() {
let source = "abc אבג xyz";
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let oracle = paragraph(source, 1., style);
let run = oracle.buffer().layout_runs().next().unwrap();
assert!(
!run.rtl,
"this existing fixture specifically has an LTR paragraph base"
);
assert!(run.glyphs.iter().any(|glyph| glyph.level.is_rtl()));
assert!(run.glyphs.iter().any(|glyph| !glyph.level.is_rtl()));
let excluded = run
.glyphs
.iter()
.find(|glyph| glyph.start == 8 && glyph.end == 10 && glyph.w > 0. && glyph.glyph_id != 0)
.unwrap();
let (session, label) = resolve(source, 900., 1., style);
let field = label
.field_layout(&session, 1., Point::ORIGIN, 1..8)
.unwrap();
assert_eq!(field.covered, vec![1..3, 4..8]);
assert!(field.unresolved.is_empty());
assert_complete_boxes(
&field.rectangles,
paragraph_boxes(&oracle, &[1..3, 4..8], 1.),
);
assert!(
field
.rectangles
.iter()
.any(|rect| rect.x + rect.width <= excluded.x)
);
assert!(
field
.rectangles
.iter()
.any(|rect| rect.x >= excluded.x + excluded.w)
);
assert!(
field
.rectangles
.iter()
.all(|rect| rect.x + rect.width <= excluded.x || rect.x >= excluded.x + excluded.w),
"logical selection must not become one envelope over the intervening visual glyph"
);
}
#[test]
fn rtl_leading_full_field_has_complete_post_alignment_rectangle_set() {
let source = "אבג abc דהו xyz operation";
assert_eq!(source.len(), 31);
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let oracle = paragraph(source, 1., style);
let run = oracle.buffer().layout_runs().next().unwrap();
assert!(
run.rtl,
"must exercise Iced's RTL paragraph alignment branch"
);
assert!(run.glyphs.iter().any(|glyph| glyph.level.is_rtl()));
assert!(run.glyphs.iter().any(|glyph| !glyph.level.is_rtl()));
eprintln!("RTL_FIELD_FONTS={:?}", resolved_fonts(&oracle));
let (session, label) = resolve(source, 900., 1., style);
assert_eq!(label.displayed, source);
let ranges = vec![2..6, 7..10, 11..17, 18..21, 22..31];
let field = label
.field_layout(&session, 1., Point::ORIGIN, 2..source.len())
.unwrap();
assert_eq!(field.covered, ranges);
assert!(field.truncated.is_empty() && field.unresolved.is_empty());
assert!(!field.partially_retained);
assert_complete_boxes(&field.rectangles, paragraph_boxes(&oracle, &ranges, 1.));
}
#[test]
fn rtl_leading_ellipsis_field_has_complete_final_buffer_rectangle_set() {
let source = "אבג abc דהו xyz operation";
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let width = paragraph("אבג abc דהו…", 1., style).min_width();
let (session, label) = resolve(source, width, 1., style);
let prefix = label
.displayed
.strip_suffix('…')
.expect("must use an ellipsized displayed buffer");
assert!(prefix.len() >= 10 && prefix.len() < source.len());
assert!(source.starts_with(prefix));
let oracle = paragraph(&label.displayed, 1., style);
let run = oracle.buffer().layout_runs().next().unwrap();
assert!(
run.rtl,
"the ellipsized winning text must still exercise RTL alignment"
);
eprintln!("RTL_ELLIPSIS_FIELD_FONTS={:?}", resolved_fonts(&oracle));
// Fixed semantic word spans from the source, clipped only by the literal
// displayed prefix. No candidate source map or retained_source is consulted.
let words = [2..6, 7..10, 11..17, 18..21, 22..31];
let retained: Vec<_> = words
.iter()
.filter_map(|word| {
let end = word.end.min(prefix.len());
(word.start < end).then_some(word.start..end)
})
.collect();
let hidden: Vec<_> = words
.iter()
.filter_map(|word| {
let start = word.start.max(prefix.len());
(start < word.end).then_some(start..word.end)
})
.collect();
let field = label
.field_layout(&session, 1., Point::ORIGIN, 2..source.len())
.unwrap();
assert_eq!(field.covered, retained);
assert_eq!(field.truncated, hidden);
assert!(field.partially_retained && field.unresolved.is_empty());
assert_complete_boxes(&field.rectangles, paragraph_boxes(&oracle, &retained, 1.));
}
/// Diagnostic only: warm font/Paragraph preparation precedes the timed resolver
/// and three lookups. No latency budget or production responsiveness claim.
#[test]
#[ignore = "bounded high-end field lookup diagnostic; run this exact test alone with --nocapture"]
fn field_lookup_4096_scalars_and_combining_heavy_full_coverage() {
let style = Style {
shaping: Shaping::Advanced,
..Style::default()
};
let cases = [
("4096_plain_scalars", "A".repeat(4096), 4096),
(
"4096_combining_heavy_scalars",
"a\u{301}\u{323}\u{327}".repeat(1024),
1024,
),
];
let mut records = vec![];
for (name, source, expected_graphemes) in cases {
assert_eq!(source.chars().count(), 4096);
assert_eq!(source.graphemes(true).count(), expected_graphemes);
assert!(source.len() <= MAX_SOURCE_BYTES);
assert!(expected_graphemes <= MAX_GRAPHEMES);
let oracle = paragraph(&source, 1., style);
assert_eq!(oracle.buffer().layout_runs().count(), 1);
let expected = paragraph_boxes(&oracle, &[0..source.len()], 1.);
let identities = resolved_fonts(&oracle);
let session = RenderSession::after_fonts_settled_and_renderer_reset().unwrap();
let mut cache = Cache::default();
let start = std::time::Instant::now();
let label = cache
.resolve(&session, &source, 1_000_000., 1., style)
.unwrap();
let resolve_ns = start.elapsed().as_nanos();
assert_eq!(label.displayed, source);
// The preserved 4c9 lookup runs on the exact same immutable shaped
// label. Its timing is separate from the optimized samples below.
let start = std::time::Instant::now();
let original = label
.original_field_layout(&session, 1., Point::ORIGIN, 0..source.len())
.unwrap();
let original_lookup_ns = start.elapsed().as_nanos();
let mut lookup_ns = vec![];
for _ in 0..3 {
let start = std::time::Instant::now();
let field = label
.field_layout(&session, 1., Point::ORIGIN, 0..source.len())
.unwrap();
lookup_ns.push(start.elapsed().as_nanos());
assert_eq!(field.covered, vec![0..source.len()]);
assert!(field.truncated.is_empty() && field.unresolved.is_empty());
assert!(!field.partially_retained && !field.shared_cluster);
assert_complete_boxes(&field.rectangles, expected.clone());
super::lookup_tests::assert_exact(&field, &original);
}
// Fresh label construction plus lookup, not just a retained-index
// measurement: moving the old quadratic work into resolve cannot hide.
let mut fresh_resolve_lookup_ns = vec![];
for _ in 0..3 {
let mut fresh_cache = Cache::default();
let start = std::time::Instant::now();
let fresh = fresh_cache
.resolve(&session, &source, 1_000_000., 1., style)
.unwrap();
let field = fresh
.field_layout(&session, 1., Point::ORIGIN, 0..source.len())
.unwrap();
fresh_resolve_lookup_ns.push(start.elapsed().as_nanos());
super::lookup_tests::assert_exact(&field, &original);
assert_complete_boxes(&field.rectangles, expected.clone());
}
records.push(serde_json::json!({
"case": name, "scalars": 4096, "graphemes": expected_graphemes,
"source_bytes": source.len(), "expected_rectangles": expected.len(),
"resolved_fonts": identities, "resolve_ns": resolve_ns, "lookup_ns": lookup_ns,
"original_lookup_ns": original_lookup_ns,
"fresh_resolve_lookup_ns": fresh_resolve_lookup_ns,
"source_spans": label.source_spans.len(), "clusters": label.clusters.len(),
"overlap_memberships": label.field_index.clusters_by_span.iter().map(Vec::len).sum::<usize>(),
"exact_original_result_including_rectangle_bits": "passed",
"full_coverage_and_exact_geometry": "passed",
}));
}
println!(
"FIELD_LOOKUP_TIMING_JSON={}",
serde_json::json!({
"schema": "scenario_label_field_lookup_v1",
"source_pin_from_runner": std::env::var("SCENARIO_LABEL_FIELDS_SOURCE_PIN").ok(),
"debug_assertions": cfg!(debug_assertions), "os": std::env::consts::OS,
"arch": std::env::consts::ARCH, "cases": records,
"invariant_status": "passed",
"scope": "warm-font source-only layout experiment; no native responsiveness threshold",
})
);
}
#[test]
#[ignore = "replaces global fonts; run only this exact test in a fresh process"]
fn auto_ascii_to_ellipsis_advanced_transition_uses_final_buffer() {
let style = isolated_ligature_style(Shaping::Auto);
let source = "ffi office assessment";
assert_eq!(
graphics_text::to_shaping(style.shaping, source),
graphics_text::cosmic_text::Shaping::Basic
);
let basic = paragraph(source, 1., style);
assert_ligature_fixture_face(&basic);
let initial_clusters: Vec<_> = basic
.buffer()
.layout_runs()
.flat_map(|run| run.glyphs)
.filter(|glyph| glyph.start < 3)
.map(|glyph| (glyph.start, glyph.end))
.collect();
assert_eq!(initial_clusters, vec![(0, 1), (1, 2), (2, 3)]);
let (session, label) = resolve(
source,
paragraph("ffi office…", 1., style).min_width(),
1.,
style,
);
assert!(label.displayed.ends_with('…'));
assert_eq!(
graphics_text::to_shaping(style.shaping, &label.displayed),
graphics_text::cosmic_text::Shaping::Advanced
);
let oracle = paragraph(&label.displayed, 1., style);
assert_ligature_fixture_face(&oracle);
let run = oracle.buffer().layout_runs().next().unwrap();
let first = run
.glyphs
.iter()
.find(|glyph| glyph.start == 0 && glyph.end >= 3 && glyph.w > 0. && glyph.glyph_id != 0)
.expect("final Advanced shape must expose the ligature precondition");
let field = label
.field_layout(&session, 1., Point::ORIGIN, 0..3)
.unwrap();
assert_eq!(field.covered, vec![0..3]);
assert!(
field
.rectangles
.iter()
.any(|rect| rect.x == first.x && rect.width == first.w)
);
assert_complete_boxes(&field.rectangles, paragraph_boxes(&oracle, &[0..3], 1.));
}
#[test]
fn field_geometry_reuses_zoom_session_guards_and_translates_actual_cluster_boxes() {
let source = "Z";
for zoom in [0.5, 1.75] {
let style = Style::default();
let oracle = paragraph(source, zoom, style);
let run = oracle.buffer().layout_runs().next().unwrap();
assert_eq!(run.glyphs.len(), 1);
let glyph = &run.glyphs[0];
assert!(glyph.glyph_id != 0 && glyph.w > 0.);
let (session, label) = resolve(source, 900., zoom, style);
let position = Point::new(-300., 90.);
let field = label.field_layout(&session, zoom, position, 0..1).unwrap();
assert_eq!(
field.rectangles,
vec![Rectangle::new(
Point::new(
position.x + glyph.x / zoom,
position.y + (run.line_top + glyph.y) / zoom
),
Size::new(
((glyph.x + glyph.w) / zoom - glyph.x / zoom).abs(),
glyph.line_height_opt.unwrap_or(run.line_height) / zoom
),
)]
);
assert_eq!(
label.field_layout(&session, zoom + 0.1, position, 0..1),
Err(Error::StaleZoom)
);
let fresh = RenderSession::after_fonts_settled_and_renderer_reset().unwrap();
assert_eq!(
label.field_layout(&fresh, zoom, position, 0..1),
Err(Error::StaleRenderSession)
);
assert_eq!(
label.field_layout(&session, zoom, Point::new(f32::NAN, 0.), 0..1),
Err(Error::InvalidPosition)
);
assert_eq!(
label.field_layout(&session, zoom, position, 0..2),
Err(Error::InvalidFieldRange)
);
let empty = label.field_layout(&session, zoom, position, 0..0).unwrap();
assert!(empty.covered.is_empty() && empty.rectangles.is_empty());
}
}
@@ -1 +0,0 @@
* -text -whitespace
@@ -1,93 +0,0 @@
Copyright 2012 Google Inc. All Rights Reserved.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1,15 +0,0 @@
# Isolated ligature font fixture
NotoSans-Regular.ttf and NotoSans-LICENSE are copied byte for byte from the fonts/ directory of the pinned cosmic-text 0.15.0 package. The font is unmodified and licensed under SIL Open Font License 1.1; retain the adjacent complete copyright/license file when redistributing it.
- Package VCS commit: c82ee1c5b5b8032e91eaff1cb34294b538727a7d (from .cargo_vcs_info.json).
- Package checksum in this workspace Cargo.lock: 173852283a9a57a3cbe365d86e74dc428a09c50421477d5ad6fe9d9509e37737.
- Upstream font: https://github.com/pop-os/cosmic-text/blob/c82ee1c5b5b8032e91eaff1cb34294b538727a7d/fonts/NotoSans-Regular.ttf
- Upstream license: https://github.com/pop-os/cosmic-text/blob/c82ee1c5b5b8032e91eaff1cb34294b538727a7d/fonts/NotoSans-LICENSE
- The pinned upstream Git LFS pointer independently reports the identical SHA-256 and 556216-byte size; the fixture contains the actual font, not the pointer.
- Font bytes: 556216; SHA-256: 2ec33f84606cbaa0a1a944488e14f97faf2f6a25ecdd8354f5358f06da13c7d9.
- License bytes: 4351; SHA-256: 5ec4347054089def6904da61d04f0360968f9ef36634b1fe007a5b6ec2f7aa96.
Static cmap/GSUB inspection found f glyph 73 and i glyph 76, with ffi [73,73,76] substituted by glyph 1654 in lookup 39 under the standard liga feature. This is a fixture-selection check, not runtime shaping evidence. Iced's bundled Fira Sans was rejected for these unchanged ffi assertions because its corresponding lookup is under discretionary dlig, which these tests do not enable.
Both consumers are ignored by default and must each run as the sole exact test in a fresh process. Their test-only setup removes host font faces before loading this fixture, then verifies every actual oracle glyph resolves to these exact bytes and face index zero. The fixture therefore does not depend on an installed font with the same family name. The original positive nonzero ffi-cluster preconditions remain mandatory. Nothing selects this font for the product or changes the production label algorithm.
@@ -1,381 +0,0 @@
//! Exact differential oracle from 4c9bc87e4e66bba573dd63b23df5ea039f85d0ca.
//! The old method body is retained verbatim; only its name/visibility changes.
//! Its unchanged validation/translation helpers remain in the parent module.
use super::*;
pub(super) fn assert_exact(actual: &FieldLayout, expected: &FieldLayout) {
assert_eq!(actual, expected);
// PartialEq deliberately equates signed zero; the observable first box
// must nevertheless retain exactly the old representation and order.
for (actual, expected) in actual.rectangles.iter().zip(&expected.rectangles) {
let bits = |r: &Rectangle| [r.x, r.y, r.width, r.height].map(f32::to_bits);
assert_eq!(bits(actual), bits(expected));
}
}
fn compare(
label: &Label,
session: &RenderSession,
zoom: f32,
position: Point,
field: Range<usize>,
) {
let old = label.original_field_layout(session, zoom, position, field.clone());
let new = label.field_layout(session, zoom, position, field);
match (new, old) {
(Ok(new), Ok(old)) => assert_exact(&new, &old),
(new, old) => assert_eq!(new, old),
}
}
fn all_fields(label: &Label, session: &RenderSession, position: Point) {
let boundaries: Vec<_> = label
.source
.char_indices()
.map(|(i, _)| i)
.chain(std::iter::once(label.source.len()))
.collect();
for &start in &boundaries {
for &end in &boundaries {
compare(label, session, label.measured_zoom, position, start..end);
}
}
}
fn synthetic(source: &str, retained: usize, clusters: Vec<FieldCluster>) -> (RenderSession, Label) {
let session = RenderSession::after_fonts_settled_and_renderer_reset().unwrap();
let normalized = Normalized::new(source);
let field_index = FieldIndex::new(&normalized.spans, &clusters);
let label = Label {
source: source.into(),
displayed: normalized.text,
retained_source: 0..source.len(),
bounds: Rectangle::with_size(Size::ZERO),
style: Style::default(),
measured_session: session.clone(),
measured_zoom: 1.,
clusters,
source_spans: normalized.spans,
retained_normalized: retained,
field_index,
};
(session, label)
}
fn cluster(range: Range<usize>, rectangles: Vec<Rectangle>, missing: bool) -> FieldCluster {
FieldCluster {
normalized: range,
rectangles,
missing,
}
}
#[test]
fn indexed_lookup_matches_original_for_real_shaping_and_every_field_boundary() {
let session = RenderSession::after_fonts_settled_and_renderer_reset().unwrap();
let sources = [
"",
" \t\n ",
"ffi office",
" \talpha \r\n beta ",
"a\u{301}\u{fe0f} b\u{2060}c",
"אבג abc דהו",
"A😀Z",
];
let mut nonempty = 0;
for source in sources {
for shaping in [Shaping::Auto, Shaping::Advanced] {
for zoom in [0.5, 1.75] {
let mut cache = Cache::default();
for width in [0., 25., 500.] {
let label = cache
.resolve(
&session,
source,
width,
zoom,
Style {
shaping,
..Style::default()
},
)
.unwrap();
nonempty += usize::from(!label.clusters.is_empty());
all_fields(&label, &session, Point::ORIGIN);
all_fields(&label, &session, Point::new(-37.25, 16.125));
}
}
}
}
assert!(
nonempty >= sources.len(),
"must compare actual shaped geometry as well as empty labels"
);
}
#[test]
fn indexed_lookup_matches_original_for_overlapping_and_reordered_clusters() {
// Normalization is "a + acute + VS16 + space + b + space + c".
// Cluster intervals overlap, nest, span separators, and occur in a
// deliberately non-source/non-visual order. This tests the join rather
// than assuming the simpler cluster partition of most actual fonts.
let source = " a\u{301}\u{fe0f} b c ";
assert_eq!(Normalized::new(source).text.len(), 10);
let a = Rectangle::new(Point::new(30., 3.), Size::new(4., 12.));
let b = Rectangle::new(Point::new(-20., -1.), Size::new(7., 11.));
let c = Rectangle::new(Point::new(9., 4.), Size::new(2., 10.));
let cases = vec![
cluster(7..10, vec![b, a], false),
cluster(0..6, vec![a, c, a], false),
cluster(1..3, vec![], false),
cluster(3..8, vec![c], true),
cluster(0..10, vec![b], false),
cluster(6..7, vec![c], false),
cluster(9..13, vec![a], false), // can extend into a synthetic ellipsis
cluster(3..3, vec![c], true), // empty interval cannot match anything
cluster(8..7, vec![b], true), // nor can a reversed interval
];
for reverse in [false, true] {
let mut clusters = cases.clone();
if reverse {
clusters.reverse();
}
for retained in [0, 1, 3, 6, 7, 8, 10] {
let (session, label) = synthetic(source, retained, clusters.clone());
all_fields(&label, &session, Point::new(-0., -0.));
all_fields(&label, &session, Point::new(0.125, -64.));
}
}
let (session, priority) = synthetic(
"a\u{2060}b",
5,
vec![
cluster(0..1, vec![], false),
cluster(1..4, vec![a], true),
cluster(4..5, vec![b], true),
],
);
all_fields(&priority, &session, Point::ORIGIN);
let result = priority
.field_layout(&session, 1., Point::ORIGIN, 0..5)
.unwrap();
assert_eq!(
result.unresolved,
vec![
UnresolvedField {
source: 0..1,
reason: FieldIssue::NoAdvanceGeometry
},
UnresolvedField {
source: 1..4,
reason: FieldIssue::NonPaintingScalar
},
UnresolvedField {
source: 4..5,
reason: FieldIssue::MissingGlyph
},
]
);
assert!(result.covered.is_empty() && result.rectangles.is_empty());
}
#[test]
fn indexed_lookup_preserves_first_rectangle_bits_and_shared_status() {
let negative = Rectangle::new(Point::new(-0., -0.), Size::new(6., 12.));
let positive = Rectangle::new(Point::ORIGIN, Size::new(6., 12.));
assert_eq!(negative, positive, "Rectangle equality merges signed zero");
let other = Rectangle::new(Point::new(-20., 4.), Size::new(3., 12.));
let (session, label) = synthetic(
"a b",
3,
vec![
cluster(2..3, vec![negative, other], false),
cluster(0..1, vec![positive, negative], false),
],
);
let result = label
.field_layout(&session, 1., Point::new(-0., -0.), 0..3)
.unwrap();
assert_eq!(result.covered, vec![0..1, 2..3]);
assert!(!result.shared_cluster);
assert_eq!(result.rectangles.len(), 2);
assert_eq!(result.rectangles[0].x.to_bits(), (-0f32).to_bits());
assert_eq!(result.rectangles[0].y.to_bits(), (-0f32).to_bits());
assert_eq!(result.rectangles[1], other);
assert_exact(
&result,
&label
.original_field_layout(&session, 1., Point::new(-0., -0.), 0..3)
.unwrap(),
);
let (session, shared) = synthetic("a b", 3, vec![cluster(0..3, vec![other], false)]);
let partial = shared
.field_layout(&session, 1., Point::ORIGIN, 0..1)
.unwrap();
assert_eq!(partial.covered, vec![0..1]);
assert!(partial.shared_cluster);
let complete = shared
.field_layout(&session, 1., Point::ORIGIN, 0..3)
.unwrap();
assert!(!complete.shared_cluster);
all_fields(&shared, &session, Point::ORIGIN);
// The same logical cluster crosses the retained prefix: its box remains
// shared while the source scalar after that prefix remains truncated.
let (session, clipped) = synthetic("abc", 2, vec![cluster(0..3, vec![other], false)]);
let clipped = clipped
.field_layout(&session, 1., Point::ORIGIN, 0..3)
.unwrap();
assert_eq!(clipped.covered, vec![0..2]);
assert_eq!(clipped.truncated, vec![2..3]);
assert!(clipped.shared_cluster && clipped.partially_retained);
}
#[test]
fn indexed_lookup_preserves_error_precedence_and_overflow_rejection() {
let (session, label) = synthetic(
"éa",
3,
vec![cluster(
0..3,
vec![Rectangle::new(
Point::new(f32::MAX, 0.),
Size::new(f32::MAX, 1.),
)],
false,
)],
);
let stale = RenderSession::after_fonts_settled_and_renderer_reset().unwrap();
assert_eq!(
label.field_layout(&stale, f32::NAN, Point::new(f32::NAN, 0.), 7..8),
Err(Error::StaleRenderSession)
);
assert_eq!(
label.field_layout(&session, 2., Point::new(f32::NAN, 0.), 7..8),
Err(Error::StaleZoom)
);
assert_eq!(
label.field_layout(&session, 1., Point::new(f32::NAN, 0.), 7..8),
Err(Error::InvalidPosition)
);
assert_eq!(
label.field_layout(&session, 1., Point::ORIGIN, 1..2),
Err(Error::InvalidFieldRange)
);
assert_eq!(
label.field_layout(&session, 1., Point::ORIGIN, 0..3),
Err(Error::InvalidPosition)
);
// An unselected overflowing box must not turn a valid empty query into an error.
assert!(
label
.field_layout(&session, 1., Point::ORIGIN, 0..0)
.unwrap()
.rectangles
.is_empty()
);
for guard in [&session, &stale] {
for zoom in [1., 2., f32::NAN] {
for position in [
Point::ORIGIN,
Point::new(f32::NAN, 0.),
Point::new(f32::MAX, 0.),
] {
for range in [0..0, 0..3, 1..2, 3..2, 0..4] {
compare(&label, guard, zoom, position, range);
}
}
}
}
}
impl Label {
pub(super) fn original_field_layout(
&self,
session: &RenderSession,
zoom: f32,
position: Point,
field: Range<usize>,
) -> Result<FieldLayout, Error> {
self.check(session, zoom)?;
translated_bounds(position, Size::ZERO)?;
if field.start > field.end || self.source.get(field.clone()).is_none() {
return Err(Error::InvalidFieldRange);
}
let mut result = FieldLayout {
rectangles: vec![],
covered: vec![],
truncated: vec![],
unresolved: vec![],
partially_retained: false,
shared_cluster: false,
};
let mut selected = vec![false; self.clusters.len()];
for span in &self.source_spans {
if span.whitespace || !overlaps(&span.source, &field) {
continue;
}
// Source spans for text are exact UTF-8 scalars, not intervals
// between ends (which could assign trimmed whitespace to text).
if span.normalized.end > self.retained_normalized {
append_range(&mut result.truncated, span.source.clone());
continue;
}
let matching: Vec<_> = self
.clusters
.iter()
.enumerate()
.filter(|(_, cluster)| overlaps(&cluster.normalized, &span.normalized))
.collect();
result.shared_cluster |= matching.iter().any(|(_, cluster)| {
cluster.normalized.end > self.retained_normalized
|| self.source_spans.iter().any(|other| {
overlaps(&other.normalized, &cluster.normalized)
&& !overlaps(&other.source, &field)
})
});
let issue = if span.non_painting {
Some(FieldIssue::NonPaintingScalar)
} else if matching.iter().any(|(_, cluster)| cluster.missing) {
Some(FieldIssue::MissingGlyph)
} else if matching.is_empty()
|| matching
.iter()
.all(|(_, cluster)| cluster.rectangles.is_empty())
{
Some(FieldIssue::NoAdvanceGeometry)
} else {
None
};
if let Some(reason) = issue {
result.unresolved.push(UnresolvedField {
source: span.source.clone(),
reason,
});
continue;
}
append_range(&mut result.covered, span.source.clone());
for (index, _) in matching {
selected[index] = true;
}
}
for (cluster, selected) in self.clusters.iter().zip(selected) {
if !selected {
continue;
}
for bounds in &cluster.rectangles {
let translated = translated_bounds(
Point::new(position.x + bounds.x, position.y + bounds.y),
bounds.size(),
)?;
if !result.rectangles.contains(&translated) {
result.rectangles.push(translated);
}
}
}
result.partially_retained = !result.truncated.is_empty()
&& (!result.covered.is_empty() || !result.unresolved.is_empty());
Ok(result)
}
}
@@ -64,7 +64,7 @@ pub(super) struct Plan {
pub(super) frames: BTreeMap<Id, Rectangle>,
pub(super) scopes: BTreeMap<Id, (f32, f32)>,
pub(super) height: f32,
pub(super) diagnostics: Vec<Diagnostic>,
diagnostics: Vec<Diagnostic>,
}
pub(super) fn occurrence(p: &Project, id: Id) -> Option<&OccurrenceBody> {
@@ -1,31 +0,0 @@
# Unwired Scenario label field experiment
This experiment starts from `c4a2cf63f11818cf7fc766acf3a2779768a2a658`. Initial extraction is commit `c3ad6f130ba6dda271fe8417db46df29e4033ad8`; the follow-up strengthens its evaluators. Neither version wires `scenario_label` into production. No renderer, App, navigation, source language, or model behavior is adopted here.
The implementation lives in `crates/oa-desktop/src/behavior/scenario_label.rs`, with focused evaluators in `scenario_label/field_tests.rs`. It preserves the winning shaped buffer's cluster advance rectangles and exact scalar source mapping. Returned covered, truncated, and unresolved ranges are distinct; partial retention and shared clusters are explicit. Synthetic ellipsis never represents source text. Missing glyphs, controls/default-ignorables, and absent advance geometry cannot establish affirmative coverage. These are advance/hit rectangles, not ink bounds or proof of actual viewport visibility.
## Follow-up evaluator corrections
The original mixed bidi fixture is Latin-leading. Its glyph embedding levels are mixed, but `LayoutRun::rtl` is false, so it cannot exercise Iced's RTL paragraph alignment branch. Two added cases require a genuinely RTL-leading full and ellipsized paragraph and assert `run.rtl == true`. Their geometry oracle builds a separate Iced Paragraph using the actual displayed string and compares the **complete rectangle set**, rejecting omissions, extras and duplicate output boxes. Explicit source word spans are clipped only against the literal displayed prefix before ellipsis; no candidate retained-source map or cluster snapshot supplies the expected answer. The existing mixed-direction case now uses the same complete-set comparison in addition to its visual-gap checks.
The relevant pinned sources are `iced_graphics 0.14.0/src/text.rs:202–256` (measurement and RTL alignment), `src/text/cache.rs` (winning buffer), and `cosmic-text 0.15.0/src/buffer.rs`/`layout.rs` (actual layout runs and clusters). `iced_widget` is 0.14.2; the graphics package is 0.14.0. Reproduce package inputs through the base commit's Cargo.lock.
## Font and execution limitations
At source 11c605f9170eae461913410f83f333e9314714a5, the isolated harness compiled and its default-test diagnostic reported 21 passed, two failed and two ignored. The intended first listing accidentally executed tests; a later literal listing reported all 25. A separate serial normal run reproduced the same two failures before either reached field_layout: the host font did not meet the tests' exact ffi-cluster preconditions. No actual face identity was captured for those failed cases, so the failure must not be attributed to a guessed family. Parent-owned closed runner receipts are the execution authority; this note does not turn the failed diagnostic into a passing gate.
The correction uses an unmodified, byte-pinned Noto Sans fixture from cosmic-text 0.15.0 for exactly those two tests; see [fixture source, hashes and license](../../../crates/oa-desktop/src/behavior/scenario_label/fixtures/README.md). Standard liga contains the required ffi substitution. Each test verifies the actual Paragraph face bytes and retains its positive nonzero ffi-cluster precondition. The partial-field case compares the complete shared rectangle; the Auto case also requires three initial Basic clusters followed by the actual Advanced final-buffer rectangle set. Neither infers successful geometry merely from a shaping enum.
The two fixture-loading tests are ignored by default because their isolated setup replaces the global font database. Run each as the sole exact test in a fresh process: --ignored --exact <actual-listed-name> --nocapture --test-threads=1. Do not run all ignored tests together. This prevents ordinary/default parallel test execution from invalidating render sessions. Their leaf names are advanced_ligature_partial_field_uses_whole_shared_cluster_not_fraction and auto_ascii_to_ellipsis_advanced_transition_uses_final_buffer. The existing font-load invalidation test remains separately isolated.
Other cases retain installed system-font selection and explicit font/cluster/coverage preconditions. RTL font IDs, PostScript names and family records are diagnostic metadata, not portable content hashes. No new dependency or production font policy is introduced. A missing precondition remains an evaluator/environment finding, not a geometry pass.
After this correction the field module contains ten normal tests and three ignored tests (two isolated ligature cases plus the lookup diagnostic). Across the parent label module the intended inventory remains 25, now 21 normal and four ignored. The corrected source is **UNEXECUTED** at handoff. The parent module remains unwired; ordinary desktop listing does not include it without the isolated evaluator harness. Source review is not compilation or execution evidence.
## Optional bounded lookup diagnostic
Ignored leaf name: `field_lookup_4096_scalars_and_combining_heavy_full_coverage`. Run only this exact test, once an isolated compiled harness exists, with `--ignored --exact <actual-listed-name> --nocapture --test-threads=1`; obtain the qualified name from its real listing. Set `SCENARIO_LABEL_FIELDS_SOURCE_PIN` to the tested commit and separately bind the executable, source and toolchain in the runner receipt.
It measures one resolver call and three full-field lookups for each of two cases: 4,096 ordinary scalars/graphemes, and 4,096 scalars arranged as 1,024 combining-heavy graphemes. Both remain within the existing 64-KiB source/4,096-grapheme experiment budgets. An independent Paragraph warms the font machinery before timing, checks glyph coverage and supplies the complete expected rectangle set. Every lookup must cover the full original source, retain no unresolved/truncated ranges, and match that set exactly; its invariants are checked outside the timed interval.
On success it prints `FIELD_LOOKUP_TIMING_JSON=` with schema `scenario_label_field_lookup_v1`, per-case counts/font identities/resolver nanoseconds/three lookup samples, profile/OS/architecture, optional runner pin, and an explicit passed invariant status. It has no latency threshold and makes no native responsiveness claim. No optimization has been attempted before measurement. The combining case stresses clustered source mapping, while the plain case reaches the existing grapheme budget; neither claims exhaustive worst-case performance over every permitted 64-KiB input.
@@ -1,26 +0,0 @@
# Indexed field lookup experiment
This unwired experiment extends source `4c9bc87e4e66bba573dd63b23df5ea039f85d0ca`. It does not adopt measured labels or field navigation in the renderer. This revision has **not been compiled or executed**. The baseline debug diagnostic reported roughly 2.4–6.6 seconds for a 4096-scalar plain field and 1.3–1.9 seconds for a 4096-scalar combining-heavy field; these are motivation, not results for this patch.
`Label` now stores an overlap index built from the winning shaped buffer's clusters and the existing ordered, disjoint normalized scalar spans. For S spans, C clusters, and I actual span/cluster overlap memberships, index construction takes O(C log S + I) work and O(S + C + I) storage. A lookup visits the source spans and their indexed matches, then emits selected cluster rectangles in the original cluster/rectangle order. Hash membership replaces repeated linear rectangle searches. Signed zeros share a deduplication key, as with `Rectangle::PartialEq`, while the first original rectangle's bits remain unchanged. Hash iteration never determines output order.
Per-cluster source end/start extrema preserve the old shared-cluster predicate, including whitespace and nonpainting spans. Source scalar overlap, truncation, missing-glyph and nonpainting precedence, partial/shared flags, invalid-range errors, session/font/zoom guards, and position/overflow rejection are unchanged. No new length limit is introduced. Index storage can be dense for intentionally overlapping synthetic clusters. Existing shaping and `field_clusters` extraction are unchanged, including that extractor's per-cluster linear rectangle deduplication; this is not a claim of globally linear shaping or preparation.
The test-only `Label::original_field_layout` retains the baseline method body verbatim. Four new normal tests compare every `FieldLayout` field and every rectangle's exact component bits and position in the output:
- Real Auto/Advanced shaping at two zooms and three widths, over every legal UTF-8 boundary pair, including scalar boundaries inside combining graphemes.
- Overlapping, reordered, whitespace-spanning, missing, empty and reversed cluster ranges; partial retention and nonpainting/coverage precedence.
- First-occurrence signed-zero bits, shared clusters and truncation.
- Guard/error precedence, malformed fields, nonfinite positions and overflow.
The existing ignored `field_lookup_4096_scalars_and_combining_heavy_full_coverage` diagnostic retains its two inputs and independent Paragraph coverage/rectangle oracle. It now times the original lookup separately, three indexed queries on the retained label, and three fresh-cache resolve-plus-lookup operations. Exact old/new results and independent complete rectangle sets are checked outside timed intervals. The original lookup precedes indexed samples; font caches are warm. These are debug experiment measurements, not a latency guarantee or a cold-process benchmark. Fresh resolution includes index construction so its cost cannot disappear into an unmeasured preprocessing step.
The isolated harness should list 29 tests: 25 normal and four ignored. The production desktop does not register this module. Reuse the explicit dependency-bound harness recipe for the baseline, replacing its source binding with this revision and adding `scenario_label/lookup_tests.rs` to the input closure. Required execution is the normal suite plus these three ignored tests, each in a fresh process:
```text
scenario_label::field_tests::advanced_ligature_partial_field_uses_whole_shared_cluster_not_fraction
scenario_label::field_tests::auto_ascii_to_ellipsis_advanced_transition_uses_final_buffer
scenario_label::tests::actual_font_load_rejects_retained_label_and_old_session
```
Run the timing diagnostic separately with `--exact scenario_label::field_tests::field_lookup_4096_scalars_and_combining_heavy_full_coverage --ignored --nocapture --test-threads=1`. It remains optional functional-gate evidence; its exact full-coverage assertions are not waived. The new differential filter is `scenario_label::lookup_tests::` (four tests). The pinned-font checks retain their existing isolated-process contract. Other real-shaping differential cases use the current system default font and compare both methods on the same resolved buffer; they do not establish cross-machine glyph identity.