wallr-core 0.3.1

Core library for wallr — wallpaper engine, animation system, theme provider dispatch, and package management.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

use image::GenericImageView;
use tracing::info;
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::{Window, WindowId};

use crate::animation::{Effect, compute_effect_uniforms};
use crate::renderer::Renderer;

#[derive(Debug, thiserror::Error)]
pub enum PreviewError {
    #[error("failed to open preview window: {0}")]
    Window(String),
}

pub struct PreviewWindow {
    pub target_path: PathBuf,
    pub duration: std::time::Duration,
    pub effect: Effect,
}

impl PreviewWindow {
    pub fn new(target_path: PathBuf) -> Self {
        Self {
            target_path,
            duration: std::time::Duration::from_millis(2000),
            effect: Effect::Grow(crate::animation::GrowParams::default()),
        }
    }

    pub async fn run(&self) -> Result<(), PreviewError> {
        info!("Initializing preview mode for: {:?}", self.target_path);

        let event_loop = EventLoop::new().map_err(|e| PreviewError::Window(e.to_string()))?;
        event_loop.set_control_flow(ControlFlow::Poll);

        let mut app = PreviewApp::new(self.target_path.clone(), self.duration, self.effect.clone());
        event_loop
            .run_app(&mut app)
            .map_err(|e| PreviewError::Window(e.to_string()))?;
        Ok(())
    }
}

/// The daemon persists the path of the last applied wallpaper here.
fn last_wallpaper_state() -> Option<PathBuf> {
    let state_path = dirs::cache_dir()
        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
        .join("wallr/last_wallpaper");
    std::fs::read_to_string(state_path)
        .ok()
        .map(|s| PathBuf::from(s.trim()))
}

/// Load the last applied wallpaper for use as the outgoing frame. Returns
/// `None` when nothing was ever applied or when it is the same file as the
/// incoming image (a same-to-same transition would show nothing).
fn load_last_wallpaper(target: &std::path::Path) -> Option<image::DynamicImage> {
    let last = last_wallpaper_state().filter(|p| p.exists())?;
    let same = last.canonicalize().unwrap_or_else(|_| last.clone())
        == target
            .canonicalize()
            .unwrap_or_else(|_| target.to_path_buf());
    if same {
        return None;
    }
    image::ImageReader::open(&last).ok()?.decode().ok()
}

struct PreviewApp {
    target_path: PathBuf,
    duration: std::time::Duration,
    effect: Effect,
    window: Option<Arc<Window>>,
    renderer: Option<Renderer>,
    surface: Option<wgpu::Surface<'static>>,
    surface_format: Option<wgpu::TextureFormat>,
    bg_bind: Option<wgpu::BindGroup>,
    new_bind: Option<wgpu::BindGroup>,
    _bg_tex: Option<wgpu::Texture>,
    _new_tex: Option<wgpu::Texture>,
    start: Option<Instant>,
    img_size: (u32, u32),
    old_img_size: (u32, u32),
    animated: Option<crate::animated::AnimatedImage>,
    play_tex: Option<wgpu::Texture>,
    play_bind: Option<wgpu::BindGroup>,
    shown_frame: usize,
    video: Option<crate::video::VideoPlayback>,
    video_texture: Option<crate::renderer::VideoTexture>,
    video_size: (u32, u32),
    per_output_uniforms: Option<crate::renderer::PerOutputUniforms>,
}

impl PreviewApp {
    fn new(target_path: PathBuf, duration: std::time::Duration, effect: Effect) -> Self {
        Self {
            target_path,
            duration,
            effect,
            window: None,
            renderer: None,
            surface: None,
            surface_format: None,
            bg_bind: None,
            new_bind: None,
            _bg_tex: None,
            _new_tex: None,
            start: None,
            img_size: (1, 1),
            old_img_size: (1, 1),
            animated: None,
            play_tex: None,
            play_bind: None,
            shown_frame: usize::MAX,
            video: None,
            video_texture: None,
            video_size: (1, 1),
            per_output_uniforms: None,
        }
    }

