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
|
use clap::Parser;
use serde::Deserialize;
use regex::RegexSet;
use rand::thread_rng;
use rand::seq::SliceRandom;
use std::fs::File;
use std::error;
use std::path::{PathBuf, Path};
use std::process::Command;
use std::fmt;
#[derive(Parser, Debug)]
#[command(version, about, long_about=None)]
struct Args {
#[arg(short, long, help="Where to load configuration from")]
config: String,
#[arg(short, long, help="Reapply last applied wallpaper")]
reapply: bool,
}
#[derive(Debug, Deserialize, Clone, Copy)]
enum Rule {
Tiled,
Scale,
Border,
Center,
}
#[derive(Debug, Deserialize)]
struct Config {
#[serde(default)]
rules: Vec<(String, Rule)>,
#[serde(default = "default_background")]
background: String,
#[serde(skip, default = "default_folder")]
folder: String,
}
#[derive(Debug)]
enum Error {
FehFailure(i32),
NoRule(String),
NoState,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::FehFailure(code) => write!(f, "Feh returned non error: {}", code),
Error::NoRule(fname) => write!(f, "No rule for file with name {}", fname),
Error::NoState => write!(f, "There is no previous wallpaper to reapply"),
}
}
}
impl error::Error for Error {}
// Default used if we could not get the parent folder of the config file
fn default_folder() -> String { String::from("/") }
fn default_background() -> String { String::from("black") }
fn main() -> Result<(), Box<dyn error::Error>> {
let args = Args::parse();
// Load configuration file
let config = Config::parse(&Path::new(&args.config))?;
if args.reapply {
let img = state::load_state()?.ok_or(Box::new(Error::NoState))?;
config.reapply_image_file(&img)?;
return Ok(());
}
if let Some((img, rule)) = config.select_image_file()? {
config.apply_image_file(&img, rule)?;
}
Ok(())
}
impl Config {
fn parse(file: &Path) -> Result<Self, Box<dyn error::Error>> {
let f = File::open(file)?;
let mut config: Config = serde_yaml::from_reader(f)?;
if let Some(folder) = file.parent() {
config.folder = folder.to_string_lossy().into();
}
Ok(config)
}
fn build_regexset(&self) -> Result<RegexSet, Box<dyn error::Error>> {
Ok(RegexSet::new(self.rules.iter().map(|(r,_)| r))?)
}
fn reapply_image_file(&self, img: &Path) -> Result<(), Box<dyn error::Error>> {
let rs = self.build_regexset()?;
// TODO handle the invalid unicode here
let file_name = img.file_name().ok_or(
Box::new(Error::NoState))?.to_str().unwrap();
if let Some(index) = rs.matches(file_name).iter().next() {
self.apply_image_file(img, self.rules[index].1)
} else {
Err(Box::new(Error::NoRule(file_name.into())))
}
}
fn select_image_file(&self) -> Result<Option<(PathBuf, Rule)>, Box<dyn error::Error>> {
let folder = Path::new(&self.folder);
let rs = self.build_regexset()?;
let mut imgs: Vec<(PathBuf, Rule)> = Vec::new();
for entry in folder.read_dir()? {
let entry = entry?;
let file_name = String::from(entry.file_name().to_string_lossy());
if let Some(index) = rs.matches(&file_name).iter().next() {
imgs.push((entry.path(), self.rules[index].1));
}
// deja vu
}
Ok(imgs.choose(&mut thread_rng()).cloned())
}
fn apply_image_file(&self, img: &Path, rule: Rule) -> Result<(), Box<dyn error::Error>> {
println!("Setting wallpaper {:?}, with {:?} mode", img, rule);
let mode = match rule {
Rule::Tiled => "--bg-tile",
Rule::Scale => "--bg-fill",
Rule::Border => "--bg-max",
Rule::Center => "--bg-center",
};
let status = Command::new("feh").arg(mode).
arg("--image-bg").arg(&self.background).arg(img).status()?;
if status.success() {
state::save_state(img)
} else {
Err(Box::new(Error::FehFailure(status.code().unwrap())))
}
}
}
mod state {
use std::error;
use std::path::{Path,PathBuf};
use std::fs;
// Hehe, not very cool but whatever
static FALLBACK_DATADIR: &str = ".";
fn state_file() -> PathBuf {
dirs::data_dir().unwrap_or(FALLBACK_DATADIR.into()).join("wallstate")
}
pub fn load_state() -> Result<Option<PathBuf>, Box<dyn error::Error>> {
let stf = state_file();
if stf.exists() {
let raw = fs::read(stf)?;
let content = String::from_utf8_lossy(&raw);
Ok(content.lines().next().map(|x| x.into()))
} else {
Ok(None)
}
}
pub fn save_state(img: &Path) -> Result<(), Box<dyn error::Error>> {
Ok(fs::write(state_file(), img.to_str().unwrap())?)
}
}
|