diff --git a/Cargo.lock b/Cargo.lock index 8a8e423..6a45255 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2245,7 +2245,7 @@ dependencies = [ [[package]] name = "pdf-presenter" -version = "0.1.77" +version = "0.1.78" dependencies = [ "bytemuck", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 38f055d..7a54d44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"] resolver = "3" [workspace.package] -version = "0.1.77" +version = "0.1.78" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter" diff --git a/crates/pdf-presenter/src/lib.rs b/crates/pdf-presenter/src/lib.rs index 98cd3c1..b0922c4 100644 --- a/crates/pdf-presenter/src/lib.rs +++ b/crates/pdf-presenter/src/lib.rs @@ -66,6 +66,8 @@ pub mod poc; pub mod document; /// Native persistent configuration. pub mod settings; +/// Optional per-user Windows shell integration for the portable executable. +pub mod windows_integration; /// Isolated background processes. pub mod worker; diff --git a/crates/pdf-presenter/src/main.rs b/crates/pdf-presenter/src/main.rs index 27767ac..f554f1d 100644 --- a/crates/pdf-presenter/src/main.rs +++ b/crates/pdf-presenter/src/main.rs @@ -1,3 +1,8 @@ +#![cfg_attr( + all(target_os = "windows", not(debug_assertions)), + windows_subsystem = "windows" +)] + use pdf_presenter::{native, poc::Options}; fn main() { diff --git a/crates/pdf-presenter/src/native.rs b/crates/pdf-presenter/src/native.rs index 753a413..178907f 100644 --- a/crates/pdf-presenter/src/native.rs +++ b/crates/pdf-presenter/src/native.rs @@ -10,6 +10,7 @@ use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender}; use std::{ collections::{HashMap, HashSet}, num::NonZeroU32, + path::PathBuf, rc::Rc, sync::{ Arc, @@ -50,10 +51,38 @@ enum Role { Browser, Presentation, } +const OUTPUT_BASE_CACHE_MAX_PIXELS: usize = 4096 * 4096; + +#[derive(Clone, Debug, PartialEq)] +struct PresentationBaseKey { + size: [u32; 2], + pixels_per_point: f32, + frame: Option<(PathBuf, String, u32, u32)>, + blank: bool, + colors: crate::settings::SlideColors, + zoom: crate::zoom::Sync, +} + +struct PresentationBase { + key: PresentationBaseKey, + pixels: Vec, +} + +impl PresentationBase { + fn restore(&self, key: &PresentationBaseKey, pixels: &mut [u32]) -> bool { + if self.key != *key || self.pixels.len() != pixels.len() { + return false; + } + pixels.copy_from_slice(&self.pixels); + true + } +} + struct NativeWindow { surface: softbuffer::Surface, Rc>, window: Rc, ctx: egui::Context, + overlay_ctx: egui::Context, input: egui_winit::State, painter: EguiSoftwareRender, ui: UiState, @@ -67,6 +96,7 @@ struct NativeWindow { zoom_change: Option, zoom_watch: crate::zoom::PerformanceWatch, zoom_slow: bool, + presentation_base: Option, #[cfg(target_os = "linux")] browser_parent: Option, } @@ -85,6 +115,7 @@ impl NativeWindow { winit::window::WindowLevel::Normal }) .with_visible(false) + .with_active(role != Role::Presentation) .with_inner_size(PhysicalSize::new(1100, 750)); #[cfg(target_os = "linux")] let attributes = if role == Role::Browser { @@ -97,6 +128,7 @@ impl NativeWindow { let surface = softbuffer::Surface::new(&softbuffer::Context::new(window.clone())?, window.clone())?; let ctx = egui::Context::default(); + let overlay_ctx = egui::Context::default(); presenter_ui::theme(&ctx); let input = egui_winit::State::new( ctx.clone(), @@ -110,6 +142,7 @@ impl NativeWindow { surface, window, ctx, + overlay_ctx, input, painter: EguiSoftwareRender::new(ColorFieldOrder::Bgra), ui: UiState::default(), @@ -123,6 +156,7 @@ impl NativeWindow { zoom_change: None, zoom_watch: Default::default(), zoom_slow: false, + presentation_base: None, #[cfg(target_os = "linux")] browser_parent: None, }) @@ -164,7 +198,7 @@ impl NativeWindow { )); } self.window.set_visible(true); - if self.role == Role::Browser { + if self.role != Role::Presentation { self.window.focus_window(); } self.window @@ -215,6 +249,8 @@ impl NativeWindow { let ctx = self.ctx.clone(); let display_action = &mut self.display_action; let zoom_change = &mut self.zoom_change; + let mut presentation_view = setup.map(|s| s.zoom.view).unwrap_or_default(); + let mut overlay_rects = None; let output = ctx.run_ui(input, |ui| match role { Role::Presenter => presenter_ui::presenter_on_display( ui, @@ -253,7 +289,7 @@ impl NativeWindow { egui::TextureOptions::LINEAR, ) }); - let mut view = setup.map(|s| s.zoom.view).unwrap_or_default(); + let mut view = presentation_view; if let Some(setup) = setup && setup.zoom.enabled && setup.route_trial.is_none() @@ -285,6 +321,7 @@ impl NativeWindow { view = next; } } + presentation_view = view; presenter_ui::paint_slide_adapted( ui.painter(), ui.max_rect(), @@ -308,7 +345,7 @@ impl NativeWindow { view, setup.zoom.keep_fitted_area, ); - crate::tools::paint(ui.painter(), target, uv, &setup.overlay); + overlay_rects = Some((ui.max_rect(), target, uv)); } } } @@ -328,17 +365,85 @@ impl NativeWindow { NonZeroU32::new(size.height).unwrap(), )?; let mut buffer = self.surface.buffer_mut()?; - buffer.fill(0); - self.painter.render( - &mut BufferMutRef::new( - bytemuck::cast_slice_mut(&mut buffer), - size.width as usize, - size.height as usize, - ), - &primitives, - &output.textures_delta, - output.pixels_per_point, - ); + let pixel_count = size.width as usize * size.height as usize; + let cache_key = (role == Role::Presentation + && pixel_count <= OUTPUT_BASE_CACHE_MAX_PIXELS + && setup.is_some_and(|s| !s.setup_controls && s.route_trial.is_none())) + .then(|| PresentationBaseKey { + size: [size.width, size.height], + pixels_per_point: output.pixels_per_point, + frame: frame.map(|frame| { + ( + frame.info.path.clone(), + frame.info.sha256.clone(), + frame.info.width, + frame.info.height, + ) + }), + blank, + colors: setup.map(|s| s.slide_colors).unwrap_or_default(), + zoom: crate::zoom::Sync { + view: presentation_view, + ..setup.map(|s| s.zoom).unwrap_or_default() + }, + }); + let restored = cache_key.as_ref().is_some_and(|key| { + self.presentation_base + .as_ref() + .is_some_and(|cached| cached.restore(key, &mut buffer)) + }); + if !restored { + buffer.fill(0); + self.painter.render( + &mut BufferMutRef::new( + bytemuck::cast_slice_mut(&mut buffer), + size.width as usize, + size.height as usize, + ), + &primitives, + &output.textures_delta, + output.pixels_per_point, + ); + self.presentation_base = cache_key.map(|key| PresentationBase { + key, + pixels: buffer.to_vec(), + }); + } else if !output.textures_delta.is_empty() { + self.painter.render( + &mut BufferMutRef::new( + bytemuck::cast_slice_mut(&mut buffer), + size.width as usize, + size.height as usize, + ), + &[], + &output.textures_delta, + output.pixels_per_point, + ); + } + if let (Some(setup), Some((screen, target, uv))) = (setup, overlay_rects) + && (setup.overlay.pointer.is_some() || !setup.overlay.marks.is_empty()) + { + let overlay = self.overlay_ctx.run_ui( + egui::RawInput { + screen_rect: Some(screen), + ..Default::default() + }, + |ui| crate::tools::paint(ui.painter(), target, uv, &setup.overlay), + ); + let overlay_primitives = self + .overlay_ctx + .tessellate(overlay.shapes, output.pixels_per_point); + self.painter.render( + &mut BufferMutRef::new( + bytemuck::cast_slice_mut(&mut buffer), + size.width as usize, + size.height as usize, + ), + &overlay_primitives, + &overlay.textures_delta, + output.pixels_per_point, + ); + } self.window.pre_present_notify(); buffer.present()?; self.frames += 1; @@ -1667,6 +1772,27 @@ pub fn run_output() -> Result<(), Failure> { mod buffer_tests { use super::*; #[test] + fn presentation_base_restores_only_an_exact_frame() { + let key = PresentationBaseKey { + size: [2, 2], + pixels_per_point: 1., + frame: Some(("slide.rgba".into(), "sha".into(), 2, 2)), + blank: false, + colors: Default::default(), + zoom: Default::default(), + }; + let cached = PresentationBase { + key: key.clone(), + pixels: vec![1, 2, 3, 4], + }; + let mut pixels = vec![0; 4]; + assert!(cached.restore(&key, &mut pixels)); + assert_eq!(pixels, [1, 2, 3, 4]); + let changed = PresentationBaseKey { blank: true, ..key }; + assert!(!cached.restore(&changed, &mut pixels)); + assert!(!cached.restore(&cached.key, &mut [0; 3])); + } + #[test] fn repaint_deadlines_bound_animation_and_leave_idle_windows_asleep() { let now = Instant::now(); assert_eq!(repaint_deadline(now, Duration::MAX), None); diff --git a/crates/pdf-presenter/src/presenter_ui.rs b/crates/pdf-presenter/src/presenter_ui.rs index 5af3317..e550249 100644 --- a/crates/pdf-presenter/src/presenter_ui.rs +++ b/crates/pdf-presenter/src/presenter_ui.rs @@ -2423,6 +2423,16 @@ fn menu(ui: &mut Ui, s: &mut Studio) { if s.blank_busy { ui.spinner(); } }); ui.separator(); + #[cfg(target_os = "windows")] + ui.collapsing(if s.settings.language.french() { "Intégration Windows" } else { "Windows integration" }, |ui| { + ui.label(if s.settings.language.french() { "Enregistre l’application et son icône pour les fichiers PDF, sans droits administrateur." } else { "Register the app and its icon for PDF files without administrator rights." }); + if ui.button(if s.settings.language.french() { "Choisir comme application PDF…" } else { "Choose as PDF app…" }).clicked() { + s.actions.push(Action::RegisterPdfAssociation); + } + ui.small(if s.settings.language.french() { "Windows ouvre Applications par défaut pour confirmer votre choix." } else { "Windows opens Default Apps so you can confirm the choice." }); + }); + #[cfg(target_os = "windows")] + ui.separator(); let mut enabled = s.settings.zoom_enabled; if ui.checkbox(&mut enabled, tr(&locale, "Enable page zoom")).changed() { s.enable_zoom(enabled); } if ui.checkbox(&mut s.settings.zoom_keep_fitted_area, tr(&locale, "Keep fitted page area when zooming")).changed() { diff --git a/crates/pdf-presenter/src/studio.rs b/crates/pdf-presenter/src/studio.rs index 865a077..c1c2903 100644 --- a/crates/pdf-presenter/src/studio.rs +++ b/crates/pdf-presenter/src/studio.rs @@ -25,6 +25,8 @@ pub enum Action { PickBlankPicture, SetBlankPicture(PathBuf), ClearBlankPicture, + #[cfg(target_os = "windows")] + RegisterPdfAssociation, ImportNotes(PathBuf), ApplyNotesImport, Go(usize), @@ -459,6 +461,13 @@ impl Studio { self.pending_save = true; self.status = "Blank presentation uses solid black.".into(); } + #[cfg(target_os = "windows")] + Action::RegisterPdfAssociation => { + self.status = match crate::windows_integration::register_pdf_association() { + Ok(()) => "Choose PDF Presenter for .pdf in Windows Default Apps. PDF files will then use its icon.".into(), + Err(error) => format!("Could not register PDF Presenter: {error}"), + }; + } Action::PickNotes => { if !self.dialog_busy && !self.loading diff --git a/crates/pdf-presenter/src/windows_integration.rs b/crates/pdf-presenter/src/windows_integration.rs new file mode 100644 index 0000000..5fe2b21 --- /dev/null +++ b/crates/pdf-presenter/src/windows_integration.rs @@ -0,0 +1,181 @@ +//! Per-user Windows shell registration for the portable executable. + +#[cfg(any(target_os = "windows", test))] +use std::path::Path; + +#[cfg(any(target_os = "windows", test))] +fn open_command(executable: &Path) -> String { + format!(r#"\"{}\" --open \"%1\""#, executable.display()) +} + +#[cfg(target_os = "windows")] +pub fn register_pdf_association() -> Result<(), String> { + use std::{ffi::c_void, os::windows::ffi::OsStrExt, ptr}; + + type Hkey = *mut c_void; + const HKEY_CURRENT_USER: Hkey = 0x8000_0001usize as Hkey; + const KEY_SET_VALUE: u32 = 0x0002; + const REG_SZ: u32 = 1; + const SHCNE_ASSOCCHANGED: i32 = 0x0800_0000; + const SHCNF_IDLIST: u32 = 0; + + #[link(name = "advapi32")] + unsafe extern "system" { + fn RegCreateKeyExW( + root: Hkey, + subkey: *const u16, + reserved: u32, + class: *mut u16, + options: u32, + access: u32, + security: *const c_void, + result: *mut Hkey, + disposition: *mut u32, + ) -> i32; + fn RegSetValueExW( + key: Hkey, + name: *const u16, + reserved: u32, + kind: u32, + data: *const u8, + bytes: u32, + ) -> i32; + fn RegCloseKey(key: Hkey) -> i32; + } + #[link(name = "shell32")] + unsafe extern "system" { + fn SHChangeNotify(event: i32, flags: u32, item1: *const c_void, item2: *const c_void); + fn ShellExecuteW( + window: *mut c_void, + operation: *const u16, + file: *const u16, + parameters: *const u16, + directory: *const u16, + show: i32, + ) -> isize; + } + + fn wide(value: &std::ffi::OsStr) -> Vec { + value.encode_wide().chain(Some(0)).collect() + } + fn set_value(root: Hkey, subkey: &str, name: Option<&str>, value: &str) -> Result<(), String> { + let subkey = wide(std::ffi::OsStr::new(subkey)); + let name = name.map(|name| wide(std::ffi::OsStr::new(name))); + let value = wide(std::ffi::OsStr::new(value)); + let mut key = ptr::null_mut(); + // SAFETY: all pointers refer to live, NUL-terminated buffers. The returned + // handle is closed before this function returns. + let created = unsafe { + RegCreateKeyExW( + root, + subkey.as_ptr(), + 0, + ptr::null_mut(), + 0, + KEY_SET_VALUE, + ptr::null(), + &mut key, + ptr::null_mut(), + ) + }; + if created != 0 { + return Err(format!("Windows registry error {created}")); + } + // SAFETY: key is valid and value/name remain live for the duration of the call. + let written = unsafe { + RegSetValueExW( + key, + name.as_ref().map_or(ptr::null(), |name| name.as_ptr()), + 0, + REG_SZ, + value.as_ptr().cast(), + (value.len() * 2) as u32, + ) + }; + // SAFETY: key was returned by RegCreateKeyExW and is no longer used. + unsafe { RegCloseKey(key) }; + (written == 0) + .then_some(()) + .ok_or_else(|| format!("Windows registry error {written}")) + } + + let executable = std::env::current_exe().map_err(|error| error.to_string())?; + let executable_text = executable.to_string_lossy(); + let icon = format!(r#"\"{executable_text}\",0"#); + let command = open_command(&executable); + let values = [ + ( + r"Software\Classes\PDFPresenter.Document", + None, + "PDF Presenter document", + ), + ( + r"Software\Classes\PDFPresenter.Document\DefaultIcon", + None, + icon.as_str(), + ), + ( + r"Software\Classes\PDFPresenter.Document\shell\open\command", + None, + command.as_str(), + ), + ( + r"Software\PDF Presenter\Capabilities", + Some("ApplicationName"), + "PDF Presenter", + ), + ( + r"Software\PDF Presenter\Capabilities", + Some("ApplicationDescription"), + "Fast multi-screen PDF presenter", + ), + ( + r"Software\PDF Presenter\Capabilities\FileAssociations", + Some(".pdf"), + "PDFPresenter.Document", + ), + ( + r"Software\RegisteredApplications", + Some("PDF Presenter"), + r"Software\PDF Presenter\Capabilities", + ), + ]; + for (subkey, name, value) in values { + set_value(HKEY_CURRENT_USER, subkey, name, value)?; + } + // SAFETY: association refresh carries no payload for SHCNE_ASSOCCHANGED. + unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, ptr::null(), ptr::null()) }; + + let operation = wide(std::ffi::OsStr::new("open")); + let settings = wide(std::ffi::OsStr::new("ms-settings:defaultapps")); + // SAFETY: strings are NUL terminated and remain live through the call. + let opened = unsafe { + ShellExecuteW( + ptr::null_mut(), + operation.as_ptr(), + settings.as_ptr(), + ptr::null(), + ptr::null(), + 1, + ) + }; + if opened <= 32 { + return Err(format!( + "Registered successfully, but Windows Settings could not open ({opened})" + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn association_command_quotes_executable_and_document() { + assert_eq!( + open_command(Path::new(r"C:\Portable Apps\pdf-presenter.exe")), + r#"\"C:\Portable Apps\pdf-presenter.exe\" --open \"%1\""# + ); + } +} diff --git a/docs/changelog.md b/docs/changelog.md index f34cdd0..1624569 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,26 @@ ## Unreleased +### 0.1.78 + +- Reuse one bounded base framebuffer per presentation window for pointer and + annotation updates instead of scaling and rasterizing the full slide again. + Slide, zoom, color, DPI, blanking and resize changes invalidate the cache; + interactive display recovery bypasses it. The cache is capped at 64 MiB per + output window. +- Build the Windows release executable as a GUI application so it does not open a + terminal, create presentation windows without activation, and explicitly focus + the presenter when its initial placement becomes visible. +- Add an optional per-user Windows PDF-app registration from Preferences. It points + the document icon and open command at the portable executable, refreshes Explorer, + and opens Default Apps for the user-controlled confirmation. +- Linux all-feature tests, formatting, Clippy, rustdoc, Python tests and the + optimized build pass; headless whole-application line coverage is 68.39%. Full + GUI coverage could not run because Xvfb is unavailable, and the local Windows + cross-check stops at the existing icon build step because MinGW windres is absent. + Windows multi-monitor latency, initial focus and association behavior remain + physical acceptance checks. + ### 0.1.77 - Add an optional custom picture for Blank presentation in Preferences, shared by diff --git a/docs/user-guide.md b/docs/user-guide.md index e066e5b..5d5a7b2 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -15,6 +15,12 @@ folder in a permanent location and run `python3 install-linux-launcher.py` there Python is only needed for this optional installer; no administrator privileges are required. +On Windows, use **Menu → Preferences → Windows integration → Choose as PDF +app…** to register the portable executable for the current user. Windows opens +Default Apps for the required confirmation. Once PDF Presenter is selected for +`.pdf`, Explorer uses the icon embedded in `pdf-presenter.exe` for PDF files. Keep +the extracted folder in a permanent location; repeat the action after moving it. + To update, close PDF Presenter, download and extract the new portable release, and run its executable. Settings and saved layouts live in your user configuration directory, outside the extracted folder. If you installed the Linux launcher, rerun