Add white PDF page backgrounds and configurable fit padding

This commit is contained in:
Dandaedre 2026-11-19 21:34:12 +01:00
parent 816ed55d49
commit e1de6665b2
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
17 changed files with 294 additions and 30 deletions

2
Cargo.lock generated
View File

@ -2212,7 +2212,7 @@ dependencies = [
[[package]]
name = "pdf-presenter"
version = "0.1.25"
version = "0.1.26"
dependencies = [
"bytemuck",
"chrono",

View File

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

View File

@ -289,7 +289,11 @@ impl Document {
}
};
let dir = self.cache.join(&self.info.key).join(&identity);
let path = dir.join(format!("{page}-{edge}-hayro09.rgba"));
let renderer_key = match self.source {
Source::Pdf(_) => "hayro09-straight",
Source::Images(_) => "hayro09",
};
let path = dir.join(format!("{page}-{edge}-{renderer_key}.rgba"));
if let Ok((width, height, rgba)) = read_frame(&path) {
return Ok(Some(Frame {
info: FrameInfo {
@ -326,7 +330,12 @@ impl Document {
);
let w = pixmap.width() as u32;
let h = pixmap.height() as u32;
(w, h, bytemuck::cast_slice(pixmap.data()).to_vec())
// Hayro stores premultiplied pixels; our cache/UI contract is straight RGBA.
(
w,
h,
pixmap.take_rgba8(hayro::vello_cpu::peniko::ImageAlphaType::Alpha),
)
}
Source::Images(_) => {
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes.unwrap()))

View File

@ -40,6 +40,11 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str {
}
match text {
"File chooser already open" => "Sélecteur de fichiers déjà ouvert",
"Page background" => "Fond de page",
"Fit padding color" => "Couleur des marges",
"Page background fills transparency; fit padding fills space around the slide." => {
"Le fond de page remplit les zones transparentes ; les marges remplissent l’espace autour de la diapositive."
}
"Appearance" => "Apparence",
"Preferences" => "Préférences",
"Storage locations" => "Emplacements de stockage",

View File

@ -208,21 +208,12 @@ impl NativeWindow {
egui::TextureOptions::LINEAR,
)
});
let rect = ui.max_rect();
let scale = (rect.width() / frame.info.width as f32)
.min(rect.height() / frame.info.height as f32);
let target = egui::Rect::from_center_size(
rect.center(),
egui::vec2(
frame.info.width as f32 * scale,
frame.info.height as f32 * scale,
),
);
ui.painter().image(
presenter_ui::paint_slide(
ui.painter(),
ui.max_rect(),
tex.id(),
target,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1., 1.)),
egui::Color32::WHITE,
[frame.info.width, frame.info.height],
setup.map(|s| s.slide_colors).unwrap_or_default(),
);
}
}
@ -653,6 +644,7 @@ impl App {
setup_controls: !s.presentation_started,
route_trial: s.route_trial.as_ref().map(|t| t.id),
sequence: s.output_sequence,
slide_colors: s.settings.slide_colors,
page: s.requested,
frame: if s.routes.presentation.is_empty() {
None

View File

@ -23,6 +23,8 @@ pub enum DisplayAction {
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct HostState {
#[serde(default)]
pub slide_colors: crate::settings::SlideColors,
#[serde(default)]
pub setup_controls: bool,
#[serde(default)]

View File

@ -10,6 +10,28 @@ use std::{
sync::Arc,
time::{Duration, Instant},
};
/// Composite a fitted slide over independent page and padding colors in every view.
pub fn paint_slide(
painter: &egui::Painter,
rect: Rect,
texture: egui::TextureId,
dimensions: [u32; 2],
colors: crate::settings::SlideColors,
) {
let [width, height] = dimensions.map(|v| v as f32);
let scale = (rect.width() / width).min(rect.height() / height);
let target = Rect::from_center_size(rect.center(), Vec2::new(width * scale, height * scale));
let [r, g, b] = colors.fit_padding;
painter.rect_filled(rect, 0., Color32::from_rgb(r, g, b));
let [r, g, b] = colors.page_background;
painter.rect_filled(target, 0., Color32::from_rgb(r, g, b));
painter.image(
texture,
target,
Rect::from_min_max(Pos2::ZERO, Pos2::new(1., 1.)),
Color32::WHITE,
);
}
const TEAL: Color32 = Color32::from_rgb(103, 226, 205);
pub struct UiState {
pub textures: HashMap<(u64, usize, u32), TextureHandle>,
@ -44,17 +66,12 @@ impl UiState {
TextureOptions::LINEAR,
)
});
let scale = (rect.width() / frame.info.width as f32)
.min(rect.height() / frame.info.height as f32);
let size = Vec2::new(
frame.info.width as f32 * scale,
frame.info.height as f32 * scale,
);
ui.painter().image(
paint_slide(
ui.painter(),
rect,
tex.id(),
Rect::from_center_size(rect.center(), size),
Rect::from_min_max(Pos2::ZERO, Pos2::new(1., 1.)),
Color32::WHITE,
[frame.info.width, frame.info.height],
s.settings.slide_colors,
);
} else {
ui.painter().text(
@ -1043,7 +1060,28 @@ fn menu(ui: &mut Ui, s: &mut Studio) {
.changed();
}
});
ui.separator();
for (label, color) in [
(
"Page background",
&mut s.settings.slide_colors.page_background,
),
(
"Fit padding color",
&mut s.settings.slide_colors.fit_padding,
),
] {
ui.horizontal(|ui| {
ui.label(tr(&locale, label));
changed |= ui.color_edit_button_srgb(color).changed();
});
}
ui.small(tr(
&locale,
"Page background fills transparency; fit padding fills space around the slide.",
));
if changed {
s.new_output = true;
s.save_preferences();
ui.ctx().request_repaint();
}

View File

@ -151,10 +151,34 @@ impl Routes {
Ok(())
}
}
/// Opaque display colors; cached slide pixels retain their original transparency.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct SlideColors {
#[serde(deserialize_with = "read_rgb")]
pub page_background: [u8; 3],
#[serde(deserialize_with = "read_rgb")]
pub fit_padding: [u8; 3],
}
fn read_rgb<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<[u8; 3], D::Error> {
let channels = Vec::<u8>::deserialize(deserializer)?;
channels
.try_into()
.map_err(|_| serde::de::Error::custom("RGB colors require exactly three channels"))
}
impl Default for SlideColors {
fn default() -> Self {
Self {
page_background: [255; 3],
fit_padding: [0; 3],
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
pub version: u32,
pub slide_colors: SlideColors,
pub layout: Layout,
pub projects: BTreeMap<String, Layout>,
pub routes: Routes,
@ -171,6 +195,7 @@ impl Default for Settings {
fn default() -> Self {
Self {
version: 1,
slide_colors: SlideColors::default(),
layout: Layout::default(),
projects: BTreeMap::new(),
routes: Routes::default(),

View File

@ -123,3 +123,40 @@ fn legacy_layouts_default_timer_positions_and_progress_is_opt_in() {
.layout
);
}
#[test]
fn slide_colors_migrate_roundtrip_and_reject_invalid_channels() {
use settings::SlideColors;
let old: Settings = toml::from_str("version = 1").unwrap();
assert_eq!(old.slide_colors, SlideColors::default());
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("settings.toml");
let mut s = old;
s.slide_colors = SlideColors {
page_background: [10, 20, 30],
fit_padding: [40, 50, 60],
};
settings::write(&path, &s).unwrap();
assert_eq!(settings::read(&path).unwrap().slide_colors, s.slide_colors);
let state = pdf_presenter::output::HostState {
slide_colors: s.slide_colors,
..Default::default()
};
let restored: pdf_presenter::output::HostState =
serde_json::from_slice(&serde_json::to_vec(&state).unwrap()).unwrap();
assert_eq!(restored.slide_colors, s.slide_colors);
for value in [
"[256, 0, 0]",
"[-1, 0, 0]",
"[0, 0]",
"[0, 0, 0, 0]",
"[0.5, 0, 0]",
] {
assert!(
toml::from_str::<Settings>(&format!(
"version=1\n[slide_colors]\npage_background={value}"
))
.is_err()
);
}
}

View File

@ -0,0 +1,112 @@
mod common;
use egui::{Context, Pos2, RawInput, Rect, TextureOptions, Vec2};
use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender};
use pdf_presenter::{document::Document, presenter_ui::paint_slide, settings::SlideColors};
#[test]
fn transparent_pdf_composites_on_white_or_custom_page_with_independent_padding() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("transparent.pdf");
common::pdf(&path);
// Same-length replacements preserve the synthetic PDF's xref offsets.
let source = String::from_utf8(std::fs::read(&path).unwrap())
.unwrap()
.replace("640 360 re", "320 180 re");
std::fs::write(&path, &source).unwrap();
let doc = Document::open(&path, temp.path().join("cache")).unwrap();
let frame = doc.render(0, 320).unwrap();
assert_eq!((frame.info.width, frame.info.height), (320, 180));
assert_eq!(frame.rgba[(90 * 320 + 240) * 4 + 3], 0);
let cached = std::fs::read(&frame.info.path).unwrap();
let ctx = Context::default();
let texture = ctx.load_texture(
"pdf",
egui::ColorImage::from_rgba_unmultiplied([320, 180], &frame.rgba),
TextureOptions::NEAREST,
);
let mut renderer = EguiSoftwareRender::new(ColorFieldOrder::Bgra);
for colors in [
SlideColors::default(),
SlideColors {
page_background: [20, 60, 100],
fit_padding: [130, 40, 10],
},
] {
for size in [[400, 400], [800, 200]] {
let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(size[0] as f32, size[1] as f32));
let output = ctx.run_ui(
RawInput {
screen_rect: Some(rect),
..Default::default()
},
|ui| {
paint_slide(ui.painter(), rect, texture.id(), [320, 180], colors);
},
);
let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
let mut pixels = vec![0u32; size[0] * size[1]];
renderer.render(
&mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), size[0], size[1]),
&primitives,
&output.textures_delta,
output.pixels_per_point,
);
let rgb = |x, y| pixels[y * size[0] + x] & 0xffffff;
let packed =
|c: [u8; 3]| u32::from(c[0]) << 16 | u32::from(c[1]) << 8 | u32::from(c[2]);
assert_eq!(rgb(5, 5), packed(colors.fit_padding));
assert_eq!(
rgb(size[0] / 2 + 80, size[1] / 2),
packed(colors.page_background)
);
// The opaque green rectangle in the lower left is unaffected by either color.
let opaque = rgb(size[0] / 2 - 80, size[1] / 2 + 40);
assert_ne!(opaque, packed(colors.page_background));
assert_ne!(opaque, packed(colors.fit_padding));
}
}
assert_eq!(std::fs::read(&frame.info.path).unwrap(), cached);
assert_eq!(std::fs::read_to_string(&path).unwrap(), source);
}
#[test]
fn translucent_pdf_pixels_use_straight_alpha_and_ignore_legacy_artifacts() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("alpha.pdf");
let content = "/GS gs 1 0 0 rg 0 0 100 100 re f";
let objects = [
"<< /Type /Catalog /Pages 2 0 R >>".to_owned(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << /ExtGState << /GS 5 0 R >> >> /Contents 4 0 R >>".to_owned(),
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
"<< /Type /ExtGState /ca 0.5 >>".to_owned(),
];
let mut bytes = b"%PDF-1.4\n".to_vec();
let mut offsets = vec![0];
for (i, object) in objects.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend(format!("{} 0 obj\n{object}\nendobj\n", i + 1).bytes());
}
let start = bytes.len();
bytes.extend(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len()).bytes());
for offset in &offsets[1..] {
bytes.extend(format!("{offset:010} 00000 n \n").bytes());
}
bytes.extend(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start}\n%%EOF\n",
offsets.len()
)
.bytes(),
);
std::fs::write(&path, bytes).unwrap();
let doc = Document::open(&path, temp.path().join("cache")).unwrap();
let frame = doc.render(0, 160).unwrap();
let pixel = &frame.rgba[(80 * 160 + 80) * 4..][..4];
assert_eq!(&pixel[..3], &[255, 0, 0]);
assert!((127..=128).contains(&pixel[3]));
let legacy = frame.info.path.with_file_name("0-160-hayro09.rgba");
std::fs::rename(&frame.info.path, legacy).unwrap();
assert!(doc.cached(0, 160).unwrap().is_none());
assert_eq!(doc.render(0, 160).unwrap().rgba, frame.rgba);
}

