Author SHA1 Message Date
micialware 142c2d3d10 correct history order on history page 2026-10-10 19:20:24 +03:00
micialware 27bdcf41b0 update compression level and logging compression time 2026-10-05 22:17:04 +03:00
micialware 5817bfcd46 Reformat code 2026-10-04 15:19:56 +03:00
micialware a36613b238 tokio update 2026-10-04 13:01:53 +03:00
micialware 496f246125 More data on exams page 2026-10-04 12:22:33 +03:00
micialware 7ad44110c3 Exam page works 2026-10-03 22:47:33 +03:00
micialware 0b23da9eda Fix display and sync bugs 2026-10-03 21:27:13 +03:00
micialware 5b2b48c88f updated card display 2026-10-03 20:32:11 +03:00
micialware 632f0c341b Basic exam page 2026-10-03 15:18:00 +03:00
micialware 65991f742e Basic exams page ready 2026-10-03 15:12:09 +03:00
micialware 79c42d0feb Exams page more code 2026-10-03 14:49:19 +03:00
micialware 4b9e257cdf Exam base 2026-10-03 01:13:11 +03:00
micialware 6628d79307 Update message text 2026-10-02 21:19:30 +03:00
micialware 936efd0e99 Fsrs pools change 2026-09-23 18:05:58 +03:00
micialware 8603e9b981 Fix editor bug 2026-09-23 14:37:42 +03:00
micialware 824a868d73 Small database sync update 2026-09-22 21:57:29 +03:00
micialware 8b673e52da Change selection type on extended editing 2026-09-22 15:48:18 +03:00
micialware b210b2013d Fix saving bug 2026-09-22 15:27:39 +03:00
micialware 48cd68d1c7 Fix incorrect states clearing 2026-09-21 11:53:07 +03:00
micialware a5526dc5e9 Migrate to String::new() 2026-09-20 22:24:42 +03:00
micialware 1d4b37e381 Update version, remove unused features 2026-09-20 22:18:59 +03:00
micialware 96a58c61bc Rollback default control radius 2026-09-15 22:11:38 +03:00
micialware 1847d4f44f apply new style 2026-09-15 22:09:06 +03:00
micialware b1902b35cb style and macros for text input 2026-09-15 21:54:24 +03:00
micialware 5d12f3b02a Fixing incorrect history reading bug 2026-09-14 19:41:02 +03:00
micialware 0e867a33ce Merge pull request 'Updated word display' (#19) from updated-word-display into master
Reviewed-on: https://gitea.micialware.ru/micialware/jap_learn/pulls/19
2026-09-13 17:42:58 +03:00
micialware ccfb302770 Prepare for new anki format 2026-09-13 12:44:51 +03:00
micialware 0de809fcce Compressing word fields 2026-09-11 22:08:50 +03:00
micialware e5622c70de Fix deck filter 2026-09-11 14:02:57 +03:00
micialware cbf49412ec additional fields encoding and decoding 2026-09-11 13:56:26 +03:00
micialware f61f93717c Custom fields repo into AppState 2026-09-11 13:28:23 +03:00
micialware be64b1da2d Fix group delete 2026-09-11 13:12:45 +03:00
micialware 2568b9f292 More fixes for dictionary panel 2026-09-11 13:09:20 +03:00
micialware 05c82bee02 Fix tag edit bug 2026-09-11 12:48:04 +03:00
micialware 5d305affd3 Fixing some bugs 2026-09-11 12:38:21 +03:00
micialware d59776d713 More keyboard handling for dictionary 2026-09-11 12:03:13 +03:00
micialware adb6388ee2 Prepare for extended word edit 2026-09-11 11:47:04 +03:00
micialware 8fe4f3b8f4 New selected field movement 2026-09-11 00:41:36 +03:00
micialware 47bc83d4ae New edit process 2026-09-11 00:01:19 +03:00
micialware 097c3c033c Merge pull request 'reformat custom fields table. will return to this topic later' (#18) from compressed-fields into master
Reviewed-on: https://gitea.micialware.ru/micialware/jap_learn/pulls/18
2026-09-09 15:16:01 +03:00
43 changed files with 2324 additions and 549 deletions

No files matched your search

Generated
+15 -18
View File
@@ -2203,7 +2203,7 @@ checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]] [[package]]
name = "jap_learn" name = "jap_learn"
version = "0.1.3" version = "0.2.0"
dependencies = [ dependencies = [
"chrono", "chrono",
"criterion", "criterion",
@@ -2230,7 +2230,7 @@ dependencies = [
"sha2", "sha2",
"tokio", "tokio",
"zip", "zip",
"zstd 0.14.0", "zstd 0.14.1",
] ]
[[package]] [[package]]
@@ -2501,9 +2501,6 @@ name = "litemap"
version = "0.8.3" version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
dependencies = [
"serde_core",
]
[[package]] [[package]]
name = "litrs" name = "litrs"
@@ -3596,9 +3593,9 @@ checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]] [[package]]
name = "rand" name = "rand"
version = "0.10.2" version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [ dependencies = [
"chacha20", "chacha20",
"getrandom 0.4.1", "getrandom 0.4.1",
@@ -3857,9 +3854,9 @@ dependencies = [
[[package]] [[package]]
name = "rhai" name = "rhai"
version = "1.26.0" version = "1.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6e1be9d697d537ce450766df42ad6adf1a93f25f21d73217354ad7e3d3dae1" checksum = "0334639972c0ea5a3fd366aa36116754a11431b619fec3ed559b3f73bcbcebf5"
dependencies = [ dependencies = [
"ahash", "ahash",
"bitflags 2.10.0", "bitflags 2.10.0",
@@ -4925,9 +4922,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.53.1" version = "1.53.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"
dependencies = [ dependencies = [
"bytes", "bytes",
"libc", "libc",
@@ -6488,11 +6485,11 @@ dependencies = [
[[package]] [[package]]
name = "zstd" name = "zstd"
version = "0.14.0" version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf06bd8162af0734b344780deb55b42a2429ae430870d13fcc12f238e880fe6e" checksum = "a4a9ecd0608fac4196ed58e1f337e9a72680fcc9ee449b8bcde6acea680b46f0"
dependencies = [ dependencies = [
"zstd-safe 8.0.0", "zstd-safe 8.1.0",
] ]
[[package]] [[package]]
@@ -6506,18 +6503,18 @@ dependencies = [
[[package]] [[package]]
name = "zstd-safe" name = "zstd-safe"
version = "8.0.0" version = "8.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae42c0555055784c70058d19ba8e275528e8a99a706684868ace5da4e716a4ab" checksum = "bdd44c6a7284e91f3717755b24315a302edd9153a01f753c3cba3d765e8eafac"
dependencies = [ dependencies = [
"zstd-sys", "zstd-sys",
] ]
[[package]] [[package]]
name = "zstd-sys" name = "zstd-sys"
version = "2.1.0+zstd.1.5.7" version = "2.1.1+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" checksum = "aeec9eaf2dffbbd09201e23bd0ffcbaa33bb8e9266a10734fd7ed90a85eca078"
dependencies = [ dependencies = [
"cc", "cc",
"pkg-config", "pkg-config",
+6 -6
View File
@@ -1,23 +1,23 @@
[package] [package]
name = "jap_learn" name = "jap_learn"
version = "0.1.3" version = "0.2.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
iced = { version = "0.14.0", features = ["tokio", "svg", "lazy", "crisp", "tiny-skia", "wayland", "wgpu"], default-features = false} iced = { version = "0.14.0", features = ["tokio", "svg", "lazy", "crisp", "tiny-skia", "wayland", "wgpu"], default-features = false}
iced_core = "0.14.0" iced_core = "0.14.0"
rand = "0.10.2" rand = "0.10.3"
dirs = "7.0.0" dirs = "7.0.0"
serde_json = "1.0.151" serde_json = "1.0.151"
rhai = { version = "1.26.0", features = ["sync"] } rhai = { version = "1.26.1", features = ["sync"] }
chrono = "0.4.45" chrono = "0.4.45"
rusqlite = { version = "0.40.2", features = ["chrono", "bundled"] } rusqlite = { version = "0.40.2", features = ["chrono", "bundled"] }
reqwest = { version = "0.13.5", features = ["json", "stream", "multipart"] } reqwest = { version = "0.13.5", features = ["json", "stream", "multipart"] }
rodio = "0.22.2" rodio = "0.22.2"
sha2 = "0.11.0" sha2 = "0.11.0"
tokio = { version = "1.53.1", features = ["rt", "rt-multi-thread", "macros"] } tokio = { version = "1.53.2", features = ["rt", "rt-multi-thread", "macros"] }
hex = "0.4.3" hex = "0.4.3"
zstd = "0.14.0" zstd = "0.14.1"
zip = "8.6.0" zip = "8.6.0"
rfd = "0.17.2" rfd = "0.17.2"
mimalloc = "0.1.52" mimalloc = "0.1.52"
@@ -27,7 +27,7 @@ parking_lot = "0.12.5"
env_logger = "0.11.11" env_logger = "0.11.11"
log = "0.4.34" log = "0.4.34"
fsrs = "6.6.2" fsrs = "6.6.2"
litemap = { version = "0.8.3", features = ["serde"] } litemap = { version = "0.8.3" }
[profile.super-release] [profile.super-release]
inherits = "release" inherits = "release"
+1 -1
View File
@@ -2,5 +2,5 @@ create table custom_fields
( (
id integer primary key, id integer primary key,
name text not null, name text not null,
custom_fields text not null identifier text not null
); );
+5
View File
@@ -0,0 +1,5 @@
create table exams(
id integer primary key,
timestamp integer,
deck_id integer not null references decks on delete cascade
);
+7
View File
@@ -0,0 +1,7 @@
create table exam_entries
(
id integer primary key,
exam_id integer not null references exams on delete cascade,
word_id integer not null references words on delete cascade,
status integer default null
);
+11 -1
View File
@@ -1,5 +1,6 @@
use crate::data::repositories::Repository; use crate::data::repositories::Repository;
use crate::data_provider::card_states::CardStateRepository; use crate::data_provider::card_states::CardStateRepository;
use crate::data_provider::custom_fields::CustomFieldRepository;
use crate::data_provider::decks::DeckRepository; use crate::data_provider::decks::DeckRepository;
use crate::data_provider::history::HistoryRepository; use crate::data_provider::history::HistoryRepository;
use crate::data_provider::settings::get_setting; use crate::data_provider::settings::get_setting;
@@ -17,6 +18,7 @@ use log::info;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use rusqlite::Connection; use rusqlite::Connection;
use std::sync::Arc; use std::sync::Arc;
use crate::data_provider::exam::{ExamEntryRepository, ExamRepository};
pub const USER_FONT: Font = Font::with_name("Noto Sans JP"); pub const USER_FONT: Font = Font::with_name("Noto Sans JP");
@@ -65,9 +67,12 @@ pub struct AppState {
pub decks: DeckRepository, pub decks: DeckRepository,
pub word_groups: WordGroupRepository, pub word_groups: WordGroupRepository,
pub card_states: CardStateRepository, pub card_states: CardStateRepository,
pub custom_fields: CustomFieldRepository,
pub connection: Arc<Mutex<SqliteConnection>>, pub connection: Arc<Mutex<SqliteConnection>>,
pub sync_data: Arc<RwLock<AppSettings>>, pub sync_data: Arc<RwLock<AppSettings>>,
pub history: HistoryRepository, pub history: HistoryRepository,
pub exam: ExamRepository,
pub exam_entries: ExamEntryRepository
} }
impl Default for AppState { impl Default for AppState {
@@ -85,6 +90,9 @@ impl AppState {
word_groups: WordGroupRepository::new(connection.clone()), word_groups: WordGroupRepository::new(connection.clone()),
card_states: CardStateRepository::new(connection.clone()), card_states: CardStateRepository::new(connection.clone()),
history: HistoryRepository::new(connection.clone()), history: HistoryRepository::new(connection.clone()),
exam: ExamRepository::new(connection.clone()),
custom_fields: CustomFieldRepository::new(connection.clone()),
exam_entries: ExamEntryRepository::new(connection.clone()),
sync_data: Arc::new(RwLock::new(AppSettings { sync_data: Arc::new(RwLock::new(AppSettings {
key: None, key: None,
auto_web_fetch: false, auto_web_fetch: false,
@@ -104,7 +112,9 @@ pub fn fill_state(state: &mut AppState) {
state.decks.write().start().unwrap(); state.decks.write().start().unwrap();
state.history.write().start().unwrap(); state.history.write().start().unwrap();
state.card_states.write().start().unwrap(); state.card_states.write().start().unwrap();
state.custom_fields.write().start().unwrap();
state.exam.write().start().unwrap();
state.exam_entries.write().start().unwrap();
state.sync_data = Arc::new(RwLock::new(setting)) state.sync_data = Arc::new(RwLock::new(setting))
} }
+17 -2
View File
@@ -4,13 +4,16 @@ use crate::core::srs::{
FsrsModule, OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule, FsrsModule, OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule,
WordOpenMode, WorstWordsSRSModule, WordOpenMode, WorstWordsSRSModule,
}; };
use crate::data::Id;
use crate::data::entities::*; use crate::data::entities::*;
use crate::data::repositories::Repository; use crate::data::repositories::Repository;
use crate::data_provider::card_states::CardStateRepositoryInner; use crate::data_provider::card_states::CardStateRepositoryInner;
use crate::notification::MaybeError; use crate::notification::MaybeError;
use chrono::Utc; use chrono::Utc;
use litemap::LiteMap;
use log::info; use log::info;
use rhai::{Engine, Scope}; use rhai::{Engine, Scope};
use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
@@ -24,6 +27,11 @@ pub struct DeckData {
open_mode: OrderMode, open_mode: OrderMode,
settings: DeckSettings, settings: DeckSettings,
} }
struct DisplayStyle {
properties: LiteMap<String, String>,
}
impl DeckData { impl DeckData {
pub fn new(settings: &DeckSettings, open_mode: OrderMode, state: AppState) -> Self { pub fn new(settings: &DeckSettings, open_mode: OrderMode, state: AppState) -> Self {
let states_repo = state.card_states.read(); let states_repo = state.card_states.read();
@@ -154,10 +162,17 @@ impl DeckData {
if let Ok(ast) = ast { if let Ok(ast) = ast {
let groups = state.word_groups.read().iter().cloned().collect::<Vec<_>>(); let groups = state.word_groups.read().iter().cloned().collect::<Vec<_>>();
let dictionary = &state.dictionary.read(); let dictionary = &state.dictionary.read();
let fields: HashMap<Id, String> = HashMap::from_iter(
state
.custom_fields
.read()
.iter()
.map(|f| (f.id, f.identifier.clone())),
);
let query = dictionary.query_par(Arc::new(move |word| { let query = dictionary.query_par(Arc::new(move |word| {
let mut more = rhai::Map::new(); let mut more = rhai::Map::new();
for iced in &word.additional { for kv in &word.additional {
more.insert(iced.0.clone().into(), iced.1.clone().into()); more.insert(fields[kv.0].clone().into(), kv.1.clone().into());
} }
let mut scope = Scope::new(); let mut scope = Scope::new();
let group_name = groups[groups let group_name = groups[groups
+31 -57
View File
@@ -1,7 +1,6 @@
use crate::data::entities::CardState; use crate::data::entities::CardState;
use chrono::{Local, TimeDelta}; use chrono::{Local, TimeDelta};
use fsrs::FSRS; use fsrs::FSRS;
use log::{debug, info};
use rand::distr::weighted::WeightedIndex; use rand::distr::weighted::WeightedIndex;
use rand::prelude::ThreadRng; use rand::prelude::ThreadRng;
use rand::prelude::{Distribution, SliceRandom}; use rand::prelude::{Distribution, SliceRandom};
@@ -67,6 +66,18 @@ pub struct SemiRandomSRSModule {
generator: ThreadRng, generator: ThreadRng,
} }
impl SRSModule for SemiRandomSRSModule { impl SRSModule for SemiRandomSRSModule {
fn new(set: &[&CardState]) -> Self {
let weights = set
.iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>();
Self {
generator: rng(),
last_weights: WeightedIndex::new(weights).expect("Incorrect weights update"),
history: vec![],
}
}
fn next(&mut self, set: &[&CardState]) -> usize { fn next(&mut self, set: &[&CardState]) -> usize {
let index = self.last_weights.sample(&mut self.generator); let index = self.last_weights.sample(&mut self.generator);
@@ -87,18 +98,6 @@ impl SRSModule for SemiRandomSRSModule {
.update_weights(&[(index, &new_weight)]) .update_weights(&[(index, &new_weight)])
.expect("update weights error"); .expect("update weights error");
} }
fn new(set: &[&CardState]) -> Self {
let weights = set
.iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>();
Self {
generator: rng(),
last_weights: WeightedIndex::new(weights).expect("Incorrect weights update"),
history: vec![],
}
}
} }
impl SemiRandomSRSModule { impl SemiRandomSRSModule {
fn history_len(&self, set: &[&CardState]) -> usize { fn history_len(&self, set: &[&CardState]) -> usize {
@@ -114,6 +113,16 @@ pub struct WorstWordsSRSModule {
rounds_count: u8, rounds_count: u8,
} }
impl SRSModule for WorstWordsSRSModule { impl SRSModule for WorstWordsSRSModule {
fn new(_: &[&CardState]) -> Self {
WorstWordsSRSModule {
pool_size: PARTIAL_POOL_SIZE,
rounds_count: 2,
rounds_remaining: 0,
pool: vec![],
queue: vec![],
}
}
fn next(&mut self, set: &[&CardState]) -> usize { fn next(&mut self, set: &[&CardState]) -> usize {
if self.rounds_remaining == 0 { if self.rounds_remaining == 0 {
self.fill_pool(set); self.fill_pool(set);
@@ -131,16 +140,6 @@ impl SRSModule for WorstWordsSRSModule {
} }
fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {} fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {}
fn new(_: &[&CardState]) -> Self {
WorstWordsSRSModule {
pool_size: PARTIAL_POOL_SIZE,
rounds_count: 2,
rounds_remaining: 0,
pool: vec![],
queue: vec![],
}
}
} }
impl WorstWordsSRSModule { impl WorstWordsSRSModule {
fn fill_pool(&mut self, set: &[&CardState]) { fn fill_pool(&mut self, set: &[&CardState]) {
@@ -157,9 +156,7 @@ impl WorstWordsSRSModule {
#[derive(Clone)] #[derive(Clone)]
pub struct FsrsModule { pub struct FsrsModule {
today_set: Vec<usize>, next_round: Vec<usize>,
solved: Vec<usize>,
current_group: Vec<usize>,
queue: Vec<usize>, queue: Vec<usize>,
rng: ThreadRng, rng: ThreadRng,
fsrs: FSRS, fsrs: FSRS,
@@ -170,29 +167,22 @@ impl SRSModule for FsrsModule {
let today = Local::now().date_naive(); let today = Local::now().date_naive();
let mut new = Self { let mut new = Self {
today_set: set queue: set
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, c)| c.fsrs_open_day <= today) .filter(|(_, c)| c.fsrs_open_day <= today)
.map(|(index, _)| index) .map(|(index, _)| index)
.collect(), .collect(),
current_group: vec![], next_round: vec![],
queue: vec![],
solved: vec![],
rng: rng(), rng: rng(),
fsrs: FSRS::default(), fsrs: FSRS::default(),
}; };
new.today_set.shuffle(&mut new.rng); new.queue.shuffle(&mut new.rng);
new.fill_partial_pool();
new new
} }
fn next(&mut self, _: &[&CardState]) -> usize { fn next(&mut self, _: &[&CardState]) -> usize {
if self.current_group.is_empty() {
self.fill_partial_pool();
}
if self.queue.is_empty() { if self.queue.is_empty() {
self.fill_queue(); self.fill_queue();
self.queue.shuffle(&mut self.rng); self.queue.shuffle(&mut self.rng);
@@ -230,37 +220,21 @@ impl SRSModule for FsrsModule {
updated_word.fsrs_open_day = next_day; updated_word.fsrs_open_day = next_day;
updated_word.fsrs_opened = updated_word.last_open.date_naive(); updated_word.fsrs_opened = updated_word.last_open.date_naive();
if (updated_word.fsrs_open_day != today && !first_time) if (updated_word.fsrs_open_day == today && !first_time)
|| (first_time && status == WordOpenMode::Easy) || (first_time && status != WordOpenMode::Easy)
{ {
info!("For today word on index {} solved", index); self.next_round.push(index);
self.solved.push(index);
let index = self.current_group.iter().position(|x| *x == index).unwrap();
self.current_group.remove(index);
} }
} }
} }
impl FsrsModule { impl FsrsModule {
fn fill_partial_pool(&mut self) {
debug!("Filling partial pool");
self.current_group.extend(
self.today_set
.iter()
.filter(|x| !self.solved.contains(*x))
.take(PARTIAL_POOL_SIZE),
);
self.queue.clear();
self.queue.extend(self.current_group.clone());
}
fn fill_queue(&mut self) { fn fill_queue(&mut self) {
self.queue.extend(self.current_group.clone()); self.queue.append(&mut self.next_round);
} }
pub fn finished(&self) -> bool { pub fn finished(&self) -> bool {
self.today_set.len() == self.solved.len() self.queue.is_empty() && self.next_round.is_empty()
} }
} }
+55 -5
View File
@@ -19,7 +19,7 @@ pub struct WordData {
pub key: String, pub key: String,
pub value: String, pub value: String,
pub tags: String, pub tags: String,
pub additional: LiteMap<String, String>, pub additional: LiteMap<Id, String>,
} }
impl EntityData for WordData { impl EntityData for WordData {
@@ -101,6 +101,9 @@ impl HistoryRepositoryInner {
count = 0; count = 0;
} }
} }
if count != 0 {
counts.push((date, count));
}
} }
counts counts
} }
@@ -130,8 +133,8 @@ impl DeckSettings {
DeckSettings { DeckSettings {
id: 0.into(), id: 0.into(),
name, name,
forward: "".to_string(), forward: String::new(),
backward: "".to_string(), backward: String::new(),
filter: "true".to_string(), filter: "true".to_string(),
} }
} }
@@ -143,7 +146,7 @@ impl DeckSettings {
ast.is_ok() ast.is_ok()
} }
pub fn require_speech(&self) -> bool { pub fn require_speech(&self) -> bool {
self.forward == "speech" || self.backward == "speech" self.forward.contains("speech") || self.backward.contains("speech")
} }
} }
@@ -196,12 +199,57 @@ impl CardState {
} }
} }
#[derive(Clone)]
pub struct CustomField { pub struct CustomField {
pub id: Id, pub id: Id,
pub name: String, pub name: String,
pub identifier: String, pub identifier: String,
} }
impl EntityData for CustomField {
fn id(&self) -> Id {
self.id
}
fn set_id(&mut self, id: Id) {
self.id = id;
}
}
#[derive(Clone)]
pub struct Exam {
pub id: Id,
pub timestamp: DateTime<Utc>,
pub deck_id: Id,
}
impl EntityData for Exam {
fn id(&self) -> Id {
self.id
}
fn set_id(&mut self, id: Id) {
self.id = id;
}
}
#[derive(Clone)]
pub struct ExamEntry{
pub id: Id,
pub exam_id: Id,
pub word_id: Id,
pub status: Option<bool>
}
impl EntityData for ExamEntry {
fn id(&self) -> Id {
self.id
}
fn set_id(&mut self, id: Id) {
self.id = id;
}
}
pub struct EntityHandle<E> { pub struct EntityHandle<E> {
pub(crate) id: Id, pub(crate) id: Id,
index: u32, index: u32,
@@ -209,7 +257,9 @@ pub struct EntityHandle<E> {
} }
impl<T> Clone for EntityHandle<T> { impl<T> Clone for EntityHandle<T> {
fn clone(&self) -> Self { *self } fn clone(&self) -> Self {
*self
}
} }
impl<T> Copy for EntityHandle<T> {} impl<T> Copy for EntityHandle<T> {}
+4
View File
@@ -215,6 +215,10 @@ impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Qu
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.cache.len() self.cache.len()
} }
pub fn get(&self, index: usize) -> Option<EntityHandle<T>> {
self.cache.get(index).cloned()
}
} }
impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Index<usize> impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Index<usize>
+10 -3
View File
@@ -1,15 +1,22 @@
use crate::data::entities::CardState; use crate::data::entities::CardState;
use crate::data::repositories::{DataRepository, DataRepositoryInner, Query}; use crate::data::repositories::{DataRepository, DataRepositoryInner, Query};
use crate::data::Id; use crate::data::Id;
use crate::data_access_methods;
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet}; use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
use chrono::NaiveDate; use chrono::NaiveDate;
use fsrs::MemoryState; use fsrs::MemoryState;
use rusqlite::{Error, Params, Row}; use rusqlite::{Error, Params, Row};
use std::sync::Arc; use std::sync::Arc;
pub type CardStateRepository = DataRepository<CardState, CardStateDbLayer>; data_access_methods!(
pub type CardStateRepositoryInner = DataRepositoryInner<CardState, CardStateDbLayer>; CardStateDbLayer,
pub type CardStateDbLayer = SqliteDbLayer<CardState, CardStatesQuerySet>; CardStateRepository,
CardStateRepositoryInner,
CardState,
CardStatesQuerySet,
CardStateQuery
);
#[derive(Clone)] #[derive(Clone)]
pub struct CardStatesQuerySet; pub struct CardStatesQuerySet;
impl TableAccessQuerySet<CardState> for CardStatesQuerySet { impl TableAccessQuerySet<CardState> for CardStatesQuerySet {
+3 -3
View File
@@ -2,10 +2,10 @@ use crate::data::entities::CustomField;
use crate::data::repositories::{DataRepository, DataRepositoryInner}; use crate::data::repositories::{DataRepository, DataRepositoryInner};
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet}; use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
use rusqlite::{Error, Params, Row}; use rusqlite::{Error, Params, Row};
use crate::data_access_methods;
pub type CustomFieldRepository = DataRepository<CustomField, CustomFieldDbLayer>; data_access_methods!(CustomFieldDbLayer, CustomFieldRepository, CustomFieldRepositoryInner, CustomField, CustomFieldsQuerySet, CustomFieldQuery);
pub type CustomFieldRepositoryInner = DataRepositoryInner<CustomField, CustomFieldDbLayer>; #[derive(Clone)]
pub type CustomFieldDbLayer = SqliteDbLayer<CustomField, CustomFieldsQuerySet>;
pub struct CustomFieldsQuerySet; pub struct CustomFieldsQuerySet;
impl TableAccessQuerySet<CustomField> for CustomFieldsQuerySet { impl TableAccessQuerySet<CustomField> for CustomFieldsQuerySet {
fn load() -> &'static str { fn load() -> &'static str {
+98
View File
@@ -0,0 +1,98 @@
use crate::data::entities::{Exam, ExamEntry};
use crate::data::repositories::*;
use crate::data_access_methods;
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
use rusqlite::{Error, Params, Row};
data_access_methods!(
ExamDataLayer,
ExamRepository,
ExamRepositoryInner,
Exam,
ExamQuerySet,
ExamQuery
);
data_access_methods!(
ExamEntryLayer,
ExamEntryRepository,
ExamEntryRepositoryInner,
ExamEntry,
ExamEntryQuerySet,
ExamEntryQuery
);
#[derive(Clone)]
pub struct ExamQuerySet;
impl TableAccessQuerySet<Exam> for ExamQuerySet {
fn load() -> &'static str {
"SELECT id, timestamp, deck_id FROM exams"
}
fn save() -> &'static str {
"UPDATE exams set deck_id = $1, timestamp = $2 WHERE id = $3"
}
fn add() -> &'static str {
"INSERT INTO exams (timestamp, deck_id) values ($1, $2)"
}
fn name() -> &'static str {
"exams"
}
fn from_sql(row: &Row) -> Result<Exam, Error> {
Ok(Exam {
id: row.get(0)?,
timestamp: row.get(1)?,
deck_id: row.get(2)?,
})
}
fn insert_params(entity: &Exam) -> impl Params {
(entity.timestamp.timestamp(), entity.deck_id)
}
fn update_params(entity: &Exam) -> impl Params {
(entity.timestamp.timestamp(), entity.deck_id, entity.id)
}
}
#[derive(Clone)]
pub struct ExamEntryQuerySet;
impl TableAccessQuerySet<ExamEntry> for ExamEntryQuerySet {
fn load() -> &'static str {
"SELECT id, exam_id, word_id, status FROM exam_entries"
}
fn save() -> &'static str {
"UPDATE exam_entries set status = $1 WHERE id = $2"
}
fn add() -> &'static str {
"INSERT into exam_entries (exam_id, word_id, status) VALUES ($1, $2, $3)"
}
fn name() -> &'static str {
"exam_entries"
}
fn from_sql(row: &Row) -> Result<ExamEntry, Error> {
Ok(ExamEntry {
id: row.get(0)?,
exam_id: row.get(1)?,
word_id: row.get(2)?,
status: row.get(3)?,
})
}
fn insert_params(entity: &ExamEntry) -> impl Params {
(entity.exam_id, entity.word_id, entity.status)
}
fn update_params(entity: &ExamEntry) -> impl Params {
(entity.status, entity.id)
}
}
+4 -5
View File
@@ -4,10 +4,9 @@ use crate::data::repositories::{DataRepository, DataRepositoryInner};
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet}; use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
use rusqlite::types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef}; use rusqlite::types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef};
use rusqlite::{Error, Params, Row, ToSql}; use rusqlite::{Error, Params, Row, ToSql};
use crate::data_access_methods;
pub type HistoryRepository = DataRepository<HistoryNote, HistoryDataLayer>; data_access_methods!(HistoryDataLayer, HistoryRepository, HistoryRepositoryInner, HistoryNote, HistoryQuerySet, HistoryQuery);
pub type HistoryRepositoryInner = DataRepositoryInner<HistoryNote, HistoryDataLayer>;
pub type HistoryDataLayer = SqliteDbLayer<HistoryNote, HistoryQuerySet>;
#[derive(Clone)] #[derive(Clone)]
pub struct HistoryQuerySet; pub struct HistoryQuerySet;
@@ -48,7 +47,7 @@ impl TableAccessQuerySet<HistoryNote> for HistoryQuerySet {
( (
entity.deck_id, entity.deck_id,
entity.word_id, entity.word_id,
entity.timestamp, entity.timestamp.timestamp(),
entity.answer, entity.answer,
entity.before, entity.before,
entity.after, entity.after,
@@ -60,7 +59,7 @@ impl TableAccessQuerySet<HistoryNote> for HistoryQuerySet {
( (
entity.deck_id, entity.deck_id,
entity.word_id, entity.word_id,
entity.timestamp, entity.timestamp.timestamp(),
entity.answer, entity.answer,
entity.before, entity.before,
entity.after, entity.after,
+15 -2
View File
@@ -1,6 +1,7 @@
use crate::helpers::into_result; use crate::helpers::into_result;
use crate::notification::NotificationData; use crate::notification::NotificationData;
use crate::notification::NotificationData::IncorrectAnkiFile; use crate::notification::NotificationData::IncorrectAnkiFile;
use crate::pages::import::AnkiSchema;
use log::info; use log::info;
use rusqlite::Connection; use rusqlite::Connection;
use serde_json::Value; use serde_json::Value;
@@ -25,7 +26,17 @@ pub struct ImportNote {
pub fields: Vec<String>, pub fields: Vec<String>,
} }
pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationData> { pub fn load_groups(
connection: &Connection,
schema: AnkiSchema,
) -> Result<ImportData, NotificationData> {
match schema {
AnkiSchema::Old => load_old_schema(connection),
AnkiSchema::Beta => load_new_schema(connection),
}
}
fn load_old_schema(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))
.map_err(|_| IncorrectAnkiFile)?; .map_err(|_| IncorrectAnkiFile)?;
@@ -82,7 +93,9 @@ pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationDa
} }
Err(IncorrectAnkiFile) Err(IncorrectAnkiFile)
} }
fn load_new_schema(_: &Connection) -> Result<ImportData, NotificationData> {
Err(IncorrectAnkiFile)
}
pub fn get_words_of_group( pub fn get_words_of_group(
connection: &Connection, connection: &Connection,
group_id: u64, group_id: u64,
+11 -3
View File
@@ -19,6 +19,7 @@ pub(crate) mod voice;
pub(crate) mod web_api; pub(crate) mod web_api;
pub mod word_groups; pub mod word_groups;
pub(crate) mod words; pub(crate) mod words;
pub(crate) mod exam;
pub trait TableAccessQuerySet<T> { pub trait TableAccessQuerySet<T> {
fn load() -> &'static str; fn load() -> &'static str;
@@ -107,9 +108,7 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> DbLayer<T> for SqliteDbLayer<T, Q
let mut stmt = connection let mut stmt = connection
.prepare(Q::load()) .prepare(Q::load())
.expect("Failed to prepare state query"); .expect("Failed to prepare state query");
let iter = stmt let iter = stmt.query_map([], |row| Q::from_sql(row)).map_err(|e| {
.query_map([], |row| Q::from_sql(row))
.map_err(|e| {
error!("{}", e); error!("{}", e);
DbSaveError DbSaveError
})?; })?;
@@ -192,3 +191,12 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> BatchedDbLayer<T> for SqliteDbLay
Ok(()) Ok(())
} }
} }
#[macro_export]
macro_rules! data_access_methods {
($layer:ident, $repo:ident, $repoinner:ident, $data:ty, $queryset:ty, $query:ident) => {
pub type $repo = DataRepository<$data, $layer>;
pub type $repoinner = DataRepositoryInner<$data, $layer>;
pub type $layer = SqliteDbLayer<$data, $queryset>;
};
}
+16 -4
View File
@@ -24,6 +24,8 @@ fn create_tables(conn: &Connection) {
make_card_stats(conn).expect("Failed to init table"); make_card_stats(conn).expect("Failed to init table");
make_history(conn).expect("Failed to init table"); make_history(conn).expect("Failed to init table");
make_custom_fields(conn).expect("Failed to init table"); make_custom_fields(conn).expect("Failed to init table");
make_exams(conn).expect("Failed to init table");
make_exam_entry(conn).expect("Failed to init table");
} }
fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> { fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> {
@@ -64,6 +66,19 @@ fn make_history(conn: &Connection) -> Result<(), rusqlite::Error> {
fn make_custom_fields(conn: &Connection) -> Result<(), rusqlite::Error> { fn make_custom_fields(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/custom_fields.sql"); let query = include_str!("../../sql/custom_fields.sql");
conn.execute(query, ())?; conn.execute(query, ())?;
conn.execute("insert into custom_fields (name, identifier) values (\"Чтение\", \"reading\"), (\"Описание\", \"description\"), (\"Пример использования\", \"context\")", ())?;
Ok(())
}
fn make_exams(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/exam.sql");
conn.execute(query, ())?;
Ok(())
}
fn make_exam_entry(conn: &Connection) -> Result<(), rusqlite::Error> {
let query = include_str!("../../sql/exam_entry.sql");
conn.execute(query, ())?;
Ok(()) Ok(())
} }
@@ -75,12 +90,9 @@ pub fn default_connection() -> Connection {
.expect("Failed to set PRAGMA"); .expect("Failed to set PRAGMA");
connection connection
.query_one("PRAGMA journal_mode = WAL;", [], |row| { .query_one("PRAGMA journal_mode = WAL;", [], |row| {
println!("{:?}", row);
Ok(()) Ok(())
}) })
.unwrap_or_else(|e| { .expect("Failed to init database");
println!("{}", e);
});
connection connection
.execute("PRAGMA synchronous = NORMAL;", []) .execute("PRAGMA synchronous = NORMAL;", [])
.expect("Failed to set PRAGMA"); .expect("Failed to set PRAGMA");
+18 -6
View File
@@ -1,9 +1,12 @@
use crate::fs::*; use crate::fs::*;
use crate::notification::NotificationData::{CompressError, PermissionDenied, WebApiUnavailable}; use crate::notification::NotificationData::{
CompressError, OpenFileError, PermissionDenied, WebApiUnavailable,
};
use crate::notification::{MaybeError, NotificationData}; use crate::notification::{MaybeError, NotificationData};
use log::info; use log::{debug, info};
use std::io; use std::io;
use tokio::fs::{File, OpenOptions}; use std::time::Instant;
use tokio::fs::{File, OpenOptions, remove_file};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder}; use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
@@ -35,10 +38,13 @@ pub async fn send_data(id: String) -> MaybeError {
} }
fn compress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> { fn compress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> {
let time = Instant::now();
let mut encoder = let mut encoder =
Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).map_err(|_| CompressError)?; Encoder::new(Vec::new(), 17).map_err(|_| CompressError)?;
io::copy(&mut &data[..], &mut encoder).map_err(|_| PermissionDenied)?; io::copy(&mut &data[..], &mut encoder).map_err(|_| PermissionDenied)?;
encoder.finish().map_err(|_| CompressError) let result = encoder.finish().map_err(|_| CompressError);
debug!("Compress time: {:?}", time.elapsed());
result
} }
pub async fn load_data(id: String, temp: bool) -> MaybeError { pub async fn load_data(id: String, temp: bool) -> MaybeError {
@@ -49,7 +55,7 @@ pub async fn load_data(id: String, temp: bool) -> MaybeError {
.get(&id_url) .get(&id_url)
.send() .send()
.await .await
.map_err(|_| WebApiUnavailable)? .map_err(|e| WebApiUnavailable)?
.bytes() .bytes()
.await .await
.map_err(|_| WebApiUnavailable)? .map_err(|_| WebApiUnavailable)?
@@ -74,6 +80,12 @@ pub async fn load_data(id: String, temp: bool) -> MaybeError {
.await .await
.map_err(|_| WebApiUnavailable)?; .map_err(|_| WebApiUnavailable)?;
set_local_version(version.parse::<u32>().unwrap_or_default()).await?; set_local_version(version.parse::<u32>().unwrap_or_default()).await?;
if db_wal().exists() {
remove_file(db_wal()).await.map_err(|_| OpenFileError)?;
}
if db_shm().exists() {
remove_file(db_shm()).await.map_err(|_| OpenFileError)?;
}
Ok(()) Ok(())
} }
+2 -3
View File
@@ -2,10 +2,9 @@ use crate::data::entities::WordGroup;
use crate::data::repositories::{DataRepository, DataRepositoryInner}; use crate::data::repositories::{DataRepository, DataRepositoryInner};
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet}; use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
use rusqlite::{Error, Params, Row}; use rusqlite::{Error, Params, Row};
use crate::data_access_methods;
pub type WordGroupRepository = DataRepository<WordGroup, WordGroupDataLayer>; data_access_methods!(WordGroupDataLayer, WordGroupRepository, WordGroupRepositoryInner, WordGroup, WordGroupQuerySet, WordGroupQuery);
pub type WordGroupRepositoryInner = DataRepositoryInner<WordGroup, WordGroupDataLayer>;
pub type WordGroupDataLayer = SqliteDbLayer<WordGroup, WordGroupQuerySet>;
#[derive(Clone)] #[derive(Clone)]
pub struct WordGroupQuerySet; pub struct WordGroupQuerySet;
+32 -6
View File
@@ -1,11 +1,13 @@
use crate::data::Id;
use crate::data::entities::WordData; use crate::data::entities::WordData;
use crate::data::repositories::{DataRepository, DataRepositoryInner}; use crate::data::repositories::{DataRepository, DataRepositoryInner};
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet}; use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
use litemap::LiteMap;
use rusqlite::{Error, Params, Row}; use rusqlite::{Error, Params, Row};
use crate::data_access_methods;
data_access_methods!(WordDataLayer, WordRepository, WordRepositoryInner, WordData, WordQuerySet, WordQuery);
pub type WordRepository = DataRepository<WordData, WordDataLayer>;
pub type WordRepositoryInner = DataRepositoryInner<WordData, WordDataLayer>;
pub type WordDataLayer = SqliteDbLayer<WordData, WordQuerySet>;
#[derive(Clone)] #[derive(Clone)]
pub struct WordQuerySet; pub struct WordQuerySet;
impl TableAccessQuerySet<WordData> for WordQuerySet { impl TableAccessQuerySet<WordData> for WordQuerySet {
@@ -32,7 +34,7 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
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(&additional).unwrap_or_default(), additional: additional_from_string(additional),
group_id: row.get(5)?, group_id: row.get(5)?,
}) })
} }
@@ -42,7 +44,7 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
&entity.key, &entity.key,
&entity.value, &entity.value,
&entity.tags, &entity.tags,
serde_json::to_string(&entity.additional).unwrap_or_default(), additional_to_string(&entity.additional),
entity.group_id, entity.group_id,
) )
} }
@@ -52,8 +54,32 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
&entity.key, &entity.key,
&entity.value, &entity.value,
&entity.tags, &entity.tags,
serde_json::to_string(&entity.additional).unwrap_or_default(), additional_to_string(&entity.additional),
entity.id, entity.id,
) )
} }
} }
fn additional_to_string(map: &LiteMap<Id, String>) -> String {
let mut parts = Vec::with_capacity(map.len() * 2);
for (id, value) in map {
parts.push(id.to_string());
parts.push(value.clone());
}
parts.join("")
}
fn additional_from_string(data: String) -> LiteMap<Id, String> {
if data.is_empty() {
return LiteMap::new();
}
let parts = data.split('').collect::<Vec<&str>>();
let chunks = parts.chunks(2).collect::<Vec<&[&str]>>();
let mut map = LiteMap::with_capacity(parts.len());
for part in &chunks {
let id: Id = part[0].parse().unwrap();
let value: String = part[1].to_string();
map.insert(id, value);
}
map
}
+8
View File
@@ -16,6 +16,14 @@ pub fn app_data_dir() -> PathBuf {
pub fn db_path() -> PathBuf { pub fn db_path() -> PathBuf {
app_data_dir().join("data.db") app_data_dir().join("data.db")
} }
pub fn db_wal() -> PathBuf {
app_data_dir().join("data.db-wal")
}
pub fn db_shm() -> PathBuf {
app_data_dir().join("data.db-shm")
}
pub fn temp_db_path() -> PathBuf { pub fn temp_db_path() -> PathBuf {
app_data_dir().join("data.db.tmp") app_data_dir().join("data.db.tmp")
} }
+1
View File
@@ -10,6 +10,7 @@ pub mod notification;
mod pages; mod pages;
mod styling; mod styling;
pub mod tests; pub mod tests;
pub mod widgets;
use crate::app::start; use crate::app::start;
use mimalloc::MiMalloc; use mimalloc::MiMalloc;
+18 -10
View File
@@ -1,4 +1,4 @@
use crate::app::{AppState, fill_state}; use crate::app::{fill_state, AppState};
use crate::data_provider::sqlite::create_db; use crate::data_provider::sqlite::create_db;
use crate::data_provider::web_api::{ use crate::data_provider::web_api::{
get_local_version, get_web_version, load_data, set_local_version, get_local_version, get_web_version, load_data, set_local_version,
@@ -12,6 +12,7 @@ use crate::notification::{
}; };
use crate::pages::dictionary::{DictionaryMessage, DictionaryState}; use crate::pages::dictionary::{DictionaryMessage, DictionaryState};
use crate::pages::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState}; use crate::pages::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState};
use crate::pages::exams::{ExamsMessage, ExamsState};
use crate::pages::history::{HistoryMessage, HistoryState}; use crate::pages::history::{HistoryMessage, HistoryState};
use crate::pages::import::{ImportMessage, ImportState}; use crate::pages::import::{ImportMessage, ImportState};
use crate::pages::quiz::{QuizMessage, QuizState}; use crate::pages::quiz::{QuizMessage, QuizState};
@@ -21,7 +22,6 @@ use crate::pages::repetition_settings::{RepetitionSettingsMessage, RepetitionSet
use crate::pages::repetitions::{RepetitionsMessage, RepetitionsState}; use crate::pages::repetitions::{RepetitionsMessage, RepetitionsState};
use crate::pages::selector::{SelectorMessage, SelectorState}; use crate::pages::selector::{SelectorMessage, SelectorState};
use crate::pages::sync::{SyncMessage, SyncState}; use crate::pages::sync::{SyncMessage, SyncState};
use crate::pages::word::{WordMessage, WordState};
use crate::pages::writing::{WritingMessage, WritingState}; use crate::pages::writing::{WritingMessage, WritingState};
use crate::state_navigate_handle; use crate::state_navigate_handle;
use crate::state_update; use crate::state_update;
@@ -33,6 +33,7 @@ use iced::{Element, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use log::{debug, info}; use log::{debug, info};
use std::time::Instant; use std::time::Instant;
use crate::pages::exam::{ExamMessage, ExamState};
impl Default for ScreenState { impl Default for ScreenState {
fn default() -> Self { fn default() -> Self {
@@ -56,11 +57,12 @@ pub enum RootMessage {
Randomizer(RandomizerMessage), Randomizer(RandomizerMessage),
Repetitions(RepetitionsMessage), Repetitions(RepetitionsMessage),
Repetition(RepetitionMessage), Repetition(RepetitionMessage),
Word(WordMessage),
Sync(SyncMessage), Sync(SyncMessage),
History(HistoryMessage), History(HistoryMessage),
RepetitionSettings(RepetitionSettingsMessage), RepetitionSettings(RepetitionSettingsMessage),
Import(ImportMessage), Import(ImportMessage),
Exams(ExamsMessage),
Exam(ExamMessage),
Keyboard(Event), Keyboard(Event),
PushNotification(NotificationRequest), PushNotification(NotificationRequest),
Notification(NotificationMessage), Notification(NotificationMessage),
@@ -78,11 +80,12 @@ pub enum Page {
Randomizer(RandomizerState), Randomizer(RandomizerState),
Repetitions(RepetitionsState), Repetitions(RepetitionsState),
Repetition(RepetitionState), Repetition(RepetitionState),
Word(WordState),
Sync(SyncState), Sync(SyncState),
History(HistoryState), History(HistoryState),
RepetitionSettings(RepetitionSettingsState), RepetitionSettings(RepetitionSettingsState),
Import(ImportState), Import(ImportState),
Exams(ExamsState),
Exam(ExamState),
PreviousPage, PreviousPage,
} }
@@ -182,11 +185,12 @@ impl ScreenState {
Randomizer, Randomizer,
Repetitions, Repetitions,
Repetition, Repetition,
Word,
Sync, Sync,
History, History,
RepetitionSettings, RepetitionSettings,
Import Import,
Exams,
Exam
); );
} }
debug!("Update took {:?}", time.elapsed()); debug!("Update took {:?}", time.elapsed());
@@ -206,11 +210,12 @@ impl ScreenState {
Randomizer, Randomizer,
Repetitions, Repetitions,
Repetition, Repetition,
Word,
Sync, Sync,
History, History,
RepetitionSettings, RepetitionSettings,
Import Import,
Exams,
Exam
) )
} }
@@ -227,11 +232,12 @@ impl ScreenState {
Randomizer, Randomizer,
Repetitions, Repetitions,
Repetition, Repetition,
Word,
Sync, Sync,
History, History,
RepetitionSettings, RepetitionSettings,
Import Import,
Exams,
Exam
); );
let notifications = self.notification_manager.draw().map(Notification); let notifications = self.notification_manager.draw().map(Notification);
@@ -244,6 +250,8 @@ impl ScreenState {
if let Some(page) = self.stack.last_mut() { if let Some(page) = self.stack.last_mut() {
return match page { return match page {
Repetition(page) => page.press(&message), Repetition(page) => page.press(&message),
Dictionary(page) => page.press(&message),
Exam(page) => page.press(&message),
_ => Task::none(), _ => Task::none(),
}; };
} }
+8 -4
View File
@@ -138,8 +138,8 @@ impl NotificationManager {
fn draw_data<'a>(data: &NotificationData) -> Element<'a, NotificationMessage> { fn draw_data<'a>(data: &NotificationData) -> Element<'a, NotificationMessage> {
match data { match data {
NotificationData::DataLoaded => { NotificationData::DataSynced => {
text!("Данные успешно загружены на сервер") text!("Данные успешно синхронизированы")
} }
NotificationData::ImportError => { NotificationData::ImportError => {
text!("Ошибка при импорте данных из Anki") text!("Ошибка при импорте данных из Anki")
@@ -148,7 +148,7 @@ impl NotificationManager {
text!("Неподдерживаемый формат файла .apkg") text!("Неподдерживаемый формат файла .apkg")
} }
NotificationData::OpenFileError => { NotificationData::OpenFileError => {
text!("Ошибка открытия файла пакета") text!("Ошибка открытия файла")
} }
NotificationData::VoiceVoxUnavailable => { NotificationData::VoiceVoxUnavailable => {
text!("Не получается подключиться к VoiceVox") text!("Не получается подключиться к VoiceVox")
@@ -168,6 +168,9 @@ impl NotificationManager {
NotificationData::CompressError => { NotificationData::CompressError => {
text!("Ошибка сжатия или распаковки данных") text!("Ошибка сжатия или распаковки данных")
} }
NotificationData::LocalVersionChanged => {
text!("Локальная версия будет заменена")
}
} }
.width(Fill) .width(Fill)
.into() .into()
@@ -184,7 +187,7 @@ pub enum NotificationRequest {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum NotificationData { pub enum NotificationData {
PermissionDenied, PermissionDenied,
DataLoaded, DataSynced,
ImportError, ImportError,
IncorrectAnkiFile, IncorrectAnkiFile,
OpenFileError, OpenFileError,
@@ -193,6 +196,7 @@ pub enum NotificationData {
DbSaveError, DbSaveError,
DbLoadError, DbLoadError,
CompressError, CompressError,
LocalVersionChanged,
} }
pub type MaybeError = Result<(), NotificationData>; pub type MaybeError = Result<(), NotificationData>;
+2
View File
@@ -11,3 +11,5 @@ pub mod selector;
pub mod sync; pub mod sync;
pub mod word; pub mod word;
pub mod writing; pub mod writing;
pub mod exams;
pub mod exam;
+376 -115
View File
@@ -5,25 +5,35 @@ use crate::data::repositories::{Query, Repository};
use crate::data_provider::word_groups::{WordGroupDataLayer, WordGroupRepositoryInner}; use crate::data_provider::word_groups::{WordGroupDataLayer, WordGroupRepositoryInner};
use crate::data_provider::words::WordDataLayer; use crate::data_provider::words::WordDataLayer;
use crate::data_provider::words::WordRepositoryInner; use crate::data_provider::words::WordRepositoryInner;
use crate::navigation::Page::{Import, Word}; use crate::navigation::Page::Import;
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
use crate::pages::dictionary::BasicWordFields::*;
use crate::pages::dictionary::DictionaryMessage::*; use crate::pages::dictionary::DictionaryMessage::*;
use crate::pages::dictionary::SelectionChangeDirection::*;
use crate::pages::dictionary_quiz::DictionaryQuizState; use crate::pages::dictionary_quiz::DictionaryQuizState;
use crate::pages::import::ImportState; use crate::pages::import::ImportState;
use crate::pages::word::WordState; use crate::pages::word::{WordEditor, WordMessage};
use crate::push_error_task;
use crate::styling::*; use crate::styling::*;
use crate::widgets::hard_mouse_area::hard_mouse_area;
use crate::{jl_button, push_error}; use crate::{jl_button, push_error};
use crate::{jl_text_input, push_error_task};
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;
use iced::widget::button::Style; use iced::widget::button::Style;
use iced::widget::button::{danger, text}; use iced::widget::button::{danger};
use iced::widget::operation::focus;
use iced::widget::space::horizontal; use iced::widget::space::horizontal;
use iced::widget::text_input::Status::Active;
use iced::widget::text_input::default; use iced::widget::text_input::default;
use iced::widget::*; use iced::widget::{row, container, column, text_input, space, button, scrollable, text, Row, checkbox, Column, toggler, lazy};
use iced::{Border, Color, Shadow, Task}; use iced::{Border, Color, Element, Shadow, Task};
use iced_core::Length::Fill; use iced_core::Length::{Fill, FillPortion};
use iced_core::border::Radius;
use iced_core::keyboard::Key::Named;
use iced_core::keyboard::key::Physical::Code;
use iced_core::keyboard::{Event, Modifiers};
use iced_core::{keyboard, Padding, Theme};
use log::info; use log::info;
use rand::random_range; use rand::random_range;
use std::ops::Add; use std::ops::Add;
@@ -43,15 +53,15 @@ pub struct DictionaryState {
auto_save_queue: HashMap<EntityHandle<WordData>, DateTime<Utc>>, auto_save_queue: HashMap<EntityHandle<WordData>, DateTime<Utc>>,
displayed_words_query: Query<WordData, WordRepositoryInner, WordDataLayer>, displayed_words_query: Query<WordData, WordRepositoryInner, WordDataLayer>,
groups_query: Query<WordGroup, WordGroupRepositoryInner, WordGroupDataLayer>, groups_query: Query<WordGroup, WordGroupRepositoryInner, WordGroupDataLayer>,
selected_cell: Option<(EntityHandle<WordData>, BasicWordFields, usize)>,
word_editor: Option<WordEditor<DictionaryMessage>>,
} }
#[derive(Clone)] #[derive(Clone)]
pub enum DictionaryMessage { pub enum DictionaryMessage {
Back, Back,
SetTags(EntityHandle<WordData>, String), ExtendedEdit(EntityHandle<WordData>),
SetKey(EntityHandle<WordData>, String), DeleteWord(EntityHandle<WordData>),
SetValue(EntityHandle<WordData>, String),
WordAction(EntityHandle<WordData>),
NewWord, NewWord,
Include(EntityHandle<WordData>, bool), Include(EntityHandle<WordData>, bool),
IncludeTag(String, bool), IncludeTag(String, bool),
@@ -68,8 +78,31 @@ pub enum DictionaryMessage {
ChangeDirection, ChangeDirection,
TrySave(EntityHandle<WordData>), TrySave(EntityHandle<WordData>),
GotoImport, GotoImport,
SelectField(EntityHandle<WordData>, BasicWordFields, usize),
EditField(String),
ChangeSelectedField(SelectionChangeDirection),
EditorAction(WordMessage),
ExtendedWordEdited,
} }
#[derive(Clone, PartialEq, Eq, Hash, Copy)]
pub enum SelectionChangeDirection {
Next,
Previous,
Forward,
Backward,
}
#[derive(Clone, PartialEq, Eq, Hash, Copy)]
pub enum BasicWordFields {
Key,
Value,
Tags,
TotalLine,
}
const FIELDS: &[BasicWordFields] = &[Key, Value, Tags];
impl NavigatedPage<DictionaryMessage> for DictionaryState { impl NavigatedPage<DictionaryMessage> for DictionaryState {
fn navigate(&mut self, message: &DictionaryMessage) -> Option<Page> { fn navigate(&mut self, message: &DictionaryMessage) -> Option<Page> {
if let Back = message { if let Back = message {
@@ -92,11 +125,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
self.state.clone(), self.state.clone(),
))); )));
} }
if let WordAction(handle) = message
&& handle.real()
{
return Some(Word(WordState::new(*handle, self.state.clone())));
}
if let GotoImport = message { if let GotoImport = message {
return Some(Import(ImportState::new(self.state.clone()))); return Some(Import(ImportState::new(self.state.clone())));
} }
@@ -121,49 +150,11 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
dictionary.create(word); dictionary.create(word);
self.displayed_words_query.load(&dictionary); self.displayed_words_query.load(&dictionary);
} }
ExtendedEdit(i) => {
SetKey(handle, v) => { self.word_editor = Some(self.editor_for_word(i));
let mut dictionary = self.state.dictionary.write(); if let Some((_, _, index)) = self.selected_cell {
dictionary.get_mut_static(handle).unwrap().key = v; self.selected_cell = Some((i, TotalLine, index))
drop(dictionary);
return self.launch_auto_save_offset(handle);
} }
SetValue(handle, v) => {
let mut dictionary = self.state.dictionary.write();
dictionary.get_mut_static(handle).unwrap().value = v;
drop(dictionary);
return self.launch_auto_save_offset(handle);
}
SetTags(i, mut v) => {
{
let mut dictionary = self.state.dictionary.write();
let word = dictionary.get_mut_static(i).unwrap();
let current_tags_value = word.tags.clone();
if v.ends_with(", ") && v.len() < current_tags_value.len() {
v = v[..v.len() - 2].to_string()
}
while let Some(index) = v.find(",,") {
v.remove(index);
}
word.tags = v;
}
self.update_tags();
return self.launch_auto_save_offset(i);
}
WordAction(i) => {
let mut dictionary = self.state.dictionary.write();
if let Err(err) = dictionary.delete(i) {
return push_error_task!(err);
}
self.displayed_words_query.load(&dictionary);
} }
Include(i, b) => { Include(i, b) => {
if b { if b {
@@ -241,18 +232,21 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
self.groups_query.load(&groups); self.groups_query.load(&groups);
} }
self.selected_cell = None;
self.word_editor = None;
self.update_tags() self.update_tags()
} }
ChangeDirection => { ChangeDirection => {
self.reverse_list = !self.reverse_list; self.reverse_list = !self.reverse_list;
} }
TrySave(mut handle) => { TrySave(mut handle) => {
let original = handle;
let now = Utc::now(); let now = Utc::now();
if !self.auto_save_queue.contains_key(&handle) { if !self.auto_save_queue.contains_key(&handle) {
return Task::none(); return Task::none();
} }
if self.auto_save_queue[&handle] <= now { if self.auto_save_queue[&handle] <= now {
self.update_tags();
self.auto_save_queue.remove(&handle); self.auto_save_queue.remove(&handle);
let mut dictionary = self.state.dictionary.write(); let mut dictionary = self.state.dictionary.write();
@@ -261,30 +255,150 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
let _ = dictionary.save(&mut handle); let _ = dictionary.save(&mut handle);
if reload_query { if reload_query {
self.displayed_words_query.load(&dictionary); self.displayed_words_query.load(&dictionary);
if let Some(selected) = self.selected_cell
&& selected.0 == original
{
self.selected_cell = Some((handle, selected.1, selected.2));
if self.word_editor.is_some() {
self.word_editor = Some(self.editor_for_word(handle));
} }
}
}
info!("Saved word");
return Task::none(); return Task::none();
} }
} }
GotoImport => {} GotoImport => {}
SelectField(e, f, index) => {
info!("Editing word {}", e.id);
if self.word_editor.is_some()
&& let Some(selected) = &self.selected_cell
&& selected.0 != e
{
self.word_editor = Some(self.editor_for_word(e));
}
self.selected_cell = Some((e, f, index));
return focus(iced::widget::Id::new("editor"));
}
EditField(value) => {
if let Some(selected) = self.selected_cell.as_ref() {
{
let mut dictionary = self.state.dictionary.write();
let word = dictionary.get_mut_static(selected.0).unwrap();
match selected.1 {
Key => {
word.key = value;
}
Value => {
word.value = value;
}
Tags => {
word.tags = value;
}
_ => {}
}
}
return self.launch_auto_save_offset(selected.0);
}
}
ChangeSelectedField(change) => {
return if let Some(selected) = self.selected_cell {
let update_vertical = move |mut dir: bool| {
if self.reverse_list {
dir = !dir;
}
let new_index = if dir {
selected.2.saturating_add(1)
} else {
selected.2.saturating_sub(1)
};
if new_index < self.displayed_words_query.len() {
return SelectField(
self.displayed_words_query.get(new_index).unwrap(),
selected.1,
new_index,
);
}
SelectField(selected.0, selected.1, selected.2)
};
let update_horizontal = move |dir: bool| {
let current = selected.1;
let delta = if dir { 1 } else { -1 };
let mut index =
FIELDS.iter().position(|&f| f == current).unwrap() as i8 + delta;
if index < 0 {
index = (FIELDS.len() - 1) as i8;
}
if index >= FIELDS.len() as i8 {
index = 0;
}
SelectField(selected.0, FIELDS[index as usize], selected.2)
};
Task::done(RootMessage::Dictionary(match change {
Next => update_vertical(true),
Previous => update_vertical(false),
Forward => update_horizontal(true),
Backward => update_horizontal(false),
}))
} else {
Task::none()
};
}
DeleteWord(i) => {
let mut dictionary = self.state.dictionary.write();
if let Err(err) = dictionary.delete(i) {
return push_error_task!(err);
}
self.displayed_words_query.load(&dictionary);
self.selected_cell = None;
self.word_editor = None;
}
EditorAction(action) => {
let result = self.word_editor.as_mut().unwrap().update(action);
if let Some(result) = result {
match result {
DeleteWord(_) | ExtendedWordEdited => {
return Task::done(RootMessage::Dictionary(result));
}
_ => {}
}
}
}
ExtendedWordEdited => {
let handle = self.word_editor.as_ref().unwrap().word_handle;
return self.launch_auto_save_offset(handle);
}
} }
Task::none() Task::none()
} }
fn view(&self) -> iced::Element<'_, DictionaryMessage> { fn view(&self) -> Element<'_, DictionaryMessage> {
back_overlay( back_overlay(
row![ row![
iced::widget::column![ column![
self.groups_panel(), self.groups_panel(),
column![
row![horizontal().width(8), self.words_list(),], row![horizontal().width(8), self.words_list(),],
self.selection_editor(),
],
row![ row![
self.add_word_button(), self.add_word_button(),
horizontal().width(Fill), horizontal().width(Fill),
button("Импорт").style(text).on_press(GotoImport), button("Импорт").style(button::text).on_press(GotoImport),
] ]
] ]
.spacing(5), .spacing(5)
self.filters(), .width(FillPortion(4)),
self.right_panel(),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.into(), .into(),
@@ -304,12 +418,14 @@ impl DictionaryState {
tag_map: HashMap::new(), tag_map: HashMap::new(),
words_tags: vec![], words_tags: vec![],
reverse: false, reverse: false,
search: "".to_string(), search: String::new(),
no_typing: true, no_typing: true,
reverse_list: true, reverse_list: true,
auto_save_queue: HashMap::new(), auto_save_queue: HashMap::new(),
displayed_words_query: words_query, displayed_words_query: words_query,
groups_query, groups_query,
selected_cell: None,
word_editor: None,
}; };
result.init(); result.init();
@@ -318,6 +434,12 @@ impl DictionaryState {
result result
} }
fn editor_for_word(&self, handle: EntityHandle<WordData>) -> WordEditor<DictionaryMessage> {
WordEditor::new(handle, self.state.clone())
.on_delete(DeleteWord(handle))
.on_edit(ExtendedWordEdited)
}
fn init(&mut self) { fn init(&mut self) {
self.displayed_words_query = self self.displayed_words_query = self
.state .state
@@ -336,16 +458,16 @@ impl DictionaryState {
} }
fn launch_auto_save_offset(&mut self, handle: EntityHandle<WordData>) -> Task<RootMessage> { fn launch_auto_save_offset(&mut self, handle: EntityHandle<WordData>) -> Task<RootMessage> {
let save_time = Utc::now().add(TimeDelta::milliseconds(900)); let save_time = Utc::now().add(TimeDelta::milliseconds(500));
self.auto_save_queue.insert(handle, save_time); self.auto_save_queue.insert(handle, save_time);
let message = RootMessage::Dictionary(TrySave(handle)); let message = RootMessage::Dictionary(TrySave(handle));
Task::perform( Task::perform(
async { tokio::time::sleep(Duration::from_secs(1)).await }, async { tokio::time::sleep(Duration::from_millis(520)).await },
|_| message, |_| message,
) )
} }
fn words_list(&self) -> iced::Element<'_, DictionaryMessage> { fn words_list(&self) -> Element<'_, DictionaryMessage> {
let time = Instant::now(); let time = Instant::now();
let mut col = Column::new().width(Fill); let mut col = Column::new().width(Fill);
@@ -368,12 +490,22 @@ impl DictionaryState {
continue; continue;
} }
let mut selection = None;
if let Some(cell) = self.selected_cell.as_ref()
&& cell.0 == *word_handle
{
selection = Some(cell.1);
}
let word_line_data = WordLineState { let word_line_data = WordLineState {
is_included: self.included.contains(word_handle), is_included: self.included.contains(word_handle),
key: word.key.clone().into(), key: word.key.clone(),
value: word.value.clone().into(), value: word.value.clone(),
tags: word.tags.clone().into(), tags: word.tags.clone(),
handle: *word_handle, handle: *word_handle,
selection,
number: i,
}; };
let lazy_line = lazy(word_line_data, Self::word_line); let lazy_line = lazy(word_line_data, Self::word_line);
@@ -385,7 +517,7 @@ impl DictionaryState {
scrollable(col).height(Fill).into() scrollable(col).height(Fill).into()
} }
fn word_line<'a>(data: &WordLineState) -> Row<'a, DictionaryMessage> { fn word_line<'a>(data: &WordLineState) -> Element<'a, DictionaryMessage> {
let mut line = Row::new().width(Fill).align_y(Center); let mut line = Row::new().width(Fill).align_y(Center);
let handle = data.handle; let handle = data.handle;
line = line.push( line = line.push(
@@ -395,45 +527,51 @@ impl DictionaryState {
.on_toggle(move |b| Include(handle, b)), .on_toggle(move |b| Include(handle, b)),
); );
line = line.push( let field = |placeholder: &str, data: &str, selected: bool| {
text_input("Слово", &data.key) text_input(placeholder, data)
.size(ACCENT_FONT_SIZE) .size(ACCENT_FONT_SIZE)
.width(Fill) .width(Fill)
.on_input(move |string| SetKey(handle, string)) .style(move |x, _| {
.style(|x, status| { let mut default_style = default(x, Active);
let mut default_style = default(x, status);
default_style.border.radius = 0.0.into(); default_style.border.radius = 0.0.into();
if selected {
default_style.border.color = x.extended_palette().secondary.base.color;
default_style.border.width = 3.0_f32;
}
default_style default_style
}), })
};
line = line.push(
hard_mouse_area(field(
"Слово",
&data.key,
data.selection.is_some() && data.selection.unwrap() == Key,
))
.on_press(SelectField(data.handle, Key, data.number)),
); );
line = line.push( line = line.push(
text_input("Перевод", &data.value) hard_mouse_area(field(
.size(ACCENT_FONT_SIZE) "Перевод",
.width(Fill) &data.value,
.on_input(move |string| SetValue(handle, string)) data.selection.is_some() && data.selection.unwrap() == Value,
.style(|x, status| { ))
let mut default_style = default(x, status); .on_press(SelectField(data.handle, Value, data.number)),
default_style.border.radius = 0.0.into();
default_style
}),
); );
line = line.push( line = line.push(
text_input("Теги", data.tags.as_ref()) hard_mouse_area(field(
.size(ACCENT_FONT_SIZE) "Теги",
.width(Fill) &data.tags,
.on_input(move |string| SetTags(handle, string)) data.selection.is_some() && data.selection.unwrap() == Tags,
.style(|x, status| { ))
let mut default_style = default(x, status); .on_press(SelectField(data.handle, Tags, data.number)),
default_style.border.radius = 0.0.into();
default_style
}),
); );
let line_button = || { let line_button = || {
if !data.handle.real() { if !data.handle.real() {
return button("-") return button("-")
.on_press(WordAction(data.handle)) .on_press(DeleteWord(data.handle))
.style(|_x: &Theme, _status: button::Status| Style { .style(|_x: &Theme, _status: button::Status| Style {
background: None, background: None,
text_color: Color::BLACK, text_color: Color::BLACK,
@@ -445,18 +583,48 @@ impl DictionaryState {
} }
button("") button("")
.on_press(WordAction(data.handle)) .on_press(ExtendedEdit(data.handle))
.style(button::primary) .style(button::primary)
.width(15) .width(15)
}; };
line.push(line_button()).push(space().width(10))
let assembled = line.push(line_button()).push(space().width(10));
if let Some(selection) = data.selection
&& selection == TotalLine
{
return container(assembled.padding(Padding {
top: 2.0,
right: 0.0,
bottom: 2.0,
left: 0.0,
}))
.style(|theme: &Theme| {
let mut style = container::Style::default();
style.border.color = theme.extended_palette().secondary.base.color;
style.border.width = 3.0_f32;
style
})
.into();
}
assembled.into()
} }
fn filters(&self) -> iced::Element<'_, DictionaryMessage> { fn right_panel(&self) -> Element<'_, DictionaryMessage> {
if let Some(editor) = &self.word_editor {
container(editor.view().map(EditorAction))
.width(FillPortion(3))
.into()
} else {
self.filters()
}
}
fn filters(&self) -> Element<'_, DictionaryMessage> {
let dict = &self.state.dictionary.read(); let dict = &self.state.dictionary.read();
iced::widget::column![ column![
text_input("Поиск", &self.search) jl_text_input!("Поиск", &self.search)
.on_input(Search) .on_input(Search)
.width(Fill), .width(Fill),
text!("Всего слов: {}", dict.len()), text!("Всего слов: {}", dict.len()),
@@ -473,12 +641,12 @@ impl DictionaryState {
.on_press(GotoTest) .on_press(GotoTest)
.width(Fill), .width(Fill),
] ]
.width(250) .width(FillPortion(1))
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.into() .into()
} }
fn tags_selector(&self) -> iced::Element<'_, DictionaryMessage> { fn tags_selector(&self) -> Element<'_, DictionaryMessage> {
let mut col = Column::new().width(Fill); let mut col = Column::new().width(Fill);
col = col.push( col = col.push(
button("Сбросить") button("Сбросить")
@@ -573,9 +741,47 @@ impl DictionaryState {
info!("Time {}", time.elapsed().as_micros()); info!("Time {}", time.elapsed().as_micros());
} }
fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> { fn selection_editor(&self) -> Element<'_, DictionaryMessage> {
let mut display = String::new();
let mut editable = false;
if let Some(selected) = self.selected_cell.as_ref()
&& selected.1 != TotalLine
{
let mut dictionary = self.state.dictionary.write();
let word = dictionary.get_mut_static(selected.0).unwrap();
match selected.1 {
Key => {
display = word.key.clone();
}
Value => {
display = word.value.clone();
}
Tags => {
display = word.tags.clone();
}
_ => {}
}
editable = true;
}
let mut field = jl_text_input!("", display.as_str())
.width(Fill)
.id(iced::widget::Id::new("editor"))
.style(|theme, status| {
let mut default = default(theme, status);
default.border.radius = Radius::new(0);
default
});
if editable {
field = field.on_input(EditField)
}
field.into()
}
fn groups_panel(&self) -> Element<'_, DictionaryMessage> {
let mut row = Row::new(); let mut row = Row::new();
row = row.push(button("+").style(text).on_press(CreateGroup)); row = row.push(button("+").style(button::text).on_press(CreateGroup));
let groups = &self.state.word_groups.read(); let groups = &self.state.word_groups.read();
@@ -583,7 +789,7 @@ impl DictionaryState {
let group_name = groups.get(&mut group).unwrap().name.clone(); let group_name = groups.get(&mut group).unwrap().name.clone();
row = row.push( row = row.push(
button(text!("{}", group_name)) button(text!("{}", group_name))
.style(text) .style(button::text)
.on_press(SelectGroup(group)), .on_press(SelectGroup(group)),
); );
} }
@@ -591,11 +797,11 @@ impl DictionaryState {
let groups = self.state.word_groups.read(); let groups = self.state.word_groups.read();
let group = groups.get_static(self.selected_group).unwrap(); let group = groups.get_static(self.selected_group).unwrap();
iced::widget::column![ column![
scrollable(row).width(Fill).horizontal(), scrollable(row).width(Fill).horizontal(),
row![ row![
jl_button!("⇳").on_press(ChangeDirection), jl_button!("⇳").on_press(ChangeDirection),
text_input("Название группы слов", &group.name) jl_text_input!("Название группы слов", &group.name)
.on_input(EditGroup) .on_input(EditGroup)
.width(250) .width(250)
.on_submit(SaveGroup), .on_submit(SaveGroup),
@@ -607,7 +813,7 @@ impl DictionaryState {
.into() .into()
} }
fn group_delete_button(&self) -> iced::Element<'_, DictionaryMessage> { fn group_delete_button(&self) -> Element<'_, DictionaryMessage> {
if self.selected_group.real() && self.selected_group.id != 1.into() { if self.selected_group.real() && self.selected_group.id != 1.into() {
button("Удалить").style(danger).on_press(DeleteGroup).into() button("Удалить").style(danger).on_press(DeleteGroup).into()
} else { } else {
@@ -615,7 +821,7 @@ impl DictionaryState {
} }
} }
fn add_word_button(&self) -> iced::Element<'_, DictionaryMessage> { fn add_word_button(&self) -> Element<'_, DictionaryMessage> {
let button = jl_button!("Добавить слово"); let button = jl_button!("Добавить слово");
if self.selected_group.real() { if self.selected_group.real() {
@@ -626,6 +832,59 @@ impl DictionaryState {
} }
} }
impl KeyPressedPage for DictionaryState {
fn press(&mut self, message: &Event) -> Task<RootMessage> {
if let Event::KeyPressed {
key: _,
modified_key: modifier,
physical_key: pk,
location: _,
modifiers: mods,
text: _,
repeat: _,
} = message
&& let Code(code) = pk
{
return match code {
keyboard::key::Code::ArrowDown => {
Task::done(RootMessage::Dictionary(ChangeSelectedField(Next)))
}
keyboard::key::Code::ArrowUp => {
Task::done(RootMessage::Dictionary(ChangeSelectedField(Previous)))
}
keyboard::key::Code::Tab => {
return if *mods == Modifiers::CTRL
&& let Some(selected) = self.selected_cell
{
Task::done(RootMessage::Dictionary(ExtendedEdit(selected.0)))
} else if let Named(keyboard::key::Named::Alt) = modifier {
Task::done(RootMessage::Dictionary(ChangeSelectedField(Backward)))
} else {
Task::done(RootMessage::Dictionary(ChangeSelectedField(Forward)))
};
}
keyboard::key::Code::Escape => {
if self.word_editor.is_some() {
self.word_editor = None;
if let Some(selected) = self.selected_cell
&& selected.1 == TotalLine
{
self.selected_cell = None;
}
} else if self.selected_cell.is_some() {
self.selected_cell = None;
}
Task::none()
}
_ => Task::none(),
};
}
Task::none()
}
}
pub fn split_with_coma(ts: &str) -> Vec<String> { pub fn split_with_coma(ts: &str) -> Vec<String> {
ts.split(',') ts.split(',')
.map(|ts| ts.to_lowercase().trim().to_string()) .map(|ts| ts.to_lowercase().trim().to_string())
@@ -636,8 +895,10 @@ pub fn split_with_coma(ts: &str) -> Vec<String> {
#[derive(Clone, Hash, PartialEq, Eq)] #[derive(Clone, Hash, PartialEq, Eq)]
struct WordLineState { struct WordLineState {
is_included: bool, is_included: bool,
key: Box<str>, key: String,
value: Box<str>, value: String,
tags: Box<str>, tags: String,
handle: EntityHandle<WordData>, handle: EntityHandle<WordData>,
selection: Option<BasicWordFields>,
number: usize,
} }
+5 -5
View File
@@ -1,7 +1,6 @@
use crate::app::AppState; use crate::app::AppState;
use crate::data::entities::{EntityHandle, WordData}; use crate::data::entities::{EntityHandle, WordData};
use crate::data::repositories::Repository; use crate::data::repositories::Repository;
use crate::jl_button;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::RootMessage; use crate::navigation::RootMessage;
use crate::navigation::*; use crate::navigation::*;
@@ -9,9 +8,10 @@ use crate::pages::dictionary::split_with_coma;
use crate::pages::dictionary_quiz::DictionaryQuizMessage::*; use crate::pages::dictionary_quiz::DictionaryQuizMessage::*;
use crate::pages::quiz::Score; use crate::pages::quiz::Score;
use crate::styling::*; use crate::styling::*;
use crate::{jl_button, jl_text_input};
use iced::border::Radius; use iced::border::Radius;
use iced::widget::container::Style; use iced::widget::container::Style;
use iced::widget::{container, row, space, text, text_input, Row}; use iced::widget::{container, row, space, text, Row};
use iced::Background::Color; use iced::Background::Color;
use iced::{alignment, Border, Element, Fill, Task, Theme}; use iced::{alignment, Border, Element, Fill, Task, Theme};
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
@@ -76,7 +76,7 @@ impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
] ]
.align_x(alignment::Horizontal::Center) .align_x(alignment::Horizontal::Center)
.spacing(5), .spacing(5),
text_input("Перевод", &self.answer) jl_text_input!("Перевод", &self.answer)
.size(28) .size(28)
.width(250) .width(250)
.on_input(AnswerChanged) .on_input(AnswerChanged)
@@ -114,9 +114,9 @@ impl DictionaryQuizState {
state, state,
words, words,
current_set: Vec::new(), current_set: Vec::new(),
answer: "".to_string(), answer: String::new(),
view: "---".to_string(), view: "---".to_string(),
correct: "".to_string(), correct: String::new(),
score: Default::default(), score: Default::default(),
is_help: false, is_help: false,
reverse, reverse,
+253
View File
@@ -0,0 +1,253 @@
use crate::app::AppState;
use crate::data::entities::{CustomField, DeckSettings, EntityHandle, ExamEntry, WordData};
use crate::data::repositories::Repository;
use crate::data::Id;
use crate::navigation::Page::PreviousPage;
use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
use crate::pages::exam::ExamMessage::*;
use crate::pages::repetition::play_sound;
use crate::styling::*;
use crate::{push_error, push_error_task};
use iced::widget::space::horizontal;
use iced::widget::{button, column, container, progress_bar, row, text, tooltip};
use iced::{Element, Task};
use iced_core::keyboard::key::Physical::Code;
use iced_core::keyboard::Event;
use iced_core::widget::text::Style;
use iced_core::Alignment::Center;
use iced_core::Length::Fill;
use iced_core::{keyboard, Theme};
use rand::prelude::SliceRandom;
use rand::rng;
use rodio::MixerDeviceSink;
use std::sync::Arc;
pub struct ExamState {
id: Id,
state: AppState,
entries: Vec<ExamEntry>,
total_count: u32,
open: bool,
custom_fields_cache: Vec<CustomField>,
current_word: WordData,
current_exam_entry_handle: EntityHandle<ExamEntry>,
deck: DeckSettings,
can_play: bool,
sink: Arc<Option<MixerDeviceSink>>,
}
#[derive(Clone)]
pub enum ExamMessage {
Back,
Open,
Answer(bool),
Play,
PlayFinished,
}
impl NavigatedPage<ExamMessage> for ExamState {
fn navigate(&mut self, message: &ExamMessage) -> Option<Page> {
if let Back = message {
return Some(PreviousPage);
}
None
}
fn navigated(&mut self) {}
fn update(&mut self, message: ExamMessage) -> Task<RootMessage> {
match message {
Back => {}
Open => {
if self.open {
return Task::none();
}
self.open = true;
}
Answer(answer) => {
if !self.open {
return Task::none();
}
let id = self.current_exam_entry_handle.id;
let mut repo = self.state.exam_entries.write();
repo.set(
&mut self.current_exam_entry_handle,
ExamEntry {
id,
exam_id: self.id,
word_id: self.current_word.id,
status: Some(answer),
},
);
if let Err(err) = repo.save(&mut self.current_exam_entry_handle) {
return push_error_task!(err);
}
drop(repo);
self.open = false;
return self.next();
}
Play => {
if !self.can_play {
return Task::none();
}
self.can_play = false;
let value = self.current_word.key.clone();
if self.deck.require_speech() {
return Task::perform(play_sound(self.sink.clone(), value), |r| match r {
Ok(_) => RootMessage::Exam(PlayFinished),
Err(err) => push_error!(err),
});
}
}
PlayFinished => {
self.can_play = true;
}
}
Task::none()
}
fn view(&self) -> Element<'_, ExamMessage> {
back_overlay(
column![
column![
progress_bar(
0.0..=(self.total_count as f32),
(self.total_count - self.entries.len() as u32) as f32
),
row![
text!("Решено: {}", self.total_count - self.entries.len() as u32),
horizontal().width(Fill),
text!("Осталось: {}", self.entries.len())
],
],
crate::widgets::card_display::word_display(
&self.deck,
&self.current_word,
self.open,
Play,
self.custom_fields_cache.as_slice()
),
container(self.answer_bar())
.width(Fill)
.align_x(Center)
.height(80),
]
.into(),
Back,
)
}
}
impl ExamState {
fn answer_bar(&self) -> Element<'_, ExamMessage> {
if !self.open {
return text!("Нажмите Пробел для открытия карточки")
.style(|theme: &Theme| Style {
color: Some(theme.palette().text.scale_alpha(0.3)),
})
.into();
}
row![
tooltip(
button("Не знаю").on_press(Answer(false)),
"Клавиша 1",
tooltip::Position::Top
),
tooltip(
button("Знаю").on_press(Answer(true)),
"Клавиша 2",
tooltip::Position::Top
),
]
.spacing(QUARTER_SPACING)
.into()
}
}
impl ExamState {
pub fn new(exam_id: Id, deck: DeckSettings, state: &AppState) -> Self {
let custom_fields_cache = state.custom_fields.read().iter().cloned().collect();
let sink_handle = if deck.require_speech() {
rodio::DeviceSinkBuilder::open_default_sink().ok()
} else {
None
};
let mut entries: Vec<_> = state
.exam_entries
.read()
.iter()
.filter(|e| e.exam_id == exam_id)
.cloned()
.collect();
let total_count = entries.len() as u32;
entries.retain(|e| e.status.is_none());
entries.shuffle(&mut rng());
let word = state
.dictionary
.read()
.get_static(EntityHandle::from_id(entries.last().unwrap().word_id))
.unwrap();
Self {
id: exam_id,
state: state.clone(),
current_word: word,
current_exam_entry_handle: EntityHandle::from_id(entries.last().unwrap().id),
entries,
total_count,
open: false,
custom_fields_cache,
deck,
can_play: true,
sink: Arc::new(sink_handle),
}
}
fn next(&mut self) -> Task<RootMessage> {
self.entries.pop().unwrap();
if self.entries.is_empty() {
return Task::done(RootMessage::Exam(Back));
}
let entry = self.entries.last().unwrap();
let handle: EntityHandle<ExamEntry> = EntityHandle::from_id(entry.id);
let word = self
.state
.dictionary
.read()
.get_static(EntityHandle::from_id(entry.word_id))
.unwrap();
self.current_word = word;
self.current_exam_entry_handle = handle;
Task::none()
}
}
impl KeyPressedPage for ExamState {
fn press(&mut self, message: &Event) -> Task<RootMessage> {
if let Event::KeyPressed {
key: _,
modified_key: _,
physical_key: pk,
location: _,
modifiers: _,
text: _,
repeat: _,
} = message
&& let Code(code) = pk
{
return match code {
keyboard::key::Code::Space => Task::done(RootMessage::Exam(Open)),
keyboard::key::Code::Digit1 => Task::done(RootMessage::Exam(Answer(false))),
keyboard::key::Code::Digit2 => Task::done(RootMessage::Exam(Answer(true))),
_ => Task::none(),
};
}
Task::none()
}
}
+440
View File
@@ -0,0 +1,440 @@
use crate::app::AppState;
use crate::data::entities::{DeckSettings, EntityHandle, Exam, ExamEntry, WordData};
use crate::data::repositories::{BatchedRepository, Repository};
use crate::data::Id;
use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::MaybeError;
use crate::pages::exam::ExamState;
use crate::pages::exams::ExamsMessage::*;
use crate::pages::repetitions::Style;
use crate::push_error;
use crate::styling::{
back_overlay, cta_button, BUTTON_RADIUS, DEFAULT_SPACING, HALF_SPACING, QUARTER_SPACING,
};
use crate::{jl_button, push_error_task};
use chrono::{Local, Utc};
use iced::widget::button::Status;
use iced::widget::container::bordered_box;
use iced::widget::space::horizontal;
use iced::widget::{
button, center_x, column, container, row, rule, scrollable, space, text, tooltip,
Column,
};
use iced::{Element, Task};
use iced_core::Alignment::*;
use iced_core::Length::{Fill, FillPortion};
use iced_core::{Background, Border, Color, Shadow, Theme};
use std::collections::BTreeMap;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
pub struct ExamsState {
state: AppState,
deck_id: EntityHandle<DeckSettings>,
deck: DeckSettings,
selected_exam_id: Option<EntityHandle<Exam>>,
exams: BTreeMap<EntityHandle<Exam>, ExamExtended>,
}
#[derive(Clone, Eq, PartialEq)]
pub enum ExamsMessage {
Back,
SelectExam(EntityHandle<Exam>),
CreateExam,
GotoExam,
}
impl NavigatedPage<ExamsMessage> for ExamsState {
fn navigate(&mut self, message: &ExamsMessage) -> Option<Page> {
if let Back = message {
return Some(PreviousPage);
}
if let Some(selected_exam_id) = self.selected_exam_id
&& GotoExam == *message
{
return Some(Page::Exam(ExamState::new(
selected_exam_id.id,
self.deck.clone(),
&self.state,
)));
}
None
}
fn navigated(&mut self) {
self.exams = Self::get_exams_list(&self.state, self.deck_id.id);
}
fn update(&mut self, message: ExamsMessage) -> Task<RootMessage> {
match message {
Back => {}
GotoExam => {}
SelectExam(id) => {
self.selected_exam_id = Some(id);
}
CreateExam => {
let exam = Exam {
id: Default::default(),
timestamp: Utc::now(),
deck_id: self.deck_id.id,
};
let mut exam_repo = self.state.exam.write();
let handle = exam_repo.create_now(exam);
if let Ok(handle) = handle {
drop(exam_repo);
if let Err(err) = self.append_exam_entries(handle) {
return push_error_task!(err);
}
self.exams = Self::get_exams_list(&self.state, self.deck_id.id);
self.selected_exam_id = Some(handle);
} else {
return push_error_task!(handle.err().unwrap());
}
}
}
Task::none()
}
fn view(&self) -> Element<'_, ExamsMessage> {
back_overlay(
column![
text(format!("Экзамены для колоды {}", self.deck.name)),
row![
column![
scrollable(self.exams_list()).height(Fill),
jl_button!("Добавить").width(Fill).on_press(CreateExam),
]
.spacing(DEFAULT_SPACING)
.width(FillPortion(1)),
self.selected_exam_view(),
].spacing(DEFAULT_SPACING)
]
.into(),
Back,
)
}
}
impl ExamsState {
pub fn new(deck_id: EntityHandle<DeckSettings>, state: AppState) -> Self {
let deck = state.decks.read().get_static(deck_id).unwrap();
Self {
exams: Self::get_exams_list(&state, deck_id.id),
state,
deck_id,
deck,
selected_exam_id: None,
}
}
fn selected_exam(&self) -> Option<&ExamExtended> {
self.exams.get(&self.selected_exam_id?)
}
fn append_exam_entries(&mut self, handle: EntityHandle<Exam>) -> MaybeError {
let deck_id = self.deck_id.id;
let words: Vec<_> = self
.state
.card_states
.read()
.iter()
.filter(|state| state.deck_id == deck_id)
.map(|state| state.word_id)
.collect();
let mut entries = words
.iter()
.map(|word_id| ExamEntry {
id: Default::default(),
exam_id: handle.id,
word_id: *word_id,
status: None,
})
.collect::<Vec<_>>();
self.state
.exam_entries
.write()
.create_now_many(entries.as_mut_slice())?;
Ok(())
}
fn get_exams_list(state: &AppState, deck_id: Id) -> BTreeMap<EntityHandle<Exam>, ExamExtended> {
let mut query = state
.exam
.read()
.query(Arc::new(move |exam| exam.deck_id == deck_id));
let handles: Vec<_> = query.handles().collect();
query
.iter(&state.exam.read())
.cloned()
.zip(handles)
.map(|(e, h)| (h, ExamExtended::from(e, state)))
.collect()
}
}
impl ExamsState {
pub fn exams_list(&self) -> Column<'_, ExamsMessage> {
let mut column = Column::new();
for (handle, deck) in self.exams.iter() {
column = column.push(
jl_button!(text!(
"{}",
&deck
.timestamp
.with_timezone(&Local)
.format("%d/%m/%Y %H:%M")
))
.on_press_with(move || SelectExam(*handle))
.style(move |_x: &Theme, status: Status| Style {
background: if status == Status::Hovered {
Some(Background::Color(Color::WHITE.scale_alpha(0.2)))
} else {
None
},
text_color: if deck.finished() {
_x.palette().success
} else {
_x.palette().primary
},
border: Border {
color: Default::default(),
width: 0.0,
radius: BUTTON_RADIUS.into(),
},
shadow: Shadow::default(),
snap: false,
}),
);
}
column
}
pub fn selected_exam_view(&self) -> Element<'_, ExamsMessage> {
if let Some(exam) = self.selected_exam() {
return column![
center_x(text!(
"Экзамен от {}",
exam.timestamp
.with_timezone(&Local)
.format("%d/%m/%Y %H:%M")
)),
row![text!("{} карточек", exam.total), Self::exam_bar(exam)]
.height(30)
.align_y(Center)
.width(Fill)
.spacing(HALF_SPACING),
rule::horizontal(2),
self.exam_variable_view(exam),
]
.spacing(DEFAULT_SPACING)
.width(FillPortion(2))
.into();
}
space().width(FillPortion(3)).into()
}
fn exam_bar(exam: &ExamExtended) -> Element<'_, ExamsMessage> {
let total = 1000.0;
let answered = (exam.answered as f64 / exam.total as f64 * total).round();
let unknown = (exam.unknown as f64 / exam.total as f64 * total).round();
let remaining = (exam.remaining() as f64 / exam.total as f64 * total).round();
let mut row = row![];
if answered > 0.0 {
row = row.push(tooltip(
container(space())
.height(Fill)
.width(FillPortion(answered as u16))
.style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().success)),
text_color: Default::default(),
border: Default::default(),
shadow: Default::default(),
snap: false,
}),
text!("Правильно: {}% ({})", answered / 10.0, exam.answered),
tooltip::Position::Bottom,
));
}
if unknown > 0.0 {
row = row.push(tooltip(
container(space())
.height(Fill)
.width(FillPortion(unknown as u16))
.style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().danger)),
text_color: Default::default(),
border: Default::default(),
shadow: Default::default(),
snap: false,
}),
text!("Не получилось: {}% ({})", unknown / 10.0, exam.unknown),
tooltip::Position::Bottom,
));
}
if remaining > 0.0 {
row = row.push(tooltip(
container(space())
.height(Fill)
.width(FillPortion(remaining as u16))
.style(|theme: &Theme| container::Style {
background: Some(Background::Color(theme.palette().primary)),
text_color: Default::default(),
border: Default::default(),
shadow: Default::default(),
snap: false,
}),
text!("Осталось {}% ({})", remaining / 10.0, exam.remaining()),
tooltip::Position::Bottom,
));
}
row.width(Fill).height(Fill).into()
}
fn exam_variable_view(&self, exam: &ExamExtended) -> Element<'_, ExamsMessage> {
if exam.finished() {
self.exam_finished_view(exam)
} else {
self.exam_ongoing_view(exam)
}
}
fn exam_finished_view(&self, exam: &ExamExtended) -> Element<'_, ExamsMessage> {
let result = (exam.answered as f64 / exam.total as f64 * 1000.0).round() / 10.0;
let words_repo = self.state.dictionary.read();
column![
center_x(text!("Итоговый результат: {}%", result).size(28)),
row![
Self::words_list(
"Правильно",
exam.answered_list
.iter()
.map(|handle| words_repo.get_ref_static(*handle).unwrap())
.collect::<Vec<_>>()
.as_slice()
)
.width(Fill),
Self::words_list(
"Не получилось",
exam.unknows_list
.iter()
.map(|handle| words_repo.get_ref_static(*handle).unwrap())
.collect::<Vec<_>>()
.as_slice()
)
.width(Fill)
]
.width(Fill)
.spacing(QUARTER_SPACING)
]
.spacing(DEFAULT_SPACING)
.into()
}
fn exam_ongoing_view(&self, _: &ExamExtended) -> Element<'_, ExamsMessage> {
center_x(
button("Продолжить экзамен")
.style(cta_button)
.on_press(GotoExam),
)
.into()
}
fn words_list<'a>(name: &str, words: &[&WordData]) -> Column<'a, ExamsMessage> {
let mut column = column![];
for word in words {
let container = container(
column![text!("{}", word.key), text!("{}", word.value)].padding(QUARTER_SPACING),
)
.width(Fill)
.style(bordered_box);
column = column.push(container);
}
column![
text!("{}", name),
scrollable(row![
column.spacing(QUARTER_SPACING),
horizontal().width(DEFAULT_SPACING)
])
]
.align_x(Center)
}
}
struct ExamExtended {
exam: Exam,
total: u32,
answered: u32,
unknown: u32,
answered_list: Vec<EntityHandle<WordData>>,
unknows_list: Vec<EntityHandle<WordData>>,
}
impl ExamExtended {
fn from(exam: Exam, state: &AppState) -> Self {
let entries = state.exam_entries.read();
let mut total = 0;
let mut answered = 0;
let mut unknown = 0;
let mut answered_list = Vec::with_capacity(128);
let mut unknows_list = Vec::with_capacity(128);
entries
.iter()
.filter(|e| e.exam_id == exam.id)
.for_each(|e| {
total += 1;
match e.status {
None => {}
Some(s) => {
if s {
answered += 1;
answered_list.push(EntityHandle::from_id(e.word_id));
} else {
unknown += 1;
unknows_list.push(EntityHandle::from_id(e.word_id));
}
}
}
});
Self {
exam,
total,
answered,
unknown,
answered_list,
unknows_list,
}
}
fn solved(&self) -> u32 {
self.answered + self.unknown
}
fn finished(&self) -> bool {
self.solved() == self.total
}
fn remaining(&self) -> u32 {
self.total - self.solved()
}
}
impl Deref for ExamExtended {
type Target = Exam;
fn deref(&self) -> &Self::Target {
&self.exam
}
}
impl DerefMut for ExamExtended {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.exam
}
}
+5 -6
View File
@@ -49,7 +49,7 @@ impl HistoryState {
let history_repo = &mut state.history.write(); let history_repo = &mut state.history.write();
history_repo.init().expect("TODO: panic message"); history_repo.init().expect("TODO: panic message");
let mut history = history_repo.query(Arc::new(move |h| h.deck_id == id)); let mut history = history_repo.query(Arc::new(move |h| h.deck_id == id));
let words = history let mut words: Vec<_> = history
.iter(history_repo) .iter(history_repo)
.map(|item| { .map(|item| {
let handle = dict.handle_by_id(item.word_id); let handle = dict.handle_by_id(item.word_id);
@@ -57,16 +57,15 @@ impl HistoryState {
id: Default::default(), id: Default::default(),
group_id: Default::default(), group_id: Default::default(),
key: "Удаленное слово".to_string(), key: "Удаленное слово".to_string(),
value: "".to_string(), value: String::new(),
tags: "".to_string(), tags: String::new(),
additional: Default::default(), additional: Default::default(),
}); });
(word, item.clone()) (word, item.clone())
}) })
.collect(); .collect();
Self { words.reverse();
list: words, Self { list: words }
}
} }
fn history_lines(&self) -> Column<'_, HistoryMessage> { fn history_lines(&self) -> Column<'_, HistoryMessage> {
+70 -18
View File
@@ -1,20 +1,21 @@
use crate::app::AppState; use crate::app::AppState;
use crate::data::entities::WordData; use crate::data::Id;
use crate::data::entities::WordGroup; use crate::data::entities::WordGroup;
use crate::data::entities::{CustomField, WordData};
use crate::data::repositories::{BatchedRepository, Repository}; use crate::data::repositories::{BatchedRepository, Repository};
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::fs::*; use crate::fs::*;
use crate::jl_button;
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::NotificationData::OpenFileError; use crate::notification::NotificationData::{CompressError, OpenFileError};
use crate::notification::{MaybeError, NotificationData}; use crate::notification::{MaybeError, NotificationData};
use crate::pages::import::ImportMessage::*; use crate::pages::import::ImportMessage::*;
use crate::push_error;
use crate::styling::*; use crate::styling::*;
use crate::{jl_button, push_error_task};
use crate::{jl_text_input, push_error};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::container::success; use iced::widget::container::success;
use iced::widget::{ use iced::widget::{
Row, button, checkbox, column, container, progress_bar, row, rule, text, text_input, Row, button, checkbox, column, container, progress_bar, row, rule, text,
}; };
use iced::widget::{scrollable, space}; use iced::widget::{scrollable, space};
use iced::{Element, Task}; use iced::{Element, Task};
@@ -25,12 +26,14 @@ use log::info;
use parking_lot::Mutex; use parking_lot::Mutex;
use rfd::AsyncFileDialog; use rfd::AsyncFileDialog;
use rusqlite::Connection; use rusqlite::Connection;
use std::collections::HashMap;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::BufReader; use std::io::BufReader;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use tokio::task::spawn_blocking; use tokio::task::spawn_blocking;
use zip::ZipArchive; use zip::ZipArchive;
use zstd::Decoder;
const DEFAULT_FIELDS: [&str; 6] = ["key", "value", "tags", "reading", "context", "description"]; const DEFAULT_FIELDS: [&str; 6] = ["key", "value", "tags", "reading", "context", "description"];
@@ -266,7 +269,7 @@ impl ImportState {
self.available_properties(), self.available_properties(),
button("Добавить напрямую").on_press(SetupDirect), button("Добавить напрямую").on_press(SetupDirect),
row![ row![
text_input("Пользовательское поле", &self.custom_property_name) jl_text_input!("Пользовательское поле", &self.custom_property_name)
.on_input(EditCustomProperty), .on_input(EditCustomProperty),
button("Установить привязку").on_press(SetupCustomProperty) button("Установить привязку").on_press(SetupCustomProperty)
] ]
@@ -294,7 +297,7 @@ impl ImportState {
.on_toggle(SwitchSkipEmpty), .on_toggle(SwitchSkipEmpty),
column![ column![
text!("Разделитель при множественном объединении"), text!("Разделитель при множественном объединении"),
text_input("", &self.separator).on_input(EditSeparator) jl_text_input!("", &self.separator).on_input(EditSeparator)
] ]
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
@@ -326,7 +329,7 @@ impl ImportState {
import_data: None, import_data: None,
selected_index: 0, selected_index: 0,
selected_property: None, selected_property: None,
custom_property_name: "".to_string(), custom_property_name: String::new(),
skip_empty: true, skip_empty: true,
separator: ", ".to_string(), separator: ", ".to_string(),
progress: None, progress: None,
@@ -360,8 +363,8 @@ impl ImportState {
Task::perform( Task::perform(
async { async {
spawn_blocking(move || { spawn_blocking(move || {
Self::extract_import_file(path)?; let schema = Self::extract_import_file(path)?;
let data = Self::read_import_file()?; let data = Self::read_import_file(schema)?;
Ok(data) Ok(data)
}) })
.await .await
@@ -374,7 +377,7 @@ impl ImportState {
) )
} }
fn extract_import_file(path: PathBuf) -> MaybeError { fn extract_import_file(path: PathBuf) -> Result<AnkiSchema, NotificationData> {
let file = File::open(path).map_err(|_| OpenFileError)?; 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(|_| OpenFileError)?; let mut archive = ZipArchive::new(reader).map_err(|_| OpenFileError)?;
@@ -385,20 +388,24 @@ impl ImportState {
.truncate(true) .truncate(true)
.open(&temp_file_path) .open(&temp_file_path)
.map_err(|_| OpenFileError)?; .map_err(|_| OpenFileError)?;
if let Ok(mut file) = archive.by_name("collection.anki21") { if let Ok(mut file) = archive.by_name("collection.anki21b") {
let mut decoder = Decoder::new(&mut file).map_err(|_| CompressError)?;
std::io::copy(&mut decoder, &mut temp_file).map_err(|_| OpenFileError)?;
Ok(AnkiSchema::Beta)
} else if let Ok(mut file) = archive.by_name("collection.anki21") {
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?; std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
Ok(()) Ok(AnkiSchema::Old)
} 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(|_| OpenFileError)?; std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
Ok(()) Ok(AnkiSchema::Old)
} else { } else {
Err(OpenFileError) Err(OpenFileError)
} }
} }
fn read_import_file() -> Result<ImportData, NotificationData> { fn read_import_file(schema: AnkiSchema) -> Result<ImportData, NotificationData> {
let temp_file_path = temp_import_path(); let temp_file_path = temp_import_path();
let connection = Connection::open(&temp_file_path).map_err(|_| OpenFileError)?; let connection = Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
let data = load_groups(&connection)?; let data = load_groups(&connection, schema)?;
Ok(data) Ok(data)
} }
fn setup_mapping(&mut self, property_name: String) { fn setup_mapping(&mut self, property_name: String) {
@@ -428,7 +435,19 @@ impl ImportState {
let separator = self.separator.clone(); let separator = self.separator.clone();
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 map_indices = Self::get_mapping_indices(&group);
let progress = self.progress.clone().unwrap(); let progress = self.progress.clone().unwrap();
if let Err(err) = Self::ensure_fields(&state, &map_indices) {
return push_error_task!(err);
}
let fields: HashMap<String, Id> = HashMap::from_iter(
state
.custom_fields
.read()
.iter()
.map(|f| (f.identifier.clone(), f.id)),
);
info!("{}", group.name); info!("{}", group.name);
Task::perform( Task::perform(
async move { async move {
@@ -439,7 +458,6 @@ impl ImportState {
let import_list = get_words_of_group(&connection, group.id)?; 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 group_handle; let group_handle;
{ {
let group_entity = WordGroup { let group_entity = WordGroup {
@@ -474,7 +492,7 @@ impl ImportState {
word.tags = collected_string; word.tags = collected_string;
} }
&_ => { &_ => {
word.additional.insert((*dest).clone(), collected_string); word.additional.insert(fields[dest], collected_string);
} }
} }
} }
@@ -554,4 +572,38 @@ impl ImportState {
|_| RootMessage::Import(NextProgress), |_| RootMessage::Import(NextProgress),
) )
} }
fn ensure_fields(
state: &AppState,
import_group: &Vec<(String, Vec<usize>)>,
) -> Result<(), NotificationData> {
let mut fields_repo = state.custom_fields.write();
let mut current_fields: Vec<String> = fields_repo
.iter()
.map(|field| field.identifier.clone())
.collect();
current_fields.append(&mut vec![
"key".to_string(),
"value".to_string(),
"tags".to_string(),
]);
for (field, _) in import_group {
if current_fields.contains(field) {
continue;
}
fields_repo.create_now(CustomField {
id: Default::default(),
name: field.clone(),
identifier: field.clone(),
})?;
}
Ok(())
}
}
pub enum AnkiSchema {
Old,
Beta,
} }
+3 -3
View File
@@ -1,10 +1,10 @@
use crate::app::USER_FONT; use crate::app::USER_FONT;
use crate::core::kana_set::KanaSet; use crate::core::kana_set::KanaSet;
use crate::jl_button;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::pages::quiz::QuizMessage::*; use crate::pages::quiz::QuizMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::{jl_button, jl_text_input};
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;
@@ -77,7 +77,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
] ]
.align_y(alignment::Vertical::Center) .align_y(alignment::Vertical::Center)
.spacing(20), .spacing(20),
text_input("Романдзи", &self.current_roman) jl_text_input!("Романдзи", &self.current_roman)
.size(28) .size(28)
.width(150) .width(150)
.on_input(ContentChanged), .on_input(ContentChanged),
@@ -113,7 +113,7 @@ impl QuizState {
kana: "ぁ".to_string(), kana: "ぁ".to_string(),
correct_roman: "a".to_string(), correct_roman: "a".to_string(),
is_help: false, is_help: false,
current_roman: "".to_string(), current_roman: String::new(),
set: KanaSet::hiragana(), set: KanaSet::hiragana(),
queue: Vec::new(), queue: Vec::new(),
score: Score { score: Score {
+13 -88
View File
@@ -1,22 +1,22 @@
use crate::app::AppState; use crate::app::AppState;
use crate::core::deck::DeckData; use crate::core::deck::DeckData;
use crate::core::srs::WordOpenMode; use crate::core::srs::WordOpenMode;
use crate::data::Id; use crate::data::entities::{CardState, CustomField, WordData};
use crate::data::entities::{CardState, WordData};
use crate::data::repositories::Repository; use crate::data::repositories::Repository;
use crate::data::Id;
use crate::data_provider::voice::get_voice; use crate::data_provider::voice::get_voice;
use crate::jl_button;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage}; use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
use crate::notification::{MaybeError, NotificationData}; use crate::notification::{MaybeError, NotificationData};
use crate::pages::repetition::RepetitionMessage::Play;
use crate::pages::repetitions::DeckRunData; use crate::pages::repetitions::DeckRunData;
use crate::styling::*; use crate::styling::*;
use crate::{push_error, push_error_task}; use crate::{push_error, push_error_task};
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::{Column, button, column, container, row, rule, space, text, tooltip}; use iced::widget::{button, column, container, row, text, tooltip};
use iced::{Element, Fill, Task, Theme, alignment, keyboard}; use iced::{keyboard, Element, Fill, Task, Theme};
use rodio::MixerDeviceSink; use rodio::MixerDeviceSink;
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::Arc; use std::sync::Arc;
@@ -32,6 +32,7 @@ pub struct RepetitionState {
can_play: bool, can_play: bool,
sink: Arc<Option<MixerDeviceSink>>, sink: Arc<Option<MixerDeviceSink>>,
opened: HashSet<Id>, opened: HashSet<Id>,
custom_fields_cache: Vec<CustomField>,
} }
impl NavigatedPage<RepetitionMessage> for RepetitionState { impl NavigatedPage<RepetitionMessage> for RepetitionState {
@@ -49,7 +50,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
RepetitionMessage::Back => {} RepetitionMessage::Back => {}
RepetitionMessage::Next => return self.next(), RepetitionMessage::Next => return self.next(),
RepetitionMessage::Answer(m) => return self.answer(m), RepetitionMessage::Answer(m) => return self.answer(m),
RepetitionMessage::Play => { Play => {
if !self.can_play { if !self.can_play {
return Task::none(); return Task::none();
} }
@@ -73,17 +74,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
fn view(&self) -> Element<'_, RepetitionMessage> { fn view(&self) -> Element<'_, RepetitionMessage> {
back_overlay( back_overlay(
column![ column![
container(self.draw_forward()) crate::widgets::card_display::word_display(&self.settings.general_settings, &self.current_word, self.open, Play, self.custom_fields_cache.as_slice()),
.width(Fill)
.height(Fill)
.align_x(Center)
.align_y(alignment::Vertical::Center),
rule::horizontal(2),
container(self.draw_backward())
.width(Fill)
.height(Fill)
.align_x(Center)
.align_y(alignment::Vertical::Center),
container(self.answer_bar()) container(self.answer_bar())
.width(Fill) .width(Fill)
.align_x(Center) .align_x(Center)
@@ -92,7 +83,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
"Затронуто слов {}, {}%", "Затронуто слов {}, {}%",
self.opened.len(), self.opened.len(),
(self.opened.len() as f32 / self.set.len() as f32 * 10000.0).round() / 100.0 (self.opened.len() as f32 / self.set.len() as f32 * 10000.0).round() / 100.0
) ),
] ]
.height(Fill) .height(Fill)
.width(Fill) .width(Fill)
@@ -117,6 +108,8 @@ impl RepetitionState {
None None
}; };
let custom_fields_cache = state.custom_fields.read().iter().cloned().collect();
Ok(RepetitionState { Ok(RepetitionState {
state, state,
settings: set, settings: set,
@@ -127,6 +120,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(),
custom_fields_cache,
}) })
} }
} }
@@ -169,43 +163,6 @@ impl RepetitionState {
Task::none() Task::none()
} }
fn draw_forward(&self) -> Element<'_, RepetitionMessage> {
self.draw_card_view(self.settings.forward.as_str())
}
fn draw_backward(&self) -> Element<'_, RepetitionMessage> {
if !self.open {
return container(text!("?").size(72))
.width(Fill)
.height(Fill)
.align_y(alignment::Vertical::Center)
.align_x(Center)
.into();
}
self.draw_card_view(self.settings.backward.as_str())
}
fn draw_card_view(&self, properties: &str) -> Element<'_, RepetitionMessage> {
let word = &self.current_word;
let mut col = Column::new();
for view_type in properties.split(" ") {
col = col.push(match view_type {
"key" => self.draw_key(word),
"value" => self.draw_value(word),
"speech" => self.draw_voice(),
"reading" => self.draw_reading(word),
"context" => self.draw_context(word),
"description" => self.draw_description(word),
_ => space().into(),
})
}
col.spacing(DEFAULT_SPACING).align_x(Center).into()
}
fn answer_bar(&self) -> Element<'_, RepetitionMessage> { fn answer_bar(&self) -> Element<'_, RepetitionMessage> {
if !self.open { if !self.open {
return text!("Нажмите Пробел для открытия карточки") return text!("Нажмите Пробел для открытия карточки")
@@ -247,38 +204,6 @@ impl RepetitionState {
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.into() .into()
} }
fn draw_key(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
text!("{}", word.key).size(36).into()
}
fn draw_value(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
text!("{}", word.value).size(24).into()
}
fn draw_voice(&self) -> Element<'_, RepetitionMessage> {
jl_button!("Воспроизвести")
.on_press(RepetitionMessage::Play)
.into()
}
fn draw_reading(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
match word.additional.get("reading") {
None => space().into(),
Some(reading) => text!("{}", reading).size(24).into(),
}
}
fn draw_context(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
match word.additional.get("context") {
None => space().into(),
Some(context) => text!("{}", context).size(24).into(),
}
}
fn draw_description(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
match word.additional.get("description") {
None => space().into(),
Some(context) => text!("{}", context).size(24).into(),
}
}
} }
impl KeyPressedPage for RepetitionState { impl KeyPressedPage for RepetitionState {
@@ -317,7 +242,7 @@ pub enum RepetitionMessage {
PlayFinished, PlayFinished,
} }
async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) -> MaybeError { pub async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) -> MaybeError {
let 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()
+8 -8
View File
@@ -2,20 +2,20 @@ use crate::app::AppState;
use crate::core::deck::DeckData; use crate::core::deck::DeckData;
use crate::data::entities::{DeckSettings, EntityHandle}; use crate::data::entities::{DeckSettings, EntityHandle};
use crate::data::repositories::{BatchedRepository, Repository}; use crate::data::repositories::{BatchedRepository, Repository};
use crate::jl_button;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::MaybeError; use crate::notification::MaybeError;
use crate::pages::repetition_settings::RepetitionSettingsMessage::*; use crate::pages::repetition_settings::RepetitionSettingsMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::{jl_button, jl_text_input};
use crate::{push_error, push_error_task}; use crate::{push_error, push_error_task};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::space::horizontal; use iced::widget::space::horizontal;
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};
use iced::{Element, Task}; use iced::{Element, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use iced_core::{Padding, Theme, color}; use iced_core::{color, Padding, Theme};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -143,22 +143,22 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
column![ column![
column![ column![
text!("Название набора"), text!("Название набора"),
text_input("", &self.settings_data.name).on_input(SetName), jl_text_input!("", &self.settings_data.name).on_input(SetName),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Передняя сторона"), text!("Передняя сторона"),
text_input("", &self.settings_data.forward).on_input(SetForward), jl_text_input!("", &self.settings_data.forward).on_input(SetForward),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Задняя сторона"), text!("Задняя сторона"),
text_input("", &self.settings_data.backward).on_input(SetBackward), jl_text_input!("", &self.settings_data.backward).on_input(SetBackward),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Фильтр"), text!("Фильтр"),
text_input("", &self.settings_data.filter) jl_text_input!("", &self.settings_data.filter)
.style(|x, status| { .style(|x, status| {
let mut primary = Theme::default()(x, status); let mut primary = Theme::default()(x, status);
if !self.correct_filter { if !self.correct_filter {
@@ -220,7 +220,7 @@ fn update_deck_stats(deck: &DeckSettings, state: &AppState) -> MaybeError {
.map(|w| w.id) .map(|w| w.id)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
filtered_words.iter().for_each(|word_id| { filtered_words.iter().for_each(|word_id| {
if let Some(index) = db_stats.iter().position(|stat_id| stat_id.id == *word_id) { if let Some(index) = db_stats.iter().position(|stat_id| stat_id.word_id == *word_id) {
db_stats.remove(index); db_stats.remove(index);
} }
}); });
+17 -11
View File
@@ -3,10 +3,10 @@ use crate::core::deck::DeckData;
use crate::core::srs::{AppendMode, OrderMode}; use crate::core::srs::{AppendMode, OrderMode};
use crate::data::entities::{CardState, DeckSettings, EntityHandle, WordData}; use crate::data::entities::{CardState, DeckSettings, EntityHandle, WordData};
use crate::data::repositories::{BatchedRepository, Repository}; use crate::data::repositories::{BatchedRepository, Repository};
use crate::jl_button; use crate::navigation::Page::{Exams, History, PreviousPage, Repetition, RepetitionSettings};
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::MaybeError; use crate::notification::MaybeError;
use crate::pages::exams::ExamsState;
use crate::pages::history::HistoryState; use crate::pages::history::HistoryState;
use crate::pages::repetition::RepetitionState; use crate::pages::repetition::RepetitionState;
use crate::pages::repetition_settings::RepetitionSettingsState; use crate::pages::repetition_settings::RepetitionSettingsState;
@@ -14,14 +14,14 @@ use crate::pages::repetitions::RepetitionsMessage::*;
use crate::push_error; use crate::push_error;
use crate::push_error_task; use crate::push_error_task;
use crate::styling::*; use crate::styling::*;
use crate::{jl_button, jl_text_input};
use chrono::{Days, Local, Utc}; use chrono::{Days, Local, Utc};
use hashbrown::HashSet; use hashbrown::HashSet;
use iced::widget::button::{danger, Status}; use iced::widget::button::{danger, Status};
pub use iced::widget::button::{Catalog, Style}; pub use iced::widget::button::{Catalog, Style};
use iced::widget::tooltip::Position::Top; use iced::widget::tooltip::Position::Top;
use iced::widget::{ use iced::widget::{
button, column, container, lazy, radio, row, scrollable, space, svg, text, text_input, tooltip, button, column, container, lazy, radio, row, scrollable, space, svg, text, tooltip, Column, Row,
Column, Row,
}; };
use iced::{Background, Border, Center, Color, Element, Fill, Length, Shadow, Task, Theme}; use iced::{Background, Border, Center, Color, Element, Fill, Length, Shadow, Task, Theme};
use iced_core::border::Radius; use iced_core::border::Radius;
@@ -74,9 +74,9 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
self.selected_deck_handle.unwrap(), self.selected_deck_handle.unwrap(),
self.state.clone(), self.state.clone(),
))) )))
} else { } else if let GoToExams = message {
None Some(Exams(ExamsState::new(self.selected_deck_handle.unwrap(), self.state.clone())))
} } else { None }
} }
fn navigated(&mut self) { fn navigated(&mut self) {
if let Some(index) = self.selected_deck_handle { if let Some(index) = self.selected_deck_handle {
@@ -96,6 +96,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
} else { } else {
self.fill_deck_word_indices(); self.fill_deck_word_indices();
} }
_ = self.state.history.write().reload()
} }
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> { fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
match message { match message {
@@ -218,6 +219,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
return push_error_task!(err); return push_error_task!(err);
} }
} }
GoToExams => {}
} }
Task::none() Task::none()
} }
@@ -302,7 +304,7 @@ impl RepetitionsState {
column![ column![
text!("Название набора"), text!("Название набора"),
row![ row![
text_input("", &deck.name).on_input(SetName), jl_text_input!("", &deck.name).on_input(SetName),
button(svg(Handle::from_memory(SETTINGS_ICON))) button(svg(Handle::from_memory(SETTINGS_ICON)))
.width(43) .width(43)
.on_press(GoToSettings), .on_press(GoToSettings),
@@ -315,17 +317,17 @@ impl RepetitionsState {
column![ column![
column![ column![
text!("Передняя сторона"), text!("Передняя сторона"),
text_input("", &deck.forward).on_input(SetForward), jl_text_input!("", &deck.forward).on_input(SetForward),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Задняя сторона"), text!("Задняя сторона"),
text_input("", &deck.backward).on_input(SetBackward), jl_text_input!("", &deck.backward).on_input(SetBackward),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Фильтр"), text!("Фильтр"),
text_input("", &deck.filter).on_input(SetFilter), jl_text_input!("", &deck.filter).on_input(SetFilter),
jl_button!("Проверить фильтр").on_press(TryFilter), jl_button!("Проверить фильтр").on_press(TryFilter),
self.count_view(deck), self.count_view(deck),
] ]
@@ -354,7 +356,10 @@ impl RepetitionsState {
Some(deck.open_mode), Some(deck.open_mode),
SetOpenMode SetOpenMode
), ),
row![
jl_button!("История").on_press(GoToHistory), jl_button!("История").on_press(GoToHistory),
jl_button!("Экзамены").on_press(GoToExams),
].spacing(DEFAULT_SPACING),
] ]
.spacing(HALF_SPACING) .spacing(HALF_SPACING)
} }
@@ -629,6 +634,7 @@ pub enum RepetitionsMessage {
SetOpenMode(OrderMode), SetOpenMode(OrderMode),
SetAppendMode(AppendMode), SetAppendMode(AppendMode),
GoToHistory, GoToHistory,
GoToExams,
GoToSettings, GoToSettings,
AppendWords(usize), AppendWords(usize),
} }
+1 -1
View File
@@ -13,7 +13,7 @@ use crate::pages::writing::WritingState;
use crate::styling::*; use crate::styling::*;
use iced::widget::button::{Status, Style}; use iced::widget::button::{Status, Style};
use iced::widget::*; use iced::widget::*;
use iced::{alignment, Element, Task}; use iced::{Element, Task, alignment};
use iced_core::Alignment::Center; use iced_core::Alignment::Center;
use iced_core::Background; use iced_core::Background;
use iced_core::Color; use iced_core::Color;
+27 -2
View File
@@ -15,6 +15,7 @@ use iced::widget::{button, column, container, progress_bar, row, space, text, to
use iced::{Center, Element, Fill, Font, Length, Task}; use iced::{Center, Element, Fill, Font, Length, Task};
use log::error; use log::error;
use std::time::Duration; use std::time::Duration;
use crate::notification::NotificationData::LocalVersionChanged;
#[derive(Clone)] #[derive(Clone)]
pub enum SyncMessage { pub enum SyncMessage {
@@ -31,11 +32,13 @@ pub enum SyncMessage {
Disable, Disable,
DisableSync, DisableSync,
SwitchAutoSync, SwitchAutoSync,
ResetRealLoad,
} }
pub struct SyncState { pub struct SyncState {
state: AppState, state: AppState,
auto_fetch: bool, auto_fetch: bool,
frozen: bool, frozen: bool,
real_load: bool,
progress: f32, progress: f32,
} }
@@ -99,13 +102,29 @@ impl NavigatedPage<SyncMessage> for SyncState {
return tasks; return tasks;
} }
GetLast => { GetLast => {
if !self.real_load {
self.real_load = true;
return Task::batch([
Task::future(async {
tokio::time::sleep(Duration::from_millis(3000)).await;
RootMessage::Sync(ResetRealLoad)
}),
Task::done(RootMessage::PushNotification(NotificationRequest::Warning(LocalVersionChanged)))
]);
}
self.real_load = false;
let id = self.state.sync_data.read().key.clone().unwrap(); let id = self.state.sync_data.read().key.clone().unwrap();
self.state.connection.lock().finish();
let tasks = Task::batch([ let tasks = Task::batch([
Task::perform( Task::perform(
async { tokio::time::sleep(Duration::from_millis(200)).await }, async { tokio::time::sleep(Duration::from_millis(200)).await },
|_| RootMessage::Sync(NextAnimation), |_| RootMessage::Sync(NextAnimation),
), ),
Task::perform(load_data(id, false), |_| RootMessage::Sync(NetworkFinished)), Task::perform(load_data(id, false), |load_result| match load_result {
Ok(_) => RootMessage::Sync(NetworkFinished),
Err(error) => push_error!(error)
}),
]); ]);
return tasks; return tasks;
@@ -134,7 +153,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
} }
return Task::done(RootMessage::PushNotification(NotificationRequest::Info( return Task::done(RootMessage::PushNotification(NotificationRequest::Info(
NotificationData::DataLoaded, NotificationData::DataSynced,
))); )));
} }
Disable => {} Disable => {}
@@ -166,6 +185,9 @@ impl NavigatedPage<SyncMessage> for SyncState {
return push_error_task!(err); return push_error_task!(err);
} }
} }
ResetRealLoad => {
self.real_load = false;
}
} }
Task::none() Task::none()
} }
@@ -189,6 +211,7 @@ impl SyncState {
auto_fetch, auto_fetch,
state, state,
frozen: false, frozen: false,
real_load: false,
progress: 0.0, progress: 0.0,
} }
} }
@@ -199,6 +222,8 @@ impl SyncState {
self.state.decks.write().reload()?; self.state.decks.write().reload()?;
self.state.dictionary.write().reload()?; self.state.dictionary.write().reload()?;
self.state.history.write().reload()?; self.state.history.write().reload()?;
self.state.exam.write().reload()?;
self.state.exam_entries.write().reload()?;
Ok(()) Ok(())
} }
+125 -147
View File
@@ -1,174 +1,154 @@
use crate::app::AppState; use crate::app::AppState;
use crate::data::entities::{EntityHandle, WordData}; use crate::data::Id;
use crate::navigation::Page::PreviousPage; use crate::data::entities::{CustomField, EntityHandle, WordData};
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::data::repositories::Repository;
use crate::jl_text_input;
use crate::pages::word::WordMessage::*; use crate::pages::word::WordMessage::*;
use crate::styling::*; use crate::styling::*;
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::{button, column, row, space, text, text_input}; use iced::widget::space::horizontal;
use iced::{Element, Fill, Task}; use iced::widget::{button, column, row, rule, scrollable, text};
use iced::{Element, Fill};
use iced_core::Padding;
pub struct WordState { pub struct WordEditor<Message : Clone> {
state: AppState, state: AppState,
handle: EntityHandle<WordData>, pub word_handle: EntityHandle<WordData>,
on_delete: Option<Message>,
on_edit: Option<Message>,
fields: Vec<CustomField>,
} }
impl NavigatedPage<WordMessage> for WordState { impl<Message: std::clone::Clone> WordEditor<Message> {
fn navigate(&mut self, message: &WordMessage) -> Option<Page> { pub(crate) fn update(&mut self, message: WordMessage) -> Option<Message> {
if let Back = message { let dictionary = &mut self.state.dictionary.write();
Some(PreviousPage) let word = dictionary.get_mut(&mut self.word_handle).unwrap();
} else { match message {
None Delete => {
return self.on_delete.clone();
}
SetTags(n) => word.tags = n,
SetKey(n) => {
word.key = n;
}
SetValue(n) => {
word.value = n;
}
SetAdditional(key, value) => {
word.additional.insert(key, value.replace("", ""));
}
AddAdditional(key) => {
word.additional.insert(key, String::new());
}
RemoveAdditional(key) => {
word.additional.remove(&key);
}
}
self.on_edit.clone()
}
pub(crate) fn view(&self) -> Element<'_, WordMessage> {
let mut fast_add = row![];
let word = self
.state
.dictionary
.read()
.get_static(self.word_handle)
.unwrap();
for field in &self.fields {
if !word.additional.contains_key(&field.id) {
fast_add = fast_add.push(
button(field.name.as_str())
.style(button::text)
.on_press(AddAdditional(field.id)),
);
} }
} }
fn navigated(&mut self) {} let mut col = iced::widget::column![
fn update(&mut self, message: WordMessage) -> Task<RootMessage> { column![
// match message { text!("Ключ"),
// Back => {} jl_text_input!("key", &word.key).on_input(SetKey),
// Save => { ]
// let mut state = self.state.lock(); .spacing(QUARTER_SPACING),
// state.dictionary[self.index] = self.word.clone(); column![
// text!("Значение"),
// if let Err(err) = update_word(&mut self.word, &state.connection) { jl_text_input!("value", &word.value).on_input(SetValue),
// return push_error_task!(err); ]
// } .spacing(QUARTER_SPACING),
// return Task::done(RootMessage::Word(Back)); column![
// } text!("Теги"),
// Delete => { jl_text_input!("tags", &word.tags).on_input(SetTags),
// let mut state = self.state.lock(); ]
// state.dictionary.remove(self.index); .spacing(QUARTER_SPACING),
// if let Err(err) = delete_word(&self.word, &state.connection) { rule::horizontal(2),
// return push_error_task!(err); scrollable(fast_add.padding(Padding {
// } top: 0.0,
// return Task::done(RootMessage::Word(Back)); right: 0.0,
// } bottom: 4.0,
// SetTags(n) => self.word.tags = n, left: 0.0,
// SetKey(n) => { }))
// self.word.key = n; .horizontal(),
// } ];
// SetValue(n) => {
// self.word.value = n; for more in &word.additional {
// } col = col.push(self.get_view_for_more(more));
// SetAdditional(key, value) => {
// self.word.additional.insert(key, value.clone());
// }
// AddAdditional(key) => {
// self.word.additional.insert(key, "".to_string());
// }
// RemoveAdditional(key) => {
// self.word.additional.remove(key.as_str());
// }
// }
Task::none()
} }
fn view(&self) -> Element<'_, WordMessage> { column![
// let mut fast_add = row![]; col.spacing(DEFAULT_SPACING / 2.0).width(Fill).height(Fill),
// if !self.word.additional.contains_key("reading") { row![
// fast_add = fast_add.push( horizontal().width(Fill),
// button("Чтение") button("Удалить").style(danger).on_press(Delete),
// .style(button::text) ]
// .on_press(AddAdditional("reading".to_string())), .spacing(DEFAULT_SPACING)
// ); ]
// } .spacing(DEFAULT_SPACING)
// if !self.word.additional.contains_key("description") { .into()
// fast_add = fast_add.push(
// button("Описание")
// .style(button::text)
// .on_press(AddAdditional("description".to_string())),
// );
// }
//
// if !self.word.additional.contains_key("context") {
// fast_add = fast_add.push(
// button("В контексте")
// .style(button::text)
// .on_press(AddAdditional("context".to_string())),
// );
// }
//
// let mut col = iced::widget::column![
// column![
// text!("Ключ"),
// text_input("key", &self.word.key).on_input(SetKey),
// ]
// .spacing(QUARTER_SPACING),
// column![
// text!("Значение"),
// text_input("value", &self.word.value).on_input(SetValue),
// ]
// .spacing(QUARTER_SPACING),
// column![
// text!("Теги"),
// text_input("tags", &self.word.tags).on_input(SetTags),
// ]
// .spacing(QUARTER_SPACING),
// rule::horizontal(2),
// scrollable(fast_add),
// ];
//
// for more in &self.word.additional {
// col = col.push(self.get_view_for_more(more));
// }
//
// back_overlay(
// column![
// col.spacing(DEFAULT_SPACING / 2.0).width(Fill).height(Fill),
// row![
// button("Сохранить").style(jl_button).on_press(Save),
// button("Удалить").style(danger).on_press(Delete),
// ]
// .spacing(DEFAULT_SPACING)
// ]
// .spacing(DEFAULT_SPACING)
// .into(),
// Back,
// )
space().into()
} }
} }
impl WordState { impl<Message: std::clone::Clone> WordEditor<Message> {
pub fn new(handle: EntityHandle<WordData>, state: AppState) -> Self { pub fn new(handle: EntityHandle<WordData>, state: AppState) -> Self {
Self { state, handle } let fields = state
.custom_fields
.read()
.iter()
.cloned()
.collect::<Vec<_>>();
Self {
state,
word_handle: handle,
on_delete: None,
on_edit: None,
fields,
} }
} }
impl WordState { pub fn on_delete(mut self, message: Message) -> Self {
fn get_view_for_more(&self, value: (&String, &String)) -> Element<'_, WordMessage> { self.on_delete = Some(message);
match value.0.as_str() { self
"reading" => self.reading_field(value.1), }
"description" => self.description_field(value.1), pub fn on_edit(mut self, message: Message) -> Self {
"context" => self.context_field(value.1), self.on_edit = Some(message);
_ => self.additional_field(value.1, value.0.clone(), value.0.clone()), self
} }
} }
fn reading_field(&self, value: &str) -> Element<'_, WordMessage> { impl<Message: std::clone::Clone> WordEditor<Message> {
self.additional_field(value, "Чтение слова".to_string(), "reading".to_string()) fn get_view_for_more(&self, value: (&Id, &String)) -> Element<'_, WordMessage> {
let field = self.fields.iter().find(|f| f.id == *value.0).unwrap();
self.additional_field(value.1, field.name.as_str(), *value.0)
} }
fn description_field(&self, value: &str) -> Element<'_, WordMessage> { fn additional_field(&self, value: &str, name: &str, id: Id) -> Element<'_, WordMessage> {
self.additional_field(value, "Описание".to_string(), "description".to_string())
}
fn context_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "В контексте".to_string(), "context".to_string())
}
fn additional_field(&self, value: &str, name: String, id: String) -> Element<'_, WordMessage> {
column![ column![
text!("{}", name), text!("{}", name),
row![ row![
text_input(id.clone().as_str(), value) jl_text_input!(name, value)
.on_input({ .on_input(move |string| SetAdditional(id, string))
let value = id.clone();
move |string| SetAdditional(value.clone(), string)
})
.width(Fill), .width(Fill),
button("-") button("-").on_press(RemoveAdditional(id)).style(danger),
.on_press(RemoveAdditional(id.clone()))
.style(danger),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
] ]
@@ -179,13 +159,11 @@ impl WordState {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum WordMessage { pub enum WordMessage {
Save,
Back,
Delete, Delete,
SetTags(String), SetTags(String),
SetKey(String), SetKey(String),
SetValue(String), SetValue(String),
AddAdditional(String), AddAdditional(Id),
RemoveAdditional(String), RemoveAdditional(Id),
SetAdditional(String, String), SetAdditional(Id, String),
} }
+6 -6
View File
@@ -65,11 +65,11 @@ impl WritingState {
let mut list = set.list(); let mut list = set.list();
list.shuffle(&mut rand::rng()); list.shuffle(&mut rand::rng());
WritingState { WritingState {
kana: "".to_string(), kana: String::new(),
set: list.clone(), set: list.clone(),
original_set: list, original_set: list,
kana_total: "".to_string(), kana_total: String::new(),
roman_total: "".to_string(), roman_total: String::new(),
next_text: "Дальше".to_string(), next_text: "Дальше".to_string(),
show_all: false, show_all: false,
} }
@@ -79,9 +79,9 @@ impl WritingState {
impl WritingState { impl WritingState {
fn next(&mut self) { fn next(&mut self) {
if self.set.is_empty() { if self.set.is_empty() {
self.kana = "".to_string(); self.kana = String::new();
self.roman_total = "".to_string(); self.roman_total = String::new();
self.kana_total = "".to_string(); self.kana_total = String::new();
self.set = self.original_set.clone(); self.set = self.original_set.clone();
self.set.shuffle(&mut rand::rng()); self.set.shuffle(&mut rand::rng());
+16
View File
@@ -23,6 +23,15 @@ pub fn jl_button_style(theme: &Theme, status: Status) -> Style {
}; };
style style
} }
pub fn jl_text_input_style(
theme: &Theme,
status: iced::widget::text_input::Status,
) -> iced::widget::text_input::Style {
let mut style = iced::widget::text_input::default(theme, status);
style.border.radius = Radius::new(BUTTON_RADIUS);
style
}
pub fn cta_button(theme: &Theme, status: Status) -> Style { pub fn cta_button(theme: &Theme, status: Status) -> Style {
let mut style = secondary(theme, status); let mut style = secondary(theme, status);
style.border.width = 1.0; style.border.width = 1.0;
@@ -37,6 +46,13 @@ macro_rules! jl_button {
}; };
} }
#[macro_export]
macro_rules! jl_text_input {
($placeholder:expr, $content:expr) => {
iced::widget::text_input($placeholder, $content).style($crate::styling::jl_text_input_style)
};
}
pub fn back_overlay<'a, T: Clone + 'a>(content: Element<'a, T>, back_message: T) -> Element<'a, T> { pub fn back_overlay<'a, T: Clone + 'a>(content: Element<'a, T>, back_message: T) -> Element<'a, T> {
container( container(
iced::widget::column![jl_button!("Назад").on_press(back_message), content] iced::widget::column![jl_button!("Назад").on_press(back_message), content]
+107
View File
@@ -0,0 +1,107 @@
use crate::data::entities::{CustomField, DeckSettings, WordData};
use crate::data::Id;
use crate::styling::HALF_SPACING;
use iced::widget::{button, center, column, rule, text};
use iced_core::Alignment::Center;
use iced_core::Length::Fill;
pub fn word_display<'a, T: 'a + Clone>(
deck: &DeckSettings,
word: &WordData,
open: bool,
speech_action: T,
fields_set: &[CustomField],
) -> iced::Element<'a, T> {
column![
forward_side(deck, word, speech_action.clone(), fields_set),
rule::horizontal(2),
backward_side(deck, word, speech_action, fields_set, open)
]
.into()
}
fn forward_side<'a, T: 'a + Clone>(
deck: &DeckSettings,
word: &WordData,
speech_action: T,
fields_set: &[CustomField],
) -> iced::Element<'a, T> {
center(property_draw(
deck.forward.as_str(),
word,
speech_action,
fields_set,
))
.into()
}
fn backward_side<'a, T: 'a + Clone>(
deck: &DeckSettings,
word: &WordData,
speech_action: T,
fields_set: &[CustomField],
open: bool,
) -> iced::Element<'a, T> {
if open {
return center(property_draw(
deck.backward.as_str(),
word,
speech_action,
fields_set,
))
.into();
}
center(text!("?").size(72)).width(Fill).height(Fill).into()
}
fn property_draw<'a, T: 'a + Clone>(
formula: &str,
word: &WordData,
speech_action: T,
fields_set: &[CustomField],
) -> iced::Element<'a, T> {
let mut column = column![];
let parts = formula.split(" ");
println!("{:?}", formula);
for part in parts {
println!("displaying {}", part);
match part {
"key" => column = column.push(text!("{}", word.key).align_x(Center).size(48)),
"value" => column = column.push(text!("{}", word.value).align_x(Center).size(28)),
"tags" => column = column.push(text!("{}", word.tags).align_x(Center).size(28)),
"speech" => {
column = column.push(button("Воспроизвести").on_press(speech_action.clone()))
}
_ => {
if part == "reading"
&& let Some(reading) = word.additional.get(&Id(1))
{
column = column.push(text!("{}", reading).align_x(Center).size(24));
continue
}
if part == "description"
&& let Some(description) = word.additional.get(&Id(2))
{
column = column.push(text!("{}", description).align_x(Center).size(20));
continue
}
if part == "context"
&& let Some(context) = word.additional.get(&Id(3))
{
column = column.push(text!("{}", context).align_x(Center).size(24));
continue
}
let field_id = fields_set.iter().find(|f| f.identifier == part);
if let Some(id) = field_id
&& let Some(custom) = word.additional.get(&id.id)
{
column = column.push(text!("{}", custom).align_x(Center).size(24))
}
}
}
}
column.align_x(Center).spacing(HALF_SPACING).into()
}
+452
View File
@@ -0,0 +1,452 @@
use iced_core::widget::{tree, Operation, Tree};
use iced_core::{
layout, mouse, overlay, renderer, touch, Clipboard, Element, Event, Layout, Length, Point,
Rectangle, Shell, Size, Vector, Widget,
};
pub fn hard_mouse_area<'a, Message, Theme, Renderer>(
widget: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> HardMouseArea<'a, Message, Theme, Renderer>
where
Renderer: iced_core::Renderer,
{
HardMouseArea::new(widget)
}
pub struct HardMouseArea<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> {
content: Element<'a, Message, Theme, Renderer>,
on_press: Option<Message>,
on_release: Option<Message>,
on_double_click: Option<Message>,
on_right_press: Option<Message>,
on_right_release: Option<Message>,
on_middle_press: Option<Message>,
on_middle_release: Option<Message>,
on_scroll: Option<Box<dyn Fn(mouse::ScrollDelta) -> Message + 'a>>,
on_enter: Option<Message>,
on_move: Option<Box<dyn Fn(Point) -> Message + 'a>>,
on_exit: Option<Message>,
interaction: Option<mouse::Interaction>,
}
impl<'a, Message, Theme, Renderer> HardMouseArea<'a, Message, Theme, Renderer> {
/// The message to emit on a left button press.
#[must_use]
pub fn on_press(mut self, message: Message) -> Self {
self.on_press = Some(message);
self
}
/// The message to emit on a left button release.
#[must_use]
pub fn on_release(mut self, message: Message) -> Self {
self.on_release = Some(message);
self
}
/// The message to emit on a double click.
///
/// If you use this with [`on_press`]/[`on_release`], those
/// event will be emit as normal.
///
/// The events stream will be: on_press -> on_release -> on_press
/// -> on_double_click -> on_release -> on_press ...
///
/// [`on_press`]: Self::on_press
/// [`on_release`]: Self::on_release
#[must_use]
pub fn on_double_click(mut self, message: Message) -> Self {
self.on_double_click = Some(message);
self
}
/// The message to emit on a right button press.
#[must_use]
pub fn on_right_press(mut self, message: Message) -> Self {
self.on_right_press = Some(message);
self
}
/// The message to emit on a right button release.
#[must_use]
pub fn on_right_release(mut self, message: Message) -> Self {
self.on_right_release = Some(message);
self
}
/// The message to emit on a middle button press.
#[must_use]
pub fn on_middle_press(mut self, message: Message) -> Self {
self.on_middle_press = Some(message);
self
}
/// The message to emit on a middle button release.
#[must_use]
pub fn on_middle_release(mut self, message: Message) -> Self {
self.on_middle_release = Some(message);
self
}
/// The message to emit when scroll wheel is used
#[must_use]
pub fn on_scroll(mut self, on_scroll: impl Fn(mouse::ScrollDelta) -> Message + 'a) -> Self {
self.on_scroll = Some(Box::new(on_scroll));
self
}
/// The message to emit when the mouse enters the area.
#[must_use]
pub fn on_enter(mut self, message: Message) -> Self {
self.on_enter = Some(message);
self
}
/// The message to emit when the mouse moves in the area.
#[must_use]
pub fn on_move(mut self, on_move: impl Fn(Point) -> Message + 'a) -> Self {
self.on_move = Some(Box::new(on_move));
self
}
/// The message to emit when the mouse exits the area.
#[must_use]
pub fn on_exit(mut self, message: Message) -> Self {
self.on_exit = Some(message);
self
}
/// The [`mouse::Interaction`] to use when hovering the area.
#[must_use]
pub fn interaction(mut self, interaction: mouse::Interaction) -> Self {
self.interaction = Some(interaction);
self
}
}
/// Local state of the [`HardMouseArea`].
#[derive(Default)]
struct State {
is_hovered: bool,
bounds: Rectangle,
cursor_position: Option<Point>,
previous_click: Option<mouse::Click>,
}
impl<'a, Message, Theme, Renderer> HardMouseArea<'a, Message, Theme, Renderer> {
/// Creates a [`HardMouseArea`] with the given content.
pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
HardMouseArea {
content: content.into(),
on_press: None,
on_release: None,
on_double_click: None,
on_right_press: None,
on_right_release: None,
on_middle_press: None,
on_middle_release: None,
on_scroll: None,
on_enter: None,
on_move: None,
on_exit: None,
interaction: None,
}
}
}
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for HardMouseArea<'_, Message, Theme, Renderer>
where
Renderer: renderer::Renderer,
Message: Clone,
{
fn size(&self) -> Size<Length> {
self.content.as_widget().size()
}
fn layout(
&mut self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
self.content
.as_widget_mut()
.layout(&mut tree.children[0], renderer, limits)
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
renderer_style: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
renderer_style,
layout,
cursor,
viewport,
);
}
fn tag(&self) -> tree::Tag {
tree::Tag::of::<State>()
}
fn state(&self) -> tree::State {
tree::State::new(State::default())
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(&self.content)]
}
fn diff(&self, tree: &mut Tree) {
tree.diff_children(std::slice::from_ref(&self.content));
}
fn operate(
&mut self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn Operation,
) {
self.content
.as_widget_mut()
.operate(&mut tree.children[0], layout, renderer, operation);
}
fn update(
&mut self,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
viewport: &Rectangle,
) {
if self.on_move.is_none()
&& let Event::Mouse(mouse::Event::CursorMoved { .. }) = event
{
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
if self.on_enter.is_none()
&& let Event::Mouse(mouse::Event::CursorEntered) = event
{
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
if self.on_exit.is_none()
&& let Event::Mouse(mouse::Event::CursorLeft) = event
{
self.content.as_widget_mut().update(
&mut tree.children[0],
event,
layout,
cursor,
renderer,
clipboard,
shell,
viewport,
);
}
if shell.is_event_captured() {
return;
}
update(self, tree, event, layout, cursor, shell);
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
let content_interaction = self.content.as_widget().mouse_interaction(
&tree.children[0],
layout,
cursor,
viewport,
renderer,
);
match (self.interaction, content_interaction) {
(Some(interaction), mouse::Interaction::None) if cursor.is_over(layout.bounds()) => {
interaction
}
_ => content_interaction,
}
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'b>,
renderer: &Renderer,
viewport: &Rectangle,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout,
renderer,
viewport,
translation,
)
}
}
impl<'a, Message, Theme, Renderer> From<HardMouseArea<'a, Message, Theme, Renderer>>
for Element<'a, Message, Theme, Renderer>
where
Message: 'a + Clone,
Theme: 'a,
Renderer: 'a + renderer::Renderer,
{
fn from(
area: HardMouseArea<'a, Message, Theme, Renderer>,
) -> Element<'a, Message, Theme, Renderer> {
Element::new(area)
}
}
/// Processes the given [`Event`] and updates the [`State`] of an [`HardMouseArea`]
/// accordingly.
fn update<Message: Clone, Theme, Renderer>(
widget: &mut HardMouseArea<'_, Message, Theme, Renderer>,
tree: &mut Tree,
event: &Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
shell: &mut Shell<'_, Message>,
) {
let state: &mut State = tree.state.downcast_mut();
let cursor_position = cursor.position();
let bounds = layout.bounds();
if state.cursor_position != cursor_position || state.bounds != bounds {
let was_hovered = state.is_hovered;
state.is_hovered = cursor.is_over(layout.bounds());
state.cursor_position = cursor_position;
state.bounds = bounds;
match (
widget.on_enter.as_ref(),
widget.on_move.as_ref(),
widget.on_exit.as_ref(),
) {
(Some(on_enter), _, _) if state.is_hovered && !was_hovered => {
shell.publish(on_enter.clone());
}
(_, Some(on_move), _) if state.is_hovered => {
if let Some(position) = cursor.position_in(layout.bounds()) {
shell.publish(on_move(position));
}
}
(_, _, Some(on_exit)) if !state.is_hovered && was_hovered => {
shell.publish(on_exit.clone());
}
_ => {}
}
}
if !cursor.is_over(layout.bounds()) {
return;
}
match event {
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
| Event::Touch(touch::Event::FingerPressed { .. }) => {
if let Some(message) = widget.on_press.as_ref() {
shell.publish(message.clone());
shell.capture_event();
}
if let Some(position) = cursor_position
&& let Some(message) = widget.on_double_click.as_ref()
{
let new_click =
mouse::Click::new(position, mouse::Button::Left, state.previous_click);
if new_click.kind() == mouse::click::Kind::Double {
shell.publish(message.clone());
}
state.previous_click = Some(new_click);
// Even if this is not a double click, but the press is nevertheless
// processed by us and should not be popup to parent widgets.
shell.capture_event();
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
| Event::Touch(touch::Event::FingerLifted { .. }) => {
if let Some(message) = widget.on_release.as_ref() {
shell.publish(message.clone());
}
}
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)) => {
if let Some(message) = widget.on_right_press.as_ref() {
shell.publish(message.clone());
shell.capture_event();
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right)) => {
if let Some(message) = widget.on_right_release.as_ref() {
shell.publish(message.clone());
}
}
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) => {
if let Some(message) = widget.on_middle_press.as_ref() {
shell.publish(message.clone());
shell.capture_event();
}
}
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle)) => {
if let Some(message) = widget.on_middle_release.as_ref() {
shell.publish(message.clone());
}
}
Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
if let Some(on_scroll) = widget.on_scroll.as_ref() {
shell.publish(on_scroll(*delta));
shell.capture_event();
}
}
_ => {}
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod hard_mouse_area;
pub mod card_display;