Add presentation timer controls countdown and progress sizing

This commit is contained in:
Dandaedre 2026-11-20 07:26:49 +01:00
parent 4601a7bafb
commit 6c617f6953
16 changed files with 414 additions and 18 deletions

2
Cargo.lock generated
View File

@ -2221,7 +2221,7 @@ dependencies = [
[[package]]
name = "pdf-presenter"
version = "0.1.48"
version = "0.1.49"
dependencies = [
"bytemuck",
"chrono",

View File

@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"]
resolver = "3"
[workspace.package]
version = "0.1.48"
version = "0.1.49"
edition = "2024"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter"

View File

@ -84,3 +84,6 @@ pub mod localization;
pub mod theme;
mod artwork;
/// Monotonic elapsed/countdown timer.
pub mod timer;

View File

@ -161,7 +161,20 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str {
" · CURRENT" => " · ACTUELLE",
"Open PDF…" => "Ouvrir un PDF…",
"Open picture folder…" => "Ouvrir un dossier d’images…",
"Reset timer" => "Réinitialiser le chronomètre",
"Restart timer" => "Redémarrer le chronomètre",
"Start timer" => "Démarrer le chronomètre",
"Pause timer" => "Mettre en pause",
"Countdown" => "Compte à rebours",
"Duration" => "Durée",
"Start on first slide" => "Démarrer à la première diapositive",
"Or use Start timer. Restart resets and starts immediately." => {
"Ou utilisez Démarrer. Redémarrer remet à zéro et démarre immédiatement."
}
"Running" => "En cours",
"Stopped" => "Arrêté",
"Waiting for first slide" => "En attente de la première diapositive",
"Time is up" => "Temps écoulé",
"Bar height" => "Hauteur de la barre",
"Exit fullscreen" => "Quitter le plein écran",
"Enter fullscreen" => "Passer en plein écran",
"RAM budget per process (presenter + output each use this allowance):" => {

View File

@ -731,6 +731,12 @@ impl App {
}
if ack.sequence == s.output_sequence {
s.displayed = ack.page;
if ack.page.is_some()
&& !s.blanked
&& ack.generation == s.buffer_generation()
{
s.slide_played();
}
}
}
if s.new_output {

View File

@ -1,7 +1,7 @@
use crate::localization::tr;
// Native controls for the approved presenter layout and safe slide browser.
use crate::{
settings::{Layout, TimerPosition},
settings::{Layout, TimerMode, TimerPosition},
studio::{Action, Studio},
};
use egui::{Color32, Context, FontId, Pos2, Rect, Sense, TextureHandle, TextureOptions, Ui, Vec2};
@ -200,6 +200,101 @@ fn widget(
);
});
}
fn timer_controls(ui: &mut Ui, s: &mut Studio, close: bool) {
let locale = ui.ctx().clone();
let running = s.timer.running(Instant::now(), s.timer_limit());
ui.horizontal_wrapped(|ui| {
if ui
.button(tr(
&locale,
if running {
"Pause timer"
} else {
"Start timer"
},
))
.clicked()
{
s.execute(Action::ToggleTimer);
if close {
ui.close();
}
}
if ui.button(tr(&locale, "Restart timer")).clicked() {
s.execute(Action::RestartTimer);
if close {
ui.close();
}
}
});
let state = if running {
"Running"
} else if s.timer.waiting_for_slide && s.layout.timer_autostart {
"Waiting for first slide"
} else if s.timer_limit().is_some() && s.timer.seconds(Instant::now(), s.timer_limit()) == 0 {
"Time is up"
} else {
"Stopped"
};
ui.small(tr(&locale, state));
}
fn timer_settings(ui: &mut Ui, s: &mut Studio) {
let locale = ui.ctx().clone();
let before = (
s.layout.timer_mode,
s.layout.countdown_seconds,
s.layout.timer_autostart,
);
ui.horizontal_wrapped(|ui| {
ui.selectable_value(
&mut s.layout.timer_mode,
TimerMode::Elapsed,
tr(&locale, "Elapsed time"),
);
ui.selectable_value(
&mut s.layout.timer_mode,
TimerMode::Countdown,
tr(&locale, "Countdown"),
);
});
if s.layout.timer_mode == TimerMode::Countdown {
let mut minutes = s.layout.countdown_seconds / 60;
let mut seconds = s.layout.countdown_seconds % 60;
ui.horizontal_wrapped(|ui| {
ui.label(tr(&locale, "Duration"));
ui.add(
egui::DragValue::new(&mut minutes)
.range(0..=1440)
.suffix(" min"),
);
ui.add(
egui::DragValue::new(&mut seconds)
.range(0..=59)
.suffix(" s"),
);
});
s.layout.countdown_seconds = (minutes * 60 + seconds).clamp(1, 86400);
}
ui.checkbox(
&mut s.layout.timer_autostart,
tr(&locale, "Start on first slide"),
);
ui.small(tr(
&locale,
"Or use Start timer. Restart resets and starts immediately.",
));
if before
!= (
s.layout.timer_mode,
s.layout.countdown_seconds,
s.layout.timer_autostart,
)
{
s.timer = crate::timer::Timer::default();
}
timer_controls(ui, s, false);
}
fn timer_position(ui: &mut Ui, id: &str, position: &mut TimerPosition) {
let locale = ui.ctx().clone();
egui::ComboBox::from_id_salt(id)
@ -222,12 +317,16 @@ fn timer_height(s: &Studio, position: TimerPosition) -> f32 {
}
fn timers(ui: &mut Ui, s: &Studio, position: TimerPosition) {
let locale = ui.ctx().clone();
let secs = s.started.elapsed().as_secs();
let secs = s.timer.seconds(Instant::now(), s.timer_limit());
let entries = [
(
&s.layout.elapsed,
s.layout.elapsed_position,
"Elapsed time",
if s.layout.timer_mode == TimerMode::Countdown {
"Countdown"
} else {
"Elapsed time"
},
format!("{:02}:{:02}", secs / 60, secs % 60),
),
(
@ -413,8 +512,12 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) {
body.max.y -= 90.;
}
if s.layout.slide_progress {
let rect = Rect::from_min_max(Pos2::new(body.left(), body.bottom() - 24.), body.max);
body.max.y -= 32.;
let height = s
.layout
.slide_progress_height
.min(body.height().max(0.) * 0.25);
let rect = Rect::from_min_max(Pos2::new(body.left(), body.bottom() - height), body.max);
body.max.y -= height + 8.;
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
let current = if s.count() == 0 {
0
@ -425,6 +528,7 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) {
ui.add(
egui::ProgressBar::new(fraction)
.desired_width(rect.width())
.desired_height(height)
.text(format!(
"{} {current} / {}",
tr(&locale, "Slide"),
@ -958,6 +1062,8 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) {
);
});
layout_section(ui, tr(&locale, "Timers and progress"), |ui| {
timer_settings(ui, s);
ui.separator();
widget(
ui,
tr(&locale, "Elapsed time"),
@ -1000,6 +1106,11 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) {
&mut s.layout.slide_progress,
tr(&locale, "Slide progress bar"),
);
ui.add_enabled(
s.layout.slide_progress,
egui::Slider::new(&mut s.layout.slide_progress_height, 8. ..=120.)
.text(tr(&locale, "Bar height")),
);
});
layout_section(ui, tr(&locale, "Header and footer"), |ui| {
ui.horizontal_wrapped(|ui| {
@ -1587,10 +1698,7 @@ fn menu(ui: &mut Ui, s: &mut Studio) {
});
});
ui.separator();
if ui.button(tr(&locale, "Reset timer")).clicked() {
s.started = Instant::now();
ui.close();
}
timer_controls(ui, s, true);
fullscreen_button(ui, s);
button(ui, tr(&locale, "Quit"), Action::Exit, &mut s.actions);
if s.actions.len() != actions_before {

View File

@ -46,6 +46,13 @@ impl TimerPosition {
}
}
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TimerMode {
#[default]
Elapsed,
Countdown,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Layout {
@ -58,6 +65,10 @@ pub struct Layout {
pub elapsed_position: TimerPosition,
pub clock_position: TimerPosition,
pub slide_progress: bool,
pub slide_progress_height: f32,
pub timer_mode: TimerMode,
pub countdown_seconds: u32,
pub timer_autostart: bool,
pub header: bool,
pub footer: bool,
}
@ -91,6 +102,10 @@ impl Default for Layout {
elapsed_position: TimerPosition::Header,
clock_position: TimerPosition::Header,
slide_progress: false,
slide_progress_height: 24.,
timer_mode: TimerMode::Elapsed,
countdown_seconds: 1200,
timer_autostart: true,
header: true,
footer: true,
}
@ -98,6 +113,12 @@ impl Default for Layout {
}
impl Layout {
pub fn validate(&self) -> Result<(), String> {
if !self.slide_progress_height.is_finite()
|| !(8. ..=120.).contains(&self.slide_progress_height)
|| !(1..=86400).contains(&self.countdown_seconds)
{
return Err("Invalid timer duration or progress bar size".into());
}
for (w, min, max) in [
(&self.previous, 30., 160.),
(&self.current, 60., 200.),

View File

@ -35,6 +35,8 @@ pub enum Action {
Refresh,
Exit,
ToggleFullscreen,
ToggleTimer,
RestartTimer,
}
pub struct RouteTrial {
pub id: u64,
@ -80,7 +82,7 @@ pub struct Studio {
pub browser_preview: Option<(u64, usize)>,
pub change_on_click: bool,
pub jump: String,
pub started: Instant,
pub timer: crate::timer::Timer,
pub actions: Vec<Action>,
pub settings_path: PathBuf,
pub cache_path: PathBuf,
@ -173,7 +175,7 @@ impl Studio {
browser_preview: None,
change_on_click: false,
jump: String::new(),
started: Instant::now(),
timer: crate::timer::Timer::default(),
actions: vec![],
settings_path,
cache_path,
@ -267,6 +269,14 @@ impl Studio {
.into();
}
}
pub fn timer_limit(&self) -> Option<Duration> {
(self.layout.timer_mode == settings::TimerMode::Countdown)
.then(|| Duration::from_secs(self.layout.countdown_seconds as u64))
}
pub fn slide_played(&mut self) {
self.timer
.first_slide(Instant::now(), self.layout.timer_autostart);
}
pub fn execute(&mut self, action: Action) {
match action {
Action::Open(path) => {
@ -312,6 +322,9 @@ impl Studio {
self.fg_job = None;
}
self.presentation_started = true;
if !self.blanked && self.routes.presentation.is_empty() {
self.slide_played();
}
self.requested = page;
self.jump.clear();
self.new_output = true;
@ -324,6 +337,9 @@ impl Studio {
self.blanked = !self.blanked;
if !self.blanked {
self.presentation_started = true;
if self.count() > 0 && self.routes.presentation.is_empty() {
self.slide_played();
}
}
self.new_output = true;
}
@ -429,6 +445,8 @@ impl Studio {
}
Action::Refresh => self.dirty_routes = true,
Action::Exit => self.close_requested = true,
Action::ToggleTimer => self.timer.toggle(Instant::now(), self.timer_limit()),
Action::RestartTimer => self.timer.restart(Instant::now()),
Action::ToggleFullscreen => {
if self.route_trial.is_some() {
return;
@ -607,6 +625,7 @@ impl Studio {
self.failed.clear();
self.requested = 0;
self.presentation_started = false;
self.timer = crate::timer::Timer::default();
self.displayed = None;
self.layout = self.settings.for_project(&info.key);
self.status = info.warnings.first().cloned().unwrap_or_else(|| {

View File

@ -0,0 +1,63 @@
//! Monotonic presentation timer; no threads or wall-clock dependence.
use std::time::{Duration, Instant};
#[derive(Debug)]
pub struct Timer {
accumulated: Duration,
running_since: Option<Instant>,
pub waiting_for_slide: bool,
}
impl Default for Timer {
fn default() -> Self {
Self {
accumulated: Duration::ZERO,
running_since: None,
waiting_for_slide: true,
}
}
}
impl Timer {
pub fn elapsed(&self, now: Instant) -> Duration {
self.accumulated
+ self
.running_since
.map_or(Duration::ZERO, |start| now.saturating_duration_since(start))
}
pub fn running(&self, now: Instant, limit: Option<Duration>) -> bool {
self.running_since.is_some() && limit.is_none_or(|limit| self.elapsed(now) < limit)
}
pub fn seconds(&self, now: Instant, limit: Option<Duration>) -> u64 {
let elapsed = self.elapsed(now);
match limit {
Some(limit) => {
let remaining = limit.saturating_sub(elapsed);
remaining.as_secs() + u64::from(remaining.subsec_nanos() > 0)
}
None => elapsed.as_secs(),
}
}
pub fn restart(&mut self, now: Instant) {
self.accumulated = Duration::ZERO;
self.running_since = Some(now);
self.waiting_for_slide = false;
}
pub fn toggle(&mut self, now: Instant, limit: Option<Duration>) {
self.waiting_for_slide = false;
if self.running(now, limit) {
self.accumulated = self.elapsed(now);
self.running_since = None;
} else if limit.is_some_and(|limit| self.elapsed(now) >= limit) {
self.restart(now);
} else {
self.running_since = Some(now);
}
}
pub fn first_slide(&mut self, now: Instant, automatic: bool) {
if self.waiting_for_slide {
self.waiting_for_slide = false;
if automatic {
self.running_since = Some(now);
}
}
}
}

View File

@ -528,7 +528,8 @@ fn nested_settings_remain_interactive_and_menu_still_dismisses() {
assert!(s.menu_open);
click(&mut s, "Storage locations");
assert!(s.menu_open);
click(&mut s, "Reset timer");
click(&mut s, "Restart timer");
assert!(s.timer.running(std::time::Instant::now(), s.timer_limit()));
assert!(!s.menu_open, "Commands should dismiss the dropdown");
click(&mut s, "Menu");
click(&mut s, "Demo");
@ -889,3 +890,58 @@ fn fullscreen_button_trials_both_directions_and_can_revert() {
s.execute(Action::KeepRoutes);
assert!(s.settings.presenter_fullscreen && s.settings.presentation_fullscreen);
}
#[test]
fn timer_actions_and_slide_triggers_do_not_restart_paused_timers() {
use std::time::Instant;
let mut s = studio();
s.blanked = true;
s.execute(Action::Go(1));
assert!(!s.timer.running(Instant::now(), s.timer_limit()));
s.blanked = false;
s.slide_played();
assert!(s.timer.running(Instant::now(), s.timer_limit()));
s.execute(Action::ToggleTimer);
s.slide_played();
assert!(!s.timer.running(Instant::now(), s.timer_limit()));
s.execute(Action::RestartTimer);
assert!(s.timer.running(Instant::now(), s.timer_limit()));
s.timer = Default::default();
s.layout.timer_autostart = false;
s.slide_played();
assert!(!s.timer.running(Instant::now(), s.timer_limit()));
s.timer = Default::default();
s.layout.timer_autostart = true;
s.routes.presentation.clear();
s.execute(Action::Go(0));
assert!(s.timer.running(Instant::now(), s.timer_limit()));
}
#[test]
fn progress_bar_height_changes_rendered_geometry() {
let ctx = Context::default();
let mut s = studio();
let mut native = UiState::default();
s.layout.header = false;
s.layout.footer = false;
s.layout.slide_progress = true;
for height in [8., 24., 80., 120.] {
s.layout.slide_progress_height = height;
let output = ctx.run_ui(input(Vec2::new(1280., 900.)), |ui| {
presenter_ui::presenter(ui, &mut s, &mut native)
});
fn contains_bar(shape: &egui::Shape, height: f32) -> bool {
match shape {
egui::Shape::Rect(r) => {
r.rect.width() > 1200. && (r.rect.height() - height).abs() < 1.
}
egui::Shape::Vec(shapes) => shapes.iter().any(|s| contains_bar(s, height)),
_ => false,
}
}
assert!(
output.shapes.iter().any(|s| contains_bar(&s.shape, height)),
"Missing bar at height {height}"
);
}
}

View File

@ -206,3 +206,32 @@ fn side_timer_positions_and_large_sizes_roundtrip() {
assert!(s.validate().is_err());
}
}
#[test]
fn timer_and_progress_settings_migrate_validate_and_roundtrip() {
let legacy: Settings = toml::from_str("version=1").unwrap();
assert_eq!(legacy.layout.timer_mode, settings::TimerMode::Elapsed);
assert_eq!(legacy.layout.countdown_seconds, 1200);
assert!(legacy.layout.timer_autostart);
assert_eq!(legacy.layout.slide_progress_height, 24.);
let mut s = legacy;
s.layout.timer_mode = settings::TimerMode::Countdown;
s.layout.countdown_seconds = 90;
s.layout.timer_autostart = false;
s.layout.slide_progress_height = 120.;
s.projects.insert("demo".into(), s.layout.clone());
s.validate().unwrap();
let loaded: Settings = toml::from_str(&toml::to_string(&s).unwrap()).unwrap();
assert_eq!(s.layout, loaded.layout);
assert_eq!(s.projects, loaded.projects);
for duration in [0, 86401] {
s.layout.countdown_seconds = duration;
assert!(s.validate().is_err());
}
s.layout.countdown_seconds = 1;
for height in [7., 121., f32::NAN] {
s.layout.slide_progress_height = height;
assert!(s.validate().is_err());
}
assert!(toml::from_str::<Settings>("[layout]\ntimer_mode='unknown'").is_err());
}

View File

@ -0,0 +1,42 @@
use pdf_presenter::timer::Timer;
use std::time::{Duration, Instant};
#[test]
fn elapsed_autostart_pause_resume_restart_use_monotonic_time() {
let now = Instant::now();
let mut timer = Timer::default();
assert_eq!(timer.seconds(now + Duration::from_secs(50), None), 0);
timer.first_slide(now, true);
assert!(timer.running(now, None));
timer.first_slide(now + Duration::from_secs(4), true);
assert_eq!(timer.seconds(now + Duration::from_secs(5), None), 5);
timer.toggle(now + Duration::from_secs(5), None);
assert!(!timer.running(now + Duration::from_secs(20), None));
timer.first_slide(now + Duration::from_secs(10), true);
assert_eq!(timer.seconds(now + Duration::from_secs(20), None), 5);
timer.toggle(now + Duration::from_secs(20), None);
assert_eq!(timer.seconds(now + Duration::from_secs(23), None), 8);
timer.restart(now + Duration::from_secs(23));
assert_eq!(timer.seconds(now + Duration::from_secs(25), None), 2);
}
#[test]
fn countdown_manual_start_preserves_fractional_seconds_and_stops_at_zero() {
let now = Instant::now();
let limit = Some(Duration::from_secs(90));
let mut timer = Timer::default();
timer.first_slide(now, false);
assert!(!timer.running(now, limit));
assert_eq!(timer.seconds(now + Duration::from_secs(5), limit), 90);
timer.toggle(now, limit);
assert_eq!(timer.seconds(now + Duration::from_millis(100), limit), 90);
timer.toggle(now + Duration::from_millis(1500), limit);
assert_eq!(timer.seconds(now + Duration::from_secs(20), limit), 89);
timer.toggle(now + Duration::from_secs(20), limit);
assert_eq!(timer.seconds(now + Duration::from_millis(20500), limit), 88);
assert_eq!(timer.seconds(now + Duration::from_secs(200), limit), 0);
assert!(!timer.running(now + Duration::from_secs(200), limit));
timer.toggle(now + Duration::from_secs(200), limit);
assert_eq!(timer.seconds(now + Duration::from_secs(200), limit), 90);
assert!(timer.running(now + Duration::from_secs(200), limit));
}

View File

@ -2,6 +2,13 @@
## Unreleased
### 0.1.49
- Add monotonic elapsed/countdown timing with Start/Pause, Restart, configurable
duration and first-output autostart. Preserve pauses across slide changes; reset
on successful source loads and stop countdown at zero. Save timer preferences
with layouts, and add an 8–120 pixel slide progress bar height control.
### 0.1.48
- Add independent left/right of notes/slides timer positions and raise clock/elapsed

View File

@ -19,6 +19,10 @@ presentation = ["Projector#1"]
elapsed_position = "above_slides"
clock_position = "below_notes"
slide_progress = true
slide_progress_height = 32.0
timer_mode = "countdown"
countdown_seconds = 1200
timer_autostart = true
header = true
footer = false

View File

@ -49,8 +49,21 @@ flushed temporary file. Unknown fields are ignored and not preserved on round tr
- `layout.slide_progress`: boolean, default false, added in 0.1.24. Shows requested
slide / total and its fraction in a reserved bottom body row; empty decks show
0 / 0 with zero fill. This is navigation progress, not render/output readiness.
These three fields round-trip in both global and project layouts. Older v1
layouts omit them and use defaults without migration.
- Since 0.1.49, `layout.slide_progress_height`: finite logical pixels 8–120,
default 24. Height is capped to 25% of available body height on small windows.
- Since 0.1.49, `layout.timer_mode`: `elapsed` (default) or `countdown`;
`layout.countdown_seconds`: integer 1–86400, default 1200;
`layout.timer_autostart`: boolean, default true. These preferences and bar size
round-trip through both global and project layouts. Missing fields use defaults.
Older v1 binaries ignore these additive fields and lose them on resave.
Running/paused state, monotonic timestamps and elapsed time are transient,
never saved. Successful source loads reset the timer to its waiting state;
failed loads preserve the current timer. Mode/duration/autostart edits reset it.
Automatic start uses the first matching, unblanked output frame acknowledgement;
without output monitors, explicit navigation/show starts rehearsal timing.
Pause disables pending autostart; later slide changes never resume a paused timer.
Restart resets and runs immediately. Countdown uses ceiling seconds, stops at
zero and never wraps; Start after expiry restarts the configured duration.
- `projects`: at most 4096 SHA-256 canonical-path keys mapping to full layouts.
Path identity uses OS encoded bytes, not source content. Moving files or switching
platforms may therefore select a different layout. Project overrides win globally.

View File

@ -224,8 +224,20 @@ Header, Above slides, Below notes, or left/right of the notes or slides.
Timer text can be set up to 320 logical pixels; it scales down only to fit its
allocated space. Timers on the same side stack vertically. Timers have separate labeled boxes; size and
visibility controls still apply. Body positions remain visible when bars are hidden.
Use **Start timer**, **Pause timer** and **Restart timer** in Menu or Layout.
Pause preserves the time; Restart resets and starts immediately. Under Layout →
Timers and progress, choose **Elapsed time** or **Countdown** and set a countdown
in minutes and seconds (up to 24 hours). **Start on first slide** is enabled by
default: timing begins when the first slide reaches the presentation output,
including automatic output after opening a document. Turn it off for manual start.
Rehearsal without an output screen starts on explicit navigation or Show presentation.
Loading a new source resets the timer; pausing is never undone by slide navigation.
Countdown stops at zero. Changing mode, duration or autostart resets the timer.
Save the layout for this project or all projects to remember these preferences.
Enable **Slide progress bar** for a presenter-only current slide / total indicator
at the bottom of the content area. It starts disabled and tracks requested slide
at the bottom of the content area. Adjust **Bar height** from 8 to 120 pixels.
It starts disabled and tracks requested slide
navigation, even while output is blank or preparing; it is separate from loading
progress. Use Save layout · This project or All projects to remember these choices.