Use an explicit duration for per-entry margins
Beffroi/beffroi-tools/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-11-04 16:51:13 +01:00
parent bcb0cce6be
commit 6447dacdd9
8 changed files with 137 additions and 23 deletions

View File

@ -643,6 +643,15 @@ fn infer_inner(
"Use strict, minimum, maximum, sum, margin or split",
));
}
if profile.duration_add_margin && profile.margin_ms().is_none() {
diagnostics.push(err(
"INVALID_MARGIN",
table,
header,
dur.unwrap_or(start),
"Enter a positive margin duration with units, for example 2 min or 30 s.",
));
}
if (profile.duration_split || duration_mode == "split")
&& profile
.duration_separator
@ -768,7 +777,7 @@ fn infer_inner(
unit.as_deref(),
profile.duration_mode.as_deref(),
profile.duration_split,
profile.duration_add_margin,
profile.margin_ms(),
profile.duration_separator.as_deref(),
)
.is_some(),
@ -798,6 +807,7 @@ fn infer_inner(
duration_separator: profile.duration_separator.clone(),
duration_split: profile.duration_split,
duration_add_margin: profile.duration_add_margin,
duration_margin: profile.duration_margin.clone(),
evidence: evidence.clone(),
column_usage,
column_labels,

View File

@ -111,6 +111,8 @@ fn duration_handling_controls(ui: &mut egui::Ui, profile: &mut Profile, id: egui
ui.add(egui::TextEdit::singleline(separator).desired_width(70.0))
.on_hover_text("Use \\n for a newline, \\n\\n for a blank line, \\t for a tab, or enter a literal separator.");
}
});
ui.horizontal_wrapped(|ui| {
ui.weak("Duration handling");
let mut mode = profile
.duration_mode
@ -131,8 +133,15 @@ fn duration_handling_controls(ui: &mut egui::Ui, profile: &mut Profile, id: egui
.response
.on_hover_text("Split first, then apply this operation independently to each separated line or group. Values from different entries are never combined.");
profile.duration_mode = (mode != "strict").then_some(mode.clone());
});
ui.horizontal_wrapped(|ui| {
ui.checkbox(&mut profile.duration_add_margin, "Add margin")
.on_hover_text("Keep the difference between the sum of source durations and the selected duration as a gap after the event. With splitting, apply this to each entry. Sum leaves no remainder.");
.on_hover_text("Add this gap after every entry, including each split entry. Event durations stay unchanged.");
if profile.duration_add_margin {
let value = profile.duration_margin.get_or_insert_with(String::new);
ui.label("Duration");
ui.add(egui::TextEdit::singleline(value).desired_width(100.0).hint_text("e.g. 2 min"));
}
});
});
@ -605,7 +614,7 @@ impl App {
self.decisions_changed();
}
}
ui.label("Optional JSON profile: columns (start/start_end/end/duration/title/secondary_title), column_usage (notes/metadata/ignore), secondary_title_mode, duration_unit, duration_mode, duration_add_margin, duration_split, duration_separator, row_kinds, titles, starts, ends, durations, untimed_as_notes, ignore_warnings. Column letters and source rows are shown in diagnostics.");
ui.label("Optional JSON profile: columns (start/start_end/end/duration/title/secondary_title), column_usage (notes/metadata/ignore), secondary_title_mode, duration_unit, duration_mode, duration_add_margin, duration_margin, duration_split, duration_separator, row_kinds, titles, starts, ends, durations, untimed_as_notes, ignore_warnings. Column letters and source rows are shown in diagnostics.");
if ui
.add(
egui::TextEdit::multiline(&mut self.profile)

View File

@ -597,6 +597,7 @@ fn column_settings_changed(current: &Profile, analyzed: &Profile) -> bool {
|| current.duration_separator != analyzed.duration_separator
|| current.duration_split != analyzed.duration_split
|| current.duration_add_margin != analyzed.duration_add_margin
|| current.duration_margin != analyzed.duration_margin
}
fn schedule_settings_changed(current: &Profile, analyzed: &Profile) -> bool {
@ -1673,9 +1674,11 @@ impl App {
}
let duration_selected = column_choice(&profile, c) == Some("duration")
|| (column_choice(&profile, c).is_none()
&& mapping
&& (mapping
.as_ref()
.is_ok_and(|mapping| mapping.duration == Some(c)));
.is_ok_and(|mapping| mapping.duration == Some(c))
|| (!profile.columns.contains_key("duration")
&& suggestions.get(&c) == Some(&"Duration"))));
if duration_selected {
super::duration_handling_controls(
ui,
@ -3540,11 +3543,25 @@ mod tests {
.unwrap()
.1
.center();
let split = labels
.iter()
.find(|(text, _)| text == "Split into multiple entries")
.unwrap()
.1;
let handling = labels
.iter()
.find(|(text, _)| text == "Duration handling")
.unwrap()
.1;
assert!(handling.top() > split.bottom());
assert!(margin.y > handling.bottom());
click_size(&mut app, &ctx, margin, size);
let profile: Profile = serde_json::from_str(&app.profile).unwrap();
assert!(profile.duration_add_margin);
assert!(profile.duration_split);
assert_eq!(profile.duration_mode.as_deref(), Some("maximum"));
let labels = render(&mut app, &ctx, size, vec![]);
assert!(labels.iter().any(|(text, _)| text == "e.g. 2 min"));
}
#[test]

View File

@ -79,6 +79,8 @@ pub struct Profile {
pub duration_split: bool,
#[serde(default)]
pub duration_add_margin: bool,
#[serde(default)]
pub duration_margin: Option<String>,
/// Explicitly retain rows without times as notes on the preceding event.
pub untimed_as_notes: bool,
/// Try excluding rows with unresolved-content warnings, then validate again.
@ -97,6 +99,20 @@ pub struct Profile {
pub gap_resolutions: BTreeMap<String, String>,
}
impl Profile {
pub fn margin_ms(&self) -> Option<i64> {
if !self.duration_add_margin {
return None;
}
crate::time::duration(
&Cell {
text: self.duration_margin.clone()?,
..Cell::default()
},
None,
)
.filter(|value| *value > 0)
}
pub fn usage(&self, col: usize) -> Option<&str> {
self.column_usage
.iter()
@ -127,6 +143,8 @@ pub struct Mapping {
pub duration_split: bool,
#[serde(default)]
pub duration_add_margin: bool,
#[serde(default)]
pub duration_margin: Option<String>,
pub evidence: Vec<String>,
#[serde(default)]
pub column_usage: BTreeMap<String, String>,

View File

@ -52,7 +52,7 @@ fn duration_plan(
)
.map(|value| SelectedDurations {
events: vec![value],
margin: 0,
margin: profile.margin_ms().unwrap_or(0),
margins: vec![],
})
} else {
@ -62,7 +62,7 @@ fn duration_plan(
map.duration_unit.as_deref(),
profile.duration_mode.as_deref(),
profile.duration_split,
profile.duration_add_margin,
profile.margin_ms(),
profile.duration_separator.as_deref(),
)
})
@ -198,6 +198,15 @@ pub fn identify_gaps(table: &Table, map: &Mapping, profile: &Profile) -> Vec<Gap
continue;
}
let (start, end) = times(table, a, map, profile);
// A single event's fixed margin starts after its explicit end. Split
// blocks already account for their margins inside the shared window.
let end = end.map(|end| {
if duration_plan(table, a, map, profile).is_some_and(|plan| plan.events.len() > 1) {
end
} else {
end + profile.margin_ms().unwrap_or(0)
}
});
let end = end.or_else(|| {
start
.zip(supplied_span(table, a, map, profile))
@ -611,7 +620,9 @@ pub fn construct(
.push("Rows share a merged timing block and remain one timer".into());
row = merge_end + 1;
}
let margin = duration_plan.as_ref().map_or(0, |plan| plan.margin);
let margin = duration_plan
.as_ref()
.map_or_else(|| profile.margin_ms().unwrap_or(0), |plan| plan.margin);
let occupied_end = end + margin;
if margin > 0 {
gaps.push(Gap {

View File

@ -189,7 +189,7 @@ pub fn select_durations(
});
}
if mode == "split" {
return select_duration_parts(cell, unit, Some("sum"), true, false, split_separator);
return select_duration_parts(cell, unit, Some("sum"), true, None, split_separator);
}
let groups: Vec<Vec<i64>> = cell
.text
@ -246,17 +246,15 @@ pub fn select_duration_parts(
unit: Option<&str>,
mode: Option<&str>,
split: bool,
add_margin: bool,
margin_ms: Option<i64>,
split_separator: Option<&str>,
) -> Option<SelectedDurations> {
let legacy = mode == Some("split");
let mode = if legacy { Some("sum") } else { mode };
let select = |cell: &Cell| -> Option<SelectedDurations> {
let mut selected = select_durations(cell, unit, mode, None)?;
if add_margin && !matches!(mode, None | Some("strict" | "margin")) {
let total = select_durations(cell, unit, Some("sum"), None)?;
selected.margin =
(total.events.iter().sum::<i64>() - selected.events.iter().sum::<i64>()).max(0);
if let Some(margin) = margin_ms {
selected.margin = margin;
}
Some(selected)
};

View File

@ -1535,10 +1535,11 @@ fn margin_toggle_combines_with_minimum_maximum_sum_and_split() {
"Talks",
],
]);
for (mode, duration, margin) in [("minimum", 5, 20), ("maximum", 20, 5), ("sum", 25, 0)] {
for (mode, duration, margin) in [("minimum", 5, 2), ("maximum", 20, 2), ("sum", 25, 2)] {
let profile = Profile {
duration_mode: Some(mode.into()),
duration_add_margin: true,
duration_margin: Some("2 min".into()),
duration_split: split,
..Default::default()
};
@ -1558,7 +1559,10 @@ fn margin_toggle_combines_with_minimum_maximum_sum_and_split() {
.all(|g| g.end_ms.unwrap() - g.start_ms.unwrap() == margin * 60_000)
);
if split {
assert_eq!(r.entries[1].start_ms, 9 * 3_600_000 + 25 * 60_000);
assert_eq!(
r.entries[1].start_ms,
9 * 3_600_000 + (duration + margin) * 60_000
);
}
assert!(export::ontime(&r).is_ok());
}
@ -1587,6 +1591,7 @@ fn splitting_precedes_every_operation_and_export_keeps_independent_results() {
duration_split: true,
duration_separator: Some(separator.into()),
duration_add_margin: margin,
duration_margin: Some("2 min".into()),
..Default::default()
};
let a = analyze(&t, &p);
@ -1606,10 +1611,51 @@ fn splitting_precedes_every_operation_and_export_keeps_independent_results() {
);
}
if margin {
assert_eq!(r.entries[1].start_ms, 9 * 3_600_000 + 25 * 60_000);
assert_eq!(r.entries[2].start_ms, 9 * 3_600_000 + 37 * 60_000);
assert_eq!(
r.entries[1].start_ms,
9 * 3_600_000 + (minutes[0] + 2) * 60_000
);
assert_eq!(
r.entries[2].start_ms,
9 * 3_600_000 + (minutes[0] + minutes[1] + 4) * 60_000
);
}
}
}
}
}
#[test]
fn fixed_margin_requires_a_value_and_applies_to_overrides_and_derived_durations() {
let t = table(&[&["Start", "End", "Title"], &["09:00", "09:10", "Talk"]]);
for value in [None, Some(""), Some("2"), Some("-2 min"), Some("0 min")] {
let p = Profile {
duration_add_margin: true,
duration_margin: value.map(str::to_string),
..Default::default()
};
assert!(
analyze(&t, &p)
.diagnostics
.iter()
.any(|d| d.code == "INVALID_MARGIN")
);
}
for corrected in [false, true] {
let mut p = Profile {
duration_add_margin: true,
duration_margin: Some("30 s".into()),
..Default::default()
};
if corrected {
p.durations.insert(2, "10 min".into());
}
let a = analyze(&t, &p);
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
let r = a.rundown.unwrap();
assert_eq!(r.entries[0].duration_ms, 600_000);
assert_eq!(r.gaps.len(), 1);
assert_eq!(r.gaps[0].start_ms, Some(r.entries[0].end_ms));
assert_eq!(r.gaps[0].end_ms, Some(r.entries[0].end_ms + 30_000));
}
}

View File

@ -126,7 +126,8 @@ visually distinct from labels and ordinary actions; the active tab uses the stro
column determines the timer. A duration column has a nested **Duration handling**
choice instead of extra column roles: whole cell, minimum, maximum or sum.
Separate **Add margin** and **Split into multiple entries** toggles can be
combined with that choice. Add margin keeps the unused duration as a gap;
combined with that choice. Add margin takes an explicit positive duration (for example `2 min`) and adds
that gap after every entry, including the last one;
splitting applies the selected handling and margin to each separated group.
The order is **Split → Duration handling → Add margin**. For example,
`20 min + 5 min` and `10 min + 2 min` on separate lines produce 25-minute
@ -224,7 +225,7 @@ values from calculated values, unresolved values and gaps.
| Cue at 11:45 lasting 15 minutes; next cue at 13:30 | Preserve a 12:00–13:30 gap and the 13:30 start |
| Start–end cell `08h00 - 08h30` | Use 08:00 and 08:30 directly and derive a 30-minute duration |
| Start cell `08h45 - 09h10`, duration `20 min + 5 min` with Maximum | Use 08:45 and a 20-minute timer; the unused end in the Start cell does not constrain it |
| Duration `20 min + 5 min` with Maximum and Add margin | Create a 20-minute event followed by a five-minute untimed gap |
| Duration `20 min + 5 min` with Maximum and a `2 min` margin | Create a 20-minute event followed by a two-minute untimed gap |
| Multiline duration with Split | Create sequential virtual entries, one for each separated duration group; a start–end range bounds their combined durations and margins, with remaining time kept as a gap |
| Named lunch row from 12:00 to 13:30 | Preserve an explicit break with its original label |
| Cue at 11:45; next cue at 13:30; no end or duration | Event duration versus break is unknown; do not invent a lunch break |
@ -312,9 +313,13 @@ both titles empty still need correction.
`duration_mode` is optional and remains attached to the single `duration` role.
`minimum`, `maximum` and `sum` select from explicit duration values in mixed text.
`duration_add_margin: true` preserves the difference between the source duration
sum and the selected duration as an untimed gap. For `20 min + 5 min`, Maximum
leaves a five-minute gap, Minimum leaves a twenty-minute gap, and Sum leaves none. `duration_split: true` creates sequential virtual
`duration_add_margin: true` with `duration_margin: "2 min"` adds a two-minute
untimed gap after each event. The value is independent of the source durations
and selected operation; it also applies with Sum and whole-cell handling.
Missing, nonpositive or ambiguous values block analysis with an actionable error.
Explicit starts remain anchors: if a margin overlaps the next event, validation
reports it instead of moving that event.
`duration_split: true` creates sequential virtual
events and applies the selected handling to each group separated by
`duration_separator`; `\\n`, `\\n\\n` and `\\t` mean newline,
blank line and tab. The default `strict` behavior requires the complete cell to be