Compare commits

..
27 changed files with 1038 additions and 1666 deletions
+38 -1
View File
@@ -10,6 +10,8 @@ mod hosted;
mod reference_authoring;
#[cfg(test)]
mod review_navigation_tests;
#[cfg(test)]
mod scenario_details_tests;
mod scenario_diagram;
mod scenario_spacing;
pub(crate) mod source_rename;
@@ -1302,6 +1304,21 @@ impl App {
{
return Task::none();
}
// A retained Details button may belong to an earlier selection or
// canvas epoch. Refuse it before retiring any newer reveal or draft.
if let behavior::scenario::CanvasEvent::Properties(_, id) = event
&& (self.scenario_context() != Some(captured)
|| self.selected != *id
|| !self.project().contains(*id)
|| !behavior::scenario::properties_target(self.project(), captured, *id)
|| self.behavior.has_pending()
|| self.draft_dirty()
|| self.source_dirty()
|| self.source_rename.open()
|| !behavior::canvas_workspace::keyboard_enabled(self))
{
return Task::none();
}
}
if let Message::BehaviorControl(intent) = &message
&& behavior::canvas_workspace::Scope::current(self).is_none_or(|scope| {
@@ -2026,6 +2043,11 @@ impl App {
if checked_owner(self.project(), requested) != Some(context.scenario) {
return Task::none();
}
// An explicitly selected current view record follows
// the arrangement picker, as with the Diagram picker.
// Independent occurrence/lifeline selection stays put.
let follow_view = matches!(context.representation,
Representation::Saved { diagram } if self.selected == diagram);
if !self.apply() {
return Task::none();
}
@@ -2043,7 +2065,15 @@ impl App {
},
other => other,
};
self.enter_scenario_representation(requested);
if self.enter_scenario_representation(requested) && follow_view {
self.selected = match requested {
Representation::Saved { diagram } => diagram,
// Automatic has no Diagram record; its Scenario
// owner is the corresponding inspectable target.
Representation::Derived { owner } => owner,
};
self.refresh_draft();
}
}
CanvasEvent::Focus(_) => {
self.behavior.scenario.toggle_focus();
@@ -2053,6 +2083,13 @@ impl App {
self.behavior.scenario.toggle_shelf(shelf);
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
CanvasEvent::Properties(_, _) => {
// The checked action opens the current record only: no
// select()/Apply side effect or representation change.
self.behavior.scenario.show_properties();
self.inspector_tab = crate::navigation::InspectorTab::Properties;
self.canvas_epoch = self.canvas_epoch.wrapping_add(1);
}
CanvasEvent::Zoom(_, scale) => {
let mut state = std::mem::take(&mut self.behavior.scenario);
if state.camera_zoom(self.project(), context.scenario, scale) {
@@ -1029,10 +1029,9 @@ fn repeated_preview_arrows_select_the_relation_and_highlight_the_exact_caller_li
let camera = app.behavior.topology.camera_boundary();
if call == calls[1]
&& let Some((previous_call, previous)) = &previous_camera
&& *previous_call != call
{
if *previous_call != call {
assert!(&camera != previous);
}
assert!(&camera != previous);
}
if let Some(epoch) = previous_epoch {
assert_ne!(app.canvas_epoch, epoch);
@@ -1375,7 +1374,7 @@ fn whole_surface_camera_fits_huge_extent_while_target_camera_remains_readable()
};
let viewport = iced::Size::new(800., 500.);
let (zoom, pan) = usage::camera_for(&Target::Whole, bounds, viewport);
assert!(zoom < 0.05 && zoom >= 0.0001);
assert!((0.0001..0.05).contains(&zoom));
assert!(bounds.width * zoom <= viewport.width - 64. + 0.01);
assert!(bounds.height * zoom <= viewport.height - 64. + 0.01);
assert!((bounds.center_x() * zoom + pan.x - viewport.width / 2.).abs() < 0.01);
@@ -0,0 +1,281 @@
//! Actual arrangement selection and current-record Details admission.
use super::*;
use crate::behavior::canvas_workspace::tests::Mounted;
use crate::behavior::scenario::{CanvasEvent, Context, Shelf};
use crate::behavior::scenario_layout::Representation;
use iced::{Point, Size, advanced::widget};
const FIXTURE: &str = include_str!("diagram_usages/tests/saved_scenario.arcadia");
fn id(app: &App, alias: &str) -> Id {
app.project()
.identities()
.into_iter()
.find(|(_, name)| *name == alias)
.unwrap()
.0
}
fn setup() -> (App, Id, Id, Id) {
let mut app = App::with_project(oa_core::language::parse(FIXTURE).unwrap());
let a = id(&app, "incident_readable");
let b = id(&app, "incident_wide");
let owner = id(&app, "incident_response");
let _ = app.update(Message::Select(owner));
let _ = app.update(Message::Page(Page::Behavior));
choose(&mut app, Representation::Saved { diagram: a });
let _ = app.update(Message::Select(a));
app.window_size = Size::new(1440., 1000.);
(app, a, b, owner)
}
fn send(app: &mut App, event: impl FnOnce(Context) -> CanvasEvent) {
let context = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(event(context)));
}
fn choose(app: &mut App, representation: Representation) {
send(app, |context| {
CanvasEvent::Representation(context, representation)
});
}
fn model_state(app: &App) -> (u64, bool, bool, bool) {
(
app.document.revision(),
app.document.dirty(),
app.document.can_undo(),
app.document.can_redo(),
)
}
#[tokio::test]
async fn actual_arrangement_picker_follows_selected_saved_record_and_opens_b_properties() {
let (mut app, a, b, _) = setup();
let mut mounted = Mounted::new(&mut app).await;
let snapshot = app.document.snapshot();
let before = model_state(&app);
let captured = app.scenario_context().unwrap();
let picker = mounted.geometry(&app).bounds("scenario-arrangement-picker");
assert!(
app.window_size.height - (picker.y + picker.height) > picker.y,
"fixture has room for Iced's menu below the actual picker"
);
assert_eq!(app.selected, a);
mounted.click(&mut app, picker.center()).await;
// iced_widget 0.14.2 overlay/menu.rs uses default line height plus
// vertical padding for each row. The real workspace orders Automatic,
// then the fixture's A/B/C Diagram IDs. Select B from the actual overlay.
let row_height =
f32::from(iced::advanced::text::LineHeight::default().to_absolute(12.into())) + 10.;
let b_row = Point::new(
picker.center_x(),
picker.y + picker.height + row_height * 2.5,
);
assert!(b_row.y < app.window_size.height);
let events = mounted.click(&mut app, b_row).await;
assert!(events.iter().any(|event| matches!(event,
Message::ScenarioCanvas(CanvasEvent::Representation(context, Representation::Saved { diagram }))
if *context == captured && *diagram == b)), "must exercise the actual arrangement callback");
assert_eq!(app.selected, b);
assert_eq!(app.draft.as_ref().unwrap().original, b);
assert_eq!(
app.draft.as_ref().unwrap().value["name"],
"B - Incident review negative and far"
);
assert_eq!(app.active_diagram, Some(b));
assert_eq!(
app.scenario_context().unwrap().representation,
Representation::Saved { diagram: b }
);
assert_ne!(app.scenario_context().unwrap().visit, captured.visit);
send(&mut app, CanvasEvent::Focus);
send(&mut app, |context| {
CanvasEvent::Shelf(context, Shelf::Selection)
});
mounted.settle(&mut app).await;
let geometry = mounted.geometry(&app);
let (details, offset) = geometry.scrolls[&widget::Id::new("scenario-details")];
let point = geometry.bounds("scenario-properties").center() - offset;
assert!(details.contains(point));
let events = mounted.click(&mut app, point).await;
assert!(events.iter().any(|event| matches!(event,
Message::ScenarioCanvas(CanvasEvent::Properties(_, selected)) if *selected == b)));
mounted.settle(&mut app).await;
let geometry = mounted.geometry(&app);
let (inspector, offset) = geometry.scrolls[&widget::Id::new("inspector")];
assert!(
geometry
.text_inputs
.iter()
.any(|bounds| inspector.contains(bounds.center() - offset)),
"current B Properties must expose an actual editable field"
);
assert!(!app.behavior.scenario.focused());
assert!(
!geometry
.scrolls
.contains_key(&widget::Id::new("scenario-details"))
);
assert_eq!(
app.inspector_tab,
crate::navigation::InspectorTab::Properties
);
assert_eq!(app.selected, b);
assert_eq!(app.draft.as_ref().unwrap().original, b);
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.project(), &snapshot.decoded.project);
assert_eq!(app.document.bundle(), &snapshot.bundle);
assert_eq!(model_state(&app), before);
}
#[test]
fn arrangement_change_preserves_independent_semantic_and_foreign_view_selection() {
for alias in [
"initial_report",
"reporter",
"incident_response",
"incident_repair",
] {
let (mut app, _, b, _) = setup();
let selected = id(&app, alias);
let _ = app.update(Message::Select(selected));
let snapshot = app.document.snapshot();
let before = model_state(&app);
choose(&mut app, Representation::Saved { diagram: b });
assert_eq!(app.selected, selected, "independent selection {alias}");
assert_eq!(app.draft.as_ref().unwrap().original, selected);
assert_eq!(app.active_diagram, Some(b));
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &snapshot.bundle);
assert_eq!(model_state(&app), before);
if alias == "incident_repair" {
assert!(!behavior::scenario::properties_target(
app.project(),
app.scenario_context().unwrap(),
selected
));
}
}
}
#[test]
fn arrangement_follows_view_record_to_automatic_owner_but_not_owner_back_to_saved() {
let (mut app, _, b, owner) = setup();
let snapshot = app.document.snapshot();
let before = model_state(&app);
choose(&mut app, Representation::Derived { owner });
assert_eq!(app.selected, owner);
assert_eq!(app.draft.as_ref().unwrap().original, owner);
assert_eq!(app.active_diagram, None);
assert!(behavior::scenario::properties_target(
app.project(),
app.scenario_context().unwrap(),
owner
));
choose(&mut app, Representation::Saved { diagram: b });
assert_eq!(
app.selected, owner,
"Scenario owner is now independent semantic selection"
);
assert_eq!(app.draft.as_ref().unwrap().original, owner);
assert_eq!(app.active_diagram, Some(b));
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &snapshot.bundle);
assert_eq!(model_state(&app), before);
}
#[test]
fn arrangement_applies_only_the_old_view_draft_then_follows_b_with_one_undo() {
let (mut app, a, b, _) = setup();
let snapshot = app.document.snapshot();
let mut expected = app.project().clone();
expected.diagrams.get_mut(&a).unwrap().name = "Reviewed A".into();
let revision = app.document.revision();
let _ = app.update(Message::Field("/name".into(), "Reviewed A".into()));
choose(&mut app, Representation::Saved { diagram: b });
assert_eq!(app.project(), &expected);
assert_eq!(app.selected, b);
assert_eq!(app.draft.as_ref().unwrap().original, b);
assert!(!app.draft_dirty());
assert_eq!(app.document.revision(), revision + 1);
let accepted = app.document.snapshot();
let _ = app.update(Message::Undo);
assert_eq!(app.project(), &snapshot.decoded.project);
assert_eq!(app.document.bundle(), &snapshot.bundle);
assert!(!app.document.can_undo() && app.document.can_redo());
let _ = app.update(Message::Redo);
assert_eq!(app.project(), &expected);
assert_eq!(app.document.bundle(), &accepted.bundle);
assert!(app.document.can_undo() && !app.document.can_redo());
}
#[test]
fn same_arrangement_uuid_edit_follows_the_reidentified_record_and_round_trips_source() {
let (mut app, a, _, _) = setup();
let snapshot = app.document.snapshot();
let replacement = Id::parse_str("70200000-0000-4000-8000-000000000099").unwrap();
let mut expected = app.project().clone();
let mut diagram = expected.diagrams.remove(&a).unwrap();
diagram.id = replacement;
expected.diagrams.insert(replacement, diagram);
let _ = app.update(Message::Field("/id".into(), replacement.to_string()));
choose(&mut app, Representation::Saved { diagram: a });
assert_eq!(app.project(), &expected);
assert_eq!(app.selected, replacement);
assert_eq!(app.draft.as_ref().unwrap().original, replacement);
assert_eq!(app.active_diagram, Some(replacement));
assert_eq!(
app.scenario_context().unwrap().representation,
Representation::Saved {
diagram: replacement
}
);
let accepted = app.document.snapshot();
let _ = app.update(Message::Undo);
assert_eq!(app.project(), &snapshot.decoded.project);
assert_eq!(app.document.bundle(), &snapshot.bundle);
assert!(!app.document.can_undo() && app.document.can_redo());
let _ = app.update(Message::Redo);
assert_eq!(app.project(), &expected);
assert_eq!(app.document.bundle(), &accepted.bundle);
assert!(!app.document.can_redo());
}
#[test]
fn invalid_draft_and_stale_arrangement_preserve_selection_inputs_and_accepted_state() {
let (mut app, a, b, _) = setup();
let old = app.scenario_context().unwrap();
let snapshot = app.document.snapshot();
let before = model_state(&app);
let _ = app.update(Message::Field("/id".into(), "not-a-uuid".into()));
let draft_value = app.draft.as_ref().unwrap().value.clone();
choose(&mut app, Representation::Saved { diagram: b });
assert_eq!(app.selected, a);
assert_eq!(app.active_diagram, Some(a));
assert_eq!(
app.scenario_context().unwrap().representation,
old.representation
);
assert_eq!(app.draft.as_ref().unwrap().value, draft_value);
assert_eq!(app.draft.as_ref().unwrap().inputs["/id"].raw, "not-a-uuid");
assert!(app.draft_dirty());
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(model_state(&app), before);
let _ = app.update(Message::RevertProperties);
choose(&mut app, Representation::Saved { diagram: b });
let current = app.scenario_context().unwrap();
let _ = app.update(Message::Field("/name".into(), "Retained B input".into()));
let selected = app.selected;
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Representation(
old,
Representation::Saved { diagram: a },
)));
assert_eq!(app.selected, selected);
assert_eq!(app.active_diagram, Some(b));
assert_eq!(app.scenario_context().unwrap().visit, current.visit);
assert_eq!(
app.draft.as_ref().unwrap().inputs["/name"].raw,
"Retained B input"
);
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &snapshot.bundle);
assert_eq!(model_state(&app), before);
}
@@ -62,7 +62,7 @@ impl App {
// 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) {
match self.document.execute(*command) {
Ok(_) => {
self.selected = selected;
self.selected_node = None;
+2 -1
View File
@@ -684,7 +684,7 @@ mod scenario_scroll {
.collect::<Vec<_>>();
assert_eq!(
actual,
vec![if change < 2 || change >= 4 {
vec![if !(2..4).contains(&change) {
Vector::ZERO
} else {
Vector::new(0., 180.)
@@ -1314,6 +1314,7 @@ impl SequenceInput {
}
}
impl Scene {
#[cfg(test)]
fn sequence(p: &Project, owner: Id, selected: Id) -> Self {
Self::sequence_geometry(p, owner, selected, None, None)
}
@@ -18,6 +18,14 @@ mod workspace;
pub(crate) use workspace::NAME_INPUT;
pub use workspace::{Shelf, view};
// A picker may select the Saved diagram record itself. Another view of the
// same Scenario is not the property target of this displayed representation.
pub(crate) fn properties_target(p: &Project, context: Context, id: Id) -> bool {
super::selected_behavior(p, id) == Some(context.scenario)
|| matches!(context.representation, Representation::Saved { diagram } if diagram == id)
&& presentation::checked_owner(p, context.representation) == Some(context.scenario)
}
#[cfg(test)]
#[path = "scenario_operation_tests.rs"]
mod operation_tests;
@@ -116,6 +124,7 @@ pub enum CanvasEvent {
Camera(Context, u64, super::canvas_workspace::Event),
Focus(Context),
Shelf(Context, Shelf),
Properties(Context, Id),
OpenUse(Context, Id),
Back(Context),
Choose(Context, CanvasTool),
@@ -157,6 +166,7 @@ impl CanvasEvent {
| Self::Camera(context, ..)
| Self::Focus(context)
| Self::Shelf(context, _)
| Self::Properties(context, _)
| Self::OpenUse(context, _)
| Self::Back(context)
| Self::Choose(context, _)
@@ -501,6 +511,12 @@ impl State {
pub(crate) fn toggle_shelf(&mut self, shelf: Shelf) {
self.presentation.shelf = (self.presentation.shelf != Some(shelf)).then_some(shelf);
}
pub(crate) fn show_properties(&mut self) {
// Properties belong to the inspector. Restore that panel and dismiss
// the competing outline without replacing this view or its camera.
self.presentation.focused = false;
self.presentation.shelf = None;
}
pub(crate) fn open_use(
&mut self,
p: &Project,
@@ -183,8 +183,9 @@ mod tests {
#[test]
fn tiny_fit_zoom_in_out_preserves_pointer_world_anchor_without_floor_jump() {
let viewport = Some(Size::new(700., 500.));
let start = fit(bounds(), viewport.unwrap()).unwrap();
let size = Size::new(700., 500.);
let viewport = Some(size);
let start = fit(bounds(), size).unwrap();
let (mut pan, mut zoom, mut fitting) = (Vector::ZERO, None, true);
let at = Point::new(210., 180.);
let world = Point::new(
@@ -218,7 +219,8 @@ mod tests {
#[test]
fn pan_leaves_fit_from_displayed_position_and_zero_motion_preserves_fit() {
let viewport = Some(Size::new(700., 500.));
let size = Size::new(700., 500.);
let viewport = Some(size);
let (mut pan, mut zoom, mut fitting) = (Vector::ZERO, None, true);
for event in [
Event::Pan(Vector::ZERO),
@@ -238,7 +240,7 @@ mod tests {
));
assert_eq!((pan, zoom, fitting), (Vector::ZERO, None, true));
}
let start = fit(bounds(), viewport.unwrap()).unwrap();
let start = fit(bounds(), size).unwrap();
assert!(change(
&mut pan,
&mut zoom,
@@ -188,28 +188,93 @@ fn complete_fallback_scene_selects_but_cannot_capture_or_finish_coordinate_gestu
);
assert!(input.press.is_none() && input.source.is_none());
}
// A gesture already captured in a Ready frame is cancelled when capability is revoked.
scene.coordinate_input = true;
scene.interaction = Some((context, CanvasTool::Select, true));
// Capture from an actual Ready presentation, then revoke coordinate input
// with the complete fallback frame of the same Saved representation.
let Representation::Saved { diagram } = rep else {
unreachable!()
};
let mut ready_project = f.project.clone();
ready_project.diagrams.get_mut(&diagram).unwrap().layout =
Some(DiagramLayout::Scenario(ScenarioLayout::default()));
let ready_original = ready_project.clone();
let ready = state.display(&ready_project, f.owner, f.call).unwrap();
assert!(matches!(
ready.status(),
presentation::PresentationStatus::Ready
));
let mut ready_scene = ready.into_scene().unwrap();
let line = ready_scene
.lines
.iter()
.find(|line| line.id == f.call)
.unwrap();
let ready_point = Point::new(
(line.points[0].x + line.points.last().unwrap().x) / 2.,
line.points[0].y,
);
let hit = ready_scene.hit_item(ready_point).unwrap();
assert_eq!(hit.id, f.call);
assert_eq!(hit.role, SceneHitRole::MessageBody);
let stamp = spacing::Stamp {
context,
camera_epoch: 17,
};
ready_scene.coordinate_input = true;
ready_scene.interaction = Some((context, CanvasTool::Select, true));
ready_scene.spacing_stamp = Some(stamp);
let mut input = SequenceInput::default();
let _ = canvas::Program::update(
&scene,
let begin = canvas::Program::update(
&ready_scene,
&mut input,
&canvas::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
bounds,
mouse::Cursor::Available(point),
);
assert!(input.press.is_some());
scene.coordinate_input = false;
mouse::Cursor::Available(ready_point),
)
.and_then(|action| action.into_inner().0)
.unwrap();
let Message::ScenarioCanvas(CanvasEvent::Spacing(spacing::Event::Begin {
stamp: captured_stamp,
token,
target: spacing::Target::Message(target),
..
})) = begin
else {
panic!("Ready Saved message must begin a stamped spacing gesture");
};
assert_eq!(captured_stamp, stamp);
assert_eq!(target, f.call);
assert!(matches!(input.press, Some(SequencePress::Spacing {
stamp: held_stamp, token: held_token
}) if held_stamp == stamp && held_token == token));
scene.interaction = Some((context, CanvasTool::Select, true));
assert!(!scene.coordinate_input && scene.spacing_stamp.is_none());
let release = canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left));
let result = canvas::Program::update(
&scene,
&mut input,
&canvas::Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
&release,
bounds,
mouse::Cursor::Available(point),
mouse::Cursor::Available(ready_point),
)
.and_then(|action| action.into_inner().0);
assert!(
matches!(result, Some(Message::ScenarioCanvas(CanvasEvent::Spacing(
spacing::Event::Cancel { stamp: cancelled_stamp, token: cancelled_token }
))) if cancelled_stamp == stamp && cancelled_token == token)
);
assert!(result.and_then(|action| action.into_inner().0).is_none());
assert!(input.press.is_none());
assert!(input.press.is_none() && input.source.is_none());
assert!(
canvas::Program::update(
&scene,
&mut input,
&release,
bounds,
mouse::Cursor::Available(ready_point),
)
.and_then(|action| action.into_inner().0)
.is_none()
);
assert_eq!(ready_project, ready_original);
assert_eq!(f.project, original);
}
@@ -89,7 +89,7 @@ pub(crate) enum Finish {
Click(Id),
Noop,
Commit {
command: Command,
command: Box<Command>,
selected: Id,
scale: f32,
pan: Vector,
@@ -285,7 +285,7 @@ impl State {
Ok(match session.preview {
None => Finish::Noop,
Some(preview) => Finish::Commit {
command: preview.command,
command: Box::new(preview.command),
selected: session.drag.target.id(),
scale: session.scale,
pan: session.pan,
@@ -328,3 +328,94 @@ fn zoomed_out_message_tolerance_matches_actual_canvas_hit() {
state.begin_spacing(doc.project(), event).unwrap();
assert_eq!(state.spacing_token(), Some(token));
}
#[test]
fn fractional_screen_packet_preserves_subpixel_motion_in_preview_and_finish() {
let (doc, owner, diagram, _, message) = fixture();
let original = doc.snapshot();
assert!(doc.project().diagrams[&diagram].layout.is_none());
let mut state = State::default();
let document = Id::new_v4();
state.enter_representation(document, owner, Representation::Saved { diagram });
state.presentation.viewport = Some(Size::new(900., 600.));
state.presentation.fit = false;
state.presentation.zoom = Some(0.5);
// 406 + 2^-15 puts the press just below the 512 screen-coordinate boundary.
state.presentation.pan = Vector::new(0., f32::from_bits(0x43cb_0001));
let camera = state.camera_boundary();
let context = state.context(document, owner, doc.revision(), 4).unwrap();
let baseline = resolve(doc.project(), context.representation, message).unwrap();
let line = baseline
.scene
.lines
.iter()
.find(|line| line.id == message)
.unwrap();
assert_eq!(line.points[0].y, 148.);
let begin = packet(doc.project(), &state, context, 9, Target::Message(message));
let Event::Begin {
press_screen,
canvas_bounds,
scale,
pan,
..
} = begin
else {
unreachable!()
};
assert_eq!(canvas_bounds.y, 23.);
assert_eq!(scale, 0.5);
assert_eq!(pan.y.to_bits(), 0x43cb_0001);
assert_eq!(press_screen.y.to_bits(), 0x43fb_8001); // 503 + 2^-15.
let end = press_screen + Vector::new(0., 10.);
assert_eq!(end.y, 513.);
assert!(canvas_bounds.contains(press_screen) && canvas_bounds.contains(end));
// The submitted f32 displacement is 10 - 2^-15, not exactly 10.
assert_eq!((end.y - press_screen.y).to_bits(), 0x411f_ffe0);
assert_eq!(((end.y - press_screen.y) / scale).to_bits(), 0x419f_ffe0);
// Independent oracle: 148 + (10 - 2^-15) / .5 = 168 - 2^-14.
let expected_y = f32::from_bits(0x4327_fffc);
let mut expected = original.decoded.project.clone();
expected.diagrams.get_mut(&diagram).unwrap().layout =
Some(oa_core::DiagramLayout::Scenario(oa_core::ScenarioLayout {
lanes: vec![],
messages: vec![oa_core::ScenarioMessagePosition {
address: oa_core::OccurrenceEndpoint {
references: vec![],
occurrence: message,
},
send_y: expected_y,
}],
}));
state.begin_spacing(doc.project(), begin).unwrap();
state.move_spacing(end);
let preview = state.spacing.as_ref().unwrap().preview.as_ref().unwrap();
assert_eq!(preview.project, expected);
let line = preview
.geometry
.scene
.lines
.iter()
.find(|line| line.id == message)
.unwrap();
assert_eq!(line.points[0].y.to_bits(), expected_y.to_bits());
let Finish::Commit {
command,
selected,
scale,
pan,
} = state.finish_spacing(end).unwrap()
else {
panic!("fractional motion must remain a commit")
};
assert_eq!(selected, message);
assert_eq!(scale, 0.5);
assert_eq!(pan.y.to_bits(), 0x43cb_0001);
let committed = oa_core::execute_batch(doc.project(), &[*command]).unwrap();
assert_eq!(committed, expected);
assert!(state.spacing_token().is_none());
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());
}
@@ -10,10 +10,10 @@ fn add_occurrence(p: &mut Project, owner: Id, name: &str, body: OccurrenceBody)
precondition: String::new(),
postcondition: String::new(),
};
if let Some(steps) = p.elements.get_mut(&owner).unwrap().steps_mut() {
if !steps.contains(&id) {
steps.push(id);
}
if let Some(steps) = p.elements.get_mut(&owner).unwrap().steps_mut()
&& !steps.contains(&id)
{
steps.push(id);
}
id
}
@@ -262,13 +262,20 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
.find(|choice| choice.representation == context.representation)
.cloned();
header = header.push(
pick_list(choices, selected, move |choice: ArrangementChoice| {
Message::ScenarioCanvas(CanvasEvent::Representation(context, choice.representation))
})
.placeholder("Choose arrangement")
.text_size(12)
.padding(5)
.width(Fill),
container(
pick_list(choices, selected, move |choice: ArrangementChoice| {
Message::ScenarioCanvas(CanvasEvent::Representation(
context,
choice.representation,
))
})
.placeholder("Choose arrangement")
.text_size(12)
.padding(5)
.width(Fill),
)
.width(Fill)
.id("scenario-arrangement-picker"),
);
}
if capabilities.geometry_navigation {
@@ -371,8 +378,12 @@ pub fn view<'a>(app: &'a App, owner: Id, out: Column<'a, Message>) -> Element<'a
);
let mut details = column![
text(format!("Selected: {}", p.named(app.selected))).size(12),
button(text("Properties").size(12))
.on_press_maybe(clean.then_some(Message::EditProperties(app.selected)))
container(button(text("Properties").size(12)).on_press_maybe(
(clean && properties_target(p, context, app.selected)).then_some(
Message::ScenarioCanvas(CanvasEvent::Properties(context, app.selected)),
),
))
.id("scenario-properties")
]
.spacing(6);
if referenced_scenario(p, owner, app.selected).is_some() {
@@ -922,6 +933,9 @@ mod tests;
#[cfg(all(test, debug_assertions))]
mod spacing_tests;
#[cfg(all(test, debug_assertions))]
mod details_tests;
fn sequence_rows<'a>(
p: &'a Project,
context: Context,
@@ -0,0 +1,443 @@
//! Mounted Scenario Details → inspector regression and retained-intent guards.
use super::*;
use crate::behavior::canvas_workspace::tests::Mounted;
use crate::behavior::scenario_layout::resolve;
use iced::advanced::widget;
use iced::{Vector, keyboard};
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
}
fn send(app: &mut App, event: impl FnOnce(Context) -> CanvasEvent) {
let context = app.scenario_context().unwrap();
let _ = app.update(Message::ScenarioCanvas(event(context)));
}
fn setup() -> (App, Id, 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 message = id(&app, "initial_report");
let _ = app.update(Message::Select(owner));
let _ = app.update(Message::Diagram(crate::app::Choice {
id: diagram,
label: "A".into(),
}));
send(&mut app, |c| CanvasEvent::Select(c, message));
app.window_size = Size::new(1440., 1000.);
(app, diagram, message)
}
fn open_focused_details(app: &mut App) {
if !app.behavior.scenario.focused() {
send(app, CanvasEvent::Focus);
}
if app.behavior.scenario.presentation.shelf.is_none() {
send(app, |c| CanvasEvent::Shelf(c, Shelf::Selection));
}
}
fn stored_camera(app: &App) -> (Vector, Option<f32>, bool) {
let p = &app.behavior.scenario.presentation;
(p.pan, p.zoom, p.fit)
}
#[tokio::test]
async fn focused_saved_details_opens_real_editable_inspector_and_returns_to_same_view() {
let (mut app, diagram, message) = setup();
let _ = app.update(Message::InspectorTab(
crate::navigation::InspectorTab::Connections,
));
let mut mounted = Mounted::new(&mut app).await;
open_focused_details(&mut app);
mounted.settle(&mut app).await;
let before = mounted.geometry(&app);
assert!(!before.scrolls.contains_key(&widget::Id::new("inspector")));
let (details, offset) = before.scrolls[&widget::Id::new("scenario-details")];
let button = before.bounds("scenario-properties").center() - offset;
assert!(
details.contains(button),
"Properties must be actually visible"
);
let context = app.scenario_context().unwrap();
let camera = stored_camera(&app);
let original = app.document.snapshot();
let bundle = app.document.bundle().clone();
let messages = mounted.click(&mut app, button).await;
assert!(messages.iter().any(|event| matches!(event,
Message::ScenarioCanvas(CanvasEvent::Properties(c, selected))
if *c == context && *selected == message)));
mounted.settle(&mut app).await;
assert!(!app.behavior.scenario.focused());
assert!(app.behavior.scenario.presentation.shelf.is_none());
assert_eq!(
app.inspector_tab,
crate::navigation::InspectorTab::Properties
);
assert_eq!(app.selected, message);
assert_eq!(app.active_diagram, Some(diagram));
assert_eq!(app.page, crate::app::Page::Behavior);
let current = app.scenario_context().unwrap();
assert_eq!(current.representation, context.representation);
assert_eq!(current.visit, context.visit);
assert_eq!(
stored_camera(&app),
camera,
"restoring panels retains camera intent"
);
assert!(Arc::ptr_eq(&original, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo() && !app.document.can_redo());
let shown = mounted.geometry(&app);
assert!(
!shown
.scrolls
.contains_key(&widget::Id::new("scenario-details"))
);
let (inspector, offset) = shown.scrolls[&widget::Id::new("inspector")];
assert!(inspector.width > 250. && inspector.height > 500.);
// Production Properties places Name before the other scalar text inputs.
// Account for the retained inspector scroll, rather than clicking content coordinates.
let input = shown
.text_inputs
.iter()
.map(|bounds| bounds.center() - offset)
.filter(|point| inspector.contains(*point))
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("visible editable property");
mounted.click(&mut app, input).await;
let typed = mounted
.batch(
&mut app,
&[iced::Event::Keyboard(keyboard::Event::KeyPressed {
key: keyboard::Key::Character("x".into()),
modified_key: keyboard::Key::Character("x".into()),
physical_key: keyboard::key::Physical::Unidentified(
keyboard::key::NativeCode::Unidentified,
),
location: keyboard::Location::Standard,
modifiers: keyboard::Modifiers::empty(),
text: Some("x".into()),
repeat: false,
})],
mouse::Cursor::Available(input),
)
.await;
assert!(
typed
.iter()
.any(|message| matches!(message, Message::Field(path, _) if path == "/name")),
"real Name editor must publish its edit: {typed:?}"
);
assert!(app.draft_dirty());
assert!(
Arc::ptr_eq(&original, &app.document.snapshot()),
"typing is only a draft"
);
let _ = app.update(Message::RevertProperties);
assert!(!app.draft_dirty());
send(&mut app, CanvasEvent::Focus);
mounted.settle(&mut app).await;
let returned = mounted.geometry(&app);
assert!(!returned.scrolls.contains_key(&widget::Id::new("inspector")));
let viewport = returned.bounds("scenario-viewport");
assert_eq!(app.selected, message);
assert_eq!(app.scenario_context().unwrap().visit, context.visit);
assert_eq!(
app.scenario_context().unwrap().representation,
context.representation
);
assert_eq!(stored_camera(&app), camera);
let geometry = resolve(app.project(), context.representation, message).unwrap();
let line = geometry
.scene
.lines
.iter()
.find(|line| line.id == message)
.unwrap();
let effective = app.behavior.scenario.presentation.camera(geometry.bounds);
let point = viewport.position()
+ effective.pan
+ Vector::new(line.points[0].x, line.points[0].y) * effective.scale;
assert!(
viewport.contains(point),
"the same selected message remains in fitted view"
);
assert!(Arc::ptr_eq(&original, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
#[test]
fn details_properties_refuses_pending_property_source_and_behavior_drafts_without_apply() {
for kind in 0..3 {
let (mut app, _, message) = setup();
open_focused_details(&mut app);
match kind {
0 => {
let _ = app.update(Message::Field(
"/name".into(),
"Retained property draft".into(),
));
assert!(app.draft_dirty());
}
1 => {
let _ = app.update(Message::SourceEdit(
iced::widget::text_editor::Action::Edit(
iced::widget::text_editor::Edit::Insert('x'),
),
));
assert!(app.source_dirty());
}
_ => {
let owner = app.scenario_context().unwrap().scenario;
let _ = app.update(Message::Behavior(super::super::super::Event::Scenario(
Event::Start(owner, Tool::Lifeline),
)));
assert!(app.behavior.has_pending());
}
}
let snapshot = app.document.snapshot();
let bundle = app.document.bundle().clone();
let property = app.draft.as_ref().unwrap().materialize();
let source = app.source_editor.text();
let behavior = app.behavior.recovery_snapshot();
let camera = app.behavior.scenario.camera_boundary();
let context = app.scenario_context().unwrap();
let epochs = (app.canvas_epoch, app.camera_epoch);
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Properties(
context, message,
)));
assert!(app.behavior.scenario.camera_boundary() == camera);
assert_eq!(app.scenario_context(), Some(context));
assert_eq!((app.canvas_epoch, app.camera_epoch), epochs);
assert_eq!(app.draft.as_ref().unwrap().materialize(), property);
assert_eq!(app.source_editor.text(), source);
assert_eq!(app.behavior.recovery_snapshot(), behavior);
assert_eq!(app.selected, message);
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
}
#[tokio::test]
async fn focused_details_opens_current_saved_view_properties_after_following_diagram_picker() {
let (mut app, a, _) = setup();
let b = id(&app, "incident_wide");
// Selecting the current view record makes the real picker follow that
// record selection to B. Do not seed selected=B or its property draft.
let _ = app.update(Message::Select(a));
assert_eq!(app.selected, a);
let _ = app.update(Message::Diagram(crate::app::Choice {
id: b,
label: "B".into(),
}));
assert_eq!(app.selected, b);
assert_eq!(app.draft.as_ref().unwrap().original, b);
assert_eq!(
app.scenario_context().unwrap().representation,
Representation::Saved { diagram: b }
);
let _ = app.update(Message::InspectorTab(
crate::navigation::InspectorTab::Connections,
));
let mut mounted = Mounted::new(&mut app).await;
open_focused_details(&mut app);
mounted.settle(&mut app).await;
let context = app.scenario_context().unwrap();
let camera = stored_camera(&app);
let snapshot = app.document.snapshot();
let bundle = app.document.bundle().clone();
let before = mounted.geometry(&app);
assert!(!before.scrolls.contains_key(&widget::Id::new("inspector")));
let (details, offset) = before.scrolls[&widget::Id::new("scenario-details")];
let point = before.bounds("scenario-properties").center() - offset;
assert!(details.contains(point));
let events = mounted.click(&mut app, point).await;
assert!(events.iter().any(|event| matches!(event,
Message::ScenarioCanvas(CanvasEvent::Properties(c, selected))
if *c == context && *selected == b)));
mounted.settle(&mut app).await;
let shown = mounted.geometry(&app);
assert!(
!shown
.scrolls
.contains_key(&widget::Id::new("scenario-details"))
);
let (inspector, offset) = shown.scrolls[&widget::Id::new("inspector")];
assert!(
shown
.text_inputs
.iter()
.any(|bounds| inspector.contains(bounds.center() - offset)),
"current Saved diagram has a visible editable inspector"
);
assert!(!app.behavior.scenario.focused());
assert_eq!(
app.inspector_tab,
crate::navigation::InspectorTab::Properties
);
assert_eq!(app.selected, b);
assert_eq!(app.draft.as_ref().unwrap().original, b);
assert_eq!(app.active_diagram, Some(b));
assert_eq!(app.page, crate::app::Page::Behavior);
assert_eq!(
app.scenario_context().unwrap().representation,
context.representation
);
assert_eq!(app.scenario_context().unwrap().visit, context.visit);
assert_eq!(stored_camera(&app), camera);
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
#[test]
fn details_properties_refuses_another_saved_view_even_with_the_same_scenario_owner() {
let (mut app, a, _) = setup();
let b = id(&app, "incident_wide");
let _ = app.update(Message::Diagram(crate::app::Choice {
id: b,
label: "B".into(),
}));
let _ = app.update(Message::Select(a));
assert_eq!(app.selected, a);
open_focused_details(&mut app);
let context = app.scenario_context().unwrap();
assert_eq!(context.representation, Representation::Saved { diagram: b });
assert_eq!(
presentation::checked_owner(app.project(), Representation::Saved { diagram: a }),
Some(context.scenario)
);
assert!(!properties_target(app.project(), context, a));
let camera = app.behavior.scenario.camera_boundary();
let epochs = (app.canvas_epoch, app.camera_epoch);
let snapshot = app.document.snapshot();
let bundle = app.document.bundle().clone();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Properties(context, a)));
assert!(app.behavior.scenario.camera_boundary() == camera);
assert_eq!((app.canvas_epoch, app.camera_epoch), epochs);
assert_eq!(app.scenario_context(), Some(context));
assert_eq!(app.selected, a);
assert_eq!(app.draft.as_ref().unwrap().original, a);
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &bundle);
assert!(!app.document.can_undo() && !app.document.can_redo());
}
#[test]
fn details_properties_rejects_retired_view_selection_and_epoch_without_changing_panels() {
for kind in 0..3 {
let (mut app, diagram, message) = setup();
open_focused_details(&mut app);
let captured = app.scenario_context().unwrap();
match kind {
0 => {
let other = id(&app, "incident_wide");
for view in [other, diagram] {
let _ = app.update(Message::Diagram(crate::app::Choice {
id: view,
label: "view".into(),
}));
}
open_focused_details(&mut app);
assert_ne!(app.scenario_context().unwrap().visit, captured.visit);
}
1 => {
let other = id(&app, "updated_report");
send(&mut app, |c| CanvasEvent::Select(c, other));
}
_ => {
send(&mut app, |c| CanvasEvent::Zoom(c, Some(0.5)));
}
}
let camera = app.behavior.scenario.camera_boundary();
let context = app.scenario_context();
let selected = app.selected;
let tab = app.inspector_tab;
let epochs = (app.canvas_epoch, app.camera_epoch);
let snapshot = app.document.snapshot();
let bundle = app.document.bundle().clone();
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Properties(
captured, message,
)));
assert!(app.behavior.scenario.camera_boundary() == camera);
assert_eq!(app.scenario_context(), context);
assert_eq!(app.selected, selected);
assert_eq!(app.inspector_tab, tab);
assert_eq!((app.canvas_epoch, app.camera_epoch), epochs);
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert_eq!(app.document.bundle(), &bundle);
}
}
#[test]
fn opening_scenario_properties_cancels_held_spacing_and_rejects_its_late_finish() {
use super::super::spacing::{Event as Spacing, Target, controller::tests::packet};
let (mut app, _, message) = setup();
send(&mut app, |c| {
CanvasEvent::Viewport(c, Size::new(900., 600.))
});
open_focused_details(&mut app);
let begin = packet(
app.project(),
&app.behavior.scenario,
app.scenario_context().unwrap(),
app.camera_epoch,
Target::Message(message),
);
let Spacing::Begin { press_screen, .. } = begin else {
panic!()
};
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(begin)));
assert_eq!(app.behavior.scenario.spacing_token(), Some(begin.token()));
let snapshot = app.document.snapshot();
let end = press_screen + Vector::new(0., 12.);
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(
Spacing::Move {
stamp: begin.stamp(),
token: begin.token(),
screen: end,
},
)));
let paint = app
.behavior
.scenario
.spacing_paint(begin.stamp().context, begin.stamp().camera_epoch)
.unwrap();
assert!(paint.refusal.is_none());
let line = paint
.scene
.lines
.iter()
.find(|line| line.id == message)
.unwrap();
assert!(
line.points[0].y > 160.,
"a real proposed scene moved the first message"
);
assert!(
Arc::ptr_eq(&snapshot, &app.document.snapshot()),
"preview is not authored"
);
let camera = stored_camera(&app);
send(&mut app, |c| CanvasEvent::Properties(c, message));
assert!(app.behavior.scenario.spacing_token().is_none());
assert_eq!(stored_camera(&app), camera);
let _ = app.update(Message::ScenarioCanvas(CanvasEvent::Spacing(
Spacing::Finish {
stamp: begin.stamp(),
token: begin.token(),
screen: end,
},
)));
assert!(Arc::ptr_eq(&snapshot, &app.document.snapshot()));
assert!(!app.document.can_undo() && !app.document.can_redo());
}
@@ -156,8 +156,26 @@ async fn saved_message_same_batch_pointer_events_commit_once_and_one_undo_redo_r
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 projected = screen(&mut mounted, &app, Point::new(400., 252.));
// This fixture asks for exactly +20 world units. A fractional start near a
// screen-coordinate exponent boundary need not retain an exact +10 delta.
let start = Point::new(projected.x.round(), projected.y.round());
let mut geometry = resolved(&app);
let camera = app.behavior.scenario.presentation.camera(geometry.bounds);
assert_eq!(camera.scale, 0.5);
let bounds = mounted.geometry(&app).bounds("scenario-viewport");
let world = Point::new(
(start.x - bounds.x - camera.pan.x) / camera.scale,
(start.y - bounds.y - camera.pan.y) / camera.scale,
);
geometry.scene.scale = camera.scale;
geometry.scene.camera_pan = camera.pan;
let hit = geometry.scene.hit_item(world).unwrap();
assert_eq!(hit.id, target);
assert_eq!(hit.role, crate::behavior::SceneHitRole::MessageBody);
let end = start + Vector::new(0., 10.); // .5 display scale: +20 authored y.
assert_eq!(end.y - start.y, 10.);
assert!(bounds.contains(start) && bounds.contains(end));
let messages = mounted
.batch(
&mut app,
@@ -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)
}
}
@@ -458,8 +458,7 @@ fn test_only_upstream_row_offsets_update_lifetime_segments_and_endpoints_without
assert_eq!(scene.activations.len(), 2);
for (call, reply) in [(c1, r1), (c2, r2)] {
assert!(scene.activations.iter().any(|segment| {
segment.call == call
&& segment.finish == Finish::Reply(reply)
segment.call == call && segment.finish == Finish::Reply(reply)
}));
}
}
+16 -11
View File
@@ -804,22 +804,27 @@ fn inspector(app: &App) -> View<'_, Message> {
);
}
}
body = body.push(
row![
button(text("Apply changes").size(12))
.padding([9, 12])
.on_press(Message::Apply)
.width(Fill),
action("Revert", Message::RevertProperties)
]
.spacing(5),
);
let actions = row![
button(text("Apply changes").size(12))
.padding([9, 12])
.on_press(Message::Apply)
.width(Fill),
action("Revert", Message::RevertProperties)
]
.spacing(5);
if let Some(d) = &app.draft {
body = body.push(forms::view(d, p));
}
container(
column![
tabs,
column![
tabs,
container(actions).padding(iced::Padding {
right: 14.,
..Default::default()
})
]
.spacing(12),
scrollable(body.padding(iced::Padding {
right: 14.,
..Default::default()
+2 -2
View File
@@ -14,14 +14,14 @@ mod communication_limits;
mod data_contracts;
#[path = "http/port_anchors.rs"]
mod port_anchors;
#[path = "http/scenario_layout.rs"]
mod scenario_layout;
#[path = "http/semantic_transitions.rs"]
mod semantic_transitions;
#[path = "http/source6_views.rs"]
mod source6_views;
#[path = "http/source7_contracts.rs"]
mod source7_contracts;
#[path = "http/scenario_layout.rs"]
mod scenario_layout;
#[path = "http/source_projects.rs"]
mod source_projects;
@@ -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.
@@ -0,0 +1,9 @@
# Scenario arrangement selection
An explicit arrangement change follows an inspector that is showing the current Saved Diagram record. Switching from Saved A to Saved B selects B and refreshes its Properties draft. Switching that view inspection to Automatic selects the Scenario owner, since Automatic has no Diagram record. An occurrence, lifeline, Scenario owner or independently selected foreign view keeps its selection. Returning from Automatic to a Saved view therefore preserves an already selected Scenario owner.
The follow intention is captured before the existing property Apply. The destination must pass the existing owner/context checks; a rejected draft or stale event cannot change selection. A same-view UUID edit follows the resulting Diagram identity. Successful entry refreshes the selected view's draft without a second Apply or a new document transaction. Passive page navigation and Back retain their existing behavior.
This corrects the actual Scenario picker (`CanvasEvent::Representation`). Previously, selecting A's whole-view usage and then choosing B left A selected, so the exact-current-view Details guard disabled Properties. Preserving that foreign view selection would make the inspector disagree with an explicit view change. Broadly selecting B after every arrangement change was rejected because it would discard an engineer's independent model-element inspection. The separate `Message::Diagram` handler already follows the current view, but its global UI picker excludes Scenario diagrams and cannot substitute for this workflow.
The regression module `app::scenario_details_tests` exercises the real picker overlay and Properties button, independent selections, Automatic, valid draft application and exact Undo/Redo, same-view UUID edits, and invalid/stale refusals. A container ID exposes the unchanged picker's bounds to the mounted evaluator. Native acceptance must retain the original A-record → Scenario arrangement B → Details → Properties workflow. Compilation and actual execution status belong to the linked review and [Gitea issue #24](http://217.177.34.108:3000/sorokin.oleg.edu/ARCADIA-Studio/issues/24).