wallr-common 0.8.3

Shared protocol between the wallr client and daemon: effects, IPC, CLI shapes, and config schema.
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
use crate::effect::{Effect, EffectOverrides, apply_effect_overrides, effect_from_name};
use crate::types::{ScalingMode, ThemeProvider};
use clap::builder::styling::{AnsiColor, Styles};
use clap::{ArgAction, Args, Parser, Subcommand};
use std::path::PathBuf;

/// transition options for wallpaper changes.
#[derive(Args, Debug, Clone, Default)]
pub struct EffectArgs {
    /// transition effect: fade, wipe, slide, wave, grow, outer (plus aliases:
    /// simple, left, right, top, bottom, center, any, random)
    #[arg(short = 'e', long, value_name = "name", value_parser = parse_effect_name)]
    pub effect: Option<String>,

    /// transition duration (e.g. 700ms, 1s, 1.2s)
    #[arg(short = 'd', long, value_name = "time")]
    pub duration: Option<String>,

    /// effect origin: preset (top_left, top, top_right, left, center, right, bottom_left, bottom, bottom_right) or "x,y" (0..1)
    #[arg(short = 'o', long, value_name = "preset|x,y")]
    pub origin: Option<String>,

    /// angle for wipe/slide in degrees (0 = right-to-left, 90 = top-to-bottom, 270 = bottom-to-top)
    #[arg(short = 'a', long, value_name = "deg")]
    pub angle: Option<f32>,

    /// direction vector "x,y" (e.g. "1,0" or "-1,0")
    #[arg(long, value_name = "x,y")]
    pub direction: Option<String>,

    /// easing curve: linear, ease_in, ease_out, ease_in_out, bezier
    #[arg(long, value_enum, value_name = "curve", hide_possible_values = true)]
    pub easing: Option<crate::effect::Easing>,

    /// initial parameter value (fade opacity)
    #[arg(long, value_name = "val")]
    pub from: Option<f32>,

    /// target parameter value (fade opacity)
    #[arg(long, value_name = "val")]
    pub to: Option<f32>,

    /// wave frequency in hz
    #[arg(long, value_name = "hz")]
    pub frequency: Option<f32>,

    /// wave amplitude
    #[arg(long, value_name = "val")]
    pub amplitude: Option<f32>,

    /// wipe feather softness (0.01 - 0.5)
    #[arg(long, value_name = "val")]
    pub softness: Option<f32>,
}

impl EffectArgs {
    /// build an `Effect` from `--effect <name>` + all override flags.
    /// falls back to `fallback` when no effect name is given.
    pub fn to_effect(&self, fallback: Effect) -> Effect {
        let mut effect = self
            .effect
            .as_deref()
            .and_then(effect_from_name)
            .unwrap_or(fallback);
        apply_effect_overrides(&mut effect, &self.to_overrides());
        effect
    }

    pub fn to_overrides(&self) -> EffectOverrides {
        let origin = self.origin.as_deref().and_then(parse_origin);
        EffectOverrides {
            origin,
            origin_preset: if origin.is_none() {
                self.origin.clone()
            } else {
                None
            },
            direction: self.direction.as_deref().and_then(parse_vec2),
            angle: self.angle,
            easing: self.easing,
            from: self.from,
            to: self.to,
            frequency: self.frequency,
            amplitude: self.amplitude,
            softness: self.softness,
        }
    }
}

/// validate `--effect`. Aliases (left, right, top, bottom, center, any,
/// random, simple) resolve through the real parser; the error message shows
/// only the six canonical transitions.
fn parse_effect_name(s: &str) -> Result<String, String> {
    if crate::effect::effect_from_name(s).is_some() {
        Ok(s.to_string())
    } else {
        Err(format!(
            "unknown effect '{}' - expected one of: {}",
            s,
            crate::effect::effect_names().join(", ")
        ))
    }
}