    fn configure_surface(
        &self,
        renderer: &Renderer,
        surface: &wgpu::Surface<'static>,
        format: wgpu::TextureFormat,
        width: u32,
        height: u32,
    ) {
        surface.configure(
            &renderer.device,
            &wgpu::SurfaceConfiguration {
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                format,
                width: width.max(1),
                height: height.max(1),
                present_mode: wgpu::PresentMode::AutoVsync,
                alpha_mode: wgpu::CompositeAlphaMode::Auto,
                view_formats: vec![],
                desired_maximum_frame_latency: 2,
            },
        );
    }
}

impl ApplicationHandler for PreviewApp {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_some() {
            return;
        }

        let window = match event_loop.create_window(
            Window::default_attributes()
                .with_title("wallr preview")
                .with_inner_size(LogicalSize::new(1280.0, 720.0)),
        ) {
            Ok(w) => Arc::new(w),
            Err(e) => {
                eprintln!("failed to create preview window: {e}");
                event_loop.exit();
                return;
            }
        };

        let renderer = match pollster::block_on(Renderer::new()) {
            Ok(r) => r,
            Err(e) => {
                eprintln!("renderer init failed: {e}");
                event_loop.exit();
                return;
            }
        };

        let surface = match renderer.instance.create_surface(window.clone()) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("surface creation failed: {e}");
                event_loop.exit();
                return;
            }
        };

        let caps = surface.get_capabilities(&renderer.adapter);
        let format = caps
            .formats
            .iter()
            .find(|f| f.is_srgb())
            .copied()
            .unwrap_or(caps.formats[0]);

        let size = window.inner_size();
        self.configure_surface(&renderer, &surface, format, size.width, size.height);

        // Video preview: stream decoded frames directly into the preview
        // window. Images and GIFs keep the transition-based preview path.
        if crate::video::VideoDecoder::is_video_file(&self.target_path) {
            let playback = crate::video::VideoPlayback::new();
            match playback.start(
                &self.target_path,
                crate::video::HwAccel::from_config("auto"),
                crate::config::VideoConfig::default().preload_frames,
                0,
            ) {
                Ok(meta) => {
                    let first = playback.wait_first_frame(std::time::Duration::from_millis(2000));
                    let (w, h) = (meta.width, meta.height);
                    let texture = renderer.create_video_texture(w, h);
                    if let Some(frame) = first {
                        if let Err(e) = renderer.update_video_texture(&texture, &frame.data) {
                            eprintln!("failed to upload first video frame: {e}");
                            event_loop.exit();
                            return;
                        }
                    }
                    self.video = Some(playback);
                    self.video_texture = Some(texture);
                    self.video_size = (w, h);
                    self.window = Some(window);
                    self.per_output_uniforms = Some(renderer.create_per_output_uniforms());
                    self.renderer = Some(renderer);
                    self.surface = Some(surface);
                    self.surface_format = Some(format);
                    self.start = Some(Instant::now());
                    return;
                }
                Err(e) => {
                    eprintln!("failed to start video preview: {e}");
                    event_loop.exit();
                    return;
                }
            }
        }

        let img = match image::ImageReader::open(&self.target_path) {
            Ok(reader) => match reader.decode() {
                Ok(img) => img,
                Err(e) => {
                    eprintln!("failed to decode image: {e}");
                    event_loop.exit();
                    return;
                }
            },
            Err(e) => {
                eprintln!("failed to open image: {e}");
                event_loop.exit();
                return;
            }
        };

        let (new_tex, new_bind) = match renderer.load_texture(&img) {
            Ok(t) => t,
            Err(e) => {
                eprintln!("failed to upload image: {e}");
                event_loop.exit();
                return;
            }
        };

        let (w, h) = img.dimensions();

        // Fade in over the last applied wallpaper (persisted by the daemon),
        // so the preview shows a real transition like on the desktop. Fall
        // back to a solid black texture when nothing was ever applied, when
        // the outgoing image cannot be loaded, or when it is the same file
        // as the incoming one (a same-to-same loop would show nothing).
        let (bg_tex, bg_bind, old_size) =
            match load_last_wallpaper(&self.target_path).and_then(|bg| {
                renderer
                    .load_texture(&bg)
                    .ok()
                    .map(|(tex, bind)| (tex, bind, bg.dimensions()))
            }) {
                Some((tex, bind, size)) => (tex, bind, size),
                None => {
                    let black = image::DynamicImage::ImageRgba8(image::ImageBuffer::from_pixel(
                        w.max(1),
                        h.max(1),
                        image::Rgba([0, 0, 0, 255]),
                    ));
                    match renderer.load_texture(&black) {
                        Ok((tex, bind)) => (tex, bind, (w, h)),
                        Err(e) => {
                            eprintln!("failed to upload background: {e}");
                            event_loop.exit();
                            return;
                        }
                    }
                }
            };

        // When the target is an animated GIF, the transition runs once over
        // the first frame and then the preview switches to live playback,
        // just like the daemon does on the desktop.
        self.animated = crate::animated::AnimatedImage::decode(&self.target_path)
            .ok()
            .flatten();
        if let Some(anim) = self.animated.as_mut() {
            let (w, h) = (anim.width, anim.height);
            let (tex, bind) = renderer.create_texture(w, h);
            let first = anim.first_frame();
            if !first.is_empty() {
                renderer.update_texture(&tex, first, w, h);
            }
            self.play_tex = Some(tex);
            self.play_bind = Some(bind);
        }

        self.window = Some(window);
        self.per_output_uniforms = Some(renderer.create_per_output_uniforms());
        self.renderer = Some(renderer);
        self.surface = Some(surface);
        self.surface_format = Some(format);
        self.bg_bind = Some(bg_bind);
        self.new_bind = Some(new_bind);
        self._bg_tex = Some(bg_tex);
        self._new_tex = Some(new_tex);
        self.img_size = img.dimensions();
        self.old_img_size = old_size;
        self.start = Some(Instant::now());
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(size) => {
                if let (Some(renderer), Some(surface), Some(format)) =
                    (&self.renderer, &self.surface, self.surface_format)
                {
                    self.configure_surface(renderer, surface, format, size.width, size.height);
                }
            }
            WindowEvent::RedrawRequested => self.render_frame(event_loop),
            _ => {}
        }
    }

    fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
        if let Some(window) = &self.window {
            window.request_redraw();
        }
    }
}

