diff --git a/src/core/deck.rs b/src/core/deck.rs index 307d7fc..d2c6558 100644 --- a/src/core/deck.rs +++ b/src/core/deck.rs @@ -6,7 +6,7 @@ use crate::data_provider::history::push_note; use chrono::Utc; use parking_lot::Mutex; use std::sync::Arc; - +use crate::notification::NotificationData; #[derive(Clone)] pub struct DeckData { @@ -18,24 +18,24 @@ pub struct DeckData { settings: DeckSettings, } impl DeckData { - pub fn new(settings: &DeckSettings, state: Arc>) -> Self { + pub fn new(settings: &DeckSettings, state: Arc>) -> Result { let state_for = state.clone(); let state_locked = state.lock(); - let stats = load_stats_of_deck(settings, &state_locked.connection); + let stats = load_stats_of_deck(settings, &state_locked.connection)?; let words = stats .iter() .map(|stat| { state_locked .dictionary .binary_search_by_key(&stat.word_id, |w| w.id) - .unwrap() + .expect("No word found in dictionary") }) .map(|index| &state_locked.dictionary[index]) .cloned() .collect(); - Self { + Ok(Self { set: stats, words, current_word_index: None, @@ -48,7 +48,7 @@ impl DeckData { OrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()), }, settings: settings.clone(), - } + }) } pub fn next(&mut self) -> (WordData, CardStatistics) { @@ -82,9 +82,9 @@ impl DeckData { self.current_word_index = Some(index); (self.words[index].clone(), self.set[index].clone()) } - pub fn open(&mut self, status: WordOpenMode) { + pub fn open(&mut self, status: WordOpenMode) -> Result<(), NotificationData> { if self.current_word_index.is_none() { - return; + return Ok(()); } let index = self.current_word_index.unwrap(); @@ -104,7 +104,7 @@ impl DeckData { module.open(status, index, word); } } - update_stat_score(word, &self.state.lock().connection); + update_stat_score(word, &self.state.lock().connection)?; let _ = push_note( self.settings.id, HistoryItem { @@ -115,6 +115,7 @@ impl DeckData { after: new_score, }, ); + Ok(()) } pub fn len(&self) -> usize { self.set.len() diff --git a/src/data_provider/card_sets.rs b/src/data_provider/card_sets.rs index ef82bcb..d5c5230 100644 --- a/src/data_provider/card_sets.rs +++ b/src/data_provider/card_sets.rs @@ -23,7 +23,7 @@ pub fn load_sets(connection: &Connection) -> Result, Notificat }) .map_err(|_| DbLoadError)?; - let mut buffer = vec![]; + let mut buffer = Vec::with_capacity(16); for word in iter.filter_map(|result| result.ok()) { buffer.push(word); } diff --git a/src/data_provider/card_stats.rs b/src/data_provider/card_stats.rs index deb81fd..bac5ccb 100644 --- a/src/data_provider/card_stats.rs +++ b/src/data_provider/card_stats.rs @@ -1,12 +1,17 @@ +use crate::data::entities::{CardStatistics, DeckSettings}; +use crate::notification::NotificationData; +use crate::notification::NotificationData::{DbLoadError, DbSaveError}; +use log::info; use rusqlite::{Connection, params}; use std::time::Instant; -use log::info; -use crate::data::entities::{CardStatistics, DeckSettings}; -pub fn load_stats_of_deck(set: &DeckSettings, connection: &Connection) -> Vec { +pub fn load_stats_of_deck( + set: &DeckSettings, + connection: &Connection, +) -> Result, NotificationData> { let mut stmt = connection .prepare("SELECT id, word_id, score, last_opened FROM card_stats WHERE set_id = ?1") - .unwrap(); + .expect("Failed to prepare state query"); let iter = stmt .query_map((set.id,), |row| { Ok(CardStatistics { @@ -17,19 +22,19 @@ pub fn load_stats_of_deck(set: &DeckSettings, connection: &Connection) -> Vec Result<(), NotificationData> { let time = Instant::now(); - let tx = connection.transaction().unwrap(); + let tx = connection.transaction().expect("Failed to create transaction"); let count = stats.len(); { @@ -37,7 +42,7 @@ pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) .prepare( "INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4)", ) - .unwrap(); + .expect("Failed to prepare state query"); for stat in stats.iter() { stmt.execute(params![ @@ -46,12 +51,12 @@ pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) stat.score, stat.last_open.timestamp() ]) - .unwrap(); + .map_err(|_| DbSaveError)?; } } let last_index: u32 = tx.last_insert_rowid() as u32; - tx.commit().unwrap(); + tx.commit().expect("Failed to commit"); let start_index = last_index - (count as u32) + 1; @@ -60,9 +65,10 @@ pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) } info!("Added {} cards for {:?}", stats.len(), time.elapsed()); + Ok(()) } -pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) { +pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) -> Result<(), NotificationData> { let time = Instant::now(); connection @@ -70,13 +76,14 @@ pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) { "UPDATE card_stats SET score = ?1, last_opened = ?2 WHERE id = ?3", (&stat.score, &stat.last_open.timestamp(), &stat.id), ) - .unwrap(); + .map_err(|_| DbSaveError)?; info!("Updated stat: {}", time.elapsed().as_millis()); + Ok(()) } -pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) { +pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) -> Result<(), NotificationData> { if stat.is_empty() { - return; + return Ok(()); } let ids = stat .iter() @@ -88,5 +95,6 @@ pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) { format!("DELETE FROM card_stats WHERE id in ({ids})").as_str(), (), ) - .unwrap(); + .map_err(|_| DbSaveError)?; + Ok(()) } diff --git a/src/helpers.rs b/src/helpers.rs new file mode 100644 index 0000000..b8536f5 --- /dev/null +++ b/src/helpers.rs @@ -0,0 +1,13 @@ +#[macro_export] +macro_rules! push_error_task { + ($e:expr) => { + iced::Task::done(push_error!($e)) + } +} + +#[macro_export] +macro_rules! push_error { + ($e:expr) => { + $crate::navigation::RootMessage::PushNotification($crate::notification::NotificationRequest::Error($e)) + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 4c9bbf2..8980fbe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ mod navigation; mod fs; mod core; mod data; +pub mod helpers; use crate::app::start; use mimalloc::MiMalloc; diff --git a/src/notification.rs b/src/notification.rs index 5e91855..e54a97a 100644 --- a/src/notification.rs +++ b/src/notification.rs @@ -176,7 +176,7 @@ pub enum NotificationRequest { Error(NotificationData), } -#[derive(Clone)] +#[derive(Clone, Debug)] pub enum NotificationData { PermissionDenied, DataLoaded, diff --git a/src/pages/import.rs b/src/pages/import.rs index 71db597..85c2fd5 100644 --- a/src/pages/import.rs +++ b/src/pages/import.rs @@ -4,7 +4,7 @@ use crate::pages::import::ImportMessage::*; use crate::data::entities::{WordData, WordGroup}; use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::notification::NotificationData::OpenFileError; -use crate::notification::{NotificationData, NotificationRequest}; +use crate::notification::NotificationData; use crate::styling::*; use iced::widget::button::danger; use iced::widget::container::success; @@ -28,6 +28,7 @@ use tokio::task::spawn_blocking; use zip::ZipArchive; use crate::app::AppState; use crate::fs::*; +use crate::push_error; const DEFAULT_FIELDS: [&str; 6] = ["key", "value", "tags", "reading", "context", "description"]; @@ -367,7 +368,7 @@ impl ImportState { }, |result: Result| match result { Ok(import) => RootMessage::Import(UpdateImport(import)), - Err(err) => RootMessage::PushNotification(NotificationRequest::Error(err)), + Err(err) => push_error!(err), }, ) } @@ -499,7 +500,7 @@ impl ImportState { }, |r: Result<(), NotificationData>| match r { Ok(_) => RootMessage::Import(ImportFinished), - Err(err) => RootMessage::PushNotification(NotificationRequest::Error(err)) + Err(err) => push_error!(err) } ) } diff --git a/src/pages/repetition.rs b/src/pages/repetition.rs index f40e33f..868d875 100644 --- a/src/pages/repetition.rs +++ b/src/pages/repetition.rs @@ -1,19 +1,20 @@ use crate::app::AppState; use crate::core::deck::DeckData; use crate::core::srs::WordOpenMode; -use crate::data::entities::{CardStatistics, DeckSettings, WordData}; use crate::data::Id; +use crate::data::entities::{CardStatistics, DeckSettings, WordData}; use crate::data_provider::voice::get_voice; use crate::navigation::Page::PreviousPage; use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage}; -use crate::notification::{NotificationData, NotificationRequest}; +use crate::notification::NotificationData; use crate::styling::*; +use crate::{push_error, push_error_task}; use chrono::Local; use iced::alignment::Horizontal::Center; use iced::keyboard::key::Physical::Code; use iced::widget::text::Style; -use iced::widget::{button, column, container, row, rule, space, text, tooltip, Column}; -use iced::{alignment, keyboard, Element, Fill, Task, Theme}; +use iced::widget::{Column, button, column, container, row, rule, space, text, tooltip}; +use iced::{Element, Fill, Task, Theme, alignment, keyboard}; use parking_lot::Mutex; use rodio::MixerDeviceSink; use std::collections::HashSet; @@ -57,7 +58,7 @@ impl NavigatedPage for RepetitionState { if self.settings.require_speech() { return Task::perform(play_sound(self.sink.clone(), value), |r| match r { Ok(_) => RootMessage::Repetition(RepetitionMessage::PlayFinished), - Err(err) => RootMessage::PushNotification(NotificationRequest::Error(err)), + Err(err) => push_error!(err), }); } } @@ -101,8 +102,11 @@ impl NavigatedPage for RepetitionState { } impl RepetitionState { - pub(crate) fn new(set: DeckSettings, state: Arc>) -> RepetitionState { - let mut card_set = DeckData::new(&set, state.clone()); + pub(crate) fn new( + set: DeckSettings, + state: Arc>, + ) -> Result { + let mut card_set = DeckData::new(&set, state.clone())?; let (word, stat) = card_set.next(); let sink_handle = if set.forward.contains("speech") || set.backward.contains("speech") { @@ -111,7 +115,7 @@ impl RepetitionState { None }; - RepetitionState { + Ok(RepetitionState { state, settings: set, set: card_set, @@ -121,7 +125,7 @@ impl RepetitionState { can_play: true, sink: Arc::new(sink_handle), opened: HashSet::new(), - } + }) } } @@ -140,7 +144,10 @@ impl RepetitionState { return Task::none(); } - self.set.open(mode); + if let Err(err) = self.set.open(mode) { + return push_error_task!(err); + } + self.open = false; self.opened.insert(self.current_word.id); let next = self.set.next(); @@ -152,7 +159,7 @@ impl RepetitionState { let task = play_sound(sink, self.current_word.key.clone()); return Task::perform(task, |r| match r { Ok(_) => RootMessage::Repetition(RepetitionMessage::PlayFinished), - Err(err) => RootMessage::PushNotification(NotificationRequest::Error(err)), + Err(err) => push_error!(err), }); } self.increment_counter(); diff --git a/src/pages/repetition_settings.rs b/src/pages/repetition_settings.rs index 0fac784..139f607 100644 --- a/src/pages/repetition_settings.rs +++ b/src/pages/repetition_settings.rs @@ -4,15 +4,16 @@ use crate::data_provider::card_sets::{delete_set, update_deck}; use crate::data_provider::card_stats::{delete_stats, load_stats_of_deck}; use crate::navigation::Page::PreviousPage; use crate::navigation::{NavigatedPage, Page, RootMessage}; -use crate::notification::NotificationRequest; +use crate::notification::NotificationData; use crate::pages::repetition_settings::RepetitionSettingsMessage::*; use crate::styling::*; +use crate::{push_error, push_error_task}; use iced::widget::button::danger; use iced::widget::text_input::Catalog; use iced::widget::{button, column, row, scrollable, space, text, text_input}; use iced::{Element, Task}; use iced_core::Length::Fill; -use iced_core::{color, Padding, Theme}; +use iced_core::{Padding, Theme, color}; use parking_lot::Mutex; use std::sync::Arc; use std::time::Duration; @@ -62,10 +63,12 @@ impl NavigatedPage for RepetitionSettingsState { Save => { let mut state = self.state.lock(); if let Err(e) = update_deck(&mut self.set, &state.connection) { - return Task::done(RootMessage::PushNotification(NotificationRequest::Error(e))); + return push_error_task!(e) } - if self.filter_changed { - update_deck_stats(&self.set, &state); + if self.filter_changed + && let Err(e) = update_deck_stats(&self.set, &state) + { + return push_error_task!(e) } state.decks[self.index] = self.set.clone(); } @@ -98,7 +101,7 @@ impl NavigatedPage for RepetitionSettingsState { } let mut state = self.state.lock(); if let Err(e) = delete_set(&self.set, &state.connection) { - return Task::done(RootMessage::PushNotification(NotificationRequest::Error(e))); + return push_error_task!(e); } state.decks.remove(self.index); @@ -176,8 +179,8 @@ impl NavigatedPage for RepetitionSettingsState { } } -fn update_deck_stats(deck: &DeckSettings, state: &AppState) { - let mut db_stats = load_stats_of_deck(deck, &state.connection); +fn update_deck_stats(deck: &DeckSettings, state: &AppState) -> Result<(), NotificationData> { + let mut db_stats = load_stats_of_deck(deck, &state.connection).expect("Wrong db operation"); let filtered_words = deck.get_word_list(state); filtered_words.iter().for_each(|word| { let word_id = state.dictionary[*word].id; @@ -186,7 +189,8 @@ fn update_deck_stats(deck: &DeckSettings, state: &AppState) { } }); - delete_stats(db_stats.as_slice(), &state.connection); + delete_stats(db_stats.as_slice(), &state.connection)?; + Ok(()) } impl RepetitionSettingsState { diff --git a/src/pages/repetitions.rs b/src/pages/repetitions.rs index 4475acb..3d1be75 100644 --- a/src/pages/repetitions.rs +++ b/src/pages/repetitions.rs @@ -6,10 +6,13 @@ use crate::data_provider::card_sets::update_deck; use crate::data_provider::card_stats::{add_stat_list, load_stats_of_deck}; use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings}; use crate::navigation::{NavigatedPage, Page, RootMessage}; +use crate::notification::{NotificationData, NotificationRequest}; use crate::pages::history::HistoryState; use crate::pages::repetition::RepetitionState; use crate::pages::repetition_settings::RepetitionSettingsState; use crate::pages::repetitions::RepetitionsMessage::*; +use crate::push_error; +use crate::push_error_task; use crate::styling::*; use chrono::{Days, Local, Utc}; use hashbrown::{HashMap, HashSet}; @@ -27,7 +30,6 @@ use iced_core::svg::Handle; use parking_lot::Mutex; use std::ops::Deref; use std::sync::Arc; -use crate::notification::NotificationRequest; #[derive(Clone)] pub struct RepetitionsState { @@ -51,7 +53,9 @@ impl NavigatedPage for RepetitionsState { let selected_set = self.selected_deck_mut().unwrap(); if selected_set.append_mode == AppendMode::Full { - Self::append_all_words(&mut clone.lock(), selected_set); + if let Err(_err) = Self::append_all_words(&mut clone.lock(), selected_set){ + return None; + } selected_set.existing_words_indices = selected_set.available_words_indices.clone(); } else { if selected_set.available_words_indices.is_empty() @@ -61,10 +65,13 @@ impl NavigatedPage for RepetitionsState { } } - Some(Repetition(RepetitionState::new( - selected_set.general_settings.clone(), - clone, - ))) + if let Ok(repetition_state) = + RepetitionState::new(selected_set.general_settings.clone(), clone) + { + return Some(Repetition(repetition_state)); + } + + None } else if let GoToSettings = message { Some(RepetitionSettings(RepetitionSettingsState::new( self.selected_deck().unwrap().index.unwrap(), @@ -83,10 +90,9 @@ impl NavigatedPage for RepetitionsState { self.decks.remove(index); self.clear_selection(); } else { - self.decks[index].general_settings = - state.decks[index].clone(); + self.decks[index].general_settings = state.decks[index].clone(); drop(state); - self.fill_deck_word_indices(); + let _ = self.fill_deck_word_indices(); } } else { drop(state); @@ -139,16 +145,20 @@ impl NavigatedPage for RepetitionsState { SelectSet(index) => { self.select_deck(index); let deck = self.selected_deck().unwrap(); - if !deck.indices_ready { - self.fill_deck_word_indices(); + if !deck.indices_ready + && let Err(err) = self.fill_deck_word_indices() + { + return push_error_task!(err); } } Save => { let mut deck = self.selected_deck().unwrap().clone(); let mut state = self.state.lock(); { - if let Err(e) = update_deck(&mut deck.general_settings, &state.connection){ - return Task::done(RootMessage::PushNotification(NotificationRequest::Error(e))) + if let Err(e) = update_deck(&mut deck.general_settings, &state.connection) { + return Task::done(RootMessage::PushNotification( + NotificationRequest::Error(e), + )); } if let Some(index) = deck.index { state.decks[index] = deck.general_settings.clone(); @@ -212,7 +222,11 @@ impl NavigatedPage for RepetitionsState { let deck = self.selected_deck().unwrap(); let mut state = self.state.lock(); - Self::append_words(&mut state, &deck.general_settings, adding.into_iter()); + if let Err(err) = + Self::append_words(&mut state, &deck.general_settings, adding.into_iter()) + { + return push_error_task!(err); + } } } Task::none() @@ -548,7 +562,7 @@ impl RepetitionsState { } impl RepetitionsState { - fn append_all_words(state: &mut AppState, deck: &DeckViewData) { + fn append_all_words(state: &mut AppState, deck: &DeckViewData) -> Result<(), NotificationData> { let existing = &deck.existing_words_indices; let mut created_set = HashSet::with_capacity(existing.len()); existing.iter().for_each(|c| { @@ -559,13 +573,14 @@ impl RepetitionsState { .iter() .filter(|i| !created_set.contains(i)) .cloned(); - Self::append_words(state, deck, required); + Self::append_words(state, deck, required)?; + Ok(()) } fn append_words( state: &mut AppState, deck: &DeckSettings, indices: impl Iterator, - ) { + ) -> Result<(), NotificationData> { let words = &state.dictionary; let stats = &mut indices .map(|i| { @@ -581,8 +596,9 @@ impl RepetitionsState { .collect::>(); if !stats.is_empty() { - add_stat_list(stats, &mut state.connection); + add_stat_list(stats, &mut state.connection)?; } + Ok(()) } fn select_deck(&mut self, index: usize) { @@ -602,10 +618,10 @@ impl RepetitionsState { self.selected_deck_index = None; } - fn fill_deck_word_indices(&mut self) { + fn fill_deck_word_indices(&mut self) -> Result<(), NotificationData> { let state = &self.state.lock(); let mut deck = self.selected_deck().unwrap().clone(); - let added: Vec<_> = load_stats_of_deck(&deck, &state.connection) + let added: Vec<_> = load_stats_of_deck(&deck, &state.connection)? .iter() .map(|c| self.word_id_index_map[&c.word_id]) .collect(); @@ -613,6 +629,7 @@ impl RepetitionsState { deck.existing_words_indices = added; deck.available_words_indices = total; self.decks[self.selected_deck_index.unwrap()] = deck; + Ok(()) } } #[derive(Clone)] diff --git a/src/pages/sync.rs b/src/pages/sync.rs index a04cae5..c48931e 100644 --- a/src/pages/sync.rs +++ b/src/pages/sync.rs @@ -14,6 +14,7 @@ use std::time::Duration; use log::error; use crate::app::{fill_state, AppState}; use crate::notification::{NotificationRequest, NotificationData}; +use crate::push_error; #[derive(Clone)] pub enum SyncMessage { @@ -64,7 +65,7 @@ impl NavigatedPage for SyncState { return Task::perform(first_sync(), |id| { match id { Ok(id) => RootMessage::Sync(IdReceived(id)), - Err(err) => RootMessage::PushNotification(NotificationRequest::Error(err)) + Err(err) => push_error!(err) } }); }