/// parse "x,y" into a normalized origin, or none if it's not numeric.
fn parse_origin(s: &str) -> Option<(f32, f32)> {
    let mut parts = s.split(',');
    let x = parts.next()?.trim().parse::<f32>().ok()?;
    let y = parts.next()?.trim().parse::<f32>().ok()?;
    Some((x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)))
}

/// parse "x,y" into a direction vector.
fn parse_vec2(s: &str) -> Option<[f32; 2]> {
    let mut parts = s.split(',');
    let x = parts.next()?.trim().parse::<f32>().ok()?;
    let y = parts.next()?.trim().parse::<f32>().ok()?;
    Some([x, y])
}

/// parse an ipc seek timestamp into milliseconds.
///
/// accepts `SS`, `MM:SS`, or `HH:MM:SS` with optional fractional seconds for
/// the bare-seconds form. Rejects non-finite, negative, and overflowing input
/// instead of saturating or wrapping through a cast.
pub fn parse_timestamp_ms(timestamp: &str) -> Result<u64, String> {
    let timestamp = timestamp.trim();
    if timestamp.is_empty() {
        return Err("timestamp cannot be empty".to_string());
    }
    if timestamp.contains(':') {
        let parts: Vec<&str> = timestamp.split(':').collect();
        if !matches!(parts.len(), 2 | 3) {
            return Err("invalid timestamp format. Use HH:MM:SS or seconds".to_string());
        }
        let mut values = Vec::with_capacity(parts.len());
        for part in &parts {
            let value: u64 = part
                .parse()
                .map_err(|_| format!("invalid timestamp component: {part}"))?;
            values.push(value);
        }
        let seconds = if values.len() == 3 {
            if values[1] >= 60 || values[2] >= 60 {
                return Err("minutes and seconds must be below 60".to_string());
            }
            values[0]
                .checked_mul(3600)
                .and_then(|v| v.checked_add(values[1] * 60))
                .and_then(|v| v.checked_add(values[2]))
                .ok_or_else(|| "timestamp overflows".to_string())?
        } else {
            if values[1] >= 60 {
                return Err("seconds must be below 60".to_string());
            }
            values[0]
                .checked_mul(60)
                .and_then(|v| v.checked_add(values[1]))
                .ok_or_else(|| "timestamp overflows".to_string())?
        };
        seconds
            .checked_mul(1000)
            .ok_or_else(|| "timestamp overflows".to_string())
    } else {
        let seconds: f64 = timestamp
            .parse()
            .map_err(|_| format!("invalid timestamp: {timestamp}"))?;
        if !seconds.is_finite() || seconds < 0.0 {
            return Err("timestamp must be a finite non-negative number".to_string());
        }
        let millis = (seconds * 1000.0).round();
        if millis > u64::MAX as f64 {
            return Err("timestamp overflows".to_string());
        }
        Ok(millis as u64)
    }
}

#[derive(Parser, Debug)]
#[command(
    name = "wallr",
    about = "wayland wallpaper engine with gpu animations and theme pipelines",
    version,
    override_usage = "wallr [options] <command>",
    disable_help_subcommand = true,
    disable_help_flag = true,
    disable_version_flag = true,
    next_help_heading = "options",
    help_template = "{before-help}{name} {version}\n\n{about}\n\nusage:\n  {usage}\n\ncommands:\n{subcommands}\n\noptions:\n{options}{after-help}",
    styles = Styles::styled()
        .header(AnsiColor::Cyan.on_default().bold())
        .usage(AnsiColor::Blue.on_default().bold())
        .literal(AnsiColor::Green.on_default().bold())
        .placeholder(AnsiColor::Yellow.on_default())
)]
pub struct WallrCli {
    #[command(subcommand)]
    pub command: Commands,

    /// custom config file path
    #[arg(global = true, short = 'c', long, value_name = "path")]
    pub config: Option<PathBuf>,

