Skip to content

Commit

Permalink
Merge pull request #9 from ahoneybun/fix-blocking-code
Browse files Browse the repository at this point in the history
fix: blocking code
  • Loading branch information
ahoneybun authored May 27, 2024
2 parents c7e6ace + d1abc93 commit e95e894
Show file tree
Hide file tree
Showing 6 changed files with 120 additions and 17 deletions.
2 changes: 2 additions & 0 deletions res/icons/bundled/harddisk-symbolic.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions res/icons/bundled/timer-sand-symbolic.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
68 changes: 51 additions & 17 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::collections::{HashMap, VecDeque};
use std::path::PathBuf;
use std::{env, process};

use cosmic::app::{Command, Core};
use cosmic::app::{message, Command, Core};
use cosmic::iced::alignment::{Horizontal, Vertical};
use cosmic::iced::{event, keyboard::Event as KeyEvent, window, Event, Subscription};
use cosmic::iced_core::keyboard::{Key, Modifiers};
Expand All @@ -24,7 +24,10 @@ use cosmic::{widget, Application, Apply, Element};
use crate::app::config::{AppTheme, Repository, CONFIG_VERSION};
use crate::fl;

use self::icon_cache::IconCache;

pub mod config;
pub mod icon_cache;
pub mod menu;
pub mod settings;

Expand Down Expand Up @@ -62,14 +65,21 @@ pub enum Message {
Modifiers(Modifiers),
WindowClose,
WindowNew,
CreateRepository(String),
Repository(RepositoryAction),
CreateSnapshot,
OpenCreateRepositoryDialog,
OpenCreateSnapshotDialog,
DeleteRepositoryDialog,
DeleteSnapshotDialog,
}

#[derive(Debug, Clone)]
pub enum RepositoryAction {
Init(String),
Created(Repository),
Error(String),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContextPage {
About,
Expand Down Expand Up @@ -183,11 +193,17 @@ impl App {
.into()
}

fn create_nav_item(&mut self, repository: Repository) -> EntityMut<SingleSelect> {
fn create_nav_item(
&mut self,
repository: Repository,
icon: &'static str,
) -> EntityMut<SingleSelect> {
self.nav_model
.insert()
.icon(IconCache::get(icon, 18))
.text(repository.name.clone())
.data(repository.clone())
.activate()
}
}

Expand Down Expand Up @@ -235,7 +251,7 @@ impl Application for App {

let repositories = app.config.repositories.clone();
for repository in repositories {
app.create_nav_item(repository);
app.create_nav_item(repository, "harddisk-symbolic");
}

(app, Command::none())
Expand Down Expand Up @@ -425,24 +441,42 @@ impl Application for App {
Message::OpenCreateSnapshotDialog => {
self.dialog_pages.push_back(DialogPage::CreateSnapshot);
}
Message::CreateRepository(path) => match crate::backup::init(&path, "password") {
Ok(_) => {
let path = PathBuf::from(&path);
let name = path
Message::Repository(state) => match state {
RepositoryAction::Init(path) => {
let init_path = path.clone();
let name = PathBuf::from(&path)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
let repository = Repository {
name,
path: PathBuf::from(&path),
};
self.create_nav_item(repository.clone(), "timer-sand-symbolic");
return Command::perform(
async move { crate::backup::init(&init_path, "password") },
|result| match result {
Ok(_) => message::app(Message::Repository(RepositoryAction::Created(
repository,
))),
Err(e) => message::app(Message::Repository(RepositoryAction::Error(
e.to_string(),
))),
},
);
}
RepositoryAction::Created(repository) => {
if self.nav_model.active_data::<Repository>().is_some() {
let entity = self.nav_model.active();
self.nav_model
.icon_set(entity, IconCache::get("harddisk-symbolic", 18));
}
let mut repositories = self.config.repositories.clone();
let repository = Repository { name, path };
repositories.push(repository.clone());
self.create_nav_item(repository);
repositories.push(repository);
config_set!(repositories, repositories);
}
Err(e) => {
// TODO: Show error to user.
eprintln!("failed to create repository: {}", e)
}
RepositoryAction::Error(error) => log::error!("{}", error),
},
Message::DeleteRepositoryDialog => {
println!("Deleting repository");
Expand Down Expand Up @@ -470,8 +504,8 @@ impl Application for App {
Message::DialogComplete => {
if let Some(dialog_page) = self.dialog_pages.pop_front() {
match dialog_page {
DialogPage::CreateRepository(name) => {
return self.update(Message::CreateRepository(name));
DialogPage::CreateRepository(path) => {
return self.update(Message::Repository(RepositoryAction::Init(path)));
}
DialogPage::CreateSnapshot => {
return self.update(Message::CreateSnapshot);
Expand Down
56 changes: 56 additions & 0 deletions src/app/icon_cache.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: GPL-3.0-only

use cosmic::widget::icon;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

pub(crate) static ICON_CACHE: OnceLock<Mutex<IconCache>> = OnceLock::new();

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct IconCacheKey {
name: &'static str,
size: u16,
}

pub struct IconCache {
cache: HashMap<IconCacheKey, icon::Handle>,
}

impl IconCache {
pub fn new() -> Self {
let mut cache = HashMap::new();

macro_rules! bundle {
($name:expr, $size:expr) => {
let data: &'static [u8] =
include_bytes!(concat!("../../res/icons/bundled/", $name, ".svg"));
cache.insert(
IconCacheKey {
name: $name,
size: $size,
},
icon::from_svg_bytes(data).symbolic(true),
);
};
}

bundle!("timer-sand-symbolic", 18);
bundle!("harddisk-symbolic", 18);

Self { cache }
}

fn get_icon(&mut self, name: &'static str, size: u16) -> icon::Icon {
let handle = self
.cache
.entry(IconCacheKey { name, size })
.or_insert_with(|| icon::from_name(name).size(size).handle())
.clone();
icon::icon(handle).size(size)
}

pub fn get(name: &'static str, size: u16) -> icon::Icon {
let mut icon_cache = ICON_CACHE.get().unwrap().lock().unwrap();
icon_cache.get_icon(name, size)
}
}
8 changes: 8 additions & 0 deletions src/app/settings.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
use std::sync::Mutex;

use super::config::CosmicBackupsConfig;
use super::icon_cache::{IconCache, ICON_CACHE};
use crate::app::Flags;
use cosmic::app::Settings;
use cosmic::iced::{Limits, Size};

pub fn init() -> (Settings, Flags) {
set_logger();
set_icon_cache();
let settings = get_app_settings();
let flags = get_flags();
(settings, flags)
Expand All @@ -25,6 +29,10 @@ pub fn set_logger() {
tracing_subscriber::fmt().json().init();
}

pub fn set_icon_cache() {
ICON_CACHE.get_or_init(|| Mutex::new(IconCache::new()));
}

pub fn get_flags() -> Flags {
let (config_handler, config) = (
CosmicBackupsConfig::config_handler(),
Expand Down
1 change: 1 addition & 0 deletions src/backup/restore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use rustic_backend::BackendOptions;
use rustic_core::{LocalDestination, LsOptions, Repository, RepositoryOptions, RestoreOptions};
use std::error::Error;

#[allow(dead_code)]
pub fn restore(
repository: &str,
password: &str,
Expand Down

0 comments on commit e95e894

Please sign in to comment.