impl PreviewApp {
    fn render_frame(&mut self, event_loop: &ActiveEventLoop) {
        // Video targets skip the transition and stream frames live.
        if self.video.is_some() {
            self.render_video_frame(event_loop);
            return;
        }

        let Some(start) = self.start else { return };

        let elapsed = start.elapsed().as_millis() as f32;
        let total = self.duration.as_millis() as f32;
        let progress = if self.animated.is_some() {
            // Animated targets: the transition runs exactly once, then the
            // preview switches to live playback of the GIF frames.
            (elapsed / total).min(1.0)
        } else {
            // Loop the transition forever so the effect can be judged
            // repeatedly. The final frame is held for 25% of the duration so
            // the loop restart reads as a deliberate pause, not a hard snap
            // back to the outgoing wallpaper.
            let hold = total * 0.25;
            let cycle = elapsed % (total + hold);
            (cycle / total).min(1.0)
        };

        let size = self
            .window
            .as_ref()
            .map(|w| w.inner_size())
            .unwrap_or(winit::dpi::PhysicalSize::new(1, 1));

        if self.animated.is_some() && progress >= 1.0 {
            self.render_live_frame(event_loop, size, elapsed, total);
            return;
        }

        let Some(renderer) = &self.renderer else {
            return;
        };
        let Some(surface) = &self.surface else { return };
        let Some(format) = self.surface_format else {
            return;
        };
        let Some(bg) = &self.bg_bind else { return };
        let Some(new_bind) = &self.new_bind else {
            return;
        };

        let (img_w, img_h) = self.img_size;
        let (old_w, old_h) = self.old_img_size;

        let uniforms = compute_effect_uniforms(&self.effect, progress);

        match renderer.render_frame(
            crate::renderer::FrameRequest {
                surface,
                format,
                bg_bind: bg,
                new_bind,
                effect: &uniforms,
                width: size.width,
                height: size.height,
                img_width: img_w,
                img_height: img_h,
                old_img_width: old_w,
                old_img_height: old_h,
                scaling_mode: 0,
            },
            self.per_output_uniforms.as_ref().unwrap(),
        ) {
            Ok(crate::renderer::FrameStatus::TimedOut) => {
                // The surface is not presenting right now (e.g. the window is
                // hidden or the monitor is off); keep polling so the preview
                // resumes cleanly once frames flow again.
            }
            Err(e) => {
                eprintln!("render error: {e}");
                event_loop.exit();
            }
            _ => {}
        }
    }