    /// verbose logging (-v, -vv)
    #[arg(global = true, short = 'v', long, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// quiet mode (suppress non-error output)
    #[arg(global = true, short = 'q', long)]
    pub quiet: bool,

    /// show help
    #[arg(global = true, short = 'h', long, action = ArgAction::Help)]
    pub help: Option<bool>,

    /// show version
    #[arg(short = 'V', long, action = ArgAction::Version)]
    pub version: Option<bool>,
}

#[derive(Parser, Debug)]
#[command(
    name = "wallr-daemon",
    about = "wayland rendering service for wallr",
    version,
    disable_help_flag = true,
    disable_version_flag = true,
    next_help_heading = "options",
    help_template = "{before-help}{name} {version}\n\n{about}\n\nusage:\n  {usage}\n\noptions:\n{options}{after-help}",
    styles = Styles::styled()
        .header(AnsiColor::Cyan.on_default().bold())
        .usage(AnsiColor::Blue.on_default().bold())
        .literal(AnsiColor::Green.on_default().bold())
        .placeholder(AnsiColor::Yellow.on_default())
)]
pub struct WallrDaemonCli {
    /// configuration file path
    #[arg(short = 'c', long, value_name = "path")]
    pub config: Option<PathBuf>,

    /// cap animated wallpaper rendering (1..=240 fps)
    #[arg(long, value_name = "fps", value_parser = clap::value_parser!(u32).range(1..=240))]
    pub max_fps: Option<u32>,

    /// show daemon diagnostics (-v, -vv)
    #[arg(short = 'v', long, action = ArgAction::Count)]
    pub verbose: u8,

    /// show errors only
    #[arg(short = 'q', long)]
    pub quiet: bool,

    /// show help
    #[arg(global = true, short = 'h', long, action = ArgAction::Help)]
    pub help: Option<bool>,

    /// show version
    #[arg(short = 'V', long, action = ArgAction::Version)]
    pub version: Option<bool>,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// set wallpaper image or video
    #[command(alias = "img")]
    Set {
        /// wallpaper file path (image, gif, or video); `-` reads from stdin
        #[arg(value_name = "path")]
        path: PathBuf,

        /// target output/monitor
        #[arg(short = 'm', long, value_name = "output")]
        monitor: Option<String>,

        /// scaling mode: fill, fit, stretch, center, tile
        #[arg(long, value_enum, value_name = "mode", hide_possible_values = true)]
        mode: Option<ScalingMode>,

        /// disable theme extraction
        #[arg(long)]
        no_theme: bool,

        /// cap video presentation rate (1..=240 fps)
        #[arg(long, value_name = "fps", value_parser = clap::value_parser!(u32).range(1..=240))]
        fps: Option<u32>,

        /// override theme engine (matugen, wallust, pywal)
        #[arg(
            short = 't',
            long,
            value_enum,
            value_name = "provider",
            hide_possible_values = true
        )]
        theme: Option<ThemeProvider>,

        /// transition overrides
        #[command(flatten)]
        effect_args: EffectArgs,
    },

    /// run system and dependency diagnostics
    Doctor,

    /// view and edit configuration
    Config {
        #[command(subcommand)]
        subcommand: ConfigCommands,
    },

    /// reload config and restart theme hooks
    Reload,

    /// query connected outputs
    Monitor {
        #[command(subcommand)]
        subcommand: MonitorCommands,
    },

    /// run background daemon
    Daemon {
        /// max render fps limit
        #[arg(long, value_name = "fps", value_parser = clap::value_parser!(u32).range(1..=240))]
        max_fps: Option<u32>,
    },

    /// daemon ipc controls (playback, blanking, info)
    Ipc {
        #[command(subcommand)]
        subcommand: IpcCommands,
    },

    /// stop running daemon
    Quit,
}

