Create gap events and distribute gap time across neighbouring cues

This commit is contained in:
Dandaedre 2026-11-05 12:06:12 +01:00
parent ae73bbc8bd
commit 88e943415f
6 changed files with 860 additions and 114 deletions

View File

@ -129,7 +129,11 @@ fn worksheet(rundown: &Rundown) -> String {
display(entry.start_ms),
display(entry.end_ms),
display(entry.duration_ms),
entry.source_rows[0].row.to_string(),
entry
.source_rows
.first()
.map(|row| row.row.to_string())
.unwrap_or_default(),
entry.title.clone(),
entry_values(entry, rundown, "notes", None),
"count-down".into(),
@ -303,7 +307,7 @@ pub fn ontime_with_settings(r: &Rundown, settings: &OntimeSettings) -> Result<Va
.into_iter()
.map(|(key, values)| (key, values.join("\n")))
.collect();
entries.insert(e.id.clone(),json!({"id":e.id,"type":"event","cue":e.source_rows[0].row.to_string(),"title":e.title,"note":notes.join("\n"),
entries.insert(e.id.clone(),json!({"id":e.id,"type":"event","cue":e.source_rows.first().map(|row| row.row.to_string()).unwrap_or_default(),"title":e.title,"note":notes.join("\n"),
"timeStart":e.start_ms,"timeEnd":e.end_ms,"duration":e.duration_ms,"linkStart":false,
"timeStrategy":"lock-duration","timerType":"count-down","endAction":"none","skip":false,
"colour":"#5744b5","timeWarning":120000.min(e.duration_ms/5),"timeDanger":60000.min(e.duration_ms/10),

View File

@ -446,7 +446,7 @@ fn preview_rows(a: &Analysis, table: Option<&Table>) -> Vec<PreviewRow> {
decisions: e.decisions.join("\n"),
kind: e.kind.clone(),
gap: false,
gap_key: None,
gap_key: e.gap_origin.clone(),
});
}
}
@ -544,8 +544,10 @@ fn preview_rows(a: &Analysis, table: Option<&Table>) -> Vec<PreviewRow> {
row.end = gap.end_ms.map(display).unwrap_or_else(|| "?".into());
row.gap = true;
row.gap_key = Some(gap.key());
if rundown.resolved_gaps.iter().any(|g| g.key() == gap.key()) {
row.kind = "Allocated gap · included in adjacent timer".into();
if gap.origin.is_none()
&& rundown.resolved_gaps.iter().any(|g| g.key() == gap.key())
{
row.kind = "Allocated gap · resolution applied".into();
}
row.duration = gap
.start_ms
@ -556,18 +558,54 @@ fn preview_rows(a: &Analysis, table: Option<&Table>) -> Vec<PreviewRow> {
}
}
rows.sort_by_key(|r| (r.row, r.split_part));
// Generated timers have no source row; insert them by their actual time
// without reordering source rows (backward-time errors must stay visible).
let mut generated = Vec::new();
rows.retain(|row| {
if row.row == 0 && row.gap_key.is_some() && !row.gap {
generated.push(row.clone());
false
} else {
true
}
});
generated.sort_by_key(|row| row.start.clone());
for row in generated {
let index = rows
.iter()
.position(|other| !other.source_only && other.start >= row.start)
.unwrap_or(rows.len());
rows.insert(index, row);
}
if let Some(rundown) = &a.rundown {
let mut gaps: Vec<_> = rundown
.gaps
.iter()
.chain(&rundown.resolved_gaps)
.filter(|gap| gap.source_rows.is_empty())
.filter(|gap| {
gap.origin.is_some()
|| !(rundown
.entries
.iter()
.any(|entry| entry.gap_origin.as_deref() == Some(&gap.key()))
|| rundown
.gaps
.iter()
.any(|other| other.origin.as_deref() == Some(&gap.key())))
})
.collect();
gaps.sort_by_key(|gap| gap.start_ms);
for gap in gaps {
let position = rows
.iter()
.position(|row| {
if gap.origin.is_some() {
return gap
.start_ms
.is_some_and(|start| row.start >= display(start) && !row.source_only);
}
row.row > 0
&& (gap.before_row.is_some_and(|before| row.row >= before)
|| (gap.before_row.is_none()
@ -583,16 +621,16 @@ fn preview_rows(a: &Analysis, table: Option<&Table>) -> Vec<PreviewRow> {
inferred_start: false,
inferred_end: false,
inferred_duration: false,
title: if rundown.resolved_gaps.iter().any(|g| g.key() == gap.key()) {
"Allocated gap · included in adjacent timer".into()
title: if gap.origin.is_none() && rundown.resolved_gaps.iter().any(|g| g.key() == gap.key()) {
"Allocated gap · resolution applied".into()
} else { gap.title.clone() },
source_only: true,
automatically_ignored: false,
issues: a.diagnostics.iter().enumerate().filter(|(_, d)| d.location == format!("{} gap {:?}–{:?}", rundown.title, gap.after_row, gap.before_row)).map(|(i, _)| i).collect(),
related_issues: vec![],
decisions: "Keep the interval untimed, extend the previous event to its end, or start the next event at its beginning. Recheck to apply the choice.".into(),
kind: if rundown.resolved_gaps.iter().any(|g| g.key() == gap.key()) {
"Allocated gap · included in adjacent timer".into()
decisions: "Choose a gap resolution or distribute its time across neighbouring events. Apply & recheck to update the schedule.".into(),
kind: if gap.origin.is_none() && rundown.resolved_gaps.iter().any(|g| g.key() == gap.key()) {
"Allocated gap · resolution applied".into()
} else { "Gap · no timer".into() },
gap: true,
gap_key: Some(gap.key()),
@ -680,9 +718,9 @@ fn modified_row(row: &PreviewRow, profile: &Profile) -> bool {
{
return true;
}
row.gap_key
.as_ref()
.is_some_and(|key| profile.gap_resolutions.contains_key(key))
row.gap_key.as_ref().is_some_and(|key| {
profile.gap_resolutions.contains_key(key) || profile.gap_options.contains_key(key)
})
}
fn column_choice(profile: &Profile, column: usize) -> Option<&str> {
@ -747,6 +785,7 @@ fn schedule_settings_changed(current: &Profile, analyzed: &Profile) -> bool {
|| current.ends != analyzed.ends
|| current.durations != analyzed.durations
|| current.gap_resolutions != analyzed.gap_resolutions
|| current.gap_options != analyzed.gap_options
}
fn preview_row_settings_changed(row: &PreviewRow, current: &Profile, analyzed: &Profile) -> bool {
@ -756,10 +795,10 @@ fn preview_row_settings_changed(row: &PreviewRow, current: &Profile, analyzed: &
|| current.starts.get(&row.row) != analyzed.starts.get(&row.row)
|| current.ends.get(&row.row) != analyzed.ends.get(&row.row)
|| current.durations.get(&row.row) != analyzed.durations.get(&row.row));
let gap_changed = row
.gap_key
.as_ref()
.is_some_and(|key| current.gap_resolutions.get(key) != analyzed.gap_resolutions.get(key));
let gap_changed = row.gap_key.as_ref().is_some_and(|key| {
current.gap_resolutions.get(key) != analyzed.gap_resolutions.get(key)
|| current.gap_options.get(key) != analyzed.gap_options.get(key)
});
let part_changed = row.split_part.is_some_and(|part| {
current
.ignored_parts
@ -788,7 +827,7 @@ fn show_row(
&& !ignored_row(row.row, table, profile, mapping)
}
RowFilter::Attention => !row.gap && !row.issues.is_empty(),
RowFilter::Gaps => row.gap,
RowFilter::Gaps => row.gap || row.gap_key.is_some(),
}
}
@ -1173,28 +1212,68 @@ impl App {
.get(key)
.cloned()
.unwrap_or_else(|| "keep".into());
let previous_action = action.clone();
egui::ComboBox::from_id_salt(("gap_resolution", key))
.width(95.0)
.selected_text(match action.as_str() {
"extend_previous" => "Extend prev.",
"add_to_next" => "Add to next",
_ => "Keep gap",
"extend_previous" => "Extend prev.", "add_to_next" => "Add to next",
"create_event" => "Create event", _ => "Keep gap",
})
.show_ui(ui, |ui| {
ui.selectable_value(&mut action, "keep".into(), "Keep gap");
ui.selectable_value(
&mut action,
"extend_previous".into(),
"Extend previous timing",
);
ui.selectable_value(&mut action, "extend_previous".into(), "Extend previous timing");
ui.selectable_value(&mut action, "add_to_next".into(), "Add to next timing");
})
.response
.on_hover_text("Keep gap leaves this interval untimed. Extend previous timing lengthens the preceding event. Add to next timing starts the next event earlier and preserves its end. Apply & recheck updates the schedule and export.");
if action == "keep" {
profile.gap_resolutions.remove(key);
ui.selectable_value(&mut action, "create_event".into(), "Create event");
}).response.on_hover_text("Keep an untimed gap, extend timers or create a timed event. Double-click the row for distribution and event-title options. Apply & recheck to update the schedule.");
if action != previous_action {
if action == "keep" {
profile.gap_resolutions.remove(key);
} else {
profile.gap_resolutions.insert(key.into(), action);
}
}
}
fn gap_distribution_controls(ui: &mut egui::Ui, profile: &mut Profile, key: &str) {
let action = profile
.gap_resolutions
.get(key)
.map(String::as_str)
.unwrap_or("keep");
let mut options = profile.gap_options.get(key).cloned().unwrap_or_default();
if action == "create_event" {
ui.label("Event title");
ui.add(egui::TextEdit::singleline(&mut options.title).hint_text("Gap name, or Break"));
}
ui.checkbox(&mut options.distribute, "Distribute across neighbours");
if options.distribute {
ui.indent("distribution", |ui| {
ui.horizontal(|ui| {
ui.label("Number of events");
ui.add(egui::DragValue::new(&mut options.count).range(1..=100));
});
if action == "extend_previous" {
options.direction = "previous".into(); ui.label("Extend the previous events equally");
} else if action == "add_to_next" {
options.direction = "following".into(); ui.label("Extend the following events equally");
} else {
egui::ComboBox::from_id_salt("gap_distribution_direction")
.selected_text(if options.direction == "following" { "Before following events" } else { "After previous events" })
.show_ui(ui, |ui| {
ui.selectable_value(&mut options.direction, "previous".into(), "After previous events");
ui.selectable_value(&mut options.direction, "following".into(), "Before following events");
});
}
ui.small(if action == "create_event" { "Creates equal timed events interleaved with the selected neighbours." }
else if action == "keep" { "Places equal untimed gaps between the selected neighbours." }
else { "Adds an equal share of gap time to each selected timer." });
ui.small("Event starts inside the block move; its overall start and end stay fixed. Events must be contiguous. Apply & recheck to preview.");
});
}
if options == Default::default() {
profile.gap_options.remove(key);
} else {
profile.gap_resolutions.insert(key.into(), action);
profile.gap_options.insert(key.into(), options);
}
}
@ -1274,6 +1353,13 @@ impl App {
});
if preview.gap { ui.small("Gap interval · duration is elapsed time; allocation follows the selected gap resolution."); }
});
if let Some(key) = &preview.gap_key {
ui.heading("Gap resolution");
ui.push_id("named_gap_editor", |ui| {
Self::gap_resolution_control(ui, &mut profile, key);
Self::gap_distribution_controls(ui, &mut profile, key);
});
}
ui.heading("Edit row");
ui.horizontal_wrapped(|ui| {
ui.label("Row type");
@ -1432,7 +1518,24 @@ impl App {
let table = self.tables.iter().find(|t| t.name == a.sheet);
preview_rows(a, table)
.into_iter()
.find(|row| row.row == 0 && row.gap_key.as_deref() == Some(key))
.find(|row| row.gap_key.as_deref() == Some(key))
.map(|mut row| {
if let Some(gap) = a
.rundown
.as_ref()
.and_then(|r| r.resolved_gaps.iter().find(|g| g.key() == key))
{
row.title = gap.title.clone();
row.start = gap.start_ms.map(display).unwrap_or_else(|| "?".into());
row.end = gap.end_ms.map(display).unwrap_or_else(|| "?".into());
row.duration = gap
.start_ms
.zip(gap.end_ms)
.map(|(s, e)| display(e - s))
.unwrap_or_else(|| "?".into());
}
row
})
});
let Some(preview) = preview else {
self.row_details = false;
@ -1456,7 +1559,7 @@ impl App {
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded)
.show(ctx, |ui| {
ui.heading(&preview.title);
ui.label("Inferred schedule interval · no source row or timer");
ui.label("Gap allocation · edit this resolution to update its generated timers or intervals");
if gap_pending {
ui.colored_label(
PREVIEW_PENDING,
@ -1486,6 +1589,7 @@ impl App {
ui.heading("Gap resolution");
ui.push_id("gap_inspector", |ui| {
Self::gap_resolution_control(ui, &mut profile, key);
Self::gap_distribution_controls(ui, &mut profile, key);
});
ui.small("Keep gap leaves this interval without an Ontime timer. Apply & recheck after changing the allocation.");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
@ -2367,7 +2471,7 @@ impl App {
ui.set_min_height(row_height);
ui.add(
egui::Label::new(RichText::new(format!("{}{}",
if row.row == 0 { "Gap".into() } else { row.row.to_string() },
if row.row == 0 { if row.gap { "Gap".into() } else { "New".into() } } else { row.row.to_string() },
if modified || pending { " ✎" } else { "" }
)).color(color))
.sense(egui::Sense::click()),
@ -2506,7 +2610,10 @@ impl App {
ui.set_width(controls_width);
ui.set_min_height(row_height);
if let Some(key) = &row.gap_key {
Self::gap_resolution_control(ui, &mut profile, key);
ui.push_id(("gap_row", row_index), |ui| Self::gap_resolution_control(ui, &mut profile, key));
if profile.gap_options.get(key).is_some_and(|options| options.distribute) {
ui.small(format!("Across {} events", profile.gap_options[key].count));
}
} else {
ui.push_id(("schedule_kind", row_index, row.row), |ui| {
let detected = if self.dirty {
@ -2637,6 +2744,97 @@ mod tests {
}
}
#[test]
fn generated_gap_events_and_distributed_gaps_render_in_schedule_order() {
let cells = |values: &[&str]| {
values
.iter()
.map(|text| crate::model::Cell {
text: (*text).into(),
..Default::default()
})
.collect()
};
let table = Table {
name: "Show".into(),
rows: vec![
cells(&["Start", "Duration", "Title"]),
cells(&["09:00", "10 min", "A"]),
cells(&["09:10", "10 min", "B"]),
cells(&["09:30", "10 min", "C"]),
],
merges: vec![],
};
let baseline = pipeline::analyze(
&table,
&Profile::default(),
&AtomicBool::new(false),
|_, _| {},
);
let key = baseline.rundown.as_ref().unwrap().gaps[0].key();
for action in ["keep", "create_event"] {
let mut profile = Profile::default();
profile.gap_resolutions.insert(key.clone(), action.into());
profile.gap_options.insert(
key.clone(),
crate::model::GapOptions {
distribute: true,
count: 2,
title: "Questions".into(),
..Default::default()
},
);
let analysis = pipeline::analyze(&table, &profile, &AtomicBool::new(false), |_, _| {});
assert!(
analysis.diagnostics.is_empty(),
"{:?}",
analysis.diagnostics
);
let rows = preview_rows(&analysis, Some(&table));
assert_eq!(rows.len(), 5);
assert!(
rows.windows(2).all(|pair| pair[0].start <= pair[1].start),
"{action}"
);
assert_eq!(rows.iter().filter(|row| row.gap_key.is_some()).count(), 2);
for row in rows.iter().filter(|row| row.gap_key.is_some()) {
assert!(show_row(
row,
RowFilter::Gaps,
Some(&table),
&profile,
analysis.mapping.as_ref()
));
assert!(modified_row(row, &profile));
let mut edited = profile.clone();
edited.gap_options.get_mut(&key).unwrap().count = 1;
assert!(preview_row_settings_changed(row, &edited, &profile));
}
let mut app = App {
sheet: "Show".into(),
tables: vec![table.clone()],
analysis: Some(analysis),
profile: serde_json::to_string(&profile).unwrap(),
analyzed_profile: Some(profile),
tab: Tab::Review,
selected_gap: Some(key.clone()),
row_details: true,
..Default::default()
};
let ctx = egui::Context::default();
configure_style(&ctx);
render(&mut app, &ctx, [1000.0, 900.0], vec![]);
let labels = render(&mut app, &ctx, [1000.0, 900.0], vec![]);
assert!(
labels
.iter()
.any(|(label, _)| label == "Distribute across neighbours")
);
assert!(labels.iter().any(|(label, _)| label == "Number of events"));
assert!(!app.dirty);
}
}
fn render(
app: &mut App,
ctx: &egui::Context,
@ -2789,7 +2987,7 @@ mod tests {
assert!(
labels
.iter()
.any(|(s, _)| s == "Inferred schedule interval · no source row or timer")
.any(|(s, _)| s == "Gap allocation · edit this resolution to update its generated timers or intervals")
);
let gap_choice = labels
.iter()

View File

@ -58,6 +58,27 @@ impl Diagnostic {
}
}
}
/// Optional distribution of one gap across adjacent, contiguous events.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct GapOptions {
pub distribute: bool,
pub count: usize,
/// previous inserts after each preceding event; following inserts before each following event.
pub direction: String,
pub title: String,
}
impl Default for GapOptions {
fn default() -> Self {
Self {
distribute: false,
count: 2,
direction: "previous".into(),
title: String::new(),
}
}
}
/// Project-level Ontime export preferences, separate from the neutral schedule IR.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
@ -124,8 +145,9 @@ pub struct Profile {
pub ends: BTreeMap<usize, String>,
/// Explicit duration overrides, expressed with units (e.g. 2 min).
pub durations: BTreeMap<usize, String>,
/// Exact gap key -> keep, extend_previous, or add_to_next.
/// Exact gap key -> keep, extend_previous, add_to_next, or create_event.
pub gap_resolutions: BTreeMap<String, String>,
pub gap_options: BTreeMap<String, GapOptions>,
}
impl Profile {
pub fn margin_ms(&self) -> Option<i64> {
@ -188,6 +210,9 @@ pub struct SourceRow {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Entry {
/// Original gap resolution that generated this timer; it has no source row.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gap_origin: Option<String>,
/// One-based position in the source duration split, stable when siblings are ignored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub split_part: Option<usize>,
@ -207,6 +232,9 @@ pub struct Entry {
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Gap {
/// Original interval controlling a redistributed untimed gap.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
pub after_row: Option<usize>,
pub before_row: Option<usize>,
pub start_ms: Option<i64>,
@ -217,6 +245,9 @@ pub struct Gap {
}
impl Gap {
pub fn key(&self) -> String {
if let Some(origin) = &self.origin {
return origin.clone();
}
format!(
"{:?}:{:?}:{:?}:{:?}",
self.after_row, self.before_row, self.start_ms, self.end_ms

View File

@ -223,6 +223,7 @@ pub fn identify_gaps(table: &Table, map: &Mapping, profile: &Profile) -> Vec<Gap
.map(|(s, d)| s + d)
});
Some(Gap {
origin: None,
after_row: r.checked_sub(1).map(|r| r + 1),
before_row: rows.iter().find(|next| **next > r).map(|next| next + 1),
start_ms: start,
@ -261,6 +262,7 @@ pub fn identify_gaps(table: &Table, map: &Mapping, profile: &Profile) -> Vec<Gap
&& next > end
{
gaps.push(Gap {
origin: None,
after_row: Some(a + 1),
before_row: Some(b + 1),
start_ms: Some(end),
@ -294,6 +296,7 @@ fn entry(
|part| format!("rundown/{}/{row}/part/{part}", table.name),
);
Entry {
gap_origin: None,
split_part: virtual_part.map(|part| part + 1),
id: Uuid::new_v5(&Uuid::NAMESPACE_URL, identity.as_bytes())
.simple()
@ -591,6 +594,7 @@ pub fn construct(
let margin = plan.margins.get(part).copied().unwrap_or(0);
if margin > 0 {
gaps.push(Gap {
origin: None,
after_row: Some(r + 1),
before_row: None,
start_ms: Some(part_end),
@ -605,6 +609,7 @@ pub fn construct(
if let Some(end) = given_end {
if part_start < end {
gaps.push(Gap {
origin: None,
after_row: Some(r + 1),
before_row: None,
start_ms: Some(part_start),
@ -701,6 +706,7 @@ pub fn construct(
let occupied_end = end + margin;
if margin > 0 {
gaps.push(Gap {
origin: None,
after_row: Some(r + 1),
before_row: None,
start_ms: Some(end),
@ -729,6 +735,7 @@ pub fn construct(
if r == last {
if occupied_end < boundary {
gaps.push(Gap {
origin: None,
after_row: Some(r + 1),
before_row: Some(r + 2),
start_ms: Some(occupied_end),
@ -767,6 +774,7 @@ pub fn construct(
{
if s > cursor {
gaps.push(Gap {
origin: None,
after_row: a.source_rows.last().map(|r| r.row),
before_row: b.source_rows.first().map(|r| r.row),
start_ms: Some(cursor),
@ -787,86 +795,304 @@ pub fn construct(
/// on every analysis, so changing a choice never accumulates timing adjustments.
fn resolve_gaps(rundown: &mut Rundown, profile: &Profile) -> Vec<Diagnostic> {
let mut errors = Vec::new();
for (key, action) in &profile.gap_resolutions {
if !matches!(action.as_str(), "keep" | "extend_previous" | "add_to_next")
|| !rundown.gaps.iter().any(|gap| gap.key() == *key)
for key in profile
.gap_resolutions
.keys()
.chain(profile.gap_options.keys())
.collect::<std::collections::BTreeSet<_>>()
{
let action = profile
.gap_resolutions
.get(key)
.map(String::as_str)
.unwrap_or("keep");
if !matches!(
action,
"keep" | "extend_previous" | "add_to_next" | "create_event"
) || !rundown.gaps.iter().any(|gap| gap.key() == *key)
{
errors.push(Diagnostic::new(3, "INVALID_GAP_RESOLUTION", &rundown.title,
format!("Gap resolution {key} is stale or has an unknown action. Remove it from gap_resolutions in Setup, or reset decisions and recheck.")));
format!("Gap resolution {key} is stale or has an unknown action. Remove its gap_resolutions / gap_options entries, or reset decisions and recheck.")));
}
}
for action in ["extend_previous", "add_to_next"] {
rundown.gaps.sort_by_key(|gap| gap.start_ms);
if action == "add_to_next" {
rundown.gaps.reverse();
}
let mut retained = Vec::new();
for gap in std::mem::take(&mut rundown.gaps) {
if profile.gap_resolutions.get(&gap.key()).map(String::as_str) != Some(action) {
retained.push(gap);
continue;
}
let location = format!(
"{} gap {:?}–{:?}",
rundown.title, gap.after_row, gap.before_row
);
let bounds = gap.start_ms.zip(gap.end_ms).filter(|(s, e)| e > s);
let target = bounds.and_then(|(start, end)| {
if rundown
.entries
.iter()
.any(|e| e.kind == "event" && e.start_ms < end && e.end_ms > start)
{
return None;
}
let candidates: Vec<_> = rundown
.entries
.iter()
.enumerate()
.filter(|(_, e)| {
e.kind == "event"
&& if action == "extend_previous" {
e.end_ms == start
} else {
e.start_ms == end
}
})
.map(|(i, _)| i)
.collect();
(candidates.len() == 1).then(|| candidates[0])
});
if let Some(index) = target {
let (start, end) = bounds.unwrap();
let event = &mut rundown.entries[index];
if action == "extend_previous" {
event.end_ms = end;
event.inferred_end = true;
} else {
event.start_ms = start;
event.explicit_start = false;
}
event.duration_ms = event.end_ms - event.start_ms;
event.inferred_duration = true;
event.decisions.push(format!(
"Gap resolution {action}: absorbed {} ms from {} to {}",
end - start,
start,
end
));
rundown.resolved_gaps.push(gap);
// Previous allocations run forwards; following allocations run backwards,
// so adjacent pieces of the same interval remain reachable.
let mut gaps = std::mem::take(&mut rundown.gaps);
gaps.sort_by_key(|gap| {
let following = match profile.gap_resolutions.get(&gap.key()).map(String::as_str) {
Some("extend_previous") => false,
Some("add_to_next") => true,
_ => profile
.gap_options
.get(&gap.key())
.is_some_and(|o| o.distribute && o.direction == "following"),
};
(
following,
if following {
-gap.start_ms.unwrap_or(0)
} else {
errors.push(Diagnostic::new(3, "GAP_RESOLUTION_UNAVAILABLE", location,
"This gap needs positive, known boundaries and one adjacent timed event without overlap. Choose Keep gap or correct the neighboring timing."));
retained.push(gap);
gap.start_ms.unwrap_or(0)
},
)
});
for gap in gaps {
let key = gap.key();
let action = profile
.gap_resolutions
.get(&key)
.map(String::as_str)
.unwrap_or("keep");
let options = profile.gap_options.get(&key).cloned().unwrap_or_default();
if action == "keep" && !options.distribute {
rundown.gaps.push(gap);
continue;
}
match allocate_gap(&rundown.entries, &gap, action, &options) {
Ok((entries, new_gaps)) => {
// Never move timers into another retained gap, including a gap
// redistributed by an earlier resolution.
if new_gaps.iter().any(|new_gap| {
rundown.gaps.iter().any(|other| {
new_gap
.start_ms
.zip(new_gap.end_ms)
.zip(other.start_ms.zip(other.end_ms))
.is_some_and(|((s, e), (os, oe))| s < oe && e > os)
})
}) || rundown.gaps.iter().any(|other| {
entries.iter().any(|entry| {
other.start_ms.zip(other.end_ms).is_some_and(|(s, e)| {
entry.kind == "event" && entry.start_ms < e && entry.end_ms > s
})
})
}) {
errors.push(Diagnostic::new(3, "GAP_RESOLUTION_UNAVAILABLE", format!("{} gap {:?}–{:?}", rundown.title, gap.after_row, gap.before_row),
"This distribution conflicts with another gap resolution. Use a smaller event count or keep one of the gaps in place."));
rundown.gaps.push(gap);
} else {
rundown.entries = entries;
rundown.gaps.extend(new_gaps);
rundown.resolved_gaps.push(gap);
}
}
Err(message) => {
errors.push(Diagnostic::new(
3,
"GAP_RESOLUTION_UNAVAILABLE",
format!(
"{} gap {:?}–{:?}",
rundown.title, gap.after_row, gap.before_row
),
message,
));
rundown.gaps.push(gap);
}
}
rundown.gaps = retained;
}
rundown.gaps.sort_by_key(|gap| gap.start_ms);
rundown.resolved_gaps.sort_by_key(|gap| gap.start_ms);
errors
}
fn gap_event(gap: &Gap, start: i64, end: i64, title: &str, part: usize, count: usize) -> Entry {
let title = if title.trim().is_empty() {
if gap.title.trim().is_empty() || gap.title.starts_with("Unallocated") {
"Break"
} else {
&gap.title
}
} else {
title.trim()
};
Entry {
gap_origin: Some(gap.key()),
split_part: Some(part + 1),
id: Uuid::new_v5(
&Uuid::NAMESPACE_URL,
format!("gap/{}/{part}", gap.key()).as_bytes(),
)
.simple()
.to_string(),
kind: "event".into(),
title: if count > 1 {
format!("{title} ({}/{count})", part + 1)
} else {
title.into()
},
start_ms: start,
end_ms: end,
duration_ms: end - start,
explicit_start: false,
inferred_end: true,
inferred_duration: true,
source_rows: vec![],
decisions: vec!["Created from gap resolution".into()],
}
}
/// Work on a copy so an unavailable allocation never partially changes the IR.
fn allocate_gap(
entries: &[Entry],
gap: &Gap,
action: &str,
options: &GapOptions,
) -> Result<(Vec<Entry>, Vec<Gap>), &'static str> {
let (start, end) = gap.start_ms.zip(gap.end_ms).filter(|(s, e)| e > s).ok_or(
"This gap needs positive, known start and end times. Correct its boundaries first.",
)?;
if entries.iter().any(|e| e.start_ms < end && e.end_ms > start) {
return Err(
"This gap overlaps an existing entry. Correct the timings before allocating it.",
);
}
if action == "create_event" && !options.distribute {
let mut result = entries.to_vec();
let index = result
.iter()
.position(|e| e.start_ms >= end)
.unwrap_or(result.len());
result.insert(index, gap_event(gap, start, end, &options.title, 0, 1));
return Ok((result, vec![]));
}
if !matches!(
action,
"keep" | "extend_previous" | "add_to_next" | "create_event"
) {
return Err("Unknown gap action; choose a supported resolution.");
}
let count = if options.distribute { options.count } else { 1 };
let quantum = if start % 1000 == 0 && end % 1000 == 0 {
1000
} else {
1
};
let units = (end - start) / quantum;
if count == 0 || count > entries.len() || units < count as i64 {
return Err(
"Choose a positive event count with enough neighbouring events and enough gap time for every share.",
);
}
let previous = match action {
"extend_previous" => true,
"add_to_next" => false,
_ => match options.direction.as_str() {
"previous" => true,
"following" => false,
_ => return Err("Choose previous or following events for the distribution."),
},
};
let candidates: Vec<_> = entries
.iter()
.enumerate()
.filter(|(_, e)| {
e.kind == "event"
&& if previous {
e.end_ms == start
} else {
e.start_ms == end
}
})
.map(|(i, _)| i)
.collect();
if candidates.len() != 1 {
return Err(
"This gap needs one adjacent timed event. Keep the gap or correct neighbouring times.",
);
}
let adjacent = candidates[0];
let first = if previous {
(adjacent + 1).checked_sub(count)
} else {
Some(adjacent)
}
.ok_or("Not enough previous events. Reduce the event count.")?;
let last = first
.checked_add(count)
.filter(|last| *last <= entries.len())
.ok_or("Not enough following events. Reduce the event count.")?;
let block = &entries[first..last];
if block
.iter()
.any(|e| e.kind != "event" || e.gap_origin.is_some())
|| block
.windows(2)
.any(|pair| pair[0].end_ms != pair[1].start_ms)
{
return Err(
"Distribution needs consecutive timed events with no intervening gaps, markers or generated events. Reduce the event count or correct the schedule.",
);
}
let block_start = if previous { block[0].start_ms } else { start };
let block_end = if previous {
end
} else {
block[count - 1].end_ms
};
if entries[..first]
.iter()
.chain(&entries[last..])
.any(|e| e.start_ms < block_end && e.end_ms > block_start)
{
return Err("The selected event block overlaps another entry. Correct the timings first.");
}
let mut result = entries[..first].to_vec();
let mut new_gaps = Vec::new();
let mut cursor = block_start;
for (part, original) in block.iter().enumerate() {
let share =
(units / count as i64 + i64::from((part as i64) < units % count as i64)) * quantum;
let extend = matches!(action, "extend_previous" | "add_to_next");
let insert_interval = |from: i64, result: &mut Vec<Entry>, new_gaps: &mut Vec<Gap>| {
if action == "create_event" {
result.push(gap_event(
gap,
from,
from + share,
&options.title,
part,
count,
));
} else {
new_gaps.push(Gap {
origin: Some(gap.key()),
after_row: None,
before_row: None,
start_ms: Some(from),
end_ms: Some(from + share),
title: format!("{} ({}/{count})", gap.title, part + 1),
source_rows: vec![],
display_timer: false,
});
}
};
if !previous && !extend {
insert_interval(cursor, &mut result, &mut new_gaps);
cursor += share;
}
let mut event = original.clone();
event.start_ms = cursor;
event.duration_ms += if extend { share } else { 0 };
event.end_ms = cursor + event.duration_ms;
event.explicit_start &= event.start_ms == original.start_ms;
event.inferred_end |= event.end_ms != original.end_ms;
event.inferred_duration |= extend;
event.decisions.push(format!(
"Gap resolution {action}: distributed {} ms across {count} event(s)",
end - start
));
cursor = event.end_ms;
result.push(event);
if previous && !extend {
insert_interval(cursor, &mut result, &mut new_gaps);
cursor += share;
}
}
debug_assert_eq!(cursor, block_end);
result.extend_from_slice(&entries[last..]);
Ok((result, new_gaps))
}
/// Stage 4 validation is also invoked by every exporter.
pub fn validate(r: &Rundown) -> Vec<Diagnostic> {
let mut errors = vec![];

View File

@ -1870,3 +1870,275 @@ fn ignoring_a_split_part_retains_its_sibling_and_recalculates_timing() {
.any(|d| d.code == "INVALID_SPLIT_RESOLUTION")
);
}
#[test]
fn gap_distribution_preserves_block_bounds_and_exports_generated_timers() {
let t = table(&[
&["Start", "Duration", "Title"],
&["09:00", "10 min", "A"],
&["09:10", "10 min", "B"],
&["09:30", "10 min", "C"],
&["09:40", "10 min", "D"],
]);
let baseline = analyze(&t, &Profile::default()).rundown.unwrap();
let gap = &baseline.gaps[0];
for (action, direction) in [
("extend_previous", "previous"),
("add_to_next", "following"),
("keep", "previous"),
("keep", "following"),
("create_event", "previous"),
("create_event", "following"),
] {
let mut profile = Profile::default();
profile.gap_resolutions.insert(gap.key(), action.into());
profile.gap_options.insert(
gap.key(),
GapOptions {
distribute: true,
count: 2,
direction: direction.into(),
title: "Questions".into(),
},
);
let profile: Profile =
serde_json::from_str(&serde_json::to_string(&profile).unwrap()).unwrap();
let a = analyze(&t, &profile);
assert!(
a.diagnostics.is_empty(),
"{action} {direction}: {:?}",
a.diagnostics
);
let r = a.rundown.unwrap();
assert_eq!(
r.entries.first().unwrap().start_ms,
baseline.entries[0].start_ms
);
assert_eq!(r.entries.last().unwrap().end_ms, baseline.entries[3].end_ms);
assert_eq!(r.resolved_gaps.len(), 1);
assert_eq!(r.gaps.len(), if action == "keep" { 2 } else { 0 });
let original: Vec<_> = r
.entries
.iter()
.filter(|e| e.gap_origin.is_none())
.collect();
assert_eq!(
original
.iter()
.map(|e| e.title.as_str())
.collect::<Vec<_>>(),
["A", "B", "C", "D"]
);
for (index, event) in original.iter().enumerate() {
let affected = if direction == "previous" {
index < 2
} else {
index >= 2
};
let extend = affected && matches!(action, "extend_previous" | "add_to_next");
assert_eq!(event.duration_ms, if extend { 900_000 } else { 600_000 });
}
let generated: Vec<_> = r
.entries
.iter()
.filter(|e| e.gap_origin.is_some())
.collect();
assert_eq!(
generated.len(),
if action == "create_event" { 2 } else { 0 }
);
for (part, event) in generated.iter().enumerate() {
assert_eq!(event.duration_ms, 300_000);
assert_eq!(event.title, format!("Questions ({}/2)", part + 1));
assert!(event.source_rows.is_empty());
}
if action == "create_event" {
let kinds: Vec<_> = r.entries.iter().map(|e| e.gap_origin.is_some()).collect();
assert_eq!(
kinds,
if direction == "previous" {
vec![false, true, false, true, false, false]
} else {
vec![false, false, true, false, true, false]
}
);
}
let json = export::ontime(&r).unwrap();
assert_eq!(
json["rundowns"]["default"]["order"]
.as_array()
.unwrap()
.len(),
r.entries.len()
);
for e in &generated {
assert_eq!(json["rundowns"]["default"]["entries"][&e.id]["cue"], "");
assert_eq!(
json["rundowns"]["default"]["entries"][&e.id]["duration"],
e.duration_ms
);
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("result.xlsx");
std::fs::write(&path, export::xlsx(&r).unwrap()).unwrap();
let sheets = reader::read(&path).unwrap();
assert_eq!(sheets[0].rows.len(), r.entries.len() + 1);
assert_eq!(
serde_json::to_value(&r).unwrap(),
serde_json::to_value(analyze(&t, &profile).rundown.unwrap()).unwrap()
);
}
let mut profile = Profile::default();
profile
.gap_resolutions
.insert(gap.key(), "create_event".into());
let a = analyze(&t, &profile);
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
let r = a.rundown.unwrap();
let e = r.entries.iter().find(|e| e.gap_origin.is_some()).unwrap();
assert_eq!(
(e.start_ms, e.end_ms),
(gap.start_ms.unwrap(), gap.end_ms.unwrap())
);
assert_eq!(e.title, "Break");
assert_eq!(r.entries.len(), 5);
assert_eq!(
serde_json::to_value(analyze(&t, &Profile::default()).rundown.unwrap()).unwrap(),
serde_json::to_value(baseline).unwrap()
);
}
#[test]
fn gap_distribution_rejects_invalid_blocks_and_keeps_whole_second_remainders() {
let t = table(&[
&["Start", "Duration", "Title"],
&["09:00:00", "10 s", "A"],
&["09:00:10", "10 s", "B"],
&["09:00:31", "10 s", "C"],
]);
let baseline = analyze(&t, &Profile::default()).rundown.unwrap();
let key = baseline.gaps[0].key();
let mut profile = Profile::default();
profile
.gap_resolutions
.insert(key.clone(), "create_event".into());
profile.gap_options.insert(
key.clone(),
GapOptions {
distribute: true,
count: 2,
..Default::default()
},
);
let a = analyze(&t, &profile);
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
let r = a.rundown.unwrap();
assert_eq!(
r.entries
.iter()
.filter(|e| e.gap_origin.is_some())
.map(|e| e.duration_ms)
.collect::<Vec<_>>(),
[6000, 5000]
);
for (count, direction) in [
(0, "previous"),
(3, "previous"),
(2, "following"),
(2, "bad"),
] {
let options = profile.gap_options.get_mut(&key).unwrap();
options.count = count;
options.direction = direction.into();
let a = analyze(&t, &profile);
assert!(
a.diagnostics
.iter()
.any(|d| d.code == "GAP_RESOLUTION_UNAVAILABLE"),
"{count} {direction}"
);
let r = a.rundown.unwrap();
assert_eq!(
serde_json::to_value(&r.entries).unwrap(),
serde_json::to_value(&baseline.entries).unwrap()
);
assert!(r.resolved_gaps.is_empty());
}
let noncontiguous = table(&[
&["Start", "Duration", "Title"],
&["09:00", "5 min", "A"],
&["09:10", "5 min", "B"],
&["09:30", "5 min", "C"],
]);
let base = analyze(&noncontiguous, &Profile::default())
.rundown
.unwrap();
let key = base.gaps[1].key();
profile.gap_resolutions = [(key.clone(), "extend_previous".into())].into();
profile.gap_options = [(
key,
GapOptions {
distribute: true,
count: 2,
..Default::default()
},
)]
.into();
assert!(
analyze(&noncontiguous, &profile)
.diagnostics
.iter()
.any(|d| d.code == "GAP_RESOLUTION_UNAVAILABLE")
);
}
#[test]
fn named_gaps_create_timers_and_multiple_gap_choices_remain_independent() {
let t = table(&[
&["Start", "Duration", "Title"],
&["09:00", "5 min", "Opening"],
&["", "", "Coffee break"],
&["09:15", "5 min", "Middle"],
&["09:30", "5 min", "Closing"],
]);
let baseline = analyze(&t, &Profile::default()).rundown.unwrap();
assert_eq!(baseline.gaps.len(), 2);
let mut profile = Profile::default();
for gap in &baseline.gaps {
profile
.gap_resolutions
.insert(gap.key(), "create_event".into());
}
let a = analyze(&t, &profile);
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
let r = a.rundown.unwrap();
assert_eq!(
r.entries
.iter()
.map(|e| e.title.as_str())
.collect::<Vec<_>>(),
["Opening", "Coffee break", "Middle", "Break", "Closing"]
);
assert!(r.gaps.is_empty());
assert_eq!(r.resolved_gaps.len(), 2);
assert_eq!(
r.entries
.iter()
.map(|e| &e.id)
.collect::<std::collections::BTreeSet<_>>()
.len(),
5
);
let json = export::ontime(&r).unwrap();
assert_eq!(
json["rundowns"]["default"]["order"]
.as_array()
.unwrap()
.len(),
5
);
profile.gap_resolutions.remove(&baseline.gaps[0].key());
let a = analyze(&t, &profile);
assert!(a.diagnostics.is_empty());
assert_eq!(a.rundown.unwrap().gaps.len(), 1);
}

View File

@ -87,15 +87,30 @@ visually distinct from labels and ordinary actions; the active tab uses the stro
follow as secondary information; raw source cells remain in the double-click
inspector. For overlaps, both affected rows explain their side of the conflict.
Gaps appear in schedule order with their start, end and elapsed duration (no timer).
Named breaks use their source row; inferred gaps update after recheck. Each gap offers **Keep gap**
(default, no timer), **Extend previous timing** (extend the preceding event's end),
or **Add to next timing** (start the following event earlier, keeping its end).
Apply & recheck updates durations and Ontime output. Allocated intervals remain
in the preview for review and undo; choose Keep gap to restore original timings.
The selected event must touch the gap, and unresolved/overlapping intervals
cannot be absorbed. Choices are saved in resolution profiles as `gap_resolutions`,
keyed by exact gap boundaries. If other corrections change those boundaries,
remove the stale choice in Setup or reset decisions and recheck.
Named breaks use their source row; inferred gaps update after recheck. Each gap offers
**Keep gap** (default, no timer), **Extend previous timing**, **Add to next timing**,
and **Create event**. Create event turns the entire gap into a timed Ontime event;
its title defaults to the named break, or “Break”, and can be edited in the gap editor.
Double-click the row or use **Edit gap…** for the additional options.
**Distribute across neighbours** divides the gap equally across N contiguous events:
- Extend previous / Add to next lengthens each of the previous / following N timers.
- Keep gap inserts N untimed intervals, after previous events or before following events.
- Create event inserts N new timed events at those same positions, interleaved with
the original events; generated titles include their part number.
Internal start times move, but the combined block's start and end stay fixed. Original
event durations stay unchanged for Keep gap / Create event. Whole-second gaps use
whole-second shares, assigning any remainder to the first parts. Insufficient neighbours,
intervening gaps or markers, overlaps, and unknown boundaries block the resolution
with an actionable error. No partial adjustment is applied for an unavailable resolution.
Apply & recheck updates the preview and both Ontime JSON and XLSX exports. Generated
events and redistributed intervals remain accessible under Gaps for review and undo.
Choose Keep gap **and turn distribution off** to restore the original interval.
Choices persist in `gap_resolutions`; `gap_options` holds `distribute`, `count`,
`direction` (`previous` or `following`) and `title`, keyed by the original gap key.
If other corrections change those original boundaries, remove the stale choice in
Setup or reset decisions and recheck. Column-layout memory does not transfer gap choices.
Unknown values show `?`.
Unresolved source rows offer **Ignore** to set the ignore resolution and
**Details** to open the row editor. Ignoring requires recheck and can be undone