    /// Mirrors the daemon's `play_video` loop: pull the next displayable frame
    /// per vsync and present it, never blocking on the bounded decoder queue.
    fn render_video_frame(&mut self, event_loop: &ActiveEventLoop) {
        let Some(renderer) = &self.renderer else {
            return;
        };
        let Some(surface) = &self.surface else { return };
        let Some(format) = self.surface_format else {
            return;
        };
        let Some(playback) = &self.video else { return };
        let Some(texture) = &self.video_texture else {
            return;
        };

        let size = self
            .window
            .as_ref()
            .map(|w| w.inner_size())
            .unwrap_or(winit::dpi::PhysicalSize::new(1, 1));

        let (w, h) = self.video_size;
        if let Some(frame) = playback.next_frame()
            && frame.width == w
            && frame.height == h
        {
            if let Err(e) = renderer.update_video_texture(texture, &frame.data) {
                eprintln!("video upload error: {e}");
                event_loop.exit();
                return;
            }
        }

        let uniforms = compute_effect_uniforms(&self.effect, 1.0);
        match renderer.render_frame(
            crate::renderer::FrameRequest {
                surface,
                format,
                bg_bind: texture.bind_group(),
                new_bind: texture.bind_group(),
                effect: &uniforms,
                width: size.width.max(1),
                height: size.height.max(1),
                img_width: w,
                img_height: h,
                old_img_width: w,
                old_img_height: h,
                scaling_mode: 0,
            },
            self.per_output_uniforms.as_ref().unwrap(),
        ) {
            Ok(crate::renderer::FrameStatus::TimedOut) => {}
            Err(e) => {
                eprintln!("render error: {e}");
                event_loop.exit();
            }
            _ => {}
        }
    }

    /// Present GIF frames live, one per vsync, after the initial transition
    /// has completed. Texture uploads only happen when the playhead crosses
    /// into a new frame, so playback is smooth without re-uploading frames
    /// that are already showing.
    fn render_live_frame(
        &mut self,
        event_loop: &ActiveEventLoop,
        size: winit::dpi::PhysicalSize<u32>,
        elapsed: f32,
        total: f32,
    ) {
        let Some(renderer) = &self.renderer else {
            return;
        };
        let Some(surface) = &self.surface else { return };
        let Some(format) = self.surface_format else {
            return;
        };
        let Some(anim) = self.animated.as_mut() else {
            return;
        };
        let Some(tex) = &self.play_tex else { return };
        let Some(bind) = &self.play_bind else { return };

        let (anim_w, anim_h) = (anim.width, anim.height);
        let live_ms = (elapsed - total).max(0.0) as u64;
        let index = anim.frame_index_at(std::time::Duration::from_millis(live_ms));
        if index != self.shown_frame {
            let frame = anim.frame_at(index);
            if !frame.is_empty() {
                renderer.update_texture(tex, frame, anim_w, anim_h);
                self.shown_frame = index;
            }
        }

        let uniforms = compute_effect_uniforms(&self.effect, 1.0);
        match renderer.render_frame(
            crate::renderer::FrameRequest {
                surface,
                format,
                bg_bind: bind,
                new_bind: bind,
                effect: &uniforms,
                width: size.width,
                height: size.height,
                img_width: anim.width,
                img_height: anim.height,
                old_img_width: anim.width,
                old_img_height: anim.height,
                scaling_mode: 0,
            },
            self.per_output_uniforms.as_ref().unwrap(),
        ) {
            Ok(crate::renderer::FrameStatus::TimedOut) => {}
            Err(e) => {
                eprintln!("render error: {e}");
                event_loop.exit();
            }
            _ => {}
        }
    }
}