#[derive(Subcommand, Debug)]
pub enum ConfigCommands {
    /// get config value by key
    Get {
        #[arg(value_name = "key")]
        key: String,
    },
    /// set config value by key
    Set {
        #[arg(value_name = "key")]
        key: String,
        #[arg(value_name = "value")]
        value: String,
    },
    /// print path to active config file
    Path,
}

#[derive(Subcommand, Debug)]
pub enum MonitorCommands {
    /// list all connected display outputs
    List,
    /// display current focused output
    Current,
}

#[derive(Subcommand, Debug)]
pub enum IpcCommands {
    /// pause video/gif playback
    Pause {
        /// target specific monitor (default: all)
        #[arg(short = 'm', long)]
        monitor: Option<String>,
    },
    /// resume video/gif playback
    Resume {
        /// target specific monitor (default: all)
        #[arg(short = 'm', long)]
        monitor: Option<String>,
    },
    /// re-render current wallpaper
    Reload,
    /// shut down the daemon
    Stop,
    /// query daemon status
    Status,
    /// query gpu, video decoder, and display info
    Info {
        /// target specific monitor
        #[arg(short = 'm', long)]
        monitor: Option<String>,
    },
    /// seek video to position (hh:mm:ss or seconds)
    Seek {
        /// position in hh:mm:ss or seconds
        #[arg(value_name = "timestamp")]
        timestamp: String,
        /// target specific monitor
        #[arg(short = 'm', long)]
        monitor: Option<String>,
    },
    /// blank output to black with transition
    Blank {
        /// target specific monitor (default: all)
        #[arg(short = 'm', long)]
        monitor: Option<String>,
        #[command(flatten)]
        effect_args: EffectArgs,
    },
    /// restore wallpaper on blanked output
    Restore {
        /// target specific monitor (default: all)
        #[arg(short = 'm', long)]
        monitor: Option<String>,
        #[command(flatten)]
        effect_args: EffectArgs,
    },
}

#[cfg(test)]
mod tests {
    use super::{WallrCli, WallrDaemonCli, parse_timestamp_ms};
    use clap::Parser;

    #[test]
    fn daemon_cli_has_a_direct_service_interface() {
        let cli = WallrDaemonCli::try_parse_from([
            "wallr-daemon",
            "--config",
            "wallr.yaml",
            "--max-fps",
            "60",
            "-vv",
        ])
        .unwrap();
        assert_eq!(
            cli.config.as_deref().unwrap(),
            std::path::Path::new("wallr.yaml")
        );
        assert_eq!(cli.max_fps, Some(60));
        assert_eq!(cli.verbose, 2);
        assert!(WallrDaemonCli::try_parse_from(["wallr-daemon", "daemon"]).is_err());
    }

    #[test]
    fn daemon_cli_rejects_invalid_fps_limits() {
        for fps in ["0", "241"] {
            assert!(WallrDaemonCli::try_parse_from(["wallr-daemon", "--max-fps", fps]).is_err());
        }
    }

    #[test]
    fn wallpaper_cli_rejects_invalid_fps_limits() {
        for fps in ["0", "241"] {
            assert!(
                WallrCli::try_parse_from(["wallr", "set", "wallpaper.png", "--fps", fps]).is_err()
            );
        }
    }

    #[test]
    fn parses_seek_timestamps() {
        assert_eq!(parse_timestamp_ms("0").unwrap(), 0);
        assert_eq!(parse_timestamp_ms("90").unwrap(), 90_000);
        assert_eq!(parse_timestamp_ms("1.5").unwrap(), 1_500);
        assert_eq!(parse_timestamp_ms("01:30").unwrap(), 90_000);
        assert_eq!(parse_timestamp_ms("01:02:03").unwrap(), 3_723_000);
    }

    #[test]
    fn rejects_invalid_seek_timestamps() {
        for value in ["", "-1", "NaN", "inf", "1e300", "1:60", "1:2:60", "1:2:3:4"] {
            assert!(parse_timestamp_ms(value).is_err(), "{value} should fail");
        }
    }
}