Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better error handling & code readibility #3

Merged
merged 1 commit into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 20 additions & 22 deletions src/gui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ struct ImageCache {
order: VecDeque<PathBuf>,
}

struct ImageLoader {
queue: VecDeque<PathBuf>,
current_folder: Option<PathBuf>,
cache: Arc<Mutex<ImageCache>>,
cancel_flag: Option<Arc<AtomicBool>>,
}

impl ImageCache {
fn new() -> Self {
Self {
Expand All @@ -35,13 +42,10 @@ impl ImageCache {
}

fn get(&mut self, path: &Path) -> Option<gdk::Texture> {
if let Some(texture) = self.cache.get(path) {
self.cache.get(path).cloned().inspect(|_| {
self.order.retain(|p| p != path);
self.order.push_front(path.to_path_buf());
Some(texture.clone())
} else {
None
}
})
}

fn insert(&mut self, path: PathBuf, texture: gdk::Texture) {
Expand All @@ -55,24 +59,15 @@ impl ImageCache {
}

fn get_or_insert(&mut self, path: &Path, max_size: i32) -> Option<Texture> {
if let Some(texture) = self.get(path) {
Some(texture)
} else {
self.get(path).or_else(|| {
let pixbuf = Pixbuf::from_file_at_scale(path, max_size, max_size, true).ok()?;
let texture = Texture::for_pixbuf(&pixbuf);
self.insert(path.to_path_buf(), texture.clone());
Some(texture)
}
})
}
}

struct ImageLoader {
queue: VecDeque<PathBuf>,
current_folder: Option<PathBuf>,
cache: Arc<Mutex<ImageCache>>,
cancel_flag: Option<Arc<AtomicBool>>,
}

impl ImageLoader {
fn new() -> Self {
Self {
Expand All @@ -84,10 +79,9 @@ impl ImageLoader {
}

fn load_folder(&mut self, folder: &Path) {
if let Some(flag) = &self.cancel_flag {
flag.store(true, Ordering::Relaxed);
if let Some(flag) = self.cancel_flag.as_ref() {
flag.store(true, Ordering::Relaxed)
}

self.queue.clear();
self.current_folder = Some(folder.to_path_buf());
if let Ok(entries) = fs::read_dir(folder) {
Expand Down Expand Up @@ -313,8 +307,9 @@ fn load_images(
});
button.add_controller(motion_controller);

button.connect_clicked(move |_| {
crate::set_wallpaper(&path_clone);
button.connect_clicked(move |_| match crate::set_wallpaper(&path_clone) {
Ok(_) => println!("Wallpaper set successfully"),
Err(e) => eprintln!("Error setting wallpaper: {}", e),
});

flowbox.insert(&button, -1);
Expand Down Expand Up @@ -379,7 +374,10 @@ fn set_random_wallpaper(_flowbox: &Rc<RefCell<FlowBox>>, image_loader: &Rc<RefCe

if let Some(random_image) = images.choose(&mut rand::thread_rng()) {
if let Some(path_str) = random_image.to_str() {
crate::set_wallpaper(path_str);
match crate::set_wallpaper(path_str) {
Ok(_) => println!("Wallpaper set successfully"),
Err(e) => eprintln!("Error setting wallpaper: {}", e),
}
}
}
}
Expand Down
25 changes: 13 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,33 +20,34 @@ fn main() {
app.run();
}

pub fn set_wallpaper(path: &str) {
pub fn set_wallpaper(path: &str) -> Result<(), String> {
println!("Attempting to set wallpaper: {}", path);

INIT.call_once(|| {
*MONITORS.lock() = get_monitors();
INIT.call_once(|| match get_monitors() {
Ok(monitors) => *MONITORS.lock() = monitors,
Err(e) => eprintln!("Failed to get monitors: {}", e),
});

println!("Found monitors: {:?}", *MONITORS.lock());

let preload_command = format!("hyprctl hyprpaper preload \"{}\"", path);
println!("Preloading wallpaper: {}", preload_command);
if !execute_command(&preload_command) {
eprintln!("Failed to preload wallpaper");
return;
return Err("Failed to preload wallpaper".to_string());
}

println!("Wallpaper preloaded successfully");

for monitor in MONITORS.lock().iter() {
let set_command = format!("hyprctl hyprpaper wallpaper \"{},{}\"", monitor, path);
println!("Executing command: {}", set_command);
if execute_command(&set_command) {
println!("Successfully set wallpaper for {}", monitor);
} else {
eprintln!("Failed to set wallpaper for {}", monitor);
if !execute_command(&set_command) {
return Err(format!("Failed to set wallpaper for {}", monitor));
}
println!("Successfully set wallpaper for {}", monitor);
}

Ok(())
}

fn execute_command(command: &str) -> bool {
Expand All @@ -69,12 +70,12 @@ fn execute_command(command: &str) -> bool {
}
}

fn get_monitors() -> Vec<String> {
fn get_monitors() -> Result<Vec<String>, String> {
println!("Retrieving monitor information");
let output = Command::new("hyprctl")
.arg("monitors")
.output()
.expect("Failed to execute hyprctl monitors");
.map_err(|e| format!("Failed to execute hyprctl monitors: {}", e))?;

let monitors: Vec<String> = String::from_utf8_lossy(&output.stdout)
.lines()
Expand All @@ -90,5 +91,5 @@ fn get_monitors() -> Vec<String> {
.collect();

println!("Retrieved monitors: {:?}", monitors);
monitors
Ok(monitors)
}
Loading