View File

@ -2,6 +2,17 @@
## Unreleased
### 0.1.26
- Display transparent slide areas on white by default. Appearance now offers
Page background and Fit padding color, shared by previews, browser and audience
output and saved globally. Existing cached slides update without rerendering;
emergency/manual blanking remains black. Correct PDF alpha conversion and regenerate
older PDF artifacts under a new key to avoid dark translucent edges. Linux tests,
native X11 smoke, formatting, Clippy/rustdoc and Python checks pass; full local
whole-app coverage is 86.40%. Physical multi-monitor and Windows/macOS checks
were not run.
### 0.1.25
- Make the README user-facing with release-first installation, portable download

View File

@ -7,5 +7,5 @@
"edge": 1280,
"width": 1280,
"height": 720,
"artifact": "0-1280-hayro09.rgba"
"artifact": "0-1280-hayro09-straight.rgba"
}

View File

@ -7,6 +7,10 @@ presentation_fullscreen = true
thumbnail_size = 220.0
buffer_mib = 1024
[slide_colors]
page_background = [255, 255, 255]
fit_padding = [0, 0, 0]
[routes]
presenter = ["Primary#1"]
presentation = ["Projector#1"]

View File

@ -12,7 +12,12 @@ Each completed artifact has `<zero-based-page>-<requested-edge>-extraction.json`
`version` 1, `source` canonical source path, `sha256` source content digest,
`renderer` `hayro-0.9/image-0.25`, `page`, `edge` (maximum pixel dimension), `width`,
`height` (actual pixels), `artifact` (basename). Example: `examples/extraction-v1.json`.
The artifact key includes page, requested edge and renderer generation (`hayro09`).
The artifact key includes page, requested edge and renderer generation. Since
0.1.26, PDF artifacts use `hayro09-straight`: Hayro premultiplied output is converted
to straight RGBA before caching. Older `hayro09` PDF artifacts are regenerated to
correct dark translucent edges; image artifacts retain `hayro09`. The v1 binary
format is unchanged. Page/padding display colors are composed after loading and
are neither baked into artifacts nor part of the cache key.
Changing rendering semantics requires a new cache namespace/key. Notes are omitted.
PDF page crop/rotation is interpreted by Hayro; no presenter-note-region crop applies.

