Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10cf7f0d2e | ||
|
|
dddac01bdf | ||
|
|
1d24fe2631 | ||
|
|
a60ed37cd4 | ||
|
|
d836b57d2a | ||
|
|
b5b1eb768c | ||
|
|
5a6747030b | ||
|
|
c56d135ce8 | ||
|
|
6f8adde06b | ||
|
|
8841a51897 | ||
|
|
06bf9138c0 | ||
|
|
3cbdf0803b | ||
|
|
d261a08932 | ||
|
|
92ca42869c | ||
|
|
c67663141f | ||
|
|
22b455a640 | ||
|
|
c74a0eb311 | ||
|
|
36e5693564 | ||
|
|
42c9a5095a | ||
|
|
0baf6cadf7 | ||
|
|
0367d5001b | ||
|
|
3fcfe95720 | ||
|
|
f113d2b3d7 | ||
|
|
5a926b1419 | ||
|
|
e1bfd9494d | ||
|
|
dfaff30efa | ||
|
|
163ebc44a5 | ||
|
|
d42d618066 |
No files matched your search
Generated
+162
-2
@@ -152,12 +152,56 @@ version = "0.1.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
|
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstream"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"anstyle-parse",
|
||||||
|
"anstyle-query",
|
||||||
|
"anstyle-wincon",
|
||||||
|
"colorchoice",
|
||||||
|
"is_terminal_polyfill",
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anstyle"
|
name = "anstyle"
|
||||||
version = "1.0.14"
|
version = "1.0.14"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-parse"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||||
|
dependencies = [
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-query"
|
||||||
|
version = "1.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-wincon"
|
||||||
|
version = "3.0.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"once_cell_polyfill",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyhow"
|
name = "anyhow"
|
||||||
version = "1.0.101"
|
version = "1.0.101"
|
||||||
@@ -728,6 +772,12 @@ version = "1.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "colorchoice"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "combine"
|
name = "combine"
|
||||||
version = "4.6.7"
|
version = "4.6.7"
|
||||||
@@ -1068,6 +1118,37 @@ version = "0.1.12"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
|
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 1.3.2",
|
||||||
|
"defmt-macros",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt-macros"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"
|
||||||
|
dependencies = [
|
||||||
|
"defmt-parser",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.114",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "defmt-parser"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
|
||||||
|
dependencies = [
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "deranged"
|
name = "deranged"
|
||||||
version = "0.5.8"
|
version = "0.5.8"
|
||||||
@@ -1215,6 +1296,29 @@ dependencies = [
|
|||||||
"syn 2.0.114",
|
"syn 2.0.114",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "env_filter"
|
||||||
|
version = "2.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
|
||||||
|
dependencies = [
|
||||||
|
"log",
|
||||||
|
"regex",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "env_logger"
|
||||||
|
version = "0.11.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
|
||||||
|
dependencies = [
|
||||||
|
"anstream",
|
||||||
|
"anstyle",
|
||||||
|
"env_filter",
|
||||||
|
"jiff",
|
||||||
|
"log",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "equivalent"
|
name = "equivalent"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@@ -2292,6 +2396,12 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is_terminal_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itertools"
|
name = "itertools"
|
||||||
version = "0.13.0"
|
version = "0.13.0"
|
||||||
@@ -2314,10 +2424,12 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"criterion",
|
"criterion",
|
||||||
"dirs",
|
"dirs",
|
||||||
|
"env_logger",
|
||||||
"hashbrown 0.17.1",
|
"hashbrown 0.17.1",
|
||||||
"hex",
|
"hex",
|
||||||
"iced",
|
"iced",
|
||||||
"iced_core",
|
"iced_core",
|
||||||
|
"log",
|
||||||
"mimalloc",
|
"mimalloc",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
"rand",
|
"rand",
|
||||||
@@ -2334,6 +2446,42 @@ dependencies = [
|
|||||||
"zstd",
|
"zstd",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jiff"
|
||||||
|
version = "0.2.35"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc"
|
||||||
|
dependencies = [
|
||||||
|
"defmt",
|
||||||
|
"jiff-core",
|
||||||
|
"jiff-static",
|
||||||
|
"log",
|
||||||
|
"portable-atomic",
|
||||||
|
"portable-atomic-util",
|
||||||
|
"serde_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jiff-core"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09"
|
||||||
|
dependencies = [
|
||||||
|
"defmt",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jiff-static"
|
||||||
|
version = "0.2.35"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204"
|
||||||
|
dependencies = [
|
||||||
|
"jiff-core",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn 2.0.114",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jni"
|
name = "jni"
|
||||||
version = "0.21.1"
|
version = "0.21.1"
|
||||||
@@ -2584,9 +2732,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "log"
|
name = "log"
|
||||||
version = "0.4.29"
|
version = "0.4.34"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lru"
|
name = "lru"
|
||||||
@@ -3309,6 +3457,12 @@ dependencies = [
|
|||||||
"portable-atomic",
|
"portable-atomic",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "oorandom"
|
name = "oorandom"
|
||||||
version = "11.1.5"
|
version = "11.1.5"
|
||||||
@@ -5390,6 +5544,12 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf8parse"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.20.0"
|
version = "1.20.0"
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ mimalloc = "0.1.52"
|
|||||||
hashbrown = "0.17.1"
|
hashbrown = "0.17.1"
|
||||||
rayon = "1.12.0"
|
rayon = "1.12.0"
|
||||||
parking_lot = "0.12.5"
|
parking_lot = "0.12.5"
|
||||||
|
env_logger = "0.11.11"
|
||||||
|
log = "0.4.34"
|
||||||
|
|
||||||
[profile.super-release]
|
[profile.super-release]
|
||||||
inherits = "release"
|
inherits = "release"
|
||||||
|
|||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
use crate::data::Id;
|
||||||
|
use crate::data::entities::DeckSettings;
|
||||||
|
use crate::data::entities::{WordData, WordGroup};
|
||||||
|
use crate::data_provider::card_sets::load_sets;
|
||||||
|
use crate::data_provider::settings::get_setting;
|
||||||
|
use crate::data_provider::sqlite::default_connection;
|
||||||
|
use crate::data_provider::words::{load_word_groups, load_words};
|
||||||
|
use crate::navigation::RootMessage::Keyboard;
|
||||||
|
use crate::navigation::{AppSettings, RootMessage, ScreenState};
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
use hashbrown::HashMap;
|
||||||
|
use iced::{Subscription, keyboard, window};
|
||||||
|
use iced_core::window::Position;
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
use iced_core::window::settings::PlatformSpecific;
|
||||||
|
use iced_core::{Font, Size, Theme};
|
||||||
|
use log::info;
|
||||||
|
use rusqlite::Connection;
|
||||||
|
pub const USER_FONT: Font = Font::with_name("Noto Sans JP");
|
||||||
|
|
||||||
|
pub fn start() -> iced::Result {
|
||||||
|
info!("Welcome to JapLearn");
|
||||||
|
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view)
|
||||||
|
.window(window_settings())
|
||||||
|
.subscription(subscription)
|
||||||
|
.title("JapLearn")
|
||||||
|
.settings(iced::Settings {
|
||||||
|
default_text_size: iced::Pixels(18.0),
|
||||||
|
..iced::Settings::default()
|
||||||
|
})
|
||||||
|
.font(include_bytes!("../noto.ttf"))
|
||||||
|
.default_font(USER_FONT)
|
||||||
|
.theme(Theme::GruvboxDark)
|
||||||
|
.run()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_mut)]
|
||||||
|
fn window_settings() -> window::Settings {
|
||||||
|
let mut settings = window::Settings {
|
||||||
|
position: Position::Centered,
|
||||||
|
min_size: Some(Size::new(700.0_f32, 700.0_f32)),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
{
|
||||||
|
settings.platform_specific = PlatformSpecific {
|
||||||
|
application_id: "JapLearn".to_string(),
|
||||||
|
override_redirect: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
settings
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subscription(_state: &ScreenState) -> Subscription<RootMessage> {
|
||||||
|
keyboard::listen().map(Keyboard)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub dictionary: Vec<WordData>,
|
||||||
|
pub decks: Vec<DeckSettings>,
|
||||||
|
pub word_groups: Vec<WordGroup>,
|
||||||
|
pub connection: Connection,
|
||||||
|
pub sync_data: AppSettings,
|
||||||
|
pub activity: HashMap<Id, Vec<(NaiveDate, u32)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for AppState {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
dictionary: vec![],
|
||||||
|
decks: vec![],
|
||||||
|
word_groups: vec![],
|
||||||
|
connection: default_connection(),
|
||||||
|
sync_data: AppSettings {
|
||||||
|
key: None,
|
||||||
|
auto_web_fetch: false,
|
||||||
|
},
|
||||||
|
activity: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fill_state(state: &mut AppState) {
|
||||||
|
let list = load_words(&state.connection);
|
||||||
|
let sets = load_sets(&state.connection);
|
||||||
|
let groups = load_word_groups(&state.connection);
|
||||||
|
let setting = load_settings(&state.connection);
|
||||||
|
|
||||||
|
state.dictionary = list.unwrap_or_default();
|
||||||
|
state.decks = sets.unwrap_or_default();
|
||||||
|
state.word_groups = groups.unwrap_or_default();
|
||||||
|
state.sync_data = setting
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_settings(connection: &Connection) -> AppSettings {
|
||||||
|
let key = get_setting("SYNC_KEY".to_string(), connection);
|
||||||
|
let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection)
|
||||||
|
.unwrap_or("false".to_string())
|
||||||
|
.parse::<bool>()
|
||||||
|
.unwrap();
|
||||||
|
AppSettings {
|
||||||
|
key,
|
||||||
|
auto_web_fetch: fetch,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
pub mod deck;
|
||||||
|
pub mod kana_set;
|
||||||
|
pub mod srs;
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
use crate::app::AppState;
|
||||||
|
use crate::core::srs::{
|
||||||
|
OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule, WordOpenMode,
|
||||||
|
WorstWordsSRSModule,
|
||||||
|
};
|
||||||
|
use crate::data::entities::*;
|
||||||
|
use crate::data_provider::card_stats::{load_stats_of_deck, update_stat_score};
|
||||||
|
use crate::data_provider::history::push_note;
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
|
use chrono::Utc;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DeckData {
|
||||||
|
pub(crate) words: Vec<WordData>,
|
||||||
|
pub(crate) set: Vec<CardStatistics>,
|
||||||
|
current_word_index: Option<usize>,
|
||||||
|
state: Arc<Mutex<AppState>>,
|
||||||
|
order_module: OrderModule,
|
||||||
|
settings: DeckSettings,
|
||||||
|
}
|
||||||
|
impl DeckData {
|
||||||
|
pub fn new(
|
||||||
|
settings: &DeckSettings,
|
||||||
|
state: Arc<Mutex<AppState>>,
|
||||||
|
) -> Result<Self, NotificationData> {
|
||||||
|
let state_for = state.clone();
|
||||||
|
let state_locked = state.lock();
|
||||||
|
|
||||||
|
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)
|
||||||
|
.expect("No word found in dictionary")
|
||||||
|
})
|
||||||
|
.map(|index| &state_locked.dictionary[index])
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
set: stats,
|
||||||
|
words,
|
||||||
|
current_word_index: None,
|
||||||
|
state: state_for,
|
||||||
|
order_module: match settings.open_mode {
|
||||||
|
OrderMode::Default => OrderModule::SemiRandomSRS(SemiRandomSRSModule::new()),
|
||||||
|
OrderMode::TrainWorstFirst => {
|
||||||
|
OrderModule::WorstWordsSRS(WorstWordsSRSModule::new())
|
||||||
|
}
|
||||||
|
OrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()),
|
||||||
|
},
|
||||||
|
settings: settings.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next(&mut self) -> (WordData, CardStatistics) {
|
||||||
|
let index = match self.order_module {
|
||||||
|
OrderModule::SemiRandomSRS(ref mut module) => {
|
||||||
|
if !module.initialized {
|
||||||
|
module.init(self.set.as_slice())
|
||||||
|
}
|
||||||
|
module.next(self.set.as_slice())
|
||||||
|
}
|
||||||
|
OrderModule::RandomSRS(ref mut module) => {
|
||||||
|
if !module.initialized {
|
||||||
|
module.init(self.set.as_slice())
|
||||||
|
}
|
||||||
|
module.next(self.set.as_slice())
|
||||||
|
}
|
||||||
|
OrderModule::WorstWordsSRS(ref mut module) => {
|
||||||
|
if !module.initialized {
|
||||||
|
module.init(self.set.as_slice())
|
||||||
|
}
|
||||||
|
module.next(self.set.as_slice())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
self.current_word_index = Some(index);
|
||||||
|
(self.words[index].clone(), self.set[index].clone())
|
||||||
|
}
|
||||||
|
pub fn open(&mut self, status: WordOpenMode) -> MaybeError {
|
||||||
|
if let Some(index) = self.current_word_index {
|
||||||
|
let word: &mut CardStatistics = &mut self.set[index];
|
||||||
|
let old_score = word.score;
|
||||||
|
word.update(status);
|
||||||
|
let new_score = word.score;
|
||||||
|
|
||||||
|
match self.order_module {
|
||||||
|
OrderModule::SemiRandomSRS(ref mut module) => {
|
||||||
|
module.open(status, index, word);
|
||||||
|
}
|
||||||
|
OrderModule::RandomSRS(ref mut module) => {
|
||||||
|
module.open(status, index, word);
|
||||||
|
}
|
||||||
|
OrderModule::WorstWordsSRS(ref mut module) => {
|
||||||
|
module.open(status, index, word);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
update_stat_score(word, &self.state.lock().connection)?;
|
||||||
|
let _ = push_note(
|
||||||
|
self.settings.id,
|
||||||
|
HistoryItem {
|
||||||
|
timestamp: Utc::now(),
|
||||||
|
word_id: word.word_id,
|
||||||
|
mode: status,
|
||||||
|
before: old_score,
|
||||||
|
after: new_score,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.set.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct KanaSet {
|
||||||
|
name: String,
|
||||||
|
pub(crate) chars_type: KanaType,
|
||||||
|
pub(crate) dictionary: Vec<Vec<(String, String)>>,
|
||||||
|
pub(crate) include_map: [bool; 10],
|
||||||
|
}
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum KanaType {
|
||||||
|
Hiragana,
|
||||||
|
Katakana,
|
||||||
|
}
|
||||||
|
impl KanaSet {
|
||||||
|
pub fn hiragana() -> Self {
|
||||||
|
Self {
|
||||||
|
name: "Хирагана".to_string(),
|
||||||
|
chars_type: KanaType::Hiragana,
|
||||||
|
dictionary: vec![
|
||||||
|
vec![
|
||||||
|
(String::from("ぁ"), String::from("a")),
|
||||||
|
(String::from("ぃ"), String::from("i")),
|
||||||
|
(String::from("ぅ"), String::from("u")),
|
||||||
|
(String::from("ぇ"), String::from("e")),
|
||||||
|
(String::from("ぉ"), String::from("o")),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
(String::from("さ"), String::from("sa")),
|
||||||
|
(String::from("し"), String::from("shi")),
|
||||||
|
(String::from("す"), String::from("su")),
|
||||||
|
(String::from("せ"), String::from("se")),
|
||||||
|
(String::from("そ"), String::from("so")),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
(String::from("か"), String::from("ka")),
|
||||||
|
(String::from("き"), String::from("ki")),
|
||||||
|
(String::from("く"), String::from("ku")),
|
||||||
|
(String::from("け"), String::from("ke")),
|
||||||
|
(String::from("こ"), String::from("ko")),
|
||||||
|
],
|
||||||
|
// Ряд «та» (たちつてと)
|
||||||
|
vec![
|
||||||
|
(String::from("た"), String::from("ta")),
|
||||||
|
(String::from("ち"), String::from("chi")),
|
||||||
|
(String::from("つ"), String::from("tsu")),
|
||||||
|
(String::from("て"), String::from("te")),
|
||||||
|
(String::from("と"), String::from("to")),
|
||||||
|
],
|
||||||
|
// Ряд «на» (なにぬねの)
|
||||||
|
vec![
|
||||||
|
(String::from("な"), String::from("na")),
|
||||||
|
(String::from("に"), String::from("ni")),
|
||||||
|
(String::from("ぬ"), String::from("nu")),
|
||||||
|
(String::from("ね"), String::from("ne")),
|
||||||
|
(String::from("の"), String::from("no")),
|
||||||
|
],
|
||||||
|
// Ряд «ха» (はひふへほ)
|
||||||
|
vec![
|
||||||
|
(String::from("は"), String::from("ha")),
|
||||||
|
(String::from("ひ"), String::from("hi")),
|
||||||
|
(String::from("ふ"), String::from("fu")),
|
||||||
|
(String::from("へ"), String::from("he")),
|
||||||
|
(String::from("ほ"), String::from("ho")),
|
||||||
|
],
|
||||||
|
// Ряд «ма» (まみむめも)
|
||||||
|
vec![
|
||||||
|
(String::from("ま"), String::from("ma")),
|
||||||
|
(String::from("み"), String::from("mi")),
|
||||||
|
(String::from("む"), String::from("mu")),
|
||||||
|
(String::from("め"), String::from("me")),
|
||||||
|
(String::from("も"), String::from("mo")),
|
||||||
|
],
|
||||||
|
// Ряд «я» (やゆよ) — только 3 символа
|
||||||
|
vec![
|
||||||
|
(String::from("や"), String::from("ya")),
|
||||||
|
(String::from("ゆ"), String::from("yu")),
|
||||||
|
(String::from("よ"), String::from("yo")),
|
||||||
|
],
|
||||||
|
// Ряд «ра» (らりるれろ)
|
||||||
|
vec![
|
||||||
|
(String::from("ら"), String::from("ra")),
|
||||||
|
(String::from("り"), String::from("ri")),
|
||||||
|
(String::from("る"), String::from("ru")),
|
||||||
|
(String::from("れ"), String::from("re")),
|
||||||
|
(String::from("ろ"), String::from("ro")),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
(String::from("わ"), String::from("wa")),
|
||||||
|
(String::from("を"), String::from("wo")),
|
||||||
|
(String::from("ん"), String::from("n")),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
include_map: [true; 10],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn katakana() -> Self {
|
||||||
|
Self {
|
||||||
|
name: "Катакана".to_string(),
|
||||||
|
chars_type: KanaType::Katakana,
|
||||||
|
dictionary: vec![
|
||||||
|
vec![
|
||||||
|
(String::from("ァ"), String::from("a")),
|
||||||
|
(String::from("ィ"), String::from("i")),
|
||||||
|
(String::from("ゥ"), String::from("u")),
|
||||||
|
(String::from("ェ"), String::from("e")),
|
||||||
|
(String::from("ォ"), String::from("o")),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
(String::from("サ"), String::from("sa")),
|
||||||
|
(String::from("シ"), String::from("shi")),
|
||||||
|
(String::from("ス"), String::from("su")),
|
||||||
|
(String::from("セ"), String::from("se")),
|
||||||
|
(String::from("ソ"), String::from("so")),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
(String::from("カ"), String::from("ka")),
|
||||||
|
(String::from("キ"), String::from("ki")),
|
||||||
|
(String::from("ク"), String::from("ku")),
|
||||||
|
(String::from("ケ"), String::from("ke")),
|
||||||
|
(String::from("コ"), String::from("ko")),
|
||||||
|
],
|
||||||
|
// Ряд «та» (タチツテト)
|
||||||
|
vec![
|
||||||
|
(String::from("タ"), String::from("ta")),
|
||||||
|
(String::from("チ"), String::from("chi")),
|
||||||
|
(String::from("ツ"), String::from("tsu")),
|
||||||
|
(String::from("テ"), String::from("te")),
|
||||||
|
(String::from("ト"), String::from("to")),
|
||||||
|
],
|
||||||
|
// Ряд «на» (ナニヌネノ)
|
||||||
|
vec![
|
||||||
|
(String::from("ナ"), String::from("na")),
|
||||||
|
(String::from("ニ"), String::from("ni")),
|
||||||
|
(String::from("ヌ"), String::from("nu")),
|
||||||
|
(String::from("ネ"), String::from("ne")),
|
||||||
|
(String::from("ノ"), String::from("no")),
|
||||||
|
],
|
||||||
|
// Ряд «ха» (ハヒフヘホ)
|
||||||
|
vec![
|
||||||
|
(String::from("ハ"), String::from("ha")),
|
||||||
|
(String::from("ヒ"), String::from("hi")),
|
||||||
|
(String::from("フ"), String::from("fu")),
|
||||||
|
(String::from("ヘ"), String::from("he")),
|
||||||
|
(String::from("ホ"), String::from("ho")),
|
||||||
|
],
|
||||||
|
// Ряд «ма» (マミムメモ)
|
||||||
|
vec![
|
||||||
|
(String::from("マ"), String::from("ma")),
|
||||||
|
(String::from("ミ"), String::from("mi")),
|
||||||
|
(String::from("ム"), String::from("mu")),
|
||||||
|
(String::from("メ"), String::from("me")),
|
||||||
|
(String::from("モ"), String::from("mo")),
|
||||||
|
],
|
||||||
|
// Ряд «я» (ヤユヨ) — только 3 символа
|
||||||
|
vec![
|
||||||
|
(String::from("ヤ"), String::from("ya")),
|
||||||
|
(String::from("ユ"), String::from("yu")),
|
||||||
|
(String::from("ヨ"), String::from("yo")),
|
||||||
|
],
|
||||||
|
// Ряд «ра» (ラリルレロ)
|
||||||
|
vec![
|
||||||
|
(String::from("ラ"), String::from("ra")),
|
||||||
|
(String::from("リ"), String::from("ri")),
|
||||||
|
(String::from("ル"), String::from("ru")),
|
||||||
|
(String::from("レ"), String::from("re")),
|
||||||
|
(String::from("ロ"), String::from("ro")),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
(String::from("ワ"), String::from("wa")),
|
||||||
|
(String::from("ヲ"), String::from("wo")),
|
||||||
|
(String::from("ン"), String::from("n")),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
include_map: [true; 10],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list(&self) -> Vec<(String, String)> {
|
||||||
|
let mut current_set: Vec<(String, String)> = Vec::new();
|
||||||
|
|
||||||
|
for i in 0..10 {
|
||||||
|
if self.include_map[i] {
|
||||||
|
self.dictionary[i].iter().for_each(|v| {
|
||||||
|
current_set.push(v.clone());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
current_set
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for KanaSet {
|
||||||
|
fn default() -> Self {
|
||||||
|
KanaSet::hiragana()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl PartialEq<Self> for KanaSet {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.name == other.name
|
||||||
|
}
|
||||||
|
}
|
||||||
+181
@@ -0,0 +1,181 @@
|
|||||||
|
use crate::data::entities::CardStatistics;
|
||||||
|
use rand::distr::weighted::WeightedIndex;
|
||||||
|
use rand::prelude::ThreadRng;
|
||||||
|
use rand::prelude::{Distribution, SliceRandom};
|
||||||
|
use rand::rng;
|
||||||
|
|
||||||
|
const MAX_HISTORY_LEN: usize = 20;
|
||||||
|
const MAX_HISTORY_LEN_PART: f32 = 0.33;
|
||||||
|
pub const MAX_SCORE: u8 = 25;
|
||||||
|
pub const FADE_PER_DAY: f32 = 0.95;
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Copy, Eq)]
|
||||||
|
pub enum OrderMode {
|
||||||
|
Default,
|
||||||
|
TrainWorstFirst,
|
||||||
|
FullRandom,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Copy, Eq, PartialEq, Default)]
|
||||||
|
pub enum AppendMode {
|
||||||
|
Full,
|
||||||
|
#[default]
|
||||||
|
Manual,
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum OrderModule {
|
||||||
|
SemiRandomSRS(SemiRandomSRSModule),
|
||||||
|
RandomSRS(RandomSRSModule),
|
||||||
|
WorstWordsSRS(WorstWordsSRSModule),
|
||||||
|
}
|
||||||
|
pub trait SRSModule {
|
||||||
|
fn next(&mut self, set: &[CardStatistics]) -> usize;
|
||||||
|
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &CardStatistics);
|
||||||
|
fn init(&mut self, set: &[CardStatistics]);
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct RandomSRSModule {
|
||||||
|
basket: Vec<usize>,
|
||||||
|
pub(crate) initialized: bool,
|
||||||
|
}
|
||||||
|
impl RandomSRSModule {
|
||||||
|
pub(crate) fn new() -> RandomSRSModule {
|
||||||
|
Self {
|
||||||
|
basket: vec![],
|
||||||
|
initialized: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl SRSModule for RandomSRSModule {
|
||||||
|
fn next(&mut self, set: &[CardStatistics]) -> usize {
|
||||||
|
match self.basket.pop() {
|
||||||
|
Some(index) => index,
|
||||||
|
None => {
|
||||||
|
self.basket = (0..set.len()).collect::<Vec<usize>>();
|
||||||
|
self.basket.shuffle(&mut rand::rng());
|
||||||
|
self.basket.pop().expect("empty basket")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open(&mut self, _: WordOpenMode, _: usize, _: &CardStatistics) {}
|
||||||
|
|
||||||
|
fn init(&mut self, set: &[CardStatistics]) {
|
||||||
|
self.initialized = true;
|
||||||
|
self.basket = (0..set.len()).collect::<Vec<usize>>();
|
||||||
|
self.basket.shuffle(&mut rand::rng())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SemiRandomSRSModule {
|
||||||
|
history: Vec<usize>,
|
||||||
|
last_weights: WeightedIndex<f32>,
|
||||||
|
generator: ThreadRng,
|
||||||
|
pub(crate) initialized: bool,
|
||||||
|
}
|
||||||
|
impl SemiRandomSRSModule {
|
||||||
|
pub(crate) fn new() -> SemiRandomSRSModule {
|
||||||
|
SemiRandomSRSModule {
|
||||||
|
history: vec![],
|
||||||
|
last_weights: WeightedIndex::new([1.0]).unwrap(),
|
||||||
|
generator: rng(),
|
||||||
|
initialized: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl SRSModule for SemiRandomSRSModule {
|
||||||
|
fn next(&mut self, set: &[CardStatistics]) -> usize {
|
||||||
|
let index = self.last_weights.sample(&mut self.generator);
|
||||||
|
|
||||||
|
if self.history.contains(&index) && self.history.len() != 1 {
|
||||||
|
return self.next(set);
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.history.len() == self.history_len(set) {
|
||||||
|
self.history.remove(0);
|
||||||
|
}
|
||||||
|
self.history.push(index);
|
||||||
|
|
||||||
|
index
|
||||||
|
}
|
||||||
|
fn open(&mut self, _: WordOpenMode, index: usize, word: &CardStatistics) {
|
||||||
|
let new_weight = (100.0 / word.calculated_score()).powf(2.0);
|
||||||
|
self.last_weights
|
||||||
|
.update_weights(&[(index, &new_weight)])
|
||||||
|
.expect("update weights error");
|
||||||
|
}
|
||||||
|
fn init(&mut self, set: &[CardStatistics]) {
|
||||||
|
self.initialized = true;
|
||||||
|
let weights = set
|
||||||
|
.iter()
|
||||||
|
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
|
||||||
|
.collect::<Vec<f32>>();
|
||||||
|
self.last_weights = WeightedIndex::new(weights).expect("Incorrect weights update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl SemiRandomSRSModule {
|
||||||
|
fn history_len(&self, set: &[CardStatistics]) -> usize {
|
||||||
|
((set.len() as f32 * MAX_HISTORY_LEN_PART) as usize).clamp(1, MAX_HISTORY_LEN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct WorstWordsSRSModule {
|
||||||
|
pub(crate) initialized: bool,
|
||||||
|
pool_size: usize,
|
||||||
|
rounds_remaining: u8,
|
||||||
|
pool: Vec<usize>,
|
||||||
|
queue: Vec<usize>,
|
||||||
|
rounds_count: u8,
|
||||||
|
}
|
||||||
|
impl SRSModule for WorstWordsSRSModule {
|
||||||
|
fn next(&mut self, set: &[CardStatistics]) -> usize {
|
||||||
|
if self.rounds_remaining == 0 {
|
||||||
|
self.fill_pool(set);
|
||||||
|
self.rounds_remaining = self.rounds_count;
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.queue.pop() {
|
||||||
|
Some(index) => index,
|
||||||
|
None => {
|
||||||
|
self.queue.append(&mut self.pool.clone());
|
||||||
|
self.rounds_remaining -= 1;
|
||||||
|
self.queue.pop().expect("empty queue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open(&mut self, _: WordOpenMode, _: usize, _: &CardStatistics) {}
|
||||||
|
|
||||||
|
fn init(&mut self, _: &[CardStatistics]) {
|
||||||
|
self.initialized = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl WorstWordsSRSModule {
|
||||||
|
pub(crate) fn new() -> WorstWordsSRSModule {
|
||||||
|
WorstWordsSRSModule {
|
||||||
|
initialized: false,
|
||||||
|
pool_size: 15,
|
||||||
|
rounds_count: 2,
|
||||||
|
rounds_remaining: 0,
|
||||||
|
pool: vec![],
|
||||||
|
queue: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn fill_pool(&mut self, set: &[CardStatistics]) {
|
||||||
|
let mut sorted = set.iter().enumerate().collect::<Vec<_>>();
|
||||||
|
sorted.sort_by_key(|c| c.1.score);
|
||||||
|
let mut worst = sorted[0..self.pool_size]
|
||||||
|
.iter()
|
||||||
|
.map(|(index, _)| *index)
|
||||||
|
.collect::<Vec<usize>>();
|
||||||
|
worst.shuffle(&mut rand::rng());
|
||||||
|
self.pool = worst;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub enum WordOpenMode {
|
||||||
|
Easy,
|
||||||
|
Ok,
|
||||||
|
Hard,
|
||||||
|
None,
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
pub mod entities;
|
||||||
|
|
||||||
|
use rusqlite::ToSql;
|
||||||
|
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
|
||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
use std::num::ParseIntError;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Eq, Debug, Hash, Copy, Ord, PartialOrd, Default)]
|
||||||
|
pub struct Id(pub(crate) u32);
|
||||||
|
pub const INVALID_ID: Id = Id(0);
|
||||||
|
impl FromStr for Id {
|
||||||
|
type Err = ParseIntError;
|
||||||
|
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
Ok(Id(s.parse::<u32>()?))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<u32> for Id {
|
||||||
|
fn from(value: u32) -> Self {
|
||||||
|
Id(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Id> for u32 {
|
||||||
|
fn from(value: Id) -> Self {
|
||||||
|
value.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Display for Id {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for Id {
|
||||||
|
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||||
|
match value {
|
||||||
|
ValueRef::Integer(i) => Ok(Id(i as u32)),
|
||||||
|
_ => Err(FromSqlError::InvalidType),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToSql for Id {
|
||||||
|
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
|
||||||
|
Ok(ToSqlOutput::from(self.0 as i64))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Id> for String {
|
||||||
|
fn from(value: Id) -> Self {
|
||||||
|
value.0.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Id {
|
||||||
|
pub(crate) fn is_valid(self) -> bool {
|
||||||
|
self.0 != 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
use crate::app::AppState;
|
||||||
|
use crate::core::srs::{FADE_PER_DAY, MAX_SCORE, OrderMode, WordOpenMode};
|
||||||
|
use crate::data::{INVALID_ID, Id};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use log::info;
|
||||||
|
use rayon::prelude::*;
|
||||||
|
use rhai::{Engine, Scope};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct WordData {
|
||||||
|
pub id: Id,
|
||||||
|
pub key: String,
|
||||||
|
pub value: String,
|
||||||
|
pub tags: String,
|
||||||
|
pub additional: HashMap<String, String>,
|
||||||
|
pub group_id: Id,
|
||||||
|
}
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct WordGroup {
|
||||||
|
pub id: Id,
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WordData {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
id: INVALID_ID,
|
||||||
|
key: String::new(),
|
||||||
|
value: String::new(),
|
||||||
|
tags: String::new(),
|
||||||
|
additional: Default::default(),
|
||||||
|
group_id: 1.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct HistoryItem {
|
||||||
|
pub timestamp: DateTime<Utc>,
|
||||||
|
pub word_id: Id,
|
||||||
|
pub mode: WordOpenMode,
|
||||||
|
pub before: u8,
|
||||||
|
pub after: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DeckSettings {
|
||||||
|
pub id: Id,
|
||||||
|
pub name: String,
|
||||||
|
pub forward: String,
|
||||||
|
pub backward: String,
|
||||||
|
pub filter: String,
|
||||||
|
pub count: Option<usize>,
|
||||||
|
pub open_mode: OrderMode,
|
||||||
|
}
|
||||||
|
impl DeckSettings {
|
||||||
|
pub(crate) fn with_name(name: String) -> DeckSettings {
|
||||||
|
DeckSettings {
|
||||||
|
id: 0.into(),
|
||||||
|
name,
|
||||||
|
forward: "".to_string(),
|
||||||
|
backward: "".to_string(),
|
||||||
|
filter: "true".to_string(),
|
||||||
|
count: None,
|
||||||
|
open_mode: OrderMode::Default,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn check_filter(&self) -> bool {
|
||||||
|
let time = Instant::now();
|
||||||
|
let engine = Engine::new();
|
||||||
|
let ast = engine.compile(&self.filter);
|
||||||
|
info!("Compile time is {:?}", time.elapsed());
|
||||||
|
ast.is_ok()
|
||||||
|
}
|
||||||
|
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
|
||||||
|
let time = Instant::now();
|
||||||
|
let mut list = vec![];
|
||||||
|
let engine = Engine::new();
|
||||||
|
|
||||||
|
let ast = engine.compile(&self.filter);
|
||||||
|
if let Ok(ast) = ast {
|
||||||
|
let groups = &state.word_groups;
|
||||||
|
|
||||||
|
list = state
|
||||||
|
.dictionary
|
||||||
|
.par_iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(_, word)| {
|
||||||
|
let mut more = rhai::Map::new();
|
||||||
|
for iced in &word.additional {
|
||||||
|
more.insert(iced.0.clone().into(), iced.1.clone().into());
|
||||||
|
}
|
||||||
|
let mut scope = Scope::new();
|
||||||
|
scope
|
||||||
|
.push_constant("id", word.id.0 as i64)
|
||||||
|
.push_constant("key", word.key.clone())
|
||||||
|
.push_constant("value", word.value.clone())
|
||||||
|
.push_constant("tags", word.tags.clone())
|
||||||
|
.push_constant("more", more)
|
||||||
|
.push_constant(
|
||||||
|
"group",
|
||||||
|
groups
|
||||||
|
.iter()
|
||||||
|
.find(|g| g.id == word.group_id)
|
||||||
|
.cloned()
|
||||||
|
.expect("No group id")
|
||||||
|
.name,
|
||||||
|
);
|
||||||
|
|
||||||
|
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
|
||||||
|
if let Ok(result) = result {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
})
|
||||||
|
.map(|(index, _)| index)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
info!("Collecting available words is {:?}", time.elapsed());
|
||||||
|
|
||||||
|
list
|
||||||
|
} else {
|
||||||
|
list
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn require_speech(&self) -> bool {
|
||||||
|
self.forward == "speech" || self.backward == "speech"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq)]
|
||||||
|
pub struct CardStatistics {
|
||||||
|
pub id: Id,
|
||||||
|
pub word_id: Id,
|
||||||
|
pub set_id: Id,
|
||||||
|
pub last_open: DateTime<Utc>,
|
||||||
|
pub score: u8,
|
||||||
|
}
|
||||||
|
impl CardStatistics {
|
||||||
|
pub fn update(&mut self, status: WordOpenMode) {
|
||||||
|
match status {
|
||||||
|
WordOpenMode::Easy => {
|
||||||
|
self.score = (self.calculated_score() + 5.0).round() as u8;
|
||||||
|
}
|
||||||
|
WordOpenMode::Ok => self.score = (self.calculated_score() + 2.0).round() as u8,
|
||||||
|
WordOpenMode::Hard => {
|
||||||
|
self.score = (self.calculated_score() * 0.75).round() as u8;
|
||||||
|
}
|
||||||
|
WordOpenMode::None => {
|
||||||
|
self.score = (self.calculated_score() * 0.4) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.score = self.score.clamp(1, MAX_SCORE);
|
||||||
|
self.last_open = Utc::now();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn calculated_score(&self) -> f32 {
|
||||||
|
let time = Utc::now() - self.last_open;
|
||||||
|
let days = time.num_days();
|
||||||
|
let multiplier = FADE_PER_DAY.powi(days as i32);
|
||||||
|
(self.score as f32 * multiplier).max(1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
use crate::lang::{DeckSettings, OrderMode};
|
use crate::core::srs::OrderMode;
|
||||||
|
|
||||||
|
use crate::data::entities::DeckSettings;
|
||||||
|
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
|
|
||||||
pub fn load_sets(connection: &Connection) -> Vec<DeckSettings> {
|
pub fn load_sets(connection: &Connection) -> Result<Vec<DeckSettings>, NotificationData> {
|
||||||
let mut stmt = connection
|
let mut stmt = connection
|
||||||
.prepare("SELECT id, name, forward, backward, filter FROM card_set")
|
.prepare("SELECT id, name, forward, backward, filter FROM card_set")
|
||||||
.unwrap();
|
.expect("Failed to prepare state query");
|
||||||
let iter = stmt
|
let iter = stmt
|
||||||
.query_map([], |row| {
|
.query_map([], |row| {
|
||||||
Ok(DeckSettings {
|
Ok(DeckSettings {
|
||||||
@@ -15,21 +18,17 @@ pub fn load_sets(connection: &Connection) -> Vec<DeckSettings> {
|
|||||||
backward: row.get(3)?,
|
backward: row.get(3)?,
|
||||||
filter: row.get(4)?,
|
filter: row.get(4)?,
|
||||||
count: None,
|
count: None,
|
||||||
worst_words_list: None,
|
|
||||||
open_mode: OrderMode::Default,
|
open_mode: OrderMode::Default,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap();
|
.map_err(|_| DbLoadError)?;
|
||||||
|
|
||||||
let mut buffer = vec![];
|
let mut buffer = Vec::with_capacity(16);
|
||||||
for word in iter {
|
iter.filter_map(|res| res.ok()).for_each(|i| buffer.push(i));
|
||||||
buffer.push(word.unwrap());
|
Ok(buffer)
|
||||||
}
|
|
||||||
|
|
||||||
buffer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_set(set: &mut DeckSettings, connection: &Connection) {
|
pub fn add_set(set: &mut DeckSettings, connection: &Connection) -> MaybeError {
|
||||||
let index : u32 = connection
|
let index : u32 = connection
|
||||||
.query_row(
|
.query_row(
|
||||||
"INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id",
|
"INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id",
|
||||||
@@ -41,14 +40,15 @@ pub fn add_set(set: &mut DeckSettings, connection: &Connection) {
|
|||||||
),
|
),
|
||||||
|row| row.get(0)
|
|row| row.get(0)
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
|
||||||
set.id = index.into();
|
set.id = index.into();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_deck(set: &mut DeckSettings, connection: &Connection) {
|
pub fn update_deck(set: &mut DeckSettings, connection: &Connection) -> MaybeError {
|
||||||
if !set.id.is_valid() {
|
if !set.id.is_valid() {
|
||||||
add_set(set, connection);
|
add_set(set, connection)?;
|
||||||
} else {
|
} else {
|
||||||
connection
|
connection
|
||||||
.execute(
|
.execute(
|
||||||
@@ -61,15 +61,17 @@ pub fn update_deck(set: &mut DeckSettings, connection: &Connection) {
|
|||||||
&set.id
|
&set.id
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_set(set: &DeckSettings, connection: &Connection) {
|
pub fn delete_set(set: &DeckSettings, connection: &Connection) -> MaybeError {
|
||||||
if !set.id.is_valid() {
|
if !set.id.is_valid() {
|
||||||
return;
|
return Err(DbSaveError);
|
||||||
}
|
}
|
||||||
connection
|
connection
|
||||||
.execute("DELETE FROM card_set WHERE id = ?1", (&set.id,))
|
.execute("DELETE FROM card_set WHERE id = ?1", (&set.id,))
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,17 @@
|
|||||||
use crate::lang::{CardStatistics, DeckSettings};
|
use crate::data::entities::{CardStatistics, DeckSettings};
|
||||||
|
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
|
use log::info;
|
||||||
use rusqlite::{Connection, params};
|
use rusqlite::{Connection, params};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
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 {
|
||||||
@@ -16,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 {
|
iter.filter_map(|res| res.ok()).for_each(|i| buffer.push(i));
|
||||||
buffer.push(word.unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
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) -> MaybeError {
|
||||||
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();
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -36,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![
|
||||||
@@ -45,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;
|
||||||
|
|
||||||
@@ -58,10 +64,11 @@ pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection)
|
|||||||
stats[index].id = id.into();
|
stats[index].id = id.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("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) -> MaybeError {
|
||||||
let time = Instant::now();
|
let time = Instant::now();
|
||||||
|
|
||||||
connection
|
connection
|
||||||
@@ -69,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)?;
|
||||||
println!("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) -> MaybeError {
|
||||||
if stat.is_empty() {
|
if stat.is_empty() {
|
||||||
return;
|
return Ok(());
|
||||||
}
|
}
|
||||||
let ids = stat
|
let ids = stat
|
||||||
.iter()
|
.iter()
|
||||||
@@ -87,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(())
|
||||||
}
|
}
|
||||||
@@ -1,29 +1,34 @@
|
|||||||
use crate::dictionary::app_data_dir;
|
use crate::core::srs::WordOpenMode;
|
||||||
use crate::lang::{Id, WordOpenMode};
|
use crate::data::Id;
|
||||||
use chrono::{DateTime, Utc};
|
use crate::data::entities::HistoryItem;
|
||||||
use std::fs;
|
use crate::fs::*;
|
||||||
|
use crate::notification::NotificationData::PermissionDenied;
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
|
use chrono::DateTime;
|
||||||
use std::fs::{File, OpenOptions};
|
use std::fs::{File, OpenOptions};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::io::{BufRead, BufReader};
|
use std::io::{BufRead, BufReader};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
pub fn get_history_of_set(id: Id) -> Vec<HistoryItem> {
|
pub fn get_history_of_set(id: Id) -> Result<Vec<HistoryItem>, NotificationData> {
|
||||||
let app_dir = history_dir();
|
let app_dir = history_dir()?;
|
||||||
let head = app_dir.clone().join(format!("set_{}_history.csv", id));
|
let head = app_dir.clone().join(format!("set_{}_history.csv", id));
|
||||||
let mut lines = Vec::new();
|
let mut lines = Vec::new();
|
||||||
|
|
||||||
append_lines_if_exists(head, &mut lines);
|
append_lines_if_exists(head, &mut lines)?;
|
||||||
lines.reverse();
|
lines.reverse();
|
||||||
parse_history_items(lines)
|
Ok(parse_history_items(lines))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn append_lines_if_exists(path: PathBuf, lines: &mut Vec<String>) {
|
fn append_lines_if_exists(path: PathBuf, lines: &mut Vec<String>) -> MaybeError {
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
let reader = BufReader::new(File::open(path).unwrap());
|
let reader = BufReader::new(File::open(path).map_err(|_| PermissionDenied)?);
|
||||||
for line in reader.lines() {
|
reader
|
||||||
lines.push(line.unwrap());
|
.lines()
|
||||||
}
|
.map_while(Result::ok)
|
||||||
|
.for_each(|i| lines.push(i));
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
|
fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
|
||||||
@@ -34,12 +39,13 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
|
|||||||
if id.is_err() {
|
if id.is_err() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let id = id.unwrap();
|
let id = id.unwrap_or_default();
|
||||||
if !id.is_valid() {
|
if !id.is_valid() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
items.push(HistoryItem {
|
items.push(HistoryItem {
|
||||||
timestamp: DateTime::from_timestamp(time.parse().unwrap_or_default(), 0).unwrap_or_default(),
|
timestamp: DateTime::from_timestamp(time.parse().unwrap_or_default(), 0)
|
||||||
|
.unwrap_or_default(),
|
||||||
word_id: id,
|
word_id: id,
|
||||||
mode: match mode.parse::<u8>().unwrap_or_default() {
|
mode: match mode.parse::<u8>().unwrap_or_default() {
|
||||||
2 => WordOpenMode::Hard,
|
2 => WordOpenMode::Hard,
|
||||||
@@ -56,15 +62,15 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
|
|||||||
items
|
items
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn push_note(set_id: Id, item: HistoryItem) {
|
pub fn push_note(set_id: Id, item: HistoryItem) -> MaybeError {
|
||||||
let app_dir = history_dir();
|
let app_dir = history_dir()?;
|
||||||
let path = app_dir.clone().join(format!("set_{}_history.csv", set_id));
|
let path = app_dir.clone().join(format!("set_{}_history.csv", set_id));
|
||||||
|
|
||||||
let mut file = OpenOptions::new()
|
let mut file = OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
.append(true)
|
.append(true)
|
||||||
.open(path)
|
.open(path)
|
||||||
.unwrap();
|
.map_err(|_| PermissionDenied)?;
|
||||||
let line_str = format!(
|
let line_str = format!(
|
||||||
"{};{};{};{};{}",
|
"{};{};{};{};{}",
|
||||||
item.timestamp.timestamp(),
|
item.timestamp.timestamp(),
|
||||||
@@ -78,22 +84,6 @@ pub fn push_note(set_id: Id, item: HistoryItem) {
|
|||||||
item.before,
|
item.before,
|
||||||
item.after
|
item.after
|
||||||
);
|
);
|
||||||
writeln!(&mut file, "{}", line_str).unwrap();
|
writeln!(&mut file, "{}", line_str).map_err(|_| PermissionDenied)?;
|
||||||
}
|
Ok(())
|
||||||
|
|
||||||
pub fn history_dir() -> PathBuf {
|
|
||||||
let directory = app_data_dir().join("history");
|
|
||||||
if !directory.exists() {
|
|
||||||
fs::create_dir(directory.clone()).unwrap();
|
|
||||||
}
|
|
||||||
directory
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct HistoryItem {
|
|
||||||
pub timestamp: DateTime<Utc>,
|
|
||||||
pub word_id: Id,
|
|
||||||
pub mode: WordOpenMode,
|
|
||||||
pub before: u8,
|
|
||||||
pub after: u8,
|
|
||||||
}
|
}
|
||||||
+41
-22
@@ -1,4 +1,8 @@
|
|||||||
|
use crate::helpers::into_result;
|
||||||
|
use crate::notification::NotificationData;
|
||||||
|
use crate::notification::NotificationData::IncorrectAnkiFile;
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
|
use log::info;
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
@@ -21,36 +25,47 @@ pub struct ImportNote {
|
|||||||
pub fields: Vec<String>,
|
pub fields: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_groups(connection: &Connection) -> ImportData {
|
pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationData> {
|
||||||
let json_models: String = connection
|
let json_models: String = connection
|
||||||
.query_one("select models from col", (), |row| row.get(0))
|
.query_one("select models from col", (), |row| row.get(0))
|
||||||
.unwrap();
|
.map_err(|_| IncorrectAnkiFile)?;
|
||||||
let raw: Value = serde_json::from_str(json_models.as_str()).unwrap();
|
let raw: Value = serde_json::from_str(json_models.as_str()).map_err(|_| IncorrectAnkiFile)?;
|
||||||
let sets = raw.as_object().unwrap();
|
let sets = raw.as_object();
|
||||||
|
if let Some(sets) = sets {
|
||||||
let mut total_data = ImportData(vec![]);
|
let mut total_data = ImportData(vec![]);
|
||||||
|
|
||||||
let mut count_stmt = connection
|
let mut count_stmt = connection
|
||||||
.prepare("select mid, count(id) from notes group by mid")
|
.prepare("select mid, count(id) from notes group by mid")
|
||||||
.unwrap();
|
.map_err(|_| IncorrectAnkiFile)?;
|
||||||
|
|
||||||
let counts = count_stmt
|
let counts = count_stmt
|
||||||
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
|
||||||
.unwrap()
|
.map_err(|_| IncorrectAnkiFile)?
|
||||||
.map(|x| x.unwrap())
|
.filter_map(|x| x.ok())
|
||||||
.collect::<Vec<(i64, i64)>>();
|
.collect::<Vec<(i64, i64)>>();
|
||||||
|
|
||||||
for (_, collection) in sets {
|
for (_, collection) in sets {
|
||||||
let fields_property = collection.get("fields");
|
let fields_property = collection.get("fields");
|
||||||
if let Some(fields_property) = fields_property {
|
if let Some(fields_property) = fields_property {
|
||||||
let fields = fields_property
|
let fields = into_result(fields_property.as_array(), IncorrectAnkiFile)?
|
||||||
.as_array()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|x| x["name"].as_str().unwrap().to_string())
|
.filter_map(|x| x.get("name"))
|
||||||
|
.map(|x| x.as_str().unwrap().to_string())
|
||||||
.collect();
|
.collect();
|
||||||
|
let id = collection.get("id");
|
||||||
|
if id.is_none() || id.unwrap().as_u64().is_none() {
|
||||||
|
return Err(IncorrectAnkiFile);
|
||||||
|
}
|
||||||
|
let id = id.unwrap().as_u64().unwrap();
|
||||||
|
let name = collection.get("name");
|
||||||
|
if name.is_none() || name.unwrap().as_str().is_none() {
|
||||||
|
return Err(IncorrectAnkiFile);
|
||||||
|
}
|
||||||
|
let name = name.unwrap().as_str().unwrap().to_string();
|
||||||
|
|
||||||
let mut group = ImportGroup {
|
let mut group = ImportGroup {
|
||||||
id: collection["id"].as_u64().unwrap(),
|
id,
|
||||||
name: collection["name"].as_str().unwrap().to_string(),
|
name,
|
||||||
fields,
|
fields,
|
||||||
mapping: Default::default(),
|
mapping: Default::default(),
|
||||||
length: 0,
|
length: 0,
|
||||||
@@ -59,20 +74,24 @@ pub fn load_groups(connection: &Connection) -> ImportData {
|
|||||||
if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) {
|
if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) {
|
||||||
group.length = *count as u64
|
group.length = *count as u64
|
||||||
}
|
}
|
||||||
println!("{:?}", group);
|
info!("{:?}", group);
|
||||||
total_data.0.push(group);
|
total_data.0.push(group);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
total_data
|
return Ok(total_data);
|
||||||
|
}
|
||||||
|
Err(IncorrectAnkiFile)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_words_of_group(connection: &Connection, group_id: u64) -> Vec<ImportNote> {
|
pub fn get_words_of_group(
|
||||||
|
connection: &Connection,
|
||||||
|
group_id: u64,
|
||||||
|
) -> Result<Vec<ImportNote>, NotificationData> {
|
||||||
let mut count_stmt = connection
|
let mut count_stmt = connection
|
||||||
.prepare("select tags, flds from notes where mid == ?1;")
|
.prepare("select tags, flds from notes where mid == ?1;")
|
||||||
.unwrap();
|
.map_err(|_| IncorrectAnkiFile)?;
|
||||||
|
|
||||||
count_stmt
|
Ok(count_stmt
|
||||||
.query_map((group_id as i64,), |row| {
|
.query_map((group_id as i64,), |row| {
|
||||||
Ok(ImportNote {
|
Ok(ImportNote {
|
||||||
tags: row.get(0)?,
|
tags: row.get(0)?,
|
||||||
@@ -83,7 +102,7 @@ pub fn get_words_of_group(connection: &Connection, group_id: u64) -> Vec<ImportN
|
|||||||
.collect(),
|
.collect(),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap()
|
.map_err(|_| IncorrectAnkiFile)?
|
||||||
.map(|x| x.unwrap())
|
.filter_map(|x| x.ok())
|
||||||
.collect::<Vec<ImportNote>>()
|
.collect::<Vec<ImportNote>>())
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
|
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
|
|
||||||
pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
|
pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
|
||||||
let mut stmt = connection
|
let mut stmt = connection
|
||||||
.prepare("SELECT value FROM settings WHERE id = ?1")
|
.prepare("SELECT value FROM settings WHERE id = ?1")
|
||||||
.unwrap();
|
.expect("Failed to prepare statement.");
|
||||||
let mut iter = stmt.query_map((key,), |row| row.get(0)).unwrap();
|
let mut iter = stmt.query_map((key,), |row| row.get(0)).ok()?;
|
||||||
|
|
||||||
if let Some(row) = iter.next()
|
if let Some(row) = iter.next()
|
||||||
&& let Ok(value) = row
|
&& let Ok(value) = row
|
||||||
@@ -15,31 +17,35 @@ pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_setting(key: String, value: String, connection: &Connection) {
|
pub fn set_setting(key: String, value: String, connection: &Connection) -> MaybeError {
|
||||||
let current = get_settings_list(connection);
|
let current = get_settings_list(connection)?;
|
||||||
if current.contains(&key) {
|
if current.contains(&key) {
|
||||||
update_settings(key, value, connection);
|
update_settings(key, value, connection)?;
|
||||||
} else {
|
} else {
|
||||||
create_settings(key, value, connection);
|
create_settings(key, value, connection)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_settings(key: String, connection: &Connection) {
|
pub fn delete_settings(key: String, connection: &Connection) -> MaybeError {
|
||||||
connection
|
connection
|
||||||
.execute("DELETE FROM settings WHERE id = ?1", (&key,))
|
.execute("DELETE FROM settings WHERE id = ?1", (&key,))
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_settings(key: String, value: String, connection: &Connection) {
|
fn create_settings(key: String, value: String, connection: &Connection) -> MaybeError {
|
||||||
connection
|
connection
|
||||||
.execute(
|
.execute(
|
||||||
"INSERT into settings (id, value) VALUES (?1, ?2)",
|
"INSERT into settings (id, value) VALUES (?1, ?2)",
|
||||||
(key, value),
|
(key, value),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_settings(key: String, value: String, connection: &Connection) {
|
fn update_settings(key: String, value: String, connection: &Connection) -> MaybeError {
|
||||||
connection
|
connection
|
||||||
.execute(
|
.execute(
|
||||||
"update settings
|
"update settings
|
||||||
@@ -47,11 +53,16 @@ set value = ?2
|
|||||||
where id = ?1",
|
where id = ?1",
|
||||||
(key, value),
|
(key, value),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_settings_list(connection: &Connection) -> Vec<String> {
|
fn get_settings_list(connection: &Connection) -> Result<Vec<String>, NotificationData> {
|
||||||
let mut stmt = connection.prepare("SELECT id FROM settings").unwrap();
|
let mut stmt = connection
|
||||||
let iter = stmt.query_map((), |row| row.get(0)).unwrap();
|
.prepare("SELECT id FROM settings")
|
||||||
iter.map(|row| row.unwrap()).collect()
|
.expect("prepare stmt failed");
|
||||||
|
let iter = stmt
|
||||||
|
.query_map((), |row| row.get(0))
|
||||||
|
.map_err(|_| DbLoadError)?;
|
||||||
|
Ok(iter.filter_map(|i| i.ok()).collect())
|
||||||
}
|
}
|
||||||
+17
-21
@@ -1,30 +1,25 @@
|
|||||||
use crate::dictionary::app_data_dir;
|
use crate::fs::*;
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
|
|
||||||
pub fn create_db() {
|
pub fn create_db() {
|
||||||
let path = app_data_dir();
|
let db_file = db_path();
|
||||||
let db_file = path.join("data.db");
|
|
||||||
if !db_file.exists() {
|
if !db_file.exists() {
|
||||||
std::fs::File::create(&db_file).unwrap();
|
std::fs::File::create(&db_file).expect("Database file creation failed");
|
||||||
let connection = Connection::open(&db_file).unwrap();
|
let connection = Connection::open(&db_file).expect("Connection open failed");
|
||||||
connection.execute("PRAGMA foreign_keys = ON;", []).unwrap();
|
connection
|
||||||
|
.execute("PRAGMA foreign_keys = ON;", [])
|
||||||
|
.expect("Failed to set PRAGMA");
|
||||||
|
|
||||||
create_tables(&connection);
|
create_tables(&connection);
|
||||||
} else {
|
|
||||||
let connection = Connection::open(&db_file).unwrap();
|
|
||||||
|
|
||||||
ensure_db_schema(&connection);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ensure_db_schema(_: &Connection) {}
|
|
||||||
|
|
||||||
fn create_tables(conn: &Connection) {
|
fn create_tables(conn: &Connection) {
|
||||||
make_card_set(conn).unwrap();
|
make_card_set(conn).expect("Failed to init table");
|
||||||
make_settings(conn).unwrap();
|
make_settings(conn).expect("Failed to init table");
|
||||||
make_word_group(conn).unwrap();
|
make_word_group(conn).expect("Failed to init table");
|
||||||
make_words(conn).unwrap();
|
make_words(conn).expect("Failed to init table");
|
||||||
make_card_stats(conn).unwrap();
|
make_card_stats(conn).expect("Failed to init table");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> {
|
fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||||
@@ -57,9 +52,10 @@ fn make_card_stats(conn: &Connection) -> Result<(), rusqlite::Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn default_connection() -> Connection {
|
pub fn default_connection() -> Connection {
|
||||||
let path = app_data_dir();
|
let db_file = db_path();
|
||||||
let db_file = path.join("data.db");
|
let connection = Connection::open(db_file).expect("Failed to open database");
|
||||||
let connection = Connection::open(db_file).unwrap();
|
connection
|
||||||
connection.execute("PRAGMA foreign_keys = ON;", []).unwrap();
|
.execute("PRAGMA foreign_keys = ON;", [])
|
||||||
|
.expect("Failed to set PRAGMA");
|
||||||
connection
|
connection
|
||||||
}
|
}
|
||||||
+19
-12
@@ -1,15 +1,14 @@
|
|||||||
use crate::dictionary::app_data_dir;
|
use crate::fs::*;
|
||||||
|
use crate::notification::NotificationData;
|
||||||
|
use crate::notification::NotificationData::*;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::BufReader;
|
use std::io::BufReader;
|
||||||
|
|
||||||
pub async fn get_voice(text: &str) -> Result<BufReader<File>, ()> {
|
pub async fn get_voice(text: &str) -> Result<BufReader<File>, NotificationData> {
|
||||||
let mut path = app_data_dir();
|
let mut path = voice_dir()?;
|
||||||
path.push("voice");
|
|
||||||
if !path.exists() {
|
|
||||||
std::fs::create_dir(path.clone()).map_err(|_| ())?;
|
|
||||||
}
|
|
||||||
let hash = format!("{}.wav", hex::encode(Sha256::digest(text.as_bytes())));
|
let hash = format!("{}.wav", hex::encode(Sha256::digest(text.as_bytes())));
|
||||||
path.push(hash);
|
path.push(hash);
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
@@ -20,7 +19,11 @@ pub async fn get_voice(text: &str) -> Result<BufReader<File>, ()> {
|
|||||||
.send()
|
.send()
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let query = query.map_err(|_| ())?.text().await.map_err(|_| ())?;
|
let query = query
|
||||||
|
.map_err(|_| VoiceVoxUnavailable)?
|
||||||
|
.text()
|
||||||
|
.await
|
||||||
|
.map_err(|_| VoiceVoxUnavailable)?;
|
||||||
// Synthesis
|
// Synthesis
|
||||||
let audio = client
|
let audio = client
|
||||||
.post(format!("{engine_url}/synthesis?speaker=11"))
|
.post(format!("{engine_url}/synthesis?speaker=11"))
|
||||||
@@ -28,13 +31,17 @@ pub async fn get_voice(text: &str) -> Result<BufReader<File>, ()> {
|
|||||||
.body(query)
|
.body(query)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|_| ())?
|
.map_err(|_| VoiceVoxUnavailable)?
|
||||||
.bytes()
|
.bytes()
|
||||||
.await
|
.await
|
||||||
.map_err(|_| ())?;
|
.map_err(|_| VoiceVoxUnavailable)?;
|
||||||
|
|
||||||
tokio::fs::write(&path, &audio).await.map_err(|_| ())?;
|
tokio::fs::write(&path, &audio)
|
||||||
|
.await
|
||||||
|
.map_err(|_| PermissionDenied)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(BufReader::new(File::open(path).map_err(|_| ())?))
|
Ok(BufReader::new(
|
||||||
|
File::open(path).map_err(|_| PermissionDenied)?,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
use crate::dictionary::app_data_dir;
|
use crate::fs::*;
|
||||||
|
use crate::notification::NotificationData::{CompressError, PermissionDenied, WebApiUnavailable};
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
|
use log::info;
|
||||||
use std::io;
|
use std::io;
|
||||||
use reqwest::Error;
|
|
||||||
use tokio::fs::{File, OpenOptions};
|
use tokio::fs::{File, OpenOptions};
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
|
use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
|
||||||
@@ -8,11 +10,12 @@ use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
|
|||||||
// const API_URL: &str = "http://127.0.0.1:8089/";
|
// const API_URL: &str = "http://127.0.0.1:8089/";
|
||||||
const API_URL: &str = "https://learning.micialware.ru/";
|
const API_URL: &str = "https://learning.micialware.ru/";
|
||||||
|
|
||||||
pub async fn send_data(id: String) -> Result<(), ()> {
|
pub async fn send_data(id: String) -> MaybeError {
|
||||||
let path = app_data_dir();
|
let db_file = db_path();
|
||||||
let db_file = path.join("data.db");
|
let data = tokio::fs::read(db_file)
|
||||||
let data = tokio::fs::read(db_file).await.map_err(|_| ())?;
|
.await
|
||||||
let data = compress(data);
|
.map_err(|_| WebApiUnavailable)?;
|
||||||
|
let data = compress(data)?;
|
||||||
|
|
||||||
let api_url = API_URL.to_string();
|
let api_url = API_URL.to_string();
|
||||||
let id_url = format!("{api_url}upload/stream/{id}");
|
let id_url = format!("{api_url}upload/stream/{id}");
|
||||||
@@ -22,60 +25,66 @@ pub async fn send_data(id: String) -> Result<(), ()> {
|
|||||||
.post(&id_url)
|
.post(&id_url)
|
||||||
.body(data)
|
.body(data)
|
||||||
.send()
|
.send()
|
||||||
.await.map_err(|_| ())?
|
.await
|
||||||
|
.map_err(|_| WebApiUnavailable)?
|
||||||
.text()
|
.text()
|
||||||
.await.map_err(|_| ())?;
|
.await
|
||||||
set_local_version(new_version.parse::<u32>().unwrap()).await;
|
.map_err(|_| WebApiUnavailable)?;
|
||||||
|
set_local_version(new_version.parse::<u32>().unwrap_or_default()).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compress(data: Vec<u8>) -> Vec<u8> {
|
fn compress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> {
|
||||||
let mut encoder = Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).unwrap();
|
let mut encoder =
|
||||||
io::copy(&mut &data[..], &mut encoder).unwrap();
|
Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).map_err(|_| CompressError)?;
|
||||||
encoder.finish().unwrap()
|
io::copy(&mut &data[..], &mut encoder).map_err(|_| PermissionDenied)?;
|
||||||
|
encoder.finish().map_err(|_| CompressError)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn load_data(id: String, temp: bool) -> Result<(), Error> {
|
pub async fn load_data(id: String, temp: bool) -> MaybeError {
|
||||||
let api_url = API_URL.to_string();
|
let api_url = API_URL.to_string();
|
||||||
let id_url = format!("{api_url}download/{id}");
|
let id_url = format!("{api_url}download/{id}");
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let data = client
|
let data = client
|
||||||
.get(&id_url)
|
.get(&id_url)
|
||||||
.send()
|
.send()
|
||||||
.await?
|
.await
|
||||||
|
.map_err(|_| WebApiUnavailable)?
|
||||||
.bytes()
|
.bytes()
|
||||||
.await?
|
.await
|
||||||
|
.map_err(|_| WebApiUnavailable)?
|
||||||
.to_vec();
|
.to_vec();
|
||||||
let data = decompress(data);
|
let data = decompress(data)?;
|
||||||
|
|
||||||
let path = app_data_dir();
|
let path = app_data_dir();
|
||||||
let file_name = if temp { "data.db.tmp" } else { "data.db" };
|
let file_name = if temp { "data.db.tmp" } else { "data.db" };
|
||||||
let db_file = path.join(file_name);
|
let db_file = path.join(file_name);
|
||||||
|
|
||||||
tokio::fs::write(db_file, data).await.unwrap();
|
tokio::fs::write(db_file, data)
|
||||||
|
.await
|
||||||
|
.map_err(|_| PermissionDenied)?;
|
||||||
|
|
||||||
let version_url = format!("{API_URL}{id}/version");
|
let version_url = format!("{API_URL}{id}/version");
|
||||||
let version = client
|
let version = client
|
||||||
.get(&version_url)
|
.get(&version_url)
|
||||||
.send()
|
.send()
|
||||||
.await?
|
.await
|
||||||
|
.map_err(|_| WebApiUnavailable)?
|
||||||
.text()
|
.text()
|
||||||
.await?;
|
.await
|
||||||
set_local_version(version.parse::<u32>().unwrap_or_default()).await;
|
.map_err(|_| WebApiUnavailable)?;
|
||||||
|
set_local_version(version.parse::<u32>().unwrap_or_default()).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decompress(data: Vec<u8>) -> Vec<u8> {
|
pub fn decompress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> {
|
||||||
let mut decoder = Decoder::new(&data[..]).unwrap();
|
let mut decoder = Decoder::new(&data[..]).map_err(|_| CompressError)?;
|
||||||
let mut decompressed = Vec::new();
|
let mut decompressed = Vec::new();
|
||||||
let res = io::copy(&mut decoder, &mut decompressed);
|
io::copy(&mut decoder, &mut decompressed).map_err(|_| PermissionDenied)?;
|
||||||
if let Err(e) = res {
|
Ok(decompressed)
|
||||||
println!("{}", e);
|
|
||||||
}
|
|
||||||
decompressed
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn first_sync() -> Result<String, ()> {
|
pub async fn first_sync() -> Result<String, NotificationData> {
|
||||||
let id_url = API_URL.to_string() + "generate";
|
let id_url = API_URL.to_string() + "generate";
|
||||||
|
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
@@ -83,33 +92,40 @@ pub async fn first_sync() -> Result<String, ()> {
|
|||||||
.get(&id_url)
|
.get(&id_url)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|_| ())?
|
.map_err(|_| WebApiUnavailable)?
|
||||||
.text()
|
.text()
|
||||||
.await
|
.await
|
||||||
.map_err(|_| ())?;
|
.map_err(|_| WebApiUnavailable)?;
|
||||||
println!("id: {}", id);
|
info!("id: {}", id);
|
||||||
Ok(id)
|
Ok(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_web_version(key: &str) -> Result<u32, reqwest::Error> {
|
pub async fn get_web_version(key: &str) -> Result<u32, NotificationData> {
|
||||||
let id_url = format!("{API_URL}{key}/version");
|
let id_url = format!("{API_URL}{key}/version");
|
||||||
let client = reqwest::Client::new();
|
let client = reqwest::Client::new();
|
||||||
let version = client.get(&id_url).send().await?.text().await?;
|
let version = client
|
||||||
println!("version: {}", version);
|
.get(&id_url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|_| WebApiUnavailable)?
|
||||||
|
.text()
|
||||||
|
.await
|
||||||
|
.map_err(|_| WebApiUnavailable)?;
|
||||||
|
info!("version: {}", version);
|
||||||
Ok(version.parse::<u32>().unwrap_or_default())
|
Ok(version.parse::<u32>().unwrap_or_default())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_local_version() -> u32 {
|
pub async fn get_local_version() -> Result<u32, NotificationData> {
|
||||||
let file = app_data_dir().join("data.meta");
|
let file = db_meta_path();
|
||||||
if file.exists() {
|
if file.exists() {
|
||||||
let mut data = String::new();
|
let mut data = String::new();
|
||||||
File::open(file.clone())
|
File::open(file.clone())
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.map_err(|_| PermissionDenied)?
|
||||||
.read_to_string(&mut data)
|
.read_to_string(&mut data)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.map_err(|_| PermissionDenied)?;
|
||||||
return data.parse::<u32>().unwrap_or_default();
|
return Ok(data.parse::<u32>().unwrap_or_default());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut file = OpenOptions::new()
|
let mut file = OpenOptions::new()
|
||||||
@@ -118,21 +134,24 @@ pub async fn get_local_version() -> u32 {
|
|||||||
.truncate(true)
|
.truncate(true)
|
||||||
.open(file)
|
.open(file)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.map_err(|_| PermissionDenied)?;
|
||||||
file.write_all("0".as_bytes()).await.unwrap();
|
file.write_all("0".as_bytes())
|
||||||
0
|
.await
|
||||||
|
.map_err(|_| PermissionDenied)?;
|
||||||
|
Ok(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_local_version(version: u32) {
|
pub async fn set_local_version(version: u32) -> Result<(), NotificationData> {
|
||||||
let file_path = app_data_dir().join("data.meta");
|
let file_path = db_meta_path();
|
||||||
let mut file = OpenOptions::new()
|
let mut file = OpenOptions::new()
|
||||||
.write(true)
|
.write(true)
|
||||||
.create(true)
|
.create(true)
|
||||||
.truncate(true)
|
.truncate(true)
|
||||||
.open(file_path)
|
.open(file_path)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.map_err(|_| PermissionDenied)?;
|
||||||
file.write_all(version.to_string().as_bytes())
|
file.write_all(version.to_string().as_bytes())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.map_err(|_| PermissionDenied)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
+53
-42
@@ -1,8 +1,10 @@
|
|||||||
use crate::lang::{WordData, WordGroup};
|
use crate::data::entities::{WordData, WordGroup};
|
||||||
|
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
use rusqlite::{Connection, params};
|
use rusqlite::{Connection, params};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
pub fn add_word(word: &mut WordData, connection: &Connection) {
|
pub fn add_word(word: &mut WordData, connection: &Connection) -> MaybeError {
|
||||||
let index : u32 = connection
|
let index : u32 = connection
|
||||||
.query_row(
|
.query_row(
|
||||||
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
|
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
|
||||||
@@ -10,17 +12,18 @@ pub fn add_word(word: &mut WordData, connection: &Connection) {
|
|||||||
&word.key,
|
&word.key,
|
||||||
&word.value,
|
&word.value,
|
||||||
&word.tags,
|
&word.tags,
|
||||||
serde_json::to_string(&word.additional).unwrap(),
|
serde_json::to_string(&word.additional).unwrap_or_default(),
|
||||||
&word.group_id,
|
&word.group_id,
|
||||||
),
|
),
|
||||||
|row| row.get(0),
|
|row| row.get(0),
|
||||||
).unwrap();
|
).map_err(|_| DbSaveError)?;
|
||||||
|
|
||||||
word.id = index.into();
|
word.id = index.into();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
|
pub fn add_words(words: &mut [WordData], connection: &mut Connection) -> MaybeError {
|
||||||
let tx = connection.transaction().unwrap();
|
let tx = connection.transaction().map_err(|_| DbLoadError)?;
|
||||||
let count = words.len();
|
let count = words.len();
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -28,33 +31,35 @@ pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
|
|||||||
.prepare(
|
.prepare(
|
||||||
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)",
|
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||||
)
|
)
|
||||||
.unwrap();
|
.expect("Failed to prepare statement");
|
||||||
|
|
||||||
for word in words.iter() {
|
for word in words.iter() {
|
||||||
stmt.execute(params![
|
stmt.execute(params![
|
||||||
word.key,
|
word.key,
|
||||||
word.value,
|
word.value,
|
||||||
word.tags,
|
word.tags,
|
||||||
serde_json::to_string(&word.additional).unwrap(),
|
serde_json::to_string(&word.additional).unwrap_or_default(),
|
||||||
word.group_id
|
word.group_id
|
||||||
])
|
])
|
||||||
.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().map_err(|_| DbSaveError)?;
|
||||||
|
|
||||||
let start_index = last_index - (count as u32) + 1;
|
let start_index = last_index - (count as u32) + 1;
|
||||||
|
|
||||||
for (index, id) in (start_index..=last_index).enumerate() {
|
for (index, id) in (start_index..=last_index).enumerate() {
|
||||||
words[index].id = id.into();
|
words[index].id = id.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_word(word: &mut WordData, connection: &Connection) {
|
pub fn update_word(word: &mut WordData, connection: &Connection) -> MaybeError {
|
||||||
if !word.id.is_valid() {
|
if !word.id.is_valid() {
|
||||||
add_word(word, connection);
|
Ok(add_word(word, connection)?)
|
||||||
} else {
|
} else {
|
||||||
connection
|
connection
|
||||||
.execute(
|
.execute(
|
||||||
@@ -63,27 +68,29 @@ pub fn update_word(word: &mut WordData, connection: &Connection) {
|
|||||||
&word.key,
|
&word.key,
|
||||||
&word.value,
|
&word.value,
|
||||||
&word.tags,
|
&word.tags,
|
||||||
serde_json::to_string(&word.additional).unwrap(),
|
serde_json::to_string(&word.additional).map_err(|_| DbSaveError)?,
|
||||||
&word.id,
|
&word.id,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_word(word: &WordData, connection: &Connection) {
|
pub fn delete_word(word: &WordData, connection: &Connection) -> MaybeError {
|
||||||
if !word.id.is_valid() {
|
if !word.id.is_valid() {
|
||||||
return;
|
return Err(DbSaveError);
|
||||||
}
|
}
|
||||||
connection
|
connection
|
||||||
.execute("DELETE FROM words WHERE id = ?1", (&word.id,))
|
.execute("DELETE FROM words WHERE id = ?1", (&word.id,))
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_words(connection: &Connection) -> Vec<WordData> {
|
pub fn load_words(connection: &Connection) -> Result<Vec<WordData>, NotificationData> {
|
||||||
let mut stmt = connection
|
let mut stmt = connection
|
||||||
.prepare("SELECT id, key, value, tags, more, group_id FROM words")
|
.prepare("SELECT id, key, value, tags, more, group_id FROM words")
|
||||||
.unwrap();
|
.expect("Failed to prepare statement");
|
||||||
let word_iter = stmt
|
let word_iter = stmt
|
||||||
.query_map([], |row| {
|
.query_map([], |row| {
|
||||||
let additional: String = row.get(4)?;
|
let additional: String = row.get(4)?;
|
||||||
@@ -92,24 +99,25 @@ pub fn load_words(connection: &Connection) -> Vec<WordData> {
|
|||||||
key: row.get(1)?,
|
key: row.get(1)?,
|
||||||
value: row.get(2)?,
|
value: row.get(2)?,
|
||||||
tags: row.get(3)?,
|
tags: row.get(3)?,
|
||||||
additional: serde_json::from_str::<HashMap<String, String>>(&additional).unwrap(),
|
additional: serde_json::from_str::<HashMap<String, String>>(&additional)
|
||||||
|
.unwrap_or_default(),
|
||||||
group_id: row.get(5)?,
|
group_id: row.get(5)?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap();
|
.map_err(|_| DbLoadError)?;
|
||||||
|
|
||||||
let mut buffer = vec![];
|
let mut buffer = Vec::with_capacity(1024);
|
||||||
for word in word_iter {
|
word_iter
|
||||||
buffer.push(word.unwrap());
|
.filter_map(|res| res.ok())
|
||||||
}
|
.for_each(|i| buffer.push(i));
|
||||||
|
|
||||||
buffer
|
Ok(buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_word_groups(connection: &Connection) -> Vec<WordGroup> {
|
pub fn load_word_groups(connection: &Connection) -> Result<Vec<WordGroup>, NotificationData> {
|
||||||
let mut stmt = connection
|
let mut stmt = connection
|
||||||
.prepare("SELECT id, name FROM word_group")
|
.prepare("SELECT id, name FROM word_group")
|
||||||
.unwrap();
|
.expect("Failed to prepare statement");
|
||||||
let group_iter = stmt
|
let group_iter = stmt
|
||||||
.query_map([], |row| {
|
.query_map([], |row| {
|
||||||
Ok(WordGroup {
|
Ok(WordGroup {
|
||||||
@@ -117,46 +125,49 @@ pub fn load_word_groups(connection: &Connection) -> Vec<WordGroup> {
|
|||||||
name: row.get(1)?,
|
name: row.get(1)?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.unwrap();
|
.map_err(|_| DbLoadError)?;
|
||||||
|
|
||||||
let mut buffer = vec![];
|
let mut buffer = Vec::with_capacity(8);
|
||||||
for group in group_iter {
|
group_iter
|
||||||
buffer.push(group.unwrap());
|
.filter_map(|res| res.ok())
|
||||||
}
|
.for_each(|i| buffer.push(i));
|
||||||
|
|
||||||
buffer
|
Ok(buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_group(group: &mut WordGroup, connection: &Connection) {
|
pub fn add_group(group: &mut WordGroup, connection: &Connection) -> MaybeError {
|
||||||
let index: u32 = connection
|
let index: u32 = connection
|
||||||
.query_row(
|
.query_row(
|
||||||
"INSERT INTO word_group (name) VALUES (?1) RETURNING id",
|
"INSERT INTO word_group (name) VALUES (?1) RETURNING id",
|
||||||
(&group.name,),
|
(&group.name,),
|
||||||
|row| row.get(0),
|
|row| row.get(0),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
|
||||||
group.id = index.into();
|
group.id = index.into();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_group(group: &mut WordGroup, connection: &Connection) {
|
pub fn update_group(group: &mut WordGroup, connection: &Connection) -> MaybeError {
|
||||||
if !group.id.is_valid() {
|
if !group.id.is_valid() {
|
||||||
add_group(group, connection);
|
Ok(add_group(group, connection)?)
|
||||||
} else {
|
} else {
|
||||||
connection
|
connection
|
||||||
.execute(
|
.execute(
|
||||||
"UPDATE word_group SET name = ?1 WHERE id = ?2",
|
"UPDATE word_group SET name = ?1 WHERE id = ?2",
|
||||||
(&group.name, &group.id),
|
(&group.name, &group.id),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn delete_group(group: &WordGroup, connection: &Connection) {
|
pub fn delete_group(group: &WordGroup, connection: &Connection) -> MaybeError {
|
||||||
if !group.id.is_valid() {
|
if !group.id.is_valid() {
|
||||||
return;
|
return Err(DbSaveError);
|
||||||
}
|
}
|
||||||
connection
|
connection
|
||||||
.execute("DELETE FROM word_group WHERE id = ?1", (&group.id,))
|
.execute("DELETE FROM word_group WHERE id = ?1", (&group.id,))
|
||||||
.unwrap();
|
.map_err(|_| DbSaveError)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
use crate::notification::NotificationData;
|
||||||
|
use crate::notification::NotificationData::PermissionDenied;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
pub fn app_data_dir() -> PathBuf {
|
||||||
|
let mut dir = dirs::data_dir().expect("Unsupported OS");
|
||||||
|
dir.push("jap_learn");
|
||||||
|
if !dir.exists() {
|
||||||
|
fs::create_dir_all(dir.clone()).expect("Unable to create directory");
|
||||||
|
}
|
||||||
|
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn db_path() -> PathBuf {
|
||||||
|
app_data_dir().join("data.db")
|
||||||
|
}
|
||||||
|
pub fn temp_db_path() -> PathBuf {
|
||||||
|
app_data_dir().join("data.db.tmp")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn temp_import_path() -> PathBuf {
|
||||||
|
app_data_dir().join("import")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn db_meta_path() -> PathBuf {
|
||||||
|
app_data_dir().join("data.meta")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn history_dir() -> Result<PathBuf, NotificationData> {
|
||||||
|
let directory = app_data_dir().join("history");
|
||||||
|
if !directory.exists() {
|
||||||
|
fs::create_dir_all(directory.clone()).map_err(|_| PermissionDenied)?;
|
||||||
|
}
|
||||||
|
Ok(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn voice_dir() -> Result<PathBuf, NotificationData> {
|
||||||
|
let directory = app_data_dir().join("voice");
|
||||||
|
if !directory.exists() {
|
||||||
|
fs::create_dir_all(directory.clone()).map_err(|_| PermissionDenied)?;
|
||||||
|
}
|
||||||
|
Ok(directory)
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#[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),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline(always)]
|
||||||
|
pub fn into_result<R, E>(option: Option<R>, error: E) -> Result<R, E> {
|
||||||
|
if let Some(r) = option {
|
||||||
|
Ok(r)
|
||||||
|
} else {
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
-718
@@ -1,718 +0,0 @@
|
|||||||
use crate::data_provider::card_stats::load_stats_of_deck;
|
|
||||||
use crate::data_provider::card_stats::update_stat_score;
|
|
||||||
use crate::data_provider::history::{push_note, HistoryItem};
|
|
||||||
use crate::AppState;
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use rand::distr::weighted::WeightedIndex;
|
|
||||||
use rand::distr::Distribution;
|
|
||||||
use rand::prelude::SliceRandom;
|
|
||||||
use rand::rng;
|
|
||||||
use rand::rngs::ThreadRng;
|
|
||||||
use rayon::iter::IndexedParallelIterator;
|
|
||||||
use rayon::iter::IntoParallelRefIterator;
|
|
||||||
use rayon::iter::ParallelIterator;
|
|
||||||
use rhai::{Engine, Scope};
|
|
||||||
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
|
|
||||||
use rusqlite::ToSql;
|
|
||||||
use std::cmp::PartialEq;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::fmt::{Display, Formatter};
|
|
||||||
use std::num::ParseIntError;
|
|
||||||
use std::str::FromStr;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
const MAX_HISTORY_LEN: usize = 20;
|
|
||||||
const MAX_HISTORY_LEN_PART: f32 = 0.33;
|
|
||||||
const MAX_SCORE: u8 = 25;
|
|
||||||
const FADE_PER_DAY: f32 = 0.95;
|
|
||||||
#[derive(Clone, PartialEq, Eq, Debug, Hash, Copy, Ord, PartialOrd)]
|
|
||||||
pub struct Id(u32);
|
|
||||||
pub const INVALID_ID: Id = Id(0);
|
|
||||||
impl FromStr for Id {
|
|
||||||
type Err = ParseIntError;
|
|
||||||
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
||||||
Ok(Id(s.parse::<u32>()?))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<u32> for Id {
|
|
||||||
fn from(value: u32) -> Self {
|
|
||||||
Id(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Id> for u32 {
|
|
||||||
fn from(value: Id) -> Self {
|
|
||||||
value.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Display for Id {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "{}", self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromSql for Id {
|
|
||||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
|
||||||
match value {
|
|
||||||
ValueRef::Integer(i) => Ok(Id(i as u32)),
|
|
||||||
_ => Err(FromSqlError::InvalidType),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql for Id {
|
|
||||||
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
|
|
||||||
Ok(ToSqlOutput::from(self.0 as i64))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Id> for String {
|
|
||||||
fn from(value: Id) -> Self {
|
|
||||||
value.0.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Id {
|
|
||||||
pub(crate) fn is_valid(self) -> bool {
|
|
||||||
self.0 != 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct KanaSet {
|
|
||||||
name: String,
|
|
||||||
pub(crate) chars_type: KanaType,
|
|
||||||
pub(crate) dictionary: Vec<Vec<(String, String)>>,
|
|
||||||
pub(crate) include_map: [bool; 10],
|
|
||||||
}
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum KanaType {
|
|
||||||
Hiragana,
|
|
||||||
Katakana,
|
|
||||||
}
|
|
||||||
impl KanaSet {
|
|
||||||
pub fn hiragana() -> Self {
|
|
||||||
Self {
|
|
||||||
name: "Хирагана".to_string(),
|
|
||||||
chars_type: KanaType::Hiragana,
|
|
||||||
dictionary: vec![
|
|
||||||
vec![
|
|
||||||
(String::from("ぁ"), String::from("a")),
|
|
||||||
(String::from("ぃ"), String::from("i")),
|
|
||||||
(String::from("ぅ"), String::from("u")),
|
|
||||||
(String::from("ぇ"), String::from("e")),
|
|
||||||
(String::from("ぉ"), String::from("o")),
|
|
||||||
],
|
|
||||||
vec![
|
|
||||||
(String::from("さ"), String::from("sa")),
|
|
||||||
(String::from("し"), String::from("shi")),
|
|
||||||
(String::from("す"), String::from("su")),
|
|
||||||
(String::from("せ"), String::from("se")),
|
|
||||||
(String::from("そ"), String::from("so")),
|
|
||||||
],
|
|
||||||
vec![
|
|
||||||
(String::from("か"), String::from("ka")),
|
|
||||||
(String::from("き"), String::from("ki")),
|
|
||||||
(String::from("く"), String::from("ku")),
|
|
||||||
(String::from("け"), String::from("ke")),
|
|
||||||
(String::from("こ"), String::from("ko")),
|
|
||||||
],
|
|
||||||
// Ряд «та» (たちつてと)
|
|
||||||
vec![
|
|
||||||
(String::from("た"), String::from("ta")),
|
|
||||||
(String::from("ち"), String::from("chi")),
|
|
||||||
(String::from("つ"), String::from("tsu")),
|
|
||||||
(String::from("て"), String::from("te")),
|
|
||||||
(String::from("と"), String::from("to")),
|
|
||||||
],
|
|
||||||
// Ряд «на» (なにぬねの)
|
|
||||||
vec![
|
|
||||||
(String::from("な"), String::from("na")),
|
|
||||||
(String::from("に"), String::from("ni")),
|
|
||||||
(String::from("ぬ"), String::from("nu")),
|
|
||||||
(String::from("ね"), String::from("ne")),
|
|
||||||
(String::from("の"), String::from("no")),
|
|
||||||
],
|
|
||||||
// Ряд «ха» (はひふへほ)
|
|
||||||
vec![
|
|
||||||
(String::from("は"), String::from("ha")),
|
|
||||||
(String::from("ひ"), String::from("hi")),
|
|
||||||
(String::from("ふ"), String::from("fu")),
|
|
||||||
(String::from("へ"), String::from("he")),
|
|
||||||
(String::from("ほ"), String::from("ho")),
|
|
||||||
],
|
|
||||||
// Ряд «ма» (まみむめも)
|
|
||||||
vec![
|
|
||||||
(String::from("ま"), String::from("ma")),
|
|
||||||
(String::from("み"), String::from("mi")),
|
|
||||||
(String::from("む"), String::from("mu")),
|
|
||||||
(String::from("め"), String::from("me")),
|
|
||||||
(String::from("も"), String::from("mo")),
|
|
||||||
],
|
|
||||||
// Ряд «я» (やゆよ) — только 3 символа
|
|
||||||
vec![
|
|
||||||
(String::from("や"), String::from("ya")),
|
|
||||||
(String::from("ゆ"), String::from("yu")),
|
|
||||||
(String::from("よ"), String::from("yo")),
|
|
||||||
],
|
|
||||||
// Ряд «ра» (らりるれろ)
|
|
||||||
vec![
|
|
||||||
(String::from("ら"), String::from("ra")),
|
|
||||||
(String::from("り"), String::from("ri")),
|
|
||||||
(String::from("る"), String::from("ru")),
|
|
||||||
(String::from("れ"), String::from("re")),
|
|
||||||
(String::from("ろ"), String::from("ro")),
|
|
||||||
],
|
|
||||||
vec![
|
|
||||||
(String::from("わ"), String::from("wa")),
|
|
||||||
(String::from("を"), String::from("wo")),
|
|
||||||
(String::from("ん"), String::from("n")),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
include_map: [true; 10],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn katakana() -> Self {
|
|
||||||
Self {
|
|
||||||
name: "Катакана".to_string(),
|
|
||||||
chars_type: KanaType::Katakana,
|
|
||||||
dictionary: vec![
|
|
||||||
vec![
|
|
||||||
(String::from("ァ"), String::from("a")),
|
|
||||||
(String::from("ィ"), String::from("i")),
|
|
||||||
(String::from("ゥ"), String::from("u")),
|
|
||||||
(String::from("ェ"), String::from("e")),
|
|
||||||
(String::from("ォ"), String::from("o")),
|
|
||||||
],
|
|
||||||
vec![
|
|
||||||
(String::from("サ"), String::from("sa")),
|
|
||||||
(String::from("シ"), String::from("shi")),
|
|
||||||
(String::from("ス"), String::from("su")),
|
|
||||||
(String::from("セ"), String::from("se")),
|
|
||||||
(String::from("ソ"), String::from("so")),
|
|
||||||
],
|
|
||||||
vec![
|
|
||||||
(String::from("カ"), String::from("ka")),
|
|
||||||
(String::from("キ"), String::from("ki")),
|
|
||||||
(String::from("ク"), String::from("ku")),
|
|
||||||
(String::from("ケ"), String::from("ke")),
|
|
||||||
(String::from("コ"), String::from("ko")),
|
|
||||||
],
|
|
||||||
// Ряд «та» (タチツテト)
|
|
||||||
vec![
|
|
||||||
(String::from("タ"), String::from("ta")),
|
|
||||||
(String::from("チ"), String::from("chi")),
|
|
||||||
(String::from("ツ"), String::from("tsu")),
|
|
||||||
(String::from("テ"), String::from("te")),
|
|
||||||
(String::from("ト"), String::from("to")),
|
|
||||||
],
|
|
||||||
// Ряд «на» (ナニヌネノ)
|
|
||||||
vec![
|
|
||||||
(String::from("ナ"), String::from("na")),
|
|
||||||
(String::from("ニ"), String::from("ni")),
|
|
||||||
(String::from("ヌ"), String::from("nu")),
|
|
||||||
(String::from("ネ"), String::from("ne")),
|
|
||||||
(String::from("ノ"), String::from("no")),
|
|
||||||
],
|
|
||||||
// Ряд «ха» (ハヒフヘホ)
|
|
||||||
vec![
|
|
||||||
(String::from("ハ"), String::from("ha")),
|
|
||||||
(String::from("ヒ"), String::from("hi")),
|
|
||||||
(String::from("フ"), String::from("fu")),
|
|
||||||
(String::from("ヘ"), String::from("he")),
|
|
||||||
(String::from("ホ"), String::from("ho")),
|
|
||||||
],
|
|
||||||
// Ряд «ма» (マミムメモ)
|
|
||||||
vec![
|
|
||||||
(String::from("マ"), String::from("ma")),
|
|
||||||
(String::from("ミ"), String::from("mi")),
|
|
||||||
(String::from("ム"), String::from("mu")),
|
|
||||||
(String::from("メ"), String::from("me")),
|
|
||||||
(String::from("モ"), String::from("mo")),
|
|
||||||
],
|
|
||||||
// Ряд «я» (ヤユヨ) — только 3 символа
|
|
||||||
vec![
|
|
||||||
(String::from("ヤ"), String::from("ya")),
|
|
||||||
(String::from("ユ"), String::from("yu")),
|
|
||||||
(String::from("ヨ"), String::from("yo")),
|
|
||||||
],
|
|
||||||
// Ряд «ра» (ラリルレロ)
|
|
||||||
vec![
|
|
||||||
(String::from("ラ"), String::from("ra")),
|
|
||||||
(String::from("リ"), String::from("ri")),
|
|
||||||
(String::from("ル"), String::from("ru")),
|
|
||||||
(String::from("レ"), String::from("re")),
|
|
||||||
(String::from("ロ"), String::from("ro")),
|
|
||||||
],
|
|
||||||
vec![
|
|
||||||
(String::from("ワ"), String::from("wa")),
|
|
||||||
(String::from("ヲ"), String::from("wo")),
|
|
||||||
(String::from("ン"), String::from("n")),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
include_map: [true; 10],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn list(&self) -> Vec<(String, String)> {
|
|
||||||
let mut current_set: Vec<(String, String)> = Vec::new();
|
|
||||||
|
|
||||||
for i in 0..10 {
|
|
||||||
if self.include_map[i] {
|
|
||||||
self.dictionary[i].iter().for_each(|v| {
|
|
||||||
current_set.push(v.clone());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
current_set
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Default for KanaSet {
|
|
||||||
fn default() -> Self {
|
|
||||||
KanaSet::hiragana()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl PartialEq<Self> for KanaSet {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.name == other.name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct WordData {
|
|
||||||
pub id: Id,
|
|
||||||
pub key: String,
|
|
||||||
pub value: String,
|
|
||||||
pub tags: String,
|
|
||||||
pub additional: HashMap<String, String>,
|
|
||||||
pub group_id: Id,
|
|
||||||
}
|
|
||||||
impl WordData {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
id: INVALID_ID,
|
|
||||||
key: String::new(),
|
|
||||||
value: String::new(),
|
|
||||||
tags: String::new(),
|
|
||||||
additional: Default::default(),
|
|
||||||
group_id: 1.into(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct WordGroup {
|
|
||||||
pub id: Id,
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
#[derive(Clone, PartialEq)]
|
|
||||||
pub struct CardStatistics {
|
|
||||||
pub id: Id,
|
|
||||||
pub word_id: Id,
|
|
||||||
pub set_id: Id,
|
|
||||||
pub last_open: DateTime<Utc>,
|
|
||||||
pub score: u8,
|
|
||||||
}
|
|
||||||
impl CardStatistics {
|
|
||||||
pub fn update(&mut self, status: WordOpenMode) {
|
|
||||||
match status {
|
|
||||||
WordOpenMode::Easy => {
|
|
||||||
self.score = (self.calculated_score() + 5.0).round() as u8;
|
|
||||||
}
|
|
||||||
WordOpenMode::Ok => self.score = (self.calculated_score() + 2.0).round() as u8,
|
|
||||||
WordOpenMode::Hard => {
|
|
||||||
self.score = (self.calculated_score() * 0.75).round() as u8;
|
|
||||||
}
|
|
||||||
WordOpenMode::None => {
|
|
||||||
self.score = (self.calculated_score() * 0.4) as u8;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.score = self.score.clamp(1, MAX_SCORE);
|
|
||||||
self.last_open = Utc::now();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn calculated_score(&self) -> f32 {
|
|
||||||
let time = Utc::now() - self.last_open;
|
|
||||||
let days = time.num_days();
|
|
||||||
let multiplier = FADE_PER_DAY.powi(days as i32);
|
|
||||||
(self.score as f32 * multiplier).max(1.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub enum WordOpenMode {
|
|
||||||
Easy,
|
|
||||||
Ok,
|
|
||||||
Hard,
|
|
||||||
None,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct DeckData {
|
|
||||||
words: Vec<WordData>,
|
|
||||||
set: Vec<CardStatistics>,
|
|
||||||
current_word_index: Option<usize>,
|
|
||||||
state: Arc<Mutex<AppState>>,
|
|
||||||
order_module: OrderModule,
|
|
||||||
settings: DeckSettings,
|
|
||||||
}
|
|
||||||
impl DeckData {
|
|
||||||
pub fn new(settings: &DeckSettings, state: Arc<Mutex<AppState>>) -> Self {
|
|
||||||
let state_for = state.clone();
|
|
||||||
let state_locked = state.lock();
|
|
||||||
|
|
||||||
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()
|
|
||||||
})
|
|
||||||
.map(|index| &state_locked.dictionary[index])
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
Self {
|
|
||||||
set: stats,
|
|
||||||
words,
|
|
||||||
current_word_index: None,
|
|
||||||
state: state_for,
|
|
||||||
order_module: match settings.open_mode {
|
|
||||||
OrderMode::Default => OrderModule::SemiRandomSRS(SemiRandomSRSModule::new()),
|
|
||||||
OrderMode::TrainWorstFirst => {
|
|
||||||
OrderModule::WorstWordsSRS(WorstWordsSRSModule::new())
|
|
||||||
}
|
|
||||||
OrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()),
|
|
||||||
},
|
|
||||||
settings: settings.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn next(&mut self) -> (WordData, CardStatistics) {
|
|
||||||
let index = match self.order_module.clone() {
|
|
||||||
OrderModule::SemiRandomSRS(mut module) => {
|
|
||||||
if !module.initialized {
|
|
||||||
module.init(self)
|
|
||||||
}
|
|
||||||
let index = module.next(self);
|
|
||||||
self.order_module = OrderModule::SemiRandomSRS(module);
|
|
||||||
index
|
|
||||||
}
|
|
||||||
OrderModule::RandomSRS(mut module) => {
|
|
||||||
if !module.initialized {
|
|
||||||
module.init(self)
|
|
||||||
}
|
|
||||||
let index = module.next(self);
|
|
||||||
self.order_module = OrderModule::RandomSRS(module);
|
|
||||||
index
|
|
||||||
}
|
|
||||||
OrderModule::WorstWordsSRS(mut module) => {
|
|
||||||
if !module.initialized {
|
|
||||||
module.init(self)
|
|
||||||
}
|
|
||||||
let index = module.next(self);
|
|
||||||
self.order_module = OrderModule::WorstWordsSRS(module);
|
|
||||||
index
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
self.current_word_index = Some(index);
|
|
||||||
(self.words[index].clone(), self.set[index].clone())
|
|
||||||
}
|
|
||||||
pub fn open(&mut self, status: WordOpenMode) {
|
|
||||||
if self.current_word_index.is_none() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let index = self.current_word_index.unwrap();
|
|
||||||
|
|
||||||
let word = &mut self.set[index];
|
|
||||||
let old_score = word.score;
|
|
||||||
word.update(status);
|
|
||||||
let new_score = word.score;
|
|
||||||
|
|
||||||
match self.order_module.clone() {
|
|
||||||
OrderModule::SemiRandomSRS(mut module) => {
|
|
||||||
module.open(status, index, word.clone());
|
|
||||||
self.order_module = OrderModule::SemiRandomSRS(module);
|
|
||||||
}
|
|
||||||
OrderModule::RandomSRS(mut module) => {
|
|
||||||
module.open(status, index, word.clone());
|
|
||||||
self.order_module = OrderModule::RandomSRS(module);
|
|
||||||
}
|
|
||||||
OrderModule::WorstWordsSRS(mut module) => {
|
|
||||||
module.open(status, index, word.clone());
|
|
||||||
self.order_module = OrderModule::WorstWordsSRS(module);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
update_stat_score(word, &self.state.lock().connection);
|
|
||||||
push_note(
|
|
||||||
self.settings.id,
|
|
||||||
HistoryItem {
|
|
||||||
timestamp: Utc::now(),
|
|
||||||
word_id: word.word_id,
|
|
||||||
mode: status,
|
|
||||||
before: old_score,
|
|
||||||
after: new_score,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
pub fn len(&self) -> usize {
|
|
||||||
self.set.len()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone, PartialEq, Copy, Eq)]
|
|
||||||
pub enum OrderMode {
|
|
||||||
Default,
|
|
||||||
TrainWorstFirst,
|
|
||||||
FullRandom,
|
|
||||||
}
|
|
||||||
#[derive(Clone, Copy, Eq, PartialEq, Default)]
|
|
||||||
pub enum AppendMode {
|
|
||||||
Full,
|
|
||||||
#[default]
|
|
||||||
Manual,
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
enum OrderModule {
|
|
||||||
SemiRandomSRS(SemiRandomSRSModule),
|
|
||||||
RandomSRS(RandomSRSModule),
|
|
||||||
WorstWordsSRS(WorstWordsSRSModule),
|
|
||||||
}
|
|
||||||
trait SRSModule {
|
|
||||||
fn next(&mut self, set: &mut DeckData) -> usize;
|
|
||||||
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: CardStatistics);
|
|
||||||
fn init(&mut self, set: &mut DeckData);
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct RandomSRSModule {
|
|
||||||
basket: Vec<usize>,
|
|
||||||
initialized: bool,
|
|
||||||
}
|
|
||||||
impl RandomSRSModule {
|
|
||||||
fn new() -> RandomSRSModule {
|
|
||||||
Self {
|
|
||||||
basket: vec![],
|
|
||||||
initialized: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl SRSModule for RandomSRSModule {
|
|
||||||
fn next(&mut self, set: &mut DeckData) -> usize {
|
|
||||||
match self.basket.pop() {
|
|
||||||
Some(index) => index,
|
|
||||||
None => {
|
|
||||||
self.basket = (0..set.words.len()).collect::<Vec<usize>>();
|
|
||||||
self.basket.shuffle(&mut rand::rng());
|
|
||||||
self.basket.pop().expect("empty basket")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
|
|
||||||
|
|
||||||
fn init(&mut self, set: &mut DeckData) {
|
|
||||||
self.initialized = true;
|
|
||||||
self.basket = (0..set.set.len()).collect::<Vec<usize>>();
|
|
||||||
self.basket.shuffle(&mut rand::rng())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct SemiRandomSRSModule {
|
|
||||||
history: Vec<usize>,
|
|
||||||
last_weights: WeightedIndex<f32>,
|
|
||||||
generator: ThreadRng,
|
|
||||||
initialized: bool,
|
|
||||||
}
|
|
||||||
impl SemiRandomSRSModule {
|
|
||||||
fn new() -> SemiRandomSRSModule {
|
|
||||||
SemiRandomSRSModule {
|
|
||||||
history: vec![],
|
|
||||||
last_weights: WeightedIndex::new([1.0]).unwrap(),
|
|
||||||
generator: rng(),
|
|
||||||
initialized: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl SRSModule for SemiRandomSRSModule {
|
|
||||||
fn next(&mut self, set: &mut DeckData) -> usize {
|
|
||||||
let index = self.last_weights.sample(&mut self.generator);
|
|
||||||
|
|
||||||
if self.history.contains(&index) && self.history.len() != 1 {
|
|
||||||
return self.next(set);
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.history.len() == self.history_len(set) {
|
|
||||||
self.history.remove(0);
|
|
||||||
}
|
|
||||||
self.history.push(index);
|
|
||||||
|
|
||||||
index
|
|
||||||
}
|
|
||||||
fn open(&mut self, _: WordOpenMode, index: usize, word: CardStatistics) {
|
|
||||||
let new_weight = (100.0 / word.calculated_score()).powf(2.0);
|
|
||||||
self.last_weights
|
|
||||||
.update_weights(&[(index, &new_weight)])
|
|
||||||
.expect("update weights error");
|
|
||||||
}
|
|
||||||
fn init(&mut self, set: &mut DeckData) {
|
|
||||||
self.initialized = true;
|
|
||||||
let weights = set
|
|
||||||
.set
|
|
||||||
.iter()
|
|
||||||
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
|
|
||||||
.collect::<Vec<f32>>();
|
|
||||||
self.last_weights = WeightedIndex::new(weights).unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl SemiRandomSRSModule {
|
|
||||||
fn history_len(&self, set: &DeckData) -> usize {
|
|
||||||
((set.len() as f32 * MAX_HISTORY_LEN_PART) as usize).clamp(1, MAX_HISTORY_LEN)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct WorstWordsSRSModule {
|
|
||||||
initialized: bool,
|
|
||||||
pool_size: usize,
|
|
||||||
rounds_remaining: u8,
|
|
||||||
pool: Vec<usize>,
|
|
||||||
queue: Vec<usize>,
|
|
||||||
rounds_count: u8,
|
|
||||||
}
|
|
||||||
impl SRSModule for WorstWordsSRSModule {
|
|
||||||
fn next(&mut self, set: &mut DeckData) -> usize {
|
|
||||||
if self.rounds_remaining == 0 {
|
|
||||||
self.fill_pool(set);
|
|
||||||
self.rounds_remaining = self.rounds_count;
|
|
||||||
}
|
|
||||||
|
|
||||||
match self.queue.pop() {
|
|
||||||
Some(index) => index,
|
|
||||||
None => {
|
|
||||||
self.queue.append(&mut self.pool.clone());
|
|
||||||
self.rounds_remaining -= 1;
|
|
||||||
self.queue.pop().expect("empty queue")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
|
|
||||||
|
|
||||||
fn init(&mut self, _: &mut DeckData) {
|
|
||||||
self.initialized = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl WorstWordsSRSModule {
|
|
||||||
fn new() -> WorstWordsSRSModule {
|
|
||||||
WorstWordsSRSModule {
|
|
||||||
initialized: false,
|
|
||||||
pool_size: 15,
|
|
||||||
rounds_count: 2,
|
|
||||||
rounds_remaining: 0,
|
|
||||||
pool: vec![],
|
|
||||||
queue: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn fill_pool(&mut self, set: &DeckData) {
|
|
||||||
let mut sorted = set
|
|
||||||
.set
|
|
||||||
.clone()
|
|
||||||
.into_iter()
|
|
||||||
.zip(0..set.set.len())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
sorted.sort_by_key(|c| c.0.score);
|
|
||||||
let mut worst = sorted[0..self.pool_size]
|
|
||||||
.iter()
|
|
||||||
.map(|(_, index)| *index)
|
|
||||||
.collect::<Vec<usize>>();
|
|
||||||
worst.shuffle(&mut rand::rng());
|
|
||||||
self.pool = worst;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct DeckSettings {
|
|
||||||
pub id: Id,
|
|
||||||
pub name: String,
|
|
||||||
pub forward: String,
|
|
||||||
pub backward: String,
|
|
||||||
pub filter: String,
|
|
||||||
pub count: Option<usize>,
|
|
||||||
pub worst_words_list: Option<Vec<WordData>>,
|
|
||||||
pub open_mode: OrderMode,
|
|
||||||
}
|
|
||||||
impl DeckSettings {
|
|
||||||
pub(crate) fn with_name(name: String) -> DeckSettings {
|
|
||||||
DeckSettings {
|
|
||||||
id: 0.into(),
|
|
||||||
name,
|
|
||||||
forward: "".to_string(),
|
|
||||||
backward: "".to_string(),
|
|
||||||
filter: "true".to_string(),
|
|
||||||
count: None,
|
|
||||||
worst_words_list: None,
|
|
||||||
open_mode: OrderMode::Default,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn check_filter(&self) -> bool {
|
|
||||||
let time = Instant::now();
|
|
||||||
let engine = Engine::new();
|
|
||||||
let ast = engine.compile(&self.filter);
|
|
||||||
println!("Compile time is {:?}", time.elapsed());
|
|
||||||
ast.is_ok()
|
|
||||||
}
|
|
||||||
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
|
|
||||||
let time = Instant::now();
|
|
||||||
let mut list = vec![];
|
|
||||||
let engine = Engine::new();
|
|
||||||
|
|
||||||
let ast = engine.compile(&self.filter);
|
|
||||||
if let Ok(ast) = ast {
|
|
||||||
let groups = &state.word_groups;
|
|
||||||
|
|
||||||
list = state
|
|
||||||
.dictionary
|
|
||||||
.par_iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter(|(_, word)| {
|
|
||||||
let mut more = rhai::Map::new();
|
|
||||||
for iced in &word.additional {
|
|
||||||
more.insert(iced.0.clone().into(), iced.1.clone().into());
|
|
||||||
}
|
|
||||||
let mut scope = Scope::new();
|
|
||||||
scope
|
|
||||||
.push_constant("id", word.id.0)
|
|
||||||
.push_constant("key", word.key.clone())
|
|
||||||
.push_constant("value", word.value.clone())
|
|
||||||
.push_constant("tags", word.tags.clone())
|
|
||||||
.push_constant("more", more)
|
|
||||||
.push_constant(
|
|
||||||
"group",
|
|
||||||
groups
|
|
||||||
.iter()
|
|
||||||
.find(|g| g.id == word.group_id)
|
|
||||||
.cloned()
|
|
||||||
.unwrap()
|
|
||||||
.name,
|
|
||||||
);
|
|
||||||
|
|
||||||
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
|
|
||||||
result.is_ok() && result.unwrap()
|
|
||||||
})
|
|
||||||
.map(|(index, _)| index)
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
println!("Collecting available words is {:?}", time.elapsed());
|
|
||||||
|
|
||||||
list
|
|
||||||
} else {
|
|
||||||
list
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn require_speech(&self) -> bool {
|
|
||||||
self.forward == "speech" || self.backward == "speech"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+13
-126
@@ -1,135 +1,22 @@
|
|||||||
#![windows_subsystem = "windows"]
|
#![windows_subsystem = "windows"]
|
||||||
|
pub mod app;
|
||||||
|
mod core;
|
||||||
|
mod data;
|
||||||
mod data_provider;
|
mod data_provider;
|
||||||
mod dictionary;
|
mod fs;
|
||||||
mod dictionary_quiz;
|
pub mod helpers;
|
||||||
mod history;
|
mod navigation;
|
||||||
pub mod import;
|
pub mod notification;
|
||||||
mod lang;
|
mod pages;
|
||||||
pub mod navigation;
|
mod styling;
|
||||||
mod quiz;
|
|
||||||
mod randomizer;
|
|
||||||
mod repetition;
|
|
||||||
mod repetition_settings;
|
|
||||||
mod repetitions;
|
|
||||||
mod selector;
|
|
||||||
pub mod styling;
|
|
||||||
mod sync;
|
|
||||||
mod word;
|
|
||||||
mod writing;
|
|
||||||
|
|
||||||
use crate::RootMessage::Keyboard;
|
use crate::app::start;
|
||||||
use crate::data_provider::card_sets::load_sets;
|
|
||||||
use crate::data_provider::settings::get_setting;
|
|
||||||
use crate::data_provider::sqlite::default_connection;
|
|
||||||
use crate::data_provider::words::{load_word_groups, load_words};
|
|
||||||
use crate::lang::{DeckSettings, Id, WordData, WordGroup};
|
|
||||||
use crate::navigation::{AppSettings, RootMessage, ScreenState};
|
|
||||||
use crate::quiz::*;
|
|
||||||
use chrono::NaiveDate;
|
|
||||||
use hashbrown::HashMap;
|
|
||||||
use iced::{Font, window};
|
|
||||||
use iced::{Subscription, Theme, keyboard};
|
|
||||||
use iced_core::Size;
|
|
||||||
use iced_core::window::Position;
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
use iced_core::window::settings::PlatformSpecific;
|
|
||||||
use mimalloc::MiMalloc;
|
use mimalloc::MiMalloc;
|
||||||
use rusqlite::Connection;
|
|
||||||
#[global_allocator]
|
#[global_allocator]
|
||||||
static GLOBAL: MiMalloc = MiMalloc;
|
static GLOBAL: MiMalloc = MiMalloc;
|
||||||
|
|
||||||
const USER_FONT: Font = Font::with_name("Noto Sans JP");
|
|
||||||
|
|
||||||
fn main() -> iced::Result {
|
fn main() -> iced::Result {
|
||||||
println!("Welcome to JapLearn");
|
env_logger::init();
|
||||||
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view)
|
start()
|
||||||
.window(window_settings())
|
|
||||||
.subscription(subscription)
|
|
||||||
.title("JapLearn")
|
|
||||||
.settings(iced::Settings {
|
|
||||||
default_text_size: iced::Pixels(18.0),
|
|
||||||
..iced::Settings::default()
|
|
||||||
})
|
|
||||||
.font(include_bytes!("../noto.ttf"))
|
|
||||||
.default_font(USER_FONT)
|
|
||||||
.theme(Theme::GruvboxDark)
|
|
||||||
.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(unused_mut)]
|
|
||||||
fn window_settings() -> window::Settings {
|
|
||||||
let mut settings = window::Settings {
|
|
||||||
position: Position::Centered,
|
|
||||||
min_size: Some(Size::new(700.0_f32, 700.0_f32)),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
{
|
|
||||||
settings.platform_specific = PlatformSpecific {
|
|
||||||
application_id: "JapLearn".to_string(),
|
|
||||||
override_redirect: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
settings
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subscription(_state: &ScreenState) -> Subscription<RootMessage> {
|
|
||||||
keyboard::listen().map(Keyboard)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct AppState {
|
|
||||||
pub dictionary: Vec<WordData>,
|
|
||||||
pub decks: Vec<DeckSettings>,
|
|
||||||
pub word_groups: Vec<WordGroup>,
|
|
||||||
pub connection: Connection,
|
|
||||||
pub sync_data: AppSettings,
|
|
||||||
pub activity: HashMap<Id, Vec<(NaiveDate, u32)>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for AppState {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AppState {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
dictionary: vec![],
|
|
||||||
decks: vec![],
|
|
||||||
word_groups: vec![],
|
|
||||||
connection: default_connection(),
|
|
||||||
sync_data: AppSettings {
|
|
||||||
key: None,
|
|
||||||
auto_web_fetch: false,
|
|
||||||
},
|
|
||||||
activity: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fill_state(state: &mut AppState) {
|
|
||||||
let list = load_words(&state.connection);
|
|
||||||
let sets = load_sets(&state.connection);
|
|
||||||
let groups = load_word_groups(&state.connection);
|
|
||||||
let setting = load_settings(&state.connection);
|
|
||||||
|
|
||||||
state.dictionary = list;
|
|
||||||
state.decks = sets;
|
|
||||||
state.word_groups = groups;
|
|
||||||
state.sync_data = setting
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load_settings(connection: &Connection) -> AppSettings {
|
|
||||||
let key = get_setting("SYNC_KEY".to_string(), connection);
|
|
||||||
let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection)
|
|
||||||
.unwrap_or("false".to_string())
|
|
||||||
.parse::<bool>()
|
|
||||||
.unwrap();
|
|
||||||
AppSettings {
|
|
||||||
key,
|
|
||||||
auto_web_fetch: fetch,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+102
-69
@@ -1,33 +1,44 @@
|
|||||||
use crate::data_provider::history::{get_history_of_set, history_dir};
|
use crate::app::{AppState, fill_state};
|
||||||
|
use crate::data::Id;
|
||||||
|
use crate::data_provider::history::get_history_of_set;
|
||||||
use crate::data_provider::sqlite::{create_db, default_connection};
|
use crate::data_provider::sqlite::{create_db, default_connection};
|
||||||
use crate::data_provider::web_api::{get_local_version, get_web_version, load_data, set_local_version};
|
use crate::data_provider::web_api::{
|
||||||
use crate::dictionary::{DictionaryMessage, DictionaryState, app_data_dir};
|
get_local_version, get_web_version, load_data, set_local_version,
|
||||||
use crate::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState};
|
};
|
||||||
use crate::history::{HistoryMessage, HistoryState};
|
use crate::fs::*;
|
||||||
use crate::import::{ImportMessage, ImportState};
|
|
||||||
use crate::lang::Id;
|
|
||||||
use crate::message_navigation;
|
|
||||||
use crate::navigation::Page::*;
|
use crate::navigation::Page::*;
|
||||||
use crate::navigation::RootMessage::{DataLoaded, Keyboard, UpdateData};
|
use crate::navigation::RootMessage::{
|
||||||
use crate::quiz::{QuizMessage, QuizState};
|
DataLoaded, Keyboard, Notification, PushNotification, UpdateData,
|
||||||
use crate::randomizer::{RandomizerMessage, RandomizerState};
|
};
|
||||||
use crate::repetition::{RepetitionMessage, RepetitionState};
|
use crate::notification::NotificationData::PermissionDenied;
|
||||||
use crate::repetition_settings::{RepetitionSettingsMessage, RepetitionSettingsState};
|
use crate::notification::{
|
||||||
use crate::repetitions::{RepetitionsMessage, RepetitionsState};
|
NotificationData, NotificationManager, NotificationMessage, NotificationRequest,
|
||||||
use crate::selector::{SelectorMessage, SelectorState};
|
};
|
||||||
|
use crate::pages::dictionary::{DictionaryMessage, DictionaryState};
|
||||||
|
use crate::pages::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState};
|
||||||
|
use crate::pages::history::{HistoryMessage, HistoryState};
|
||||||
|
use crate::pages::import::{ImportMessage, ImportState};
|
||||||
|
use crate::pages::quiz::{QuizMessage, QuizState};
|
||||||
|
use crate::pages::randomizer::{RandomizerMessage, RandomizerState};
|
||||||
|
use crate::pages::repetition::{RepetitionMessage, RepetitionState};
|
||||||
|
use crate::pages::repetition_settings::{RepetitionSettingsMessage, RepetitionSettingsState};
|
||||||
|
use crate::pages::repetitions::{RepetitionsMessage, RepetitionsState};
|
||||||
|
use crate::pages::selector::{SelectorMessage, SelectorState};
|
||||||
|
use crate::pages::sync::{SyncMessage, SyncState};
|
||||||
|
use crate::pages::word::{WordMessage, WordState};
|
||||||
|
use crate::pages::writing::{WritingMessage, WritingState};
|
||||||
use crate::state_navigate_handle;
|
use crate::state_navigate_handle;
|
||||||
use crate::state_update;
|
use crate::state_update;
|
||||||
use crate::sync::{SyncMessage, SyncState};
|
|
||||||
use crate::view_navigation;
|
use crate::view_navigation;
|
||||||
use crate::word::{WordMessage, WordState};
|
use crate::{message_navigation, push_error, push_error_task};
|
||||||
use crate::writing::{WritingMessage, WritingState};
|
|
||||||
use crate::{AppState, fill_state};
|
|
||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
use hashbrown::HashMap;
|
use hashbrown::HashMap;
|
||||||
use iced::keyboard::Event;
|
use iced::keyboard::Event;
|
||||||
|
use iced::widget::stack;
|
||||||
use iced::{Element, Task};
|
use iced::{Element, Task};
|
||||||
|
use iced_core::Length::Fill;
|
||||||
|
use log::info;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use reqwest::Error;
|
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
@@ -40,6 +51,7 @@ impl Default for ScreenState {
|
|||||||
ScreenState {
|
ScreenState {
|
||||||
stack: vec![Selector(SelectorState::new(state.clone()))],
|
stack: vec![Selector(SelectorState::new(state.clone()))],
|
||||||
app_state: state.clone(),
|
app_state: state.clone(),
|
||||||
|
notification_manager: NotificationManager::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,10 +73,13 @@ pub enum RootMessage {
|
|||||||
Import(ImportMessage),
|
Import(ImportMessage),
|
||||||
Keyboard(Event),
|
Keyboard(Event),
|
||||||
DataLoaded(HashMap<Id, Vec<(NaiveDate, u32)>>),
|
DataLoaded(HashMap<Id, Vec<(NaiveDate, u32)>>),
|
||||||
|
PushNotification(NotificationRequest),
|
||||||
|
Notification(NotificationMessage),
|
||||||
None,
|
None,
|
||||||
UpdateData,
|
UpdateData,
|
||||||
}
|
}
|
||||||
|
#[allow(clippy::enum_variant_names)]
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum Page {
|
pub enum Page {
|
||||||
Selector(SelectorState),
|
Selector(SelectorState),
|
||||||
Quiz(QuizState),
|
Quiz(QuizState),
|
||||||
@@ -85,56 +100,62 @@ pub enum Page {
|
|||||||
pub struct ScreenState {
|
pub struct ScreenState {
|
||||||
stack: Vec<Page>,
|
stack: Vec<Page>,
|
||||||
app_state: Arc<Mutex<AppState>>,
|
app_state: Arc<Mutex<AppState>>,
|
||||||
|
notification_manager: NotificationManager,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ScreenState {
|
impl ScreenState {
|
||||||
pub fn boot() -> (ScreenState, Task<RootMessage>) {
|
pub fn boot() -> (ScreenState, Task<RootMessage>) {
|
||||||
println!("Booting");
|
info!("Booting");
|
||||||
create_db();
|
create_db();
|
||||||
println!("Db created");
|
info!("Db created");
|
||||||
let state = ScreenState::default();
|
let state = ScreenState::default();
|
||||||
let reading_additional_task = Task::perform(Self::load_additional_data(), |data| data);
|
let reading_additional_task = Task::perform(Self::load_additional_data(), |data| {
|
||||||
|
data.unwrap_or_else(|err| push_error!(err))
|
||||||
|
});
|
||||||
|
|
||||||
let final_task;
|
let mut final_task = reading_additional_task;
|
||||||
let state_guard = state.app_state.lock();
|
let state_guard = state.app_state.lock();
|
||||||
if state_guard.sync_data.auto_web_fetch {
|
if state_guard.sync_data.auto_web_fetch
|
||||||
let key = state_guard.sync_data.key.clone().unwrap();
|
&& let Some(key) = state_guard.sync_data.key.clone()
|
||||||
final_task = Task::batch([
|
|
||||||
reading_additional_task,
|
|
||||||
Task::perform(Self::load_web_backup(key), |result| {
|
|
||||||
if let Ok(update) = result
|
|
||||||
&& update
|
|
||||||
{
|
{
|
||||||
|
final_task = Task::batch([
|
||||||
|
final_task,
|
||||||
|
Task::perform(Self::load_web_backup(key), |result| match result {
|
||||||
|
Ok(update) => {
|
||||||
|
if update {
|
||||||
UpdateData
|
UpdateData
|
||||||
} else {
|
} else {
|
||||||
RootMessage::None
|
RootMessage::None
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
Err(err) => push_error!(err),
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
} else {
|
|
||||||
final_task = reading_additional_task;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
drop(state_guard);
|
drop(state_guard);
|
||||||
println!("Boot finished");
|
info!("Boot finished");
|
||||||
(state, final_task)
|
(state, final_task)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn load_additional_data() -> RootMessage {
|
async fn load_additional_data() -> Result<RootMessage, NotificationData> {
|
||||||
let directory = history_dir();
|
let directory = history_dir()?;
|
||||||
|
|
||||||
let mut map = HashMap::new();
|
let mut map = HashMap::new();
|
||||||
for file in directory.read_dir().unwrap().flatten() {
|
for file in directory
|
||||||
|
.read_dir()
|
||||||
|
.map_err(|_| PermissionDenied)?
|
||||||
|
.filter_map(Result::ok)
|
||||||
|
{
|
||||||
let mut vec = vec![];
|
let mut vec = vec![];
|
||||||
let history_file_name = match file.file_name().into_string() {
|
let history_file_name = match file.file_name().into_string() {
|
||||||
Err(_) => continue,
|
Err(_) => continue,
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
};
|
};
|
||||||
|
|
||||||
let id = history_file_name[4..history_file_name.len() - 12]
|
if let Ok(id) = history_file_name.split('_').collect::<Vec<_>>()[1].parse::<Id>()
|
||||||
.parse::<Id>()
|
&& let Ok(history) = get_history_of_set(id)
|
||||||
.unwrap();
|
{
|
||||||
|
|
||||||
let history = get_history_of_set(id);
|
|
||||||
let by_date = history.chunk_by(|x, x1| {
|
let by_date = history.chunk_by(|x, x1| {
|
||||||
x.timestamp.naive_local().date() == x1.timestamp.naive_local().date()
|
x.timestamp.naive_local().date() == x1.timestamp.naive_local().date()
|
||||||
});
|
});
|
||||||
@@ -142,18 +163,21 @@ impl ScreenState {
|
|||||||
vec.push((group[0].timestamp.naive_local().date(), group.len() as u32));
|
vec.push((group[0].timestamp.naive_local().date(), group.len() as u32));
|
||||||
}
|
}
|
||||||
map.insert(id, vec);
|
map.insert(id, vec);
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
DataLoaded(map)
|
}
|
||||||
|
Ok(DataLoaded(map))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn load_web_backup(string: String) -> Result<bool, Error> {
|
async fn load_web_backup(string: String) -> Result<bool, NotificationData> {
|
||||||
let local = get_local_version().await;
|
let local = get_local_version().await?;
|
||||||
let web = get_web_version(string.as_str()).await?;
|
let web = get_web_version(string.as_str()).await?;
|
||||||
println!("{} {}", local, web);
|
info!("{} {}", local, web);
|
||||||
if web > local {
|
if web > local {
|
||||||
println!("Web version is newer than local version");
|
info!("Web version is newer than local version");
|
||||||
load_data(string, true).await?;
|
load_data(string, true).await?;
|
||||||
set_local_version(web).await;
|
set_local_version(web).await?;
|
||||||
} else {
|
} else {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
@@ -161,7 +185,7 @@ impl ScreenState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn update(&mut self, message: RootMessage) -> Task<RootMessage> {
|
pub fn update(&mut self, message: RootMessage) -> Task<RootMessage> {
|
||||||
println!("Updating");
|
info!("Updating");
|
||||||
let time = Instant::now();
|
let time = Instant::now();
|
||||||
if let Keyboard(e) = message {
|
if let Keyboard(e) = message {
|
||||||
return self.handle_keyboard(e);
|
return self.handle_keyboard(e);
|
||||||
@@ -173,20 +197,30 @@ impl ScreenState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let UpdateData = message {
|
if let UpdateData = message {
|
||||||
println!("Loading data");
|
info!("Loading data");
|
||||||
let mut state = self.app_state.lock();
|
let mut state = self.app_state.lock();
|
||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
state.connection = Connection::open_in_memory().unwrap();
|
state.connection = Connection::open_in_memory().unwrap();
|
||||||
}
|
}
|
||||||
let path = app_data_dir();
|
let db_file = db_path();
|
||||||
let db_file = path.join("data.db");
|
let temp_db_file = temp_db_path();
|
||||||
let temp_db_file = path.join("data.db.tmp");
|
if std::fs::rename(temp_db_file, &db_file).is_err() {
|
||||||
std::fs::rename(temp_db_file, &db_file).unwrap();
|
return push_error_task!(PermissionDenied);
|
||||||
|
}
|
||||||
|
|
||||||
state.connection = default_connection();
|
state.connection = default_connection();
|
||||||
fill_state(&mut state);
|
fill_state(&mut state);
|
||||||
return Task::none();
|
return Task::none();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Notification(message) = message {
|
||||||
|
return self.notification_manager.update(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let PushNotification(notification) = &message {
|
||||||
|
return self.notification_manager.push(notification.clone());
|
||||||
|
}
|
||||||
|
|
||||||
let task: (Task<RootMessage>, bool) = self.navigate_or_update(message);
|
let task: (Task<RootMessage>, bool) = self.navigate_or_update(message);
|
||||||
|
|
||||||
if task.1 {
|
if task.1 {
|
||||||
@@ -207,7 +241,7 @@ impl ScreenState {
|
|||||||
Import
|
Import
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
println!("Update took {:?}", time.elapsed());
|
info!("Update took {:?}", time.elapsed());
|
||||||
|
|
||||||
task.0
|
task.0
|
||||||
}
|
}
|
||||||
@@ -233,7 +267,7 @@ impl ScreenState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn view(&self) -> Element<'_, RootMessage> {
|
pub fn view(&self) -> Element<'_, RootMessage> {
|
||||||
println!("View update");
|
info!("View update");
|
||||||
let time = Instant::now();
|
let time = Instant::now();
|
||||||
let view = view_navigation!(
|
let view = view_navigation!(
|
||||||
self.stack,
|
self.stack,
|
||||||
@@ -252,16 +286,20 @@ impl ScreenState {
|
|||||||
Import
|
Import
|
||||||
);
|
);
|
||||||
|
|
||||||
println!("View took {:?}", time.elapsed());
|
let notifications = self.notification_manager.draw().map(Notification);
|
||||||
view
|
|
||||||
|
info!("View took {:?}", time.elapsed());
|
||||||
|
stack![view, notifications].width(Fill).height(Fill).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_keyboard(&mut self, message: Event) -> Task<RootMessage> {
|
fn handle_keyboard(&mut self, message: Event) -> Task<RootMessage> {
|
||||||
let page = self.stack.last_mut().unwrap();
|
if let Some(page) = self.stack.last_mut() {
|
||||||
match page {
|
return match page {
|
||||||
Repetition(page) => page.press(&message),
|
Repetition(page) => page.press(&message),
|
||||||
_ => Task::none(),
|
_ => Task::none(),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
Task::none()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,7 +311,7 @@ pub struct AppSettings {
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! view_navigation {
|
macro_rules! view_navigation {
|
||||||
($stack:expr, $($e:ident), *) => {
|
($stack:expr, $($e:ident), *) => {
|
||||||
match &$stack.last().unwrap() {
|
match &$stack.last().expect("Unexpected stack state") {
|
||||||
$(
|
$(
|
||||||
$e(s) => s.view().map(RootMessage::$e),
|
$e(s) => s.view().map(RootMessage::$e),
|
||||||
)*
|
)*
|
||||||
@@ -281,14 +319,13 @@ macro_rules! view_navigation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! state_update {
|
macro_rules! state_update {
|
||||||
($message:expr, $stack:expr, $($e:ident), *) => {
|
($message:expr, $stack:expr, $($e:ident), *) => {
|
||||||
match $message {
|
match $message {
|
||||||
$(
|
$(
|
||||||
RootMessage::$e(msg) => {
|
RootMessage::$e(msg) => {
|
||||||
if let $e(s) = $stack.last_mut().unwrap() {
|
if let $e(s) = $stack.last_mut().expect("Unexpected stack state") {
|
||||||
message_navigation!(msg, $stack, s)
|
message_navigation!(msg, $stack, s)
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -300,7 +337,6 @@ macro_rules! state_update {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! message_navigation {
|
macro_rules! message_navigation {
|
||||||
($msg:expr, $stack:expr, $state:expr) => {
|
($msg:expr, $stack:expr, $state:expr) => {
|
||||||
@@ -321,11 +357,10 @@ macro_rules! message_navigation {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! state_navigate_handle {
|
macro_rules! state_navigate_handle {
|
||||||
($stack:expr, $($e:ident), *) => {
|
($stack:expr, $($e:ident), *) => {
|
||||||
match $stack.last_mut().unwrap() {
|
match $stack.last_mut().expect("Unexpected stack state") {
|
||||||
$(
|
$(
|
||||||
Page::$e(page) => {
|
Page::$e(page) => {
|
||||||
page.navigated();
|
page.navigated();
|
||||||
@@ -335,14 +370,12 @@ macro_rules! state_navigate_handle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait NavigatedPage<T> {
|
pub trait NavigatedPage<T> {
|
||||||
fn navigate(&mut self, message: &T) -> Option<Page>;
|
fn navigate(&mut self, message: &T) -> Option<Page>;
|
||||||
fn navigated(&mut self);
|
fn navigated(&mut self);
|
||||||
fn update(&mut self, message: T) -> Task<RootMessage>;
|
fn update(&mut self, message: T) -> Task<RootMessage>;
|
||||||
fn view(&self) -> Element<'_, T>;
|
fn view(&self) -> Element<'_, T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait KeyPressedPage {
|
pub trait KeyPressedPage {
|
||||||
fn press(&mut self, message: &Event) -> Task<RootMessage>;
|
fn press(&mut self, message: &Event) -> Task<RootMessage>;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
use crate::navigation::RootMessage;
|
||||||
|
use crate::styling::{BUTTON_RADIUS, HALF_SPACING};
|
||||||
|
use chrono::Utc;
|
||||||
|
use iced::widget::container::Style;
|
||||||
|
use iced::widget::{Column, container, row, scrollable, text};
|
||||||
|
use iced::{Element, Task};
|
||||||
|
use iced_core::Alignment::Center;
|
||||||
|
use iced_core::Background::Color;
|
||||||
|
use iced_core::Border;
|
||||||
|
use iced_core::Length::Fill;
|
||||||
|
use iced_core::alignment::Horizontal::Right;
|
||||||
|
use iced_core::alignment::Vertical;
|
||||||
|
|
||||||
|
pub struct NotificationManager {
|
||||||
|
list: Vec<(u32, NotificationRequest, u32)>,
|
||||||
|
notification_lifetime: u32,
|
||||||
|
next_id: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum NotificationMessage {
|
||||||
|
Remove(u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for NotificationManager {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NotificationManager {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
list: Vec::new(),
|
||||||
|
notification_lifetime: 10,
|
||||||
|
next_id: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw(&self) -> Element<'_, NotificationMessage> {
|
||||||
|
let mut column = Column::new().spacing(HALF_SPACING);
|
||||||
|
|
||||||
|
for (id, notif, time) in &self.list {
|
||||||
|
column = column.push(Self::draw_notif(id, notif, time));
|
||||||
|
}
|
||||||
|
|
||||||
|
container(scrollable(column))
|
||||||
|
.width(Fill)
|
||||||
|
.height(Fill)
|
||||||
|
.align_x(Right)
|
||||||
|
.align_y(Vertical::Top)
|
||||||
|
.padding(HALF_SPACING)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(&mut self, notification: NotificationRequest) -> Task<RootMessage> {
|
||||||
|
let id = self.next_id;
|
||||||
|
self.list.push((
|
||||||
|
id,
|
||||||
|
notification,
|
||||||
|
Utc::now().timestamp() as u32 + self.notification_lifetime,
|
||||||
|
));
|
||||||
|
self.next_id += 1;
|
||||||
|
let message = NotificationMessage::Remove(id);
|
||||||
|
let time = self.notification_lifetime;
|
||||||
|
Task::perform(
|
||||||
|
async move {
|
||||||
|
tokio::time::sleep(core::time::Duration::from_secs(time as u64)).await;
|
||||||
|
},
|
||||||
|
|_| RootMessage::Notification(message),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self, message: NotificationMessage) -> Task<RootMessage> {
|
||||||
|
match message {
|
||||||
|
NotificationMessage::Remove(id) => {
|
||||||
|
if let Some(index) = self.list.iter().position(|item| item.0 == id) {
|
||||||
|
self.list.remove(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Task::none()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_notif<'a>(
|
||||||
|
id: &u32,
|
||||||
|
notif: &NotificationRequest,
|
||||||
|
_time: &u32,
|
||||||
|
) -> Element<'a, NotificationMessage> {
|
||||||
|
let color_id;
|
||||||
|
let content = match notif {
|
||||||
|
NotificationRequest::Info(data) => {
|
||||||
|
color_id = 1;
|
||||||
|
Self::draw_data(data)
|
||||||
|
}
|
||||||
|
NotificationRequest::Warning(data) => {
|
||||||
|
color_id = 2;
|
||||||
|
Self::draw_data(data)
|
||||||
|
}
|
||||||
|
NotificationRequest::Error(data) => {
|
||||||
|
color_id = 3;
|
||||||
|
Self::draw_data(data)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let container = container(
|
||||||
|
row![
|
||||||
|
content,
|
||||||
|
iced::widget::button("✕")
|
||||||
|
.on_press(NotificationMessage::Remove(*id))
|
||||||
|
.style(iced::widget::button::text)
|
||||||
|
]
|
||||||
|
.align_y(Center)
|
||||||
|
.width(300)
|
||||||
|
.padding(HALF_SPACING),
|
||||||
|
);
|
||||||
|
container
|
||||||
|
.style(move |theme| {
|
||||||
|
let color = match color_id {
|
||||||
|
1 => theme.palette().success,
|
||||||
|
2 => theme.palette().warning,
|
||||||
|
3 => theme.palette().danger,
|
||||||
|
_ => theme.palette().warning,
|
||||||
|
};
|
||||||
|
Style {
|
||||||
|
text_color: None,
|
||||||
|
background: Some(Color(color.scale_alpha(0.3))),
|
||||||
|
border: Border::default()
|
||||||
|
.width(1)
|
||||||
|
.color(color)
|
||||||
|
.rounded(BUTTON_RADIUS),
|
||||||
|
shadow: Default::default(),
|
||||||
|
snap: false,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_data<'a>(data: &NotificationData) -> Element<'a, NotificationMessage> {
|
||||||
|
match data {
|
||||||
|
NotificationData::DataLoaded => {
|
||||||
|
text!("Данные успешно скачаны")
|
||||||
|
}
|
||||||
|
NotificationData::ImportError => {
|
||||||
|
text!("Ошибка при импорте данных из Anki")
|
||||||
|
}
|
||||||
|
NotificationData::IncorrectAnkiFile => {
|
||||||
|
text!("Неподдерживаемый формат файла .apkg")
|
||||||
|
}
|
||||||
|
NotificationData::OpenFileError => {
|
||||||
|
text!("Ошибка открытия файла пакета")
|
||||||
|
}
|
||||||
|
NotificationData::VoiceVoxUnavailable => {
|
||||||
|
text!("Не получается подключиться к VoiceVox")
|
||||||
|
}
|
||||||
|
NotificationData::PermissionDenied => {
|
||||||
|
text!("У приложение недостаточно прав")
|
||||||
|
}
|
||||||
|
NotificationData::WebApiUnavailable => {
|
||||||
|
text!("Не получается подключиться к Api")
|
||||||
|
}
|
||||||
|
NotificationData::DbSaveError => {
|
||||||
|
text!("Не получается сохранить данные")
|
||||||
|
}
|
||||||
|
NotificationData::DbLoadError => {
|
||||||
|
text!("Не получается загрузить данные")
|
||||||
|
}
|
||||||
|
NotificationData::CompressError => {
|
||||||
|
text!("Ошибка сжатия или распаковки данных")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.width(Fill)
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum NotificationRequest {
|
||||||
|
Info(NotificationData),
|
||||||
|
Warning(NotificationData),
|
||||||
|
Error(NotificationData),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum NotificationData {
|
||||||
|
PermissionDenied,
|
||||||
|
DataLoaded,
|
||||||
|
ImportError,
|
||||||
|
IncorrectAnkiFile,
|
||||||
|
OpenFileError,
|
||||||
|
VoiceVoxUnavailable,
|
||||||
|
WebApiUnavailable,
|
||||||
|
DbSaveError,
|
||||||
|
DbLoadError,
|
||||||
|
CompressError,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type MaybeError = Result<(), NotificationData>;
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
pub mod dictionary;
|
||||||
|
pub mod dictionary_quiz;
|
||||||
|
pub mod history;
|
||||||
|
pub mod import;
|
||||||
|
pub mod quiz;
|
||||||
|
pub mod randomizer;
|
||||||
|
pub mod repetition;
|
||||||
|
pub mod repetition_settings;
|
||||||
|
pub mod repetitions;
|
||||||
|
pub mod selector;
|
||||||
|
pub mod sync;
|
||||||
|
pub mod word;
|
||||||
|
pub mod writing;
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
|
use crate::app::AppState;
|
||||||
|
use crate::data::Id;
|
||||||
|
use crate::data::entities::{WordData, WordGroup};
|
||||||
use crate::data_provider::words::{delete_group, delete_word, update_group, update_word};
|
use crate::data_provider::words::{delete_group, delete_word, update_group, update_word};
|
||||||
use crate::dictionary::DictionaryMessage::*;
|
|
||||||
use crate::dictionary_quiz::DictionaryQuizState;
|
|
||||||
use crate::import::ImportState;
|
|
||||||
use crate::lang::{WordData, WordGroup};
|
|
||||||
use crate::navigation::Page::{Import, Word};
|
use crate::navigation::Page::{Import, Word};
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
|
use crate::pages::dictionary::DictionaryMessage::*;
|
||||||
|
use crate::pages::dictionary_quiz::DictionaryQuizState;
|
||||||
|
use crate::pages::import::ImportState;
|
||||||
|
use crate::pages::word::WordState;
|
||||||
|
use crate::push_error;
|
||||||
|
use crate::push_error_task;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::word::WordState;
|
|
||||||
use crate::{AppState, RootMessage};
|
|
||||||
use chrono::{DateTime, TimeDelta, Utc};
|
use chrono::{DateTime, TimeDelta, Utc};
|
||||||
use hashbrown::{HashMap, HashSet};
|
use hashbrown::{HashMap, HashSet};
|
||||||
use iced::alignment::Vertical::Center;
|
use iced::alignment::Vertical::Center;
|
||||||
@@ -18,11 +21,10 @@ use iced::widget::text_input::default;
|
|||||||
use iced::widget::*;
|
use iced::widget::*;
|
||||||
use iced::{Border, Color, Shadow, Task};
|
use iced::{Border, Color, Shadow, Task};
|
||||||
use iced_core::Length::Fill;
|
use iced_core::Length::Fill;
|
||||||
|
use log::info;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use rand::random_range;
|
use rand::random_range;
|
||||||
use std::fs;
|
|
||||||
use std::ops::Add;
|
use std::ops::Add;
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
@@ -168,7 +170,9 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
|||||||
let word = dict.remove(i);
|
let word = dict.remove(i);
|
||||||
self.include_map.remove(i);
|
self.include_map.remove(i);
|
||||||
self.auto_save_queue.remove(&i);
|
self.auto_save_queue.remove(&i);
|
||||||
delete_word(&word, &state.connection)
|
if let Err(err) = delete_word(&word, &state.connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Include(i, b) => self.include_map[i] = b,
|
Include(i, b) => self.include_map[i] = b,
|
||||||
IncludeTag(t, v) => {
|
IncludeTag(t, v) => {
|
||||||
@@ -190,7 +194,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
|||||||
self.search = s;
|
self.search = s;
|
||||||
}
|
}
|
||||||
SetTyping(b) => self.no_typing = b,
|
SetTyping(b) => self.no_typing = b,
|
||||||
SubmitWord(i) => self.save_word(i),
|
SubmitWord(i) => return self.save_word(i),
|
||||||
Back => {}
|
Back => {}
|
||||||
Test => {}
|
Test => {}
|
||||||
CreateGroup => {
|
CreateGroup => {
|
||||||
@@ -213,7 +217,10 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
|||||||
let connection = &state.connection;
|
let connection = &state.connection;
|
||||||
let mut group = state.word_groups[self.selected_group_index].clone();
|
let mut group = state.word_groups[self.selected_group_index].clone();
|
||||||
|
|
||||||
update_group(&mut group, connection);
|
if let Err(err) = update_group(&mut group, connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
|
|
||||||
state.word_groups[self.selected_group_index] = group;
|
state.word_groups[self.selected_group_index] = group;
|
||||||
}
|
}
|
||||||
SelectGroup(i) => {
|
SelectGroup(i) => {
|
||||||
@@ -236,7 +243,10 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
|||||||
let remove_group_id = group.id;
|
let remove_group_id = group.id;
|
||||||
let connection = &state.connection;
|
let connection = &state.connection;
|
||||||
|
|
||||||
delete_group(group, connection);
|
if let Err(err) = delete_group(group, connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
|
|
||||||
state.word_groups.remove(self.selected_group_index);
|
state.word_groups.remove(self.selected_group_index);
|
||||||
state
|
state
|
||||||
.dictionary
|
.dictionary
|
||||||
@@ -257,7 +267,8 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
|||||||
}
|
}
|
||||||
if self.auto_save_queue[&word_index] <= now {
|
if self.auto_save_queue[&word_index] <= now {
|
||||||
self.auto_save_queue.remove(&word_index);
|
self.auto_save_queue.remove(&word_index);
|
||||||
self.save_word(word_index);
|
|
||||||
|
return self.save_word(word_index);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ToImport => {}
|
ToImport => {}
|
||||||
@@ -309,13 +320,17 @@ impl DictionaryState {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_word(&mut self, i: usize) {
|
fn save_word(&mut self, i: usize) -> Task<RootMessage> {
|
||||||
let state = &mut self.state.lock();
|
let state = &mut self.state.lock();
|
||||||
let connection = &state.connection;
|
let connection = &state.connection;
|
||||||
let word = &mut state.dictionary[i].clone();
|
let word = &mut state.dictionary[i].clone();
|
||||||
|
|
||||||
update_word(word, connection);
|
if let Err(err) = update_word(word, connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
|
|
||||||
state.dictionary[i] = word.clone();
|
state.dictionary[i] = word.clone();
|
||||||
|
Task::none()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn launch_auto_save_offset(&mut self, index: usize) -> Task<RootMessage> {
|
fn launch_auto_save_offset(&mut self, index: usize) -> Task<RootMessage> {
|
||||||
@@ -438,8 +453,8 @@ impl DictionaryState {
|
|||||||
col = col.push(lazy_line);
|
col = col.push(lazy_line);
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("Drawing {index} lines");
|
info!("Drawing {index} lines");
|
||||||
println!("Words rendering time: {:?}", time.elapsed());
|
info!("Words rendering time: {:?}", time.elapsed());
|
||||||
scrollable(col).height(Fill).into()
|
scrollable(col).height(Fill).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -528,7 +543,7 @@ impl DictionaryState {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_words_include(&mut self, group_id: crate::lang::Id) {
|
fn update_words_include(&mut self, group_id: Id) {
|
||||||
let include_tags = self
|
let include_tags = self
|
||||||
.tag_map
|
.tag_map
|
||||||
.iter()
|
.iter()
|
||||||
@@ -554,7 +569,7 @@ impl DictionaryState {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
println!("Time {}", time.elapsed().as_micros());
|
info!("Time {}", time.elapsed().as_micros());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> {
|
fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||||
@@ -618,22 +633,12 @@ pub fn split_with_coma(ts: &str) -> Vec<String> {
|
|||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn app_data_dir() -> PathBuf {
|
|
||||||
let mut dir = dirs::data_dir().unwrap();
|
|
||||||
dir.push("jap_learn");
|
|
||||||
if !dir.exists() {
|
|
||||||
fs::create_dir_all(dir.clone()).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Hash, PartialEq, Eq)]
|
#[derive(Hash, PartialEq, Eq)]
|
||||||
struct WordLineState {
|
struct WordLineState {
|
||||||
is_included: bool,
|
is_included: bool,
|
||||||
key: String,
|
key: String,
|
||||||
value: String,
|
value: String,
|
||||||
tags: String,
|
tags: String,
|
||||||
id: crate::lang::Id,
|
id: Id,
|
||||||
index: usize,
|
index: usize,
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
use crate::RootMessage;
|
use crate::data::entities::WordData;
|
||||||
use crate::dictionary::split_with_coma;
|
|
||||||
use crate::dictionary_quiz::DictionaryQuizMessage::*;
|
|
||||||
use crate::lang::WordData;
|
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
|
use crate::navigation::RootMessage;
|
||||||
use crate::navigation::*;
|
use crate::navigation::*;
|
||||||
use crate::quiz::Score;
|
use crate::pages::dictionary::split_with_coma;
|
||||||
|
use crate::pages::dictionary_quiz::DictionaryQuizMessage::*;
|
||||||
|
use crate::pages::quiz::Score;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use iced::Background::Color;
|
use iced::Background::Color;
|
||||||
use iced::border::Radius;
|
use iced::border::Radius;
|
||||||
@@ -146,8 +146,9 @@ impl DictionaryQuizState {
|
|||||||
if !self.is_help {
|
if !self.is_help {
|
||||||
self.score.total += 1;
|
self.score.total += 1;
|
||||||
}
|
}
|
||||||
if self.answer == self.correct
|
if self.answer.to_lowercase() == self.correct.to_lowercase()
|
||||||
|| split_with_coma(self.correct.as_str()).contains(&self.answer)
|
|| split_with_coma(self.correct.to_lowercase().as_str())
|
||||||
|
.contains(&self.answer.to_lowercase())
|
||||||
{
|
{
|
||||||
if !self.is_help {
|
if !self.is_help {
|
||||||
self.score.correct += 1;
|
self.score.correct += 1;
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
use crate::data_provider::history::{get_history_of_set, HistoryItem};
|
use crate::app::AppState;
|
||||||
use crate::lang::{WordData, INVALID_ID};
|
use crate::data::INVALID_ID;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::data::entities::{HistoryItem, WordData};
|
||||||
|
use crate::data_provider::history::get_history_of_set;
|
||||||
|
use crate::navigation::*;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::{AppState, RootMessage};
|
use HistoryMessage::Back;
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
use iced::alignment::Horizontal::Center;
|
use iced::alignment::Horizontal::Center;
|
||||||
use iced::widget::space::horizontal;
|
use iced::widget::space::horizontal;
|
||||||
@@ -10,7 +12,6 @@ use iced::widget::*;
|
|||||||
use iced::{Element, Fill, FillPortion, Task};
|
use iced::{Element, Fill, FillPortion, Task};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use HistoryMessage::Back;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct HistoryState {
|
pub struct HistoryState {
|
||||||
@@ -47,9 +48,9 @@ impl NavigatedPage<HistoryMessage> for HistoryState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl HistoryState {
|
impl HistoryState {
|
||||||
pub fn new(id: crate::lang::Id, state: Arc<Mutex<AppState>>) -> Self {
|
pub fn new(id: crate::data::Id, state: Arc<Mutex<AppState>>) -> Self {
|
||||||
let state = state.lock();
|
let state = state.lock();
|
||||||
let history = get_history_of_set(id);
|
let history = get_history_of_set(id).unwrap_or_default();
|
||||||
let words = history
|
let words = history
|
||||||
.iter()
|
.iter()
|
||||||
.map(
|
.map(
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
use crate::AppState;
|
use crate::app::AppState;
|
||||||
|
use crate::data::entities::{WordData, WordGroup};
|
||||||
use crate::data_provider::import::{ImportData, ImportGroup, get_words_of_group, load_groups};
|
use crate::data_provider::import::{ImportData, ImportGroup, get_words_of_group, load_groups};
|
||||||
use crate::data_provider::words::{add_group, add_words};
|
use crate::data_provider::words::{add_group, add_words};
|
||||||
use crate::dictionary::app_data_dir;
|
use crate::fs::*;
|
||||||
use crate::import::ImportMessage::*;
|
|
||||||
use crate::lang::{WordData, WordGroup};
|
|
||||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
|
use crate::notification::NotificationData::OpenFileError;
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
|
use crate::pages::import::ImportMessage::*;
|
||||||
|
use crate::push_error;
|
||||||
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;
|
||||||
@@ -16,6 +19,7 @@ use iced::{Element, Task};
|
|||||||
use iced_core::Alignment::Center;
|
use iced_core::Alignment::Center;
|
||||||
use iced_core::Length::Fill;
|
use iced_core::Length::Fill;
|
||||||
use iced_core::Padding;
|
use iced_core::Padding;
|
||||||
|
use log::info;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use rfd::AsyncFileDialog;
|
use rfd::AsyncFileDialog;
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
@@ -275,9 +279,6 @@ impl ImportState {
|
|||||||
let mut row = Row::new();
|
let mut row = Row::new();
|
||||||
|
|
||||||
for default in DEFAULT_FIELDS {
|
for default in DEFAULT_FIELDS {
|
||||||
// if group.mapping.values().any(|name| name == default) {
|
|
||||||
// continue;
|
|
||||||
// }
|
|
||||||
row = row.push(
|
row = row.push(
|
||||||
button(text!("{default}")).on_press(SetupDefaultProperty(default.to_string())),
|
button(text!("{default}")).on_press(SetupDefaultProperty(default.to_string())),
|
||||||
);
|
);
|
||||||
@@ -365,41 +366,38 @@ impl ImportState {
|
|||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
},
|
},
|
||||||
|result: Result<ImportData, ()>| {
|
|result: Result<ImportData, NotificationData>| match result {
|
||||||
if let Ok(import) = result {
|
Ok(import) => RootMessage::Import(UpdateImport(import)),
|
||||||
RootMessage::Import(UpdateImport(import))
|
Err(err) => push_error!(err),
|
||||||
} else {
|
|
||||||
RootMessage::None
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn extract_import_file(path: PathBuf) -> Result<(), ()> {
|
fn extract_import_file(path: PathBuf) -> MaybeError {
|
||||||
let file = File::open(path).map_err(|_| ())?;
|
let file = File::open(path).map_err(|_| OpenFileError)?;
|
||||||
let reader = BufReader::new(file);
|
let reader = BufReader::new(file);
|
||||||
let mut archive = ZipArchive::new(reader).map_err(|_| ())?;
|
let mut archive = ZipArchive::new(reader).map_err(|_| OpenFileError)?;
|
||||||
let temp_file_path = app_data_dir().join("import");
|
let temp_file_path = temp_import_path();
|
||||||
let mut temp_file = OpenOptions::new()
|
let mut temp_file = OpenOptions::new()
|
||||||
.write(true)
|
.write(true)
|
||||||
.create(true)
|
.create(true)
|
||||||
.truncate(true)
|
.truncate(true)
|
||||||
.open(&temp_file_path)
|
.open(&temp_file_path)
|
||||||
.map_err(|_| ())?;
|
.map_err(|_| OpenFileError)?;
|
||||||
if let Ok(mut file) = archive.by_name("collection.anki21") {
|
if let Ok(mut file) = archive.by_name("collection.anki21") {
|
||||||
std::io::copy(&mut file, &mut temp_file).map_err(|_| ())?;
|
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
} else if let Ok(mut file) = archive.by_name("collection.anki2") {
|
} else if let Ok(mut file) = archive.by_name("collection.anki2") {
|
||||||
std::io::copy(&mut file, &mut temp_file).map_err(|_| ())?;
|
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
Err(())
|
Err(OpenFileError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn read_import_file() -> Result<ImportData, ()> {
|
fn read_import_file() -> Result<ImportData, NotificationData> {
|
||||||
let temp_file_path = app_data_dir().join("import");
|
let temp_file_path = temp_import_path();
|
||||||
let connection = Connection::open(&temp_file_path).map_err(|_| ())?;
|
let connection = Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
|
||||||
let data = load_groups(&connection);
|
let data = load_groups(&connection)?;
|
||||||
Ok(data)
|
Ok(data)
|
||||||
}
|
}
|
||||||
fn setup_mapping(&mut self, property_name: String) {
|
fn setup_mapping(&mut self, property_name: String) {
|
||||||
@@ -430,13 +428,14 @@ impl ImportState {
|
|||||||
let skip_empty = self.skip_empty;
|
let skip_empty = self.skip_empty;
|
||||||
let group = self.import_data.as_ref().unwrap().0[self.selected_index].clone();
|
let group = self.import_data.as_ref().unwrap().0[self.selected_index].clone();
|
||||||
let progress = self.progress.clone().unwrap();
|
let progress = self.progress.clone().unwrap();
|
||||||
println!("{}", group.name);
|
info!("{}", group.name);
|
||||||
Task::perform(
|
Task::perform(
|
||||||
async move {
|
async move {
|
||||||
spawn_blocking(move || {
|
spawn_blocking(move || {
|
||||||
let temp_file_path = app_data_dir().join("import");
|
let temp_file_path = temp_import_path();
|
||||||
let connection = Connection::open(&temp_file_path).map_err(|_| ())?;
|
let connection =
|
||||||
let import_list = get_words_of_group(&connection, group.id);
|
Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
|
||||||
|
let import_list = get_words_of_group(&connection, group.id)?;
|
||||||
let mut words_list = Vec::with_capacity(import_list.len());
|
let mut words_list = Vec::with_capacity(import_list.len());
|
||||||
|
|
||||||
let map_indices = Self::get_mapping_indices(&group);
|
let map_indices = Self::get_mapping_indices(&group);
|
||||||
@@ -446,7 +445,7 @@ impl ImportState {
|
|||||||
};
|
};
|
||||||
{
|
{
|
||||||
let state = state.lock();
|
let state = state.lock();
|
||||||
add_group(&mut group_entity, &state.connection);
|
add_group(&mut group_entity, &state.connection)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let group_id = group_entity.id;
|
let group_id = group_entity.id;
|
||||||
@@ -486,7 +485,7 @@ impl ImportState {
|
|||||||
let mut index = 0;
|
let mut index = 0;
|
||||||
let total_len = words_list.len() as f32 / 1024.0;
|
let total_len = words_list.len() as f32 / 1024.0;
|
||||||
for word in &mut words_list.chunks_mut(1024) {
|
for word in &mut words_list.chunks_mut(1024) {
|
||||||
add_words(word, connection);
|
add_words(word, connection)?;
|
||||||
index += 1;
|
index += 1;
|
||||||
let mut progress = progress.lock();
|
let mut progress = progress.lock();
|
||||||
*progress = (index as f32 / total_len).min(1.0);
|
*progress = (index as f32 / total_len).min(1.0);
|
||||||
@@ -500,7 +499,10 @@ impl ImportState {
|
|||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
},
|
},
|
||||||
|_: Result<(), ()>| RootMessage::Import(ImportFinished),
|
|r: Result<(), NotificationData>| match r {
|
||||||
|
Ok(_) => RootMessage::Import(ImportFinished),
|
||||||
|
Err(err) => push_error!(err),
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
use crate::lang::KanaSet;
|
use crate::app::USER_FONT;
|
||||||
|
use crate::core::kana_set::KanaSet;
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
use crate::quiz::QuizMessage::*;
|
use crate::pages::quiz::QuizMessage::*;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::{RootMessage, USER_FONT};
|
|
||||||
use iced::widget::*;
|
use iced::widget::*;
|
||||||
use iced::{Element, Fill, Task, alignment};
|
use iced::{Element, Fill, Task, alignment};
|
||||||
use rand::seq::SliceRandom;
|
use rand::seq::SliceRandom;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::RootMessage;
|
use crate::navigation::RootMessage;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page};
|
||||||
use crate::randomizer::RandomizerMessage::{Back, Edit, Start};
|
use crate::pages::randomizer::RandomizerMessage::{Back, Edit, Start};
|
||||||
use crate::styling::{HALF_SPACING, back_overlay, jl_button};
|
use crate::styling::{HALF_SPACING, back_overlay, jl_button};
|
||||||
use iced::Task;
|
use iced::Task;
|
||||||
use iced::widget::{button, text_editor};
|
use iced::widget::{button, text_editor};
|
||||||
@@ -1,16 +1,20 @@
|
|||||||
|
use crate::app::AppState;
|
||||||
|
use crate::core::deck::DeckData;
|
||||||
|
use crate::core::srs::WordOpenMode;
|
||||||
|
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::lang::Id;
|
|
||||||
use crate::lang::{CardStatistics, DeckData, DeckSettings, WordData, WordOpenMode};
|
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
use crate::navigation::{KeyPressedPage, NavigatedPage, Page};
|
use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
|
||||||
|
use crate::notification::{MaybeError, NotificationData};
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::{AppState, RootMessage};
|
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;
|
||||||
@@ -52,8 +56,9 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
|||||||
self.can_play = false;
|
self.can_play = false;
|
||||||
let value = self.current_word.key.clone();
|
let value = self.current_word.key.clone();
|
||||||
if self.settings.require_speech() {
|
if self.settings.require_speech() {
|
||||||
return Task::perform(play_sound(self.sink.clone(), value), |_| {
|
return Task::perform(play_sound(self.sink.clone(), value), |r| match r {
|
||||||
RootMessage::Repetition(RepetitionMessage::PlayFinished)
|
Ok(_) => RootMessage::Repetition(RepetitionMessage::PlayFinished),
|
||||||
|
Err(err) => push_error!(err),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,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") {
|
||||||
@@ -107,7 +115,7 @@ impl RepetitionState {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
RepetitionState {
|
Ok(RepetitionState {
|
||||||
state,
|
state,
|
||||||
settings: set,
|
settings: set,
|
||||||
set: card_set,
|
set: card_set,
|
||||||
@@ -117,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(),
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,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();
|
||||||
@@ -146,8 +157,9 @@ impl RepetitionState {
|
|||||||
if self.settings.require_speech() && self.sink.is_some() {
|
if self.settings.require_speech() && self.sink.is_some() {
|
||||||
let sink = self.sink.clone();
|
let sink = self.sink.clone();
|
||||||
let task = play_sound(sink, self.current_word.key.clone());
|
let task = play_sound(sink, self.current_word.key.clone());
|
||||||
return Task::perform(task, |_| {
|
return Task::perform(task, |r| match r {
|
||||||
RootMessage::Repetition(RepetitionMessage::PlayFinished)
|
Ok(_) => RootMessage::Repetition(RepetitionMessage::PlayFinished),
|
||||||
|
Err(err) => push_error!(err),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
self.increment_counter();
|
self.increment_counter();
|
||||||
@@ -322,8 +334,8 @@ pub enum RepetitionMessage {
|
|||||||
PlayFinished,
|
PlayFinished,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) {
|
async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) -> MaybeError {
|
||||||
if let Ok(data) = get_voice(text.as_str()).await {
|
let data = get_voice(text.as_str()).await?;
|
||||||
spawn_blocking(move || {
|
spawn_blocking(move || {
|
||||||
if let Some(sink) = sink.as_ref()
|
if let Some(sink) = sink.as_ref()
|
||||||
&& let Ok(play) = rodio::play(sink.mixer(), data)
|
&& let Ok(play) = rodio::play(sink.mixer(), data)
|
||||||
@@ -332,6 +344,6 @@ async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.expect("Playing sound failed");
|
||||||
}
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
use crate::AppState;
|
use crate::app::AppState;
|
||||||
|
use crate::data::entities::DeckSettings;
|
||||||
use crate::data_provider::card_sets::{delete_set, update_deck};
|
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::lang::DeckSettings;
|
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
use crate::repetition_settings::RepetitionSettingsMessage::*;
|
use crate::notification::MaybeError;
|
||||||
|
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};
|
||||||
@@ -60,9 +62,13 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
|||||||
Back => {}
|
Back => {}
|
||||||
Save => {
|
Save => {
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
update_deck(&mut self.set, &state.connection);
|
if let Err(e) = update_deck(&mut self.set, &state.connection) {
|
||||||
if self.filter_changed {
|
return push_error_task!(e);
|
||||||
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();
|
state.decks[self.index] = self.set.clone();
|
||||||
}
|
}
|
||||||
@@ -94,7 +100,10 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
delete_set(&self.set, &state.connection);
|
if let Err(e) = delete_set(&self.set, &state.connection) {
|
||||||
|
return push_error_task!(e);
|
||||||
|
}
|
||||||
|
|
||||||
state.decks.remove(self.index);
|
state.decks.remove(self.index);
|
||||||
return Task::done(RootMessage::RepetitionSettings(Back));
|
return Task::done(RootMessage::RepetitionSettings(Back));
|
||||||
}
|
}
|
||||||
@@ -170,8 +179,8 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_deck_stats(deck: &DeckSettings, state: &AppState) {
|
fn update_deck_stats(deck: &DeckSettings, state: &AppState) -> MaybeError {
|
||||||
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;
|
||||||
@@ -180,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 {
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
|
use crate::app::AppState;
|
||||||
|
use crate::core::srs::{AppendMode, OrderMode};
|
||||||
|
use crate::data::Id;
|
||||||
|
use crate::data::entities::{CardStatistics, DeckSettings};
|
||||||
use crate::data_provider::card_sets::update_deck;
|
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::history::HistoryState;
|
|
||||||
use crate::lang::{AppendMode, CardStatistics, DeckSettings, Id, OrderMode};
|
|
||||||
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
|
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
use crate::repetition::RepetitionState;
|
use crate::notification::{MaybeError, NotificationRequest};
|
||||||
use crate::repetition_settings::RepetitionSettingsState;
|
use crate::pages::history::HistoryState;
|
||||||
use crate::repetitions::RepetitionsMessage::*;
|
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 crate::styling::*;
|
||||||
use crate::{AppState, RootMessage};
|
|
||||||
use chrono::{Days, Local, Utc};
|
use chrono::{Days, Local, Utc};
|
||||||
use hashbrown::{HashMap, HashSet};
|
use hashbrown::{HashMap, HashSet};
|
||||||
pub use iced::widget::button::{Catalog, Style};
|
pub use iced::widget::button::{Catalog, Style};
|
||||||
@@ -48,28 +53,25 @@ 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
|
if selected_set.available_words_indices.is_empty()
|
||||||
.available_words_indices
|
|| selected_set.existing_words_indices.is_empty()
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.is_empty()
|
|
||||||
|| selected_set
|
|
||||||
.existing_words_indices
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.is_empty()
|
|
||||||
{
|
{
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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(),
|
||||||
@@ -80,7 +82,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn navigated(&mut self) {
|
fn navigated(&mut self) {
|
||||||
let index = self.selected_deck_index.unwrap();
|
if let Some(index) = self.selected_deck_index {
|
||||||
let state = self.state.lock();
|
let state = self.state.lock();
|
||||||
if let Some(global_deck) = state.decks.get(index) {
|
if let Some(global_deck) = state.decks.get(index) {
|
||||||
if global_deck.id != self.selected_deck().unwrap().id {
|
if global_deck.id != self.selected_deck().unwrap().id {
|
||||||
@@ -88,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[self.selected_deck_index.unwrap()].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);
|
||||||
@@ -99,6 +100,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
|||||||
self.clear_selection()
|
self.clear_selection()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
|
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
|
||||||
match message {
|
match message {
|
||||||
Next => {}
|
Next => {}
|
||||||
@@ -111,8 +113,9 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
|||||||
let index = self.decks.len() + 1;
|
let index = self.decks.len() + 1;
|
||||||
self.decks.push(DeckViewData {
|
self.decks.push(DeckViewData {
|
||||||
general_settings: DeckSettings::with_name(format!("Колода #{}", index)),
|
general_settings: DeckSettings::with_name(format!("Колода #{}", index)),
|
||||||
existing_words_indices: None,
|
existing_words_indices: Default::default(),
|
||||||
available_words_indices: None,
|
available_words_indices: Default::default(),
|
||||||
|
indices_ready: false,
|
||||||
append_mode: Default::default(),
|
append_mode: Default::default(),
|
||||||
index: None,
|
index: None,
|
||||||
});
|
});
|
||||||
@@ -142,15 +145,21 @@ 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.existing_words_indices.is_none() {
|
if !deck.indices_ready
|
||||||
self.fill_deck_word_indices();
|
&& let Err(err) = self.fill_deck_word_indices()
|
||||||
|
{
|
||||||
|
return push_error_task!(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Save => {
|
Save => {
|
||||||
let mut deck = self.selected_deck().unwrap().clone();
|
let mut deck = self.selected_deck().unwrap().clone();
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
{
|
{
|
||||||
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),
|
||||||
|
));
|
||||||
|
}
|
||||||
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();
|
||||||
} else {
|
} else {
|
||||||
@@ -193,15 +202,13 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
|||||||
{
|
{
|
||||||
{
|
{
|
||||||
let deck = self.selected_deck().unwrap();
|
let deck = self.selected_deck().unwrap();
|
||||||
let existing_words_indices = deck.existing_words_indices.as_ref().unwrap();
|
let existing_words_indices = &deck.existing_words_indices;
|
||||||
let mut created_set = HashSet::with_capacity(existing_words_indices.len());
|
let mut created_set = HashSet::with_capacity(existing_words_indices.len());
|
||||||
existing_words_indices.iter().for_each(|c| {
|
existing_words_indices.iter().for_each(|c| {
|
||||||
created_set.insert(c);
|
created_set.insert(c);
|
||||||
});
|
});
|
||||||
adding = deck
|
adding = deck
|
||||||
.available_words_indices
|
.available_words_indices
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|c| !created_set.contains(c))
|
.filter(|c| !created_set.contains(c))
|
||||||
.take(count)
|
.take(count)
|
||||||
@@ -210,15 +217,16 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let deck = self.selected_deck_mut().unwrap();
|
let deck = self.selected_deck_mut().unwrap();
|
||||||
deck.existing_words_indices
|
deck.existing_words_indices.append(&mut adding.clone());
|
||||||
.as_mut()
|
|
||||||
.unwrap()
|
|
||||||
.append(&mut adding.clone());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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()
|
||||||
@@ -278,8 +286,9 @@ impl RepetitionsState {
|
|||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(index, deck)| DeckViewData {
|
.map(|(index, deck)| DeckViewData {
|
||||||
general_settings: deck.clone(),
|
general_settings: deck.clone(),
|
||||||
existing_words_indices: None,
|
existing_words_indices: Default::default(),
|
||||||
available_words_indices: None,
|
available_words_indices: Default::default(),
|
||||||
|
indices_ready: false,
|
||||||
append_mode: Default::default(),
|
append_mode: Default::default(),
|
||||||
index: Some(index),
|
index: Some(index),
|
||||||
})
|
})
|
||||||
@@ -290,9 +299,7 @@ impl RepetitionsState {
|
|||||||
impl RepetitionsState {
|
impl RepetitionsState {
|
||||||
fn launch_delete_button(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
fn launch_delete_button(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||||
if deck.id.is_valid() {
|
if deck.id.is_valid() {
|
||||||
if deck.append_mode == AppendMode::Manual
|
if deck.append_mode == AppendMode::Manual && deck.existing_words_indices.is_empty() {
|
||||||
&& deck.existing_words_indices.as_ref().unwrap().is_empty()
|
|
||||||
{
|
|
||||||
return text!("Добавьте карточки или измените фильтр").into();
|
return text!("Добавьте карточки или измените фильтр").into();
|
||||||
}
|
}
|
||||||
return row![
|
return row![
|
||||||
@@ -443,7 +450,7 @@ impl RepetitionsState {
|
|||||||
|
|
||||||
let date = (*now)
|
let date = (*now)
|
||||||
.checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1))
|
.checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1))
|
||||||
.unwrap();
|
.unwrap_or_default();
|
||||||
|
|
||||||
column = column.push(tooltip(
|
column = column.push(tooltip(
|
||||||
iced::widget::container(space().height(15).width(15)).style(
|
iced::widget::container(space().height(15).width(15)).style(
|
||||||
@@ -515,12 +522,8 @@ impl RepetitionsState {
|
|||||||
|
|
||||||
fn count_comparator_view(&self) -> Element<'_, RepetitionsMessage> {
|
fn count_comparator_view(&self) -> Element<'_, RepetitionsMessage> {
|
||||||
let selected_deck = self.selected_deck().unwrap();
|
let selected_deck = self.selected_deck().unwrap();
|
||||||
let now = selected_deck.existing_words_indices.as_ref().unwrap().len();
|
let now = selected_deck.existing_words_indices.len();
|
||||||
let available = selected_deck
|
let available = selected_deck.available_words_indices.len();
|
||||||
.available_words_indices
|
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.len();
|
|
||||||
text!("{} слова добавлено из {}", now, available).into()
|
text!("{} слова добавлено из {}", now, available).into()
|
||||||
}
|
}
|
||||||
fn count_view(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
|
fn count_view(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
|
||||||
@@ -559,26 +562,25 @@ impl RepetitionsState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RepetitionsState {
|
impl RepetitionsState {
|
||||||
fn append_all_words(state: &mut AppState, deck: &DeckViewData) {
|
fn append_all_words(state: &mut AppState, deck: &DeckViewData) -> MaybeError {
|
||||||
let existing = deck.existing_words_indices.as_ref().unwrap();
|
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| {
|
||||||
created_set.insert(c);
|
created_set.insert(c);
|
||||||
});
|
});
|
||||||
let required = deck
|
let required = deck
|
||||||
.available_words_indices
|
.available_words_indices
|
||||||
.as_ref()
|
|
||||||
.unwrap()
|
|
||||||
.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>,
|
||||||
) {
|
) -> MaybeError {
|
||||||
let words = &state.dictionary;
|
let words = &state.dictionary;
|
||||||
let stats = &mut indices
|
let stats = &mut indices
|
||||||
.map(|i| {
|
.map(|i| {
|
||||||
@@ -594,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) {
|
||||||
@@ -615,17 +618,18 @@ 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) -> MaybeError {
|
||||||
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();
|
||||||
let total = deck.get_word_list(state);
|
let total = deck.get_word_list(state);
|
||||||
deck.existing_words_indices = Some(added);
|
deck.existing_words_indices = added;
|
||||||
deck.available_words_indices = Some(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)]
|
||||||
@@ -652,8 +656,9 @@ pub enum RepetitionsMessage {
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct DeckViewData {
|
struct DeckViewData {
|
||||||
general_settings: DeckSettings,
|
general_settings: DeckSettings,
|
||||||
existing_words_indices: Option<Vec<usize>>,
|
existing_words_indices: Vec<usize>,
|
||||||
available_words_indices: Option<Vec<usize>>,
|
available_words_indices: Vec<usize>,
|
||||||
|
indices_ready: bool,
|
||||||
append_mode: AppendMode,
|
append_mode: AppendMode,
|
||||||
index: Option<usize>,
|
index: Option<usize>,
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
use crate::dictionary::DictionaryState;
|
use crate::app::AppState;
|
||||||
use crate::lang::{KanaSet, KanaType};
|
use crate::core::kana_set::{KanaSet, KanaType};
|
||||||
use crate::navigation::Page::*;
|
use crate::navigation::Page::*;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
use crate::randomizer::RandomizerState;
|
use crate::pages::dictionary::DictionaryState;
|
||||||
use crate::repetitions::RepetitionsState;
|
use crate::pages::quiz::QuizState;
|
||||||
use crate::selector::SelectorMessage::ChangeMode;
|
use crate::pages::randomizer::RandomizerState;
|
||||||
|
use crate::pages::repetitions::RepetitionsState;
|
||||||
|
use crate::pages::selector::SelectorMessage::ChangeMode;
|
||||||
|
use crate::pages::sync::SyncState;
|
||||||
|
use crate::pages::writing::WritingState;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::sync::SyncState;
|
|
||||||
use crate::writing::WritingState;
|
|
||||||
use crate::{AppState, QuizState, RootMessage};
|
|
||||||
use iced::widget::button::{Status, Style};
|
use iced::widget::button::{Status, Style};
|
||||||
use iced::widget::*;
|
use iced::widget::*;
|
||||||
use iced::{Element, Task, alignment};
|
use iced::{Element, Task, alignment};
|
||||||
@@ -1,14 +1,17 @@
|
|||||||
|
use crate::app::{AppState, fill_state};
|
||||||
use crate::data_provider::settings::{delete_settings, set_setting};
|
use crate::data_provider::settings::{delete_settings, set_setting};
|
||||||
use crate::data_provider::web_api::*;
|
use crate::data_provider::web_api::*;
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
|
use crate::notification::{NotificationData, NotificationRequest};
|
||||||
|
use crate::pages::sync::SyncMessage::*;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::sync::SyncMessage::*;
|
use crate::{push_error, push_error_task};
|
||||||
use crate::{fill_state, AppState, RootMessage};
|
|
||||||
use iced::widget::button::danger;
|
use iced::widget::button::danger;
|
||||||
use iced::widget::container::rounded_box;
|
use iced::widget::container::rounded_box;
|
||||||
use iced::widget::{button, column, container, progress_bar, row, space, text, toggler};
|
use iced::widget::{button, column, container, progress_bar, row, space, text, toggler};
|
||||||
use iced::{Center, Element, Fill, Font, Length, Task};
|
use iced::{Center, Element, Fill, Font, Length, Task};
|
||||||
|
use log::error;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -59,11 +62,9 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
|||||||
.map(|_val: String| RootMessage::Sync(KeyCopied));
|
.map(|_val: String| RootMessage::Sync(KeyCopied));
|
||||||
}
|
}
|
||||||
InitSync => {
|
InitSync => {
|
||||||
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(_) => RootMessage::None
|
Err(err) => push_error!(err),
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
GetKey => {
|
GetKey => {
|
||||||
@@ -77,7 +78,9 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
|||||||
}
|
}
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
state.sync_data.key = Some(new_id.clone());
|
state.sync_data.key = Some(new_id.clone());
|
||||||
set_setting("SYNC_KEY".to_string(), new_id, &state.connection);
|
if let Err(err) = set_setting("SYNC_KEY".to_string(), new_id, &state.connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Send => {
|
Send => {
|
||||||
self.prepare_to_db_interaction();
|
self.prepare_to_db_interaction();
|
||||||
@@ -128,23 +131,35 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
|||||||
state.decks = updated_state.decks;
|
state.decks = updated_state.decks;
|
||||||
state.dictionary = updated_state.dictionary;
|
state.dictionary = updated_state.dictionary;
|
||||||
state.word_groups = updated_state.word_groups;
|
state.word_groups = updated_state.word_groups;
|
||||||
|
return Task::done(RootMessage::PushNotification(NotificationRequest::Info(
|
||||||
|
NotificationData::DataLoaded,
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
Disable => {}
|
Disable => {}
|
||||||
DisableSync => {
|
DisableSync => {
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
state.sync_data.key = None;
|
state.sync_data.key = None;
|
||||||
delete_settings("SYNC_KEY".to_string(), &state.connection);
|
let save_result = || {
|
||||||
delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection);
|
delete_settings("SYNC_KEY".to_string(), &state.connection)?;
|
||||||
|
delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection)?;
|
||||||
|
Ok::<(), NotificationData>(())
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(error) = save_result() {
|
||||||
|
return push_error_task!(error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
SwitchAutoSync => {
|
SwitchAutoSync => {
|
||||||
self.auto_fetch = !self.auto_fetch;
|
self.auto_fetch = !self.auto_fetch;
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
state.sync_data.auto_web_fetch = self.auto_fetch;
|
state.sync_data.auto_web_fetch = self.auto_fetch;
|
||||||
set_setting(
|
if let Err(err) = set_setting(
|
||||||
"AUTO_WEB_FETCH".to_string(),
|
"AUTO_WEB_FETCH".to_string(),
|
||||||
self.auto_fetch.to_string(),
|
self.auto_fetch.to_string(),
|
||||||
&state.connection,
|
&state.connection,
|
||||||
);
|
) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Task::none()
|
Task::none()
|
||||||
@@ -244,7 +259,7 @@ impl SyncState {
|
|||||||
.connection
|
.connection
|
||||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
|
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
|
||||||
.unwrap_or_else(|e| {
|
.unwrap_or_else(|e| {
|
||||||
eprintln!("Ошибка при checkpoint WAL: {e}");
|
error!("Ошибка при checkpoint WAL: {e}");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
|
use crate::app::AppState;
|
||||||
|
use crate::data::entities::WordData;
|
||||||
use crate::data_provider::words::{delete_word, update_word};
|
use crate::data_provider::words::{delete_word, update_word};
|
||||||
use crate::lang::WordData;
|
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
|
use crate::pages::word::WordMessage::*;
|
||||||
|
use crate::push_error;
|
||||||
|
use crate::push_error_task;
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use crate::word::WordMessage::*;
|
|
||||||
use crate::{AppState, RootMessage};
|
|
||||||
use iced::widget::button::danger;
|
use iced::widget::button::danger;
|
||||||
use iced::widget::{button, column, row, rule, scrollable, text, text_input};
|
use iced::widget::{button, column, row, rule, scrollable, text, text_input};
|
||||||
use iced::{Element, Fill, Task};
|
use iced::{Element, Fill, Task};
|
||||||
@@ -34,13 +36,18 @@ impl NavigatedPage<WordMessage> for WordState {
|
|||||||
Save => {
|
Save => {
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
state.dictionary[self.index] = self.word.clone();
|
state.dictionary[self.index] = self.word.clone();
|
||||||
update_word(&mut self.word, &state.connection);
|
|
||||||
|
if let Err(err) = update_word(&mut self.word, &state.connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
return Task::done(RootMessage::Word(Back));
|
return Task::done(RootMessage::Word(Back));
|
||||||
}
|
}
|
||||||
Delete => {
|
Delete => {
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
state.dictionary.remove(self.index);
|
state.dictionary.remove(self.index);
|
||||||
delete_word(&self.word, &state.connection);
|
if let Err(err) = delete_word(&self.word, &state.connection) {
|
||||||
|
return push_error_task!(err);
|
||||||
|
}
|
||||||
return Task::done(RootMessage::Word(Back));
|
return Task::done(RootMessage::Word(Back));
|
||||||
}
|
}
|
||||||
SetTags(n) => self.word.tags = n,
|
SetTags(n) => self.word.tags = n,
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
use crate::RootMessage;
|
use crate::core::kana_set::KanaSet;
|
||||||
use crate::lang::KanaSet;
|
|
||||||
use crate::navigation::Page::PreviousPage;
|
use crate::navigation::Page::PreviousPage;
|
||||||
use crate::navigation::{NavigatedPage, Page};
|
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||||
use crate::styling::*;
|
use crate::styling::*;
|
||||||
use iced::widget::*;
|
use iced::widget::*;
|
||||||
use iced::{Element, Fill, Task, alignment};
|
use iced::{Element, Fill, Task, alignment};
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
use crate::repetitions::Style;
|
|
||||||
use iced::Element;
|
use iced::Element;
|
||||||
use iced::border::Radius;
|
use iced::border::Radius;
|
||||||
use iced::widget::button::*;
|
use iced::widget::button::*;
|
||||||
|
|||||||
Reference in new issue
Block a user