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