cosmic-files/src/operation.rs

104 lines
3.1 KiB
Rust
Raw Normal View History

use cosmic::iced::futures::{channel::mpsc, SinkExt};
2024-02-27 13:25:50 -07:00
use std::{fs, path::PathBuf};
2024-01-29 11:58:50 -07:00
2024-02-01 15:14:14 -07:00
use crate::app::Message;
fn err_str<T: ToString>(err: T) -> String {
err.to_string()
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
2024-01-29 11:58:50 -07:00
pub enum Operation {
/// Copy items
2024-02-27 13:25:50 -07:00
Copy {
paths: Vec<PathBuf>,
to: PathBuf,
},
/// Move items to the trash
2024-02-27 13:25:50 -07:00
Delete {
paths: Vec<PathBuf>,
},
/// Move items
2024-02-27 13:25:50 -07:00
Move {
paths: Vec<PathBuf>,
to: PathBuf,
},
NewFile {
path: PathBuf,
},
NewFolder {
path: PathBuf,
},
2024-01-29 11:58:50 -07:00
/// Restore a path from the trash
2024-02-27 13:25:50 -07:00
Restore {
paths: Vec<trash::TrashItem>,
},
2024-01-29 11:58:50 -07:00
}
impl Operation {
/// Perform the operation
pub async fn perform(self, id: u64, msg_tx: &mut mpsc::Sender<Message>) -> Result<(), String> {
2024-02-27 09:58:22 -07:00
let _ = msg_tx.send(Message::PendingProgress(id, 0.0)).await;
2024-01-29 11:58:50 -07:00
//TODO: IF ERROR, RETURN AN Operation THAT CAN UNDO THE CURRENT STATE
//TODO: SAFELY HANDLE CANCEL
2024-01-29 11:58:50 -07:00
match self {
Self::Delete { paths } => {
2024-02-27 09:58:22 -07:00
let total = paths.len();
let mut count = 0;
for path in paths {
tokio::task::spawn_blocking(|| trash::delete(path))
.await
.map_err(err_str)?
.map_err(err_str)?;
count += 1;
2024-02-27 09:58:22 -07:00
let _ = msg_tx
.send(Message::PendingProgress(
id,
100.0 * (count as f32) / (total as f32),
))
.await;
}
}
2024-02-27 13:25:50 -07:00
Self::NewFolder { path } => {
tokio::task::spawn_blocking(|| fs::create_dir(path))
.await
.map_err(err_str)?
.map_err(err_str)?;
let _ = msg_tx.send(Message::PendingProgress(id, 100.0)).await;
}
Self::NewFile { path } => {
tokio::task::spawn_blocking(|| fs::File::create(path))
.await
.map_err(err_str)?
.map_err(err_str)?;
let _ = msg_tx.send(Message::PendingProgress(id, 100.0)).await;
}
Self::Restore { paths } => {
2024-02-27 09:58:22 -07:00
let total = paths.len();
let mut count = 0;
for path in paths {
tokio::task::spawn_blocking(|| trash::os_limited::restore_all([path]))
.await
.map_err(err_str)?
.map_err(err_str)?;
count += 1;
2024-02-27 09:58:22 -07:00
let _ = msg_tx
.send(Message::PendingProgress(
id,
100.0 * (count as f32) / (total as f32),
))
.await;
}
}
_ => {
return Err("not implemented".to_string());
}
2024-01-29 11:58:50 -07:00
}
2024-02-27 09:58:22 -07:00
let _ = msg_tx.send(Message::PendingProgress(id, 100.0)).await;
2024-01-29 11:58:50 -07:00
Ok(())
2024-01-29 11:58:50 -07:00
}
}