View File

@ -95,3 +95,10 @@ monotonic deadline and does not persist routes/fullscreen flags until confirmed.
A late Keep is treated as rollback. Host EOF clears recovery controls so orphan
Escape/Close remains available. Notes, source paths and operator layout data are
still absent from this control payload. Private same-build IPC only.
## Slide background colors, 0.1.26
HostState carries `slide_colors` with `page_background` and `fit_padding` RGB byte
triples (default white/black). Color updates use the existing state sequence and
repaint existing textures without changing buffer generation or reading slide files.
Blank output remains black. Same-executable protocol only.

View File

@ -12,6 +12,14 @@ with an error, without rewriting the bad file. Missing files use defaults. Reads
bounded to 4 MiB. Writes validate then atomically replace using a same-directory
flushed temporary file. Unknown fields are ignored and not preserved on round trip.
- `slide_colors.page_background` and `slide_colors.fit_padding`: opaque sRGB
arrays of exactly three integers, each 0–255, added in 0.1.26. Defaults are
`[255, 255, 255]` (white beneath transparent slide pixels) and `[0, 0, 0]`
(black around the aspect-fitted slide). Missing tables/fields in older v1 files
use these defaults; malformed lengths/out-of-range channels fail deserialization.
Both are global, round-trip unchanged, persist asynchronously and apply immediately
to all previews and audience windows. They do not alter source or cached pixels,
project layouts, or manual/emergency black blanking.
- `auto_show`: boolean, default true (0.1.14). Enables output on startup and successful
document open; false starts/opens blanked. Manual navigation preserves blanking.
Display topology changes, safe fullscreen exit and host recovery still blank output.

View File

@ -210,3 +210,12 @@ Enable **Slide progress bar** for a presenter-only current slide / total indicat
at the bottom of the content area. 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.
## Slide background colors
In **Menu → Appearance**, **Page background** fills transparent areas of PDFs and
pictures (white by default). **Fit padding color** fills the space above/below or
beside a slide when its proportions differ from the display (black by default).
Both controls update the presenter previews, slide browser and audience output,
and are saved for future sessions. Opaque artwork keeps its original colors.
Blanking the audience output still shows black. Source documents remain unchanged.