Author SHA1 Message Date
micialware ac1b516a88 Fixing Into<u32> clippy 2026-08-20 00:18:16 +03:00
micialware 66f8a83dec Migrate to parking_lot 2026-08-20 00:07:09 +03:00
micialware bf805b79e5 Formating with fmt 2026-08-19 23:51:41 +03:00
micialware de2dbaf6c1 Remove silent unwrap in data providers 2026-08-19 23:37:59 +03:00
micialware 01f0999772 Remove many unwrap 2026-08-19 19:21:21 +03:00
micialware 39f8845119 Rewrite for dictionary rw indexer 2026-08-19 18:49:32 +03:00
micialware e7023752f1 Rewrite for dictionary indexer 2026-08-19 18:00:03 +03:00
micialware 746071125a Remove unnecessary into() 2026-08-19 17:39:52 +03:00
micialware bb673ed7c7 Remove debug from repetitions.rs 2026-08-19 17:34:48 +03:00
micialware 98c8093961 Fixing some code problems 2026-08-19 17:33:22 +03:00
micialware a4d77196d0 Small code edit 2026-08-18 17:47:37 +03:00
micialware 4187344a29 Filter check on edit page 2026-08-18 17:45:50 +03:00
micialware d3c28179b6 Use is_valid for Id 2026-08-18 17:31:19 +03:00
micialware 3cd7c12baa Fixing bugs 2026-08-18 17:15:03 +03:00
micialware 306febc514 Rename set to deck in repetitions.rs 2026-08-18 15:16:51 +03:00
micialware 80785ff9e6 Rewrite repetitions page 2026-08-18 15:13:10 +03:00
micialware 9e28b05167 More migration code 2026-08-18 12:58:02 +03:00
micialware 97c76350e1 Migrate to Id type 2026-08-18 12:47:06 +03:00
micialware 99b3818181 Rename and clear bad code 2026-08-18 12:14:35 +03:00
micialware 3fcbd235cf Migrate to hashbrown structures 2026-08-16 23:50:14 +03:00
micialware dcf7352553 Fix windows autofetch 2026-08-16 23:42:56 +03:00
micialware 11b38479c1 Fixing partial adding bug 2026-08-16 14:23:00 +03:00
micialware 51c8d7be74 Adding words by parts 2026-08-15 21:32:24 +03:00
micialware 8f789facd7 Add anki21 format and fix multi import bug 2026-08-15 20:16:48 +03:00
micialware e676898135 Clippy code cleanup 2026-08-15 13:22:59 +03:00
30 changed files with 1344 additions and 1004 deletions
Generated
+27 -1
View File
@@ -73,6 +73,12 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]] [[package]]
name = "alsa" name = "alsa"
version = "0.11.0" version = "0.11.0"
@@ -1750,6 +1756,8 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [ dependencies = [
"allocator-api2",
"equivalent",
"foldhash 0.2.0", "foldhash 0.2.0",
] ]
@@ -2306,17 +2314,19 @@ dependencies = [
"chrono", "chrono",
"criterion", "criterion",
"dirs", "dirs",
"hashbrown 0.17.1",
"hex", "hex",
"iced", "iced",
"iced_core", "iced_core",
"mimalloc", "mimalloc",
"parking_lot",
"rand", "rand",
"rayon",
"reqwest", "reqwest",
"rfd", "rfd",
"rhai", "rhai",
"rodio", "rodio",
"rusqlite", "rusqlite",
"serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tokio", "tokio",
@@ -2783,6 +2793,15 @@ dependencies = [
"jni-sys 0.3.0", "jni-sys 0.3.0",
] ]
[[package]]
name = "no-std-compat"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c"
dependencies = [
"spin",
]
[[package]] [[package]]
name = "num-bigint" name = "num-bigint"
version = "0.4.6" version = "0.4.6"
@@ -3986,6 +4005,7 @@ checksum = "dd4dd0f8c36625202a4ba553c416c19b719947cd2a31d1bda06126e4a5727daf"
dependencies = [ dependencies = [
"ahash", "ahash",
"bitflags 2.10.0", "bitflags 2.10.0",
"no-std-compat",
"num-traits", "num-traits",
"once_cell", "once_cell",
"rhai_codegen", "rhai_codegen",
@@ -4582,6 +4602,12 @@ dependencies = [
"x11rb", "x11rb",
] ]
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]] [[package]]
name = "spirv" name = "spirv"
version = "0.3.0+sdk-1.3.268.0" version = "0.3.0+sdk-1.3.268.0"
+7 -5
View File
@@ -8,9 +8,8 @@ iced = { version = "0.14.0", features = ["tokio", "svg", "lazy"]}
iced_core = "0.14.0" iced_core = "0.14.0"
rand = "0.10.2" rand = "0.10.2"
dirs = "6.0.0" dirs = "6.0.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151" serde_json = "1.0.151"
rhai = "1.25.1" rhai = { version = "1.25.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.4", features = ["json", "stream", "multipart"] } reqwest = { version = "0.13.4", features = ["json", "stream", "multipart"] }
@@ -22,6 +21,9 @@ zstd = "0.13.3"
zip = "8.6.0" zip = "8.6.0"
rfd = "0.17.2" rfd = "0.17.2"
mimalloc = "0.1.52" mimalloc = "0.1.52"
hashbrown = "0.17.1"
rayon = "1.12.0"
parking_lot = "0.12.5"
[profile.super-release] [profile.super-release]
inherits = "release" inherits = "release"
@@ -32,10 +34,10 @@ strip = true
panic = "abort" panic = "abort"
[dev-dependencies] [dev-dependencies]
criterion = "0.8.2" criterion = { version = "0.8.2", features = ["html_reports"] }
[[bench]] [[bench]]
name = "split_bench" # Имя файла в benches/ без расширения name = "map_bench"
harness = false # Отключаем стандартный тестовый раннер harness = false
+126
View File
@@ -0,0 +1,126 @@
use criterion::{Criterion, criterion_group, criterion_main};
use std::collections::HashMap as StdHashMap;
use std::hint::black_box;
use hashbrown::HashMap as BrownHashMap;
const SIZES: [usize; 3] = [5, 10, 50];
const QUERY_COUNT: usize = 4096;
/// Детерминированный ключ ~17 символов, например "key_9e3779b9_0042".
fn make_key(i: u64) -> String {
let h = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
format!("key_{:08x}_{:04}", h & 0xFFFF_FFFF, i)
}
// Для длинных ключей (пути/URL) замени на:
// fn make_key(i: u64) -> String {
// format!(
// "/api/v2/users/{i}/settings/visibility_{:08x}",
// i.wrapping_mul(0x9E37_79B9)
// )
// }
fn make_vec(n: usize) -> Vec<(String, u64)> {
(0..n as u64).map(|i| (make_key(i), i)).collect()
}
fn make_std_map(data: &[(String, u64)]) -> StdHashMap<String, u64> {
data.iter().map(|(k, v)| (k.clone(), *v)).collect()
}
fn make_brown_map(data: &[(String, u64)]) -> BrownHashMap<String, u64> {
data.iter().map(|(k, v)| (k.clone(), *v)).collect()
}
fn make_queries(n: usize, with_misses: bool) -> Vec<String> {
let keys: Vec<String> = (0..n as u64).map(make_key).collect();
let missing = "__missing_key__".to_string();
(0..QUERY_COUNT)
.map(|i| {
if with_misses && i % 16 == 15 {
missing.clone()
} else {
let idx = i.wrapping_mul(2_654_435_761) % n;
keys[idx].clone()
}
})
.collect()
}
fn lookup_std(map: &StdHashMap<String, u64>, queries: &[String]) -> u64 {
let mut sum = 0u64;
for q in queries {
match map.get(black_box(q.as_str())) {
Some(v) => sum = sum.wrapping_add(*v),
None => sum = sum.wrapping_add(1),
}
}
black_box(sum)
}
fn lookup_brown(map: &BrownHashMap<String, u64>, queries: &[String]) -> u64 {
let mut sum = 0u64;
for q in queries {
match map.get(black_box(q.as_str())) {
Some(v) => sum = sum.wrapping_add(*v),
None => sum = sum.wrapping_add(1),
}
}
black_box(sum)
}
fn lookup_vec(data: &[(String, u64)], queries: &[String]) -> u64 {
let mut sum = 0u64;
for q in queries {
let q = black_box(q);
match data.iter().find(|(k, _)| k == q) {
Some((_, v)) => sum = sum.wrapping_add(*v),
None => sum = sum.wrapping_add(1),
}
}
black_box(sum)
}
fn bench(c: &mut Criterion) {
let mut group = c.benchmark_group("map_vs_vec_str");
for n in SIZES {
let vec_data = make_vec(n);
let std_map = make_std_map(&vec_data);
let brown_map = make_brown_map(&vec_data);
let queries_hit = make_queries(n, false);
let queries_mixed = make_queries(n, true);
// std::collections::HashMap (SipHash)
group.bench_function(format!("std_hashmap_hit/{n}"), |b| {
b.iter(|| lookup_std(black_box(&std_map), black_box(&queries_hit)))
});
group.bench_function(format!("std_hashmap_mixed/{n}"), |b| {
b.iter(|| lookup_std(black_box(&std_map), black_box(&queries_mixed)))
});
// hashbrown (SwissTable + foldhash)
group.bench_function(format!("hashbrown_hit/{n}"), |b| {
b.iter(|| lookup_brown(black_box(&brown_map), black_box(&queries_hit)))
});
group.bench_function(format!("hashbrown_mixed/{n}"), |b| {
b.iter(|| lookup_brown(black_box(&brown_map), black_box(&queries_mixed)))
});
// Vec<(String, u64)>, линейный поиск
group.bench_function(format!("vec_linear_hit/{n}"), |b| {
b.iter(|| lookup_vec(black_box(&vec_data), black_box(&queries_hit)))
});
group.bench_function(format!("vec_linear_mixed/{n}"), |b| {
b.iter(|| lookup_vec(black_box(&vec_data), black_box(&queries_mixed)))
});
}
group.finish();
}
criterion_group!(benches, bench);
criterion_main!(benches);
-43
View File
@@ -1,43 +0,0 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn bench_split(c: &mut Criterion) {
let input = "data_1";
c.bench_function("split_with_comma", |b| {
b.iter(|| {
// black_box запрещает компилятору оптимизировать результат
black_box(split_with_coma(black_box(input)))
})
});
}
fn bench_split_new(c: &mut Criterion) {
let input = "data_1";
c.bench_function("split_with_comma gpt", |b| {
b.iter(|| {
// black_box запрещает компилятору оптимизировать результат
black_box(split_with_coma(black_box(input)))
})
});
}
pub fn split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|ts| ts.to_lowercase().trim().to_string())
.filter(|t| !t.is_empty())
.collect::<Vec<String>>()
}
pub fn new_split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|s| s.trim()) // 0 аллокаций, просто срез
.filter(|s| !s.is_empty()) // отбрасываем пустые до аллокации
.map(|s| s.to_lowercase()) // 1 аллокация на валидный токен
.collect()
}
// Можно добавить несколько бенчмарков в группу
criterion_group!(benches, bench_split, bench_split_new);
criterion_main!(benches);
+16 -19
View File
@@ -1,14 +1,14 @@
use crate::lang::SetOrderMode; use crate::lang::{DeckSettings, OrderMode};
use crate::repetitions::CardSetSettings;
use rusqlite::Connection; use rusqlite::Connection;
pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> { pub fn load_sets(connection: &Connection) -> Vec<DeckSettings> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT id, name, forward, backward, filter FROM card_set") .prepare("SELECT id, name, forward, backward, filter FROM card_set")
.unwrap(); .unwrap();
let iter = stmt let iter = stmt
.query_map([], |row| { .query_map([], |row| {
Ok(CardSetSettings { Ok(DeckSettings {
id: row.get(0)?, id: row.get(0)?,
name: row.get(1)?, name: row.get(1)?,
forward: row.get(2)?, forward: row.get(2)?,
@@ -16,7 +16,7 @@ pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> {
filter: row.get(4)?, filter: row.get(4)?,
count: None, count: None,
worst_words_list: None, worst_words_list: None,
open_mode: SetOrderMode::Default, open_mode: OrderMode::Default,
}) })
}) })
.unwrap(); .unwrap();
@@ -29,8 +29,8 @@ pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> {
buffer buffer
} }
pub fn add_set(set: &mut CardSetSettings, connection: &Connection) { pub fn add_set(set: &mut DeckSettings, connection: &Connection) {
let index = connection let index : u32 = connection
.query_row( .query_row(
"INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id", "INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id",
( (
@@ -41,14 +41,14 @@ pub fn add_set(set: &mut CardSetSettings, connection: &Connection) {
), ),
|row| row.get(0) |row| row.get(0)
) )
.unwrap_or_else(|e| {println!("{}", e); 0}); .unwrap();
set.id = index; set.id = index.into();
} }
pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) { pub fn update_deck(set: &mut DeckSettings, connection: &Connection) {
if set.id == 0 { if !set.id.is_valid() {
add_set(set, &connection); add_set(set, connection);
} else { } else {
connection connection
.execute( .execute(
@@ -61,18 +61,15 @@ pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) {
&set.id &set.id
), ),
) )
.unwrap_or_else(|e| {println!("{}", e); 0}); .unwrap();
} }
} }
pub fn delete_set(set: &CardSetSettings, connection: &Connection) { pub fn delete_set(set: &DeckSettings, connection: &Connection) {
if set.id == 0 { if !set.id.is_valid() {
return; return;
} }
connection connection
.execute("DELETE FROM card_set WHERE id = ?1", (&set.id,)) .execute("DELETE FROM card_set WHERE id = ?1", (&set.id,))
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
+32 -65
View File
@@ -1,9 +1,8 @@
use crate::lang::CardStatistics; use crate::lang::{CardStatistics, DeckSettings};
use crate::repetitions::CardSetSettings; use rusqlite::{Connection, params};
use rusqlite::Connection;
use std::time::Instant; use std::time::Instant;
pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec<CardStatistics> { pub fn load_stats_of_deck(set: &DeckSettings, connection: &Connection) -> Vec<CardStatistics> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT id, word_id, score, last_opened FROM card_stats WHERE set_id = ?1") .prepare("SELECT id, word_id, score, last_opened FROM card_stats WHERE set_id = ?1")
.unwrap(); .unwrap();
@@ -27,67 +26,41 @@ pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec<
buffer buffer
} }
pub fn add_stat_list(stat: &mut Vec<CardStatistics>, connection: &Connection) { pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) {
let inserting = stat let time = Instant::now();
.iter() let tx = connection.transaction().unwrap();
.map(|stat| { let count = stats.len();
format!(
"({}, {}, {}, {})", {
stat.word_id.to_string(), let mut stmt = tx
stat.set_id.to_string(), .prepare(
stat.score.to_string(), "INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4)",
stat.last_open.timestamp().to_string()
) )
}) .unwrap();
.collect::<Vec<_>>()
.join(", ");
let query = format!(
"INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES {}",
inserting
);
let count = connection.execute(query.as_str(), ());
if count.is_err() { for stat in stats.iter() {
println!("{}", count.unwrap_err()); stmt.execute(params![
return; stat.word_id,
stat.set_id,
stat.score,
stat.last_open.timestamp()
])
.unwrap();
}
} }
let last_index: u32 = connection let last_index: u32 = tx.last_insert_rowid() as u32;
.query_one( tx.commit().unwrap();
"SELECT seq from sqlite_sequence WHERE name == ?1",
("card_stats".to_string(),),
|row| row.get(0),
)
.unwrap();
let start_index = last_index - (count.unwrap() as u32) + 1; let start_index = last_index - (count as u32) + 1;
let mut index = 0; for (index, id) in (start_index..=last_index).enumerate() {
for id in start_index..=last_index { stats[index].id = id.into();
stat[index].id = id;
index += 1;
} }
println!("Added {} cards for {:?}", stats.len(), time.elapsed());
} }
// pub fn add_stat(stat: &mut CardStatistics, connection: &Connection) {
// let time = Instant::now();
// let index = connection
// .query_row(
// "INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4) RETURNING id",
// (
// &stat.word_id,
// &stat.set_id,
// &stat.score,
// &stat.last_open.timestamp(),
// ),
// |row| row.get(0)
// )
// .unwrap_or_else(|e| {println!("{}", e); 0});
//
// stat.id = index;
// println!("Added stat: {}", time.elapsed().as_millis());
// }
pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) { pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
let time = Instant::now(); let time = Instant::now();
@@ -96,21 +69,15 @@ pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
"UPDATE card_stats SET score = ?1, last_opened = ?2 WHERE id = ?3", "UPDATE card_stats SET score = ?1, last_opened = ?2 WHERE id = ?3",
(&stat.score, &stat.last_open.timestamp(), &stat.id), (&stat.score, &stat.last_open.timestamp(), &stat.id),
) )
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
println!("Updated stat: {}", time.elapsed().as_millis()); println!("Updated stat: {}", time.elapsed().as_millis());
} }
pub fn delete_stat(stat: &CardStatistics, connection: &Connection) { pub fn delete_stat(stat: &CardStatistics, connection: &Connection) {
if stat.id == 0 { if !stat.id.is_valid() {
return; return;
} }
connection connection
.execute("DELETE FROM card_stats WHERE id = ?1", (&stat.id,)) .execute("DELETE FROM card_stats WHERE id = ?1", (&stat.id,))
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
+19 -11
View File
@@ -1,13 +1,13 @@
use std::fs;
use crate::dictionary::app_data_dir; use crate::dictionary::app_data_dir;
use crate::lang::WordOpenMode; use crate::lang::{Id, WordOpenMode};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use std::fs;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::Write; use std::io::Write;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::path::PathBuf; use std::path::PathBuf;
pub fn get_history_of_set(id: u32) -> Vec<HistoryItem> { pub fn get_history_of_set(id: Id) -> Vec<HistoryItem> {
let app_dir = history_dir(); let app_dir = history_dir();
let head = app_dir.clone().join(format!("set_{}_history.csv", id)); let head = app_dir.clone().join(format!("set_{}_history.csv", id));
let mut lines = Vec::new(); let mut lines = Vec::new();
@@ -30,17 +30,25 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
let mut items = Vec::with_capacity(strings.len()); let mut items = Vec::with_capacity(strings.len());
for string in strings { for string in strings {
if let [time, word, mode, before, after] = string.split(';').collect::<Vec<&str>>()[..] { if let [time, word, mode, before, after] = string.split(';').collect::<Vec<&str>>()[..] {
let id = word.parse::<Id>();
if id.is_err() {
continue;
}
let id = id.unwrap();
if !id.is_valid() {
continue;
}
items.push(HistoryItem { items.push(HistoryItem {
timestamp: DateTime::from_timestamp(time.parse().unwrap(), 0).unwrap(), timestamp: DateTime::from_timestamp(time.parse().unwrap_or_default(), 0).unwrap(),
word_id: word.parse::<u32>().unwrap(), word_id: id,
mode: match mode.parse::<u8>().unwrap() { mode: match mode.parse::<u8>().unwrap_or_default() {
2 => WordOpenMode::Hard, 2 => WordOpenMode::Hard,
3 => WordOpenMode::Ok, 3 => WordOpenMode::Ok,
4 => WordOpenMode::Easy, 4 => WordOpenMode::Easy,
_ => WordOpenMode::None, _ => WordOpenMode::None,
}, },
before: before.parse().unwrap(), before: before.parse().unwrap_or_default(),
after: after.parse().unwrap(), after: after.parse().unwrap_or_default(),
}); });
} }
} }
@@ -48,7 +56,7 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
items items
} }
pub fn push_note(set_id: u32, item: HistoryItem) { pub fn push_note(set_id: Id, item: HistoryItem) {
let app_dir = history_dir(); let app_dir = history_dir();
let path = app_dir.clone().join(format!("set_{}_history.csv", set_id)); let path = app_dir.clone().join(format!("set_{}_history.csv", set_id));
@@ -70,7 +78,7 @@ pub fn push_note(set_id: u32, item: HistoryItem) {
item.before, item.before,
item.after item.after
); );
writeln!(&mut file, "{}", line_str.to_string()).unwrap(); writeln!(&mut file, "{}", line_str).unwrap();
} }
pub fn history_dir() -> PathBuf { pub fn history_dir() -> PathBuf {
@@ -84,7 +92,7 @@ pub fn history_dir() -> PathBuf {
#[derive(Clone)] #[derive(Clone)]
pub struct HistoryItem { pub struct HistoryItem {
pub timestamp: DateTime<Utc>, pub timestamp: DateTime<Utc>,
pub word_id: u32, pub word_id: Id,
pub mode: WordOpenMode, pub mode: WordOpenMode,
pub before: u8, pub before: u8,
pub after: u8, pub after: u8,
+15 -10
View File
@@ -1,6 +1,6 @@
use hashbrown::HashMap;
use rusqlite::Connection; use rusqlite::Connection;
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap;
#[derive(Clone)] #[derive(Clone)]
pub struct ImportData(pub(crate) Vec<ImportGroup>); pub struct ImportData(pub(crate) Vec<ImportGroup>);
@@ -12,7 +12,7 @@ pub struct ImportGroup {
pub fields: Vec<String>, pub fields: Vec<String>,
pub length: u64, pub length: u64,
pub mapping: HashMap<String, String>, pub mapping: HashMap<String, String>,
pub imported: bool pub imported: bool,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -68,13 +68,18 @@ pub fn get_words_of_group(connection: &Connection, group_id: u64) -> Vec<ImportN
.prepare("select tags, flds from notes where mid == ?1;") .prepare("select tags, flds from notes where mid == ?1;")
.unwrap(); .unwrap();
count_stmt.query_map((group_id as i64, ), |row| { count_stmt
Ok(ImportNote { .query_map((group_id as i64,), |row| {
tags: row.get(0)?, Ok(ImportNote {
fields: row.get::<usize, String>(1)? tags: row.get(0)?,
.split('') fields: row
.map(|x| x.to_string()) .get::<usize, String>(1)?
.collect() .split('')
.map(|x| x.to_string())
.collect(),
})
}) })
}).unwrap().map(|x| x.unwrap()).collect::<Vec<ImportNote>>() .unwrap()
.map(|x| x.unwrap())
.collect::<Vec<ImportNote>>()
} }
+2 -2
View File
@@ -1,9 +1,9 @@
pub(crate) mod card_sets; pub(crate) mod card_sets;
pub(crate) mod card_stats; pub(crate) mod card_stats;
pub(crate) mod history; pub(crate) mod history;
pub(crate) mod import;
pub(crate) mod settings; pub(crate) mod settings;
pub(crate) mod sqlite; pub(crate) mod sqlite;
pub(crate) mod voice; pub(crate) mod voice;
pub(crate) mod words;
pub(crate) mod web_api; pub(crate) mod web_api;
pub(crate) mod import; pub(crate) mod words;
+9 -18
View File
@@ -4,14 +4,14 @@ pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT value FROM settings WHERE id = ?1") .prepare("SELECT value FROM settings WHERE id = ?1")
.unwrap(); .unwrap();
let iter = stmt.query_map((key,), |row| row.get(0)).unwrap(); let mut iter = stmt.query_map((key,), |row| row.get(0)).unwrap();
for row in iter { if let Some(row) = iter.next()
if let Ok(value) = row { && let Ok(value) = row
return Some(value); {
} return Some(value);
return None;
} }
None None
} }
@@ -27,10 +27,7 @@ pub fn set_setting(key: String, value: String, connection: &Connection) {
pub fn delete_settings(key: String, connection: &Connection) { pub fn delete_settings(key: String, connection: &Connection) {
connection connection
.execute("DELETE FROM settings WHERE id = ?1", (&key,)) .execute("DELETE FROM settings WHERE id = ?1", (&key,))
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
fn create_settings(key: String, value: String, connection: &Connection) { fn create_settings(key: String, value: String, connection: &Connection) {
@@ -39,10 +36,7 @@ fn create_settings(key: String, value: String, connection: &Connection) {
"INSERT into settings (id, value) VALUES (?1, ?2)", "INSERT into settings (id, value) VALUES (?1, ?2)",
(key, value), (key, value),
) )
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
fn update_settings(key: String, value: String, connection: &Connection) { fn update_settings(key: String, value: String, connection: &Connection) {
@@ -53,10 +47,7 @@ set value = ?2
where id = ?1", where id = ?1",
(key, value), (key, value),
) )
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
fn get_settings_list(connection: &Connection) -> Vec<String> { fn get_settings_list(connection: &Connection) -> Vec<String> {
+1 -1
View File
@@ -62,4 +62,4 @@ pub fn default_connection() -> Connection {
let connection = Connection::open(db_file).unwrap(); let connection = Connection::open(db_file).unwrap();
connection.execute("PRAGMA foreign_keys = ON;", []).unwrap(); connection.execute("PRAGMA foreign_keys = ON;", []).unwrap();
connection connection
} }
+44 -11
View File
@@ -2,7 +2,7 @@ use crate::dictionary::app_data_dir;
use std::io; use std::io;
use tokio::fs::{File, OpenOptions}; use tokio::fs::{File, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use zstd::{Decoder, Encoder, DEFAULT_COMPRESSION_LEVEL}; use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
// const API_URL: &str = "http://127.0.0.1:8089/"; // const API_URL: &str = "http://127.0.0.1:8089/";
const API_URL: &str = "https://learning.micialware.ru/"; const API_URL: &str = "https://learning.micialware.ru/";
@@ -17,15 +17,22 @@ pub async fn send_data(id: String) {
let id_url = format!("{api_url}upload/stream/{id}"); let id_url = format!("{api_url}upload/stream/{id}");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let new_version = client.post(&id_url).body(data).send().await.unwrap().text().await.unwrap(); let new_version = client
.post(&id_url)
.body(data)
.send()
.await
.unwrap()
.text()
.await
.unwrap();
set_local_version(new_version.parse::<u32>().unwrap()).await; set_local_version(new_version.parse::<u32>().unwrap()).await;
} }
fn compress(data: Vec<u8>) -> Vec<u8> { fn compress(data: Vec<u8>) -> Vec<u8> {
let mut encoder = Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).unwrap(); let mut encoder = Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).unwrap();
io::copy(&mut &data[..], &mut encoder).unwrap(); io::copy(&mut &data[..], &mut encoder).unwrap();
let compressed = encoder.finish().unwrap(); encoder.finish().unwrap()
compressed
} }
pub async fn load_data(id: String, temp: bool) { pub async fn load_data(id: String, temp: bool) {
@@ -50,7 +57,14 @@ pub async fn load_data(id: String, temp: bool) {
tokio::fs::write(db_file, data).await.unwrap(); tokio::fs::write(db_file, data).await.unwrap();
let version_url = format!("{API_URL}{id}/version"); let version_url = format!("{API_URL}{id}/version");
let version = client.get(&version_url).send().await.unwrap().text().await.unwrap(); let version = client
.get(&version_url)
.send()
.await
.unwrap()
.text()
.await
.unwrap();
set_local_version(version.parse::<u32>().unwrap()).await; set_local_version(version.parse::<u32>().unwrap()).await;
} }
@@ -84,25 +98,44 @@ pub async fn get_web_version(key: &str) -> Result<u32, reqwest::Error> {
let id_url = format!("{API_URL}{key}/version"); let id_url = format!("{API_URL}{key}/version");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let version = client.get(&id_url).send().await?.text().await?; let version = client.get(&id_url).send().await?.text().await?;
return Ok(version.parse::<u32>().unwrap()); println!("version: {}", version);
Ok(version.parse::<u32>().unwrap_or_default())
} }
pub async fn get_local_version() -> u32 { pub async fn get_local_version() -> u32 {
let file = app_data_dir().join("data.meta"); let file = app_data_dir().join("data.meta");
if file.exists() { if file.exists() {
let mut data = String::new(); let mut data = String::new();
File::open(file.clone()).await.unwrap().read_to_string(&mut data).await.unwrap(); File::open(file.clone())
.await
.unwrap()
.read_to_string(&mut data)
.await
.unwrap();
return data.parse::<u32>().unwrap(); return data.parse::<u32>().unwrap();
} }
let mut file = OpenOptions::new().write(true).create(true).open(file).await.unwrap(); let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(file)
.await
.unwrap();
file.write_all("0".as_bytes()).await.unwrap(); file.write_all("0".as_bytes()).await.unwrap();
0 0
} }
pub async fn set_local_version(version: u32) { pub async fn set_local_version(version: u32) {
let file_path = app_data_dir().join("data.meta"); let file_path = app_data_dir().join("data.meta");
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(file_path).await.unwrap(); let mut file = OpenOptions::new()
file.write_all(version.to_string().as_bytes()).await.unwrap(); .write(true)
.create(true)
.truncate(true)
.open(file_path)
.await
.unwrap();
file.write_all(version.to_string().as_bytes())
.await
.unwrap();
} }
+34 -54
View File
@@ -1,9 +1,9 @@
use crate::lang::{WordData, WordGroup}; use crate::lang::{WordData, WordGroup};
use rusqlite::{params, Connection}; use rusqlite::{Connection, params};
use std::collections::HashMap; use std::collections::HashMap;
pub fn add_word(word: &mut WordData, connection: &Connection) { pub fn add_word(word: &mut WordData, connection: &Connection) {
let index = connection let index : u32 = connection
.query_row( .query_row(
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", "INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
( (
@@ -14,52 +14,47 @@ pub fn add_word(word: &mut WordData, connection: &Connection) {
&word.group_id, &word.group_id,
), ),
|row| row.get(0), |row| row.get(0),
) ).unwrap();
.unwrap_or_else(|e| {
println!("{}", e);
0
});
word.id = index; word.id = index.into();
} }
pub fn add_words(words: &mut[WordData], connection: &mut Connection) { pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
let tx = connection.transaction().unwrap(); let tx = connection.transaction().unwrap();
let count = words.len(); let count = words.len();
{ {
let mut stmt = tx.prepare( let mut stmt = tx
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)", .prepare(
).unwrap(); "INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)",
)
.unwrap();
for word in words.iter() { for word in words.iter() {
stmt.execute(params![word.key, word.value, word.tags, serde_json::to_string(&word.additional).unwrap(), word.group_id]).unwrap(); stmt.execute(params![
word.key,
word.value,
word.tags,
serde_json::to_string(&word.additional).unwrap(),
word.group_id
])
.unwrap();
} }
} }
let last_index: u32 = tx.last_insert_rowid() as u32;
tx.commit().unwrap(); tx.commit().unwrap();
let last_index: u32 = connection
.query_one(
"SELECT seq from sqlite_sequence WHERE name == ?1",
("words".to_string(),),
|row| row.get(0),
)
.unwrap();
let start_index = last_index - (count as u32) + 1; let start_index = last_index - (count as u32) + 1;
let mut index = 0; for (index, id) in (start_index..=last_index).enumerate() {
for id in start_index..=last_index { words[index].id = id.into();
words[index].id = id;
index += 1;
} }
} }
pub fn update_word(word: &mut WordData, connection: &Connection) { pub fn update_word(word: &mut WordData, connection: &Connection) {
if word.id == 0 { if !word.id.is_valid() {
add_word(word, &connection); add_word(word, connection);
} else { } else {
connection connection
.execute( .execute(
@@ -72,23 +67,17 @@ pub fn update_word(word: &mut WordData, connection: &Connection) {
&word.id, &word.id,
), ),
) )
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
} }
pub fn delete_word(word: &WordData, connection: &Connection) { pub fn delete_word(word: &WordData, connection: &Connection) {
if word.id == 0 { if !word.id.is_valid() {
return; return;
} }
connection connection
.execute("DELETE FROM words WHERE id = ?1", (&word.id,)) .execute("DELETE FROM words WHERE id = ?1", (&word.id,))
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
pub fn load_words(connection: &Connection) -> Vec<WordData> { pub fn load_words(connection: &Connection) -> Vec<WordData> {
@@ -139,44 +128,35 @@ pub fn load_word_groups(connection: &Connection) -> Vec<WordGroup> {
} }
pub fn add_group(group: &mut WordGroup, connection: &Connection) { pub fn add_group(group: &mut WordGroup, connection: &Connection) {
let index = connection let index: u32 = connection
.query_row( .query_row(
"INSERT INTO word_group (name) VALUES (?1) RETURNING id", "INSERT INTO word_group (name) VALUES (?1) RETURNING id",
(&group.name,), (&group.name,),
|row| row.get(0), |row| row.get(0),
) )
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
group.id = index; group.id = index.into();
} }
pub fn update_group(group: &mut WordGroup, connection: &Connection) { pub fn update_group(group: &mut WordGroup, connection: &Connection) {
if group.id == 0 { if !group.id.is_valid() {
add_group(group, &connection); add_group(group, connection);
} else { } else {
connection connection
.execute( .execute(
"UPDATE word_group SET name = ?1 WHERE id = ?2", "UPDATE word_group SET name = ?1 WHERE id = ?2",
(&group.name, &group.id), (&group.name, &group.id),
) )
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
} }
pub fn delete_group(group: &WordGroup, connection: &Connection) { pub fn delete_group(group: &WordGroup, connection: &Connection) {
if group.id == 0 { if !group.id.is_valid() {
return; return;
} }
connection connection
.execute("DELETE FROM word_group WHERE id = ?1", (&group.id,)) .execute("DELETE FROM word_group WHERE id = ?1", (&group.id,))
.unwrap_or_else(|e| { .unwrap();
println!("{}", e);
0
});
} }
+80 -73
View File
@@ -9,6 +9,7 @@ use crate::styling::*;
use crate::word::WordState; use crate::word::WordState;
use crate::{AppState, RootMessage}; use crate::{AppState, RootMessage};
use chrono::{DateTime, TimeDelta, Utc}; use chrono::{DateTime, TimeDelta, Utc};
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, text};
@@ -18,11 +19,11 @@ use iced::widget::*;
use iced::{Border, Color, Shadow, Task}; use iced::{Border, Color, Shadow, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use rand::random_range; use rand::random_range;
use std::collections::{HashMap, HashSet};
use std::fs; use std::fs;
use std::ops::Add; use std::ops::Add;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
#[derive(Clone)] #[derive(Clone)]
@@ -65,38 +66,38 @@ pub enum DictionaryMessage {
} }
impl NavigatedPage<DictionaryMessage> for DictionaryState { impl NavigatedPage<DictionaryMessage> for DictionaryState {
fn navigate(&self, message: &DictionaryMessage) -> Option<Page> { fn navigate(&mut self, message: &DictionaryMessage) -> Option<Page> {
if let Back = message { if let Back = message {
return Some(Page::PreviousPage); return Some(Page::PreviousPage);
} }
if let Test = message { if let Test = message
if self.include_map.iter().any(|x| *x) { && self.include_map.iter().any(|x| *x)
let mut words = vec![]; {
let dict = &self.state.lock().unwrap().dictionary; let mut words = vec![];
let dict = &self.state.lock().dictionary;
words = self words = self
.include_map .include_map
.iter() .iter()
.zip(0..self.include_map.len()) .zip(0..self.include_map.len())
.filter(|(flag, _)| **flag) .filter(|(flag, _)| **flag)
.map(|(_, index)| dict[index].clone()) .map(|(_, index)| dict[index].clone())
.collect(); .collect();
return Some(Page::DictionaryQuiz(DictionaryQuizState::new( return Some(Page::DictionaryQuiz(DictionaryQuizState::new(
words, words,
self.reverse, self.reverse,
self.no_typing, self.no_typing,
))); )));
}
} }
if let WordAction(index) = message { if let WordAction(index) = message {
let word: WordData; let word: WordData;
{ {
let state = self.state.lock().unwrap(); let state = self.state.lock();
let dict = &state.dictionary; let dict = &state.dictionary;
word = dict[*index].clone(); word = dict[*index].clone();
} }
if word.id != 0 { if word.id.is_valid() {
return Some(Word(WordState::new(word, *index, self.state.clone()))); return Some(Word(WordState::new(word, *index, self.state.clone())));
} }
} }
@@ -107,7 +108,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
fn navigated(&mut self) { fn navigated(&mut self) {
let len = self.state.lock().unwrap().dictionary.len(); let len = self.state.lock().dictionary.len();
self.include_map = vec![false; len]; self.include_map = vec![false; len];
self.tag_map = Default::default(); self.tag_map = Default::default();
@@ -117,9 +118,9 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
fn update(&mut self, message: DictionaryMessage) -> Task<RootMessage> { fn update(&mut self, message: DictionaryMessage) -> Task<RootMessage> {
match message { match message {
NewWord => { NewWord => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
let mut word = WordData::new(); let mut word = WordData::new();
word.group_id = state.word_groups[self.selected_group_index].id.clone(); word.group_id = state.word_groups[self.selected_group_index].id;
let dict = &mut state.dictionary; let dict = &mut state.dictionary;
dict.push(word); dict.push(word);
@@ -128,21 +129,21 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
SetKey(i, v) => { SetKey(i, v) => {
{ {
let dict = &mut self.state.lock().unwrap().dictionary; let dict = &mut self.state.lock().dictionary;
dict[i].key = v; dict[i].key = v;
} }
return self.launch_auto_save_offset(i); return self.launch_auto_save_offset(i);
} }
SetValue(i, v) => { SetValue(i, v) => {
{ {
let dict = &mut self.state.lock().unwrap().dictionary; let dict = &mut self.state.lock().dictionary;
dict[i].value = v dict[i].value = v
} }
return self.launch_auto_save_offset(i); return self.launch_auto_save_offset(i);
} }
SetTags(i, mut v) => { SetTags(i, mut v) => {
{ {
let dict = &mut self.state.lock().unwrap().dictionary; let dict = &mut self.state.lock().dictionary;
let current_tags_value = dict[i].tags.clone(); let current_tags_value = dict[i].tags.clone();
@@ -150,12 +151,11 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
v = v[..v.len() - 2].to_string() v = v[..v.len() - 2].to_string()
} }
while v.contains(",,") { while let Some(index) = v.find(",,") {
let index = v.find(",,").unwrap();
v.remove(index); v.remove(index);
} }
dict.get_mut(i).unwrap().tags = v; dict[i].tags = v;
} }
self.update_tags(); self.update_tags();
@@ -163,7 +163,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
WordAction(i) => { WordAction(i) => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let dict = &mut state.dictionary; let dict = &mut state.dictionary;
let word = dict.remove(i); let word = dict.remove(i);
self.include_map.remove(i); self.include_map.remove(i);
@@ -172,9 +172,9 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
Include(i, b) => self.include_map[i] = b, Include(i, b) => self.include_map[i] = b,
IncludeTag(t, v) => { IncludeTag(t, v) => {
let index: u32; let index;
{ {
let state = self.state.lock().unwrap(); let state = self.state.lock();
index = state.word_groups[self.selected_group_index].id; index = state.word_groups[self.selected_group_index].id;
} }
self.tag_map.insert(t, v); self.tag_map.insert(t, v);
@@ -194,37 +194,33 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
Back => {} Back => {}
Test => {} Test => {}
CreateGroup => { CreateGroup => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
state.word_groups.push(WordGroup { state.word_groups.push(WordGroup {
id: 0, id: 0.into(),
name: format!("Группа слов {}", random_range(100..1000)), name: format!("Группа слов {}", random_range(100..1000)),
}); });
} }
EditGroup(new) => { EditGroup(new) => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let group = state.word_groups.get_mut(self.selected_group_index); let group = state.word_groups.get_mut(self.selected_group_index);
if let Some(group) = group { if let Some(group) = group {
group.name = new.clone(); group.name = new.clone();
} }
} }
SaveGroup => { SaveGroup => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let connection = &state.connection; let connection = &state.connection;
let group = &mut state let mut group = state.word_groups[self.selected_group_index].clone();
.word_groups
.get(self.selected_group_index)
.unwrap()
.clone();
update_group(group, connection); update_group(&mut group, connection);
state.word_groups[self.selected_group_index] = group.clone(); state.word_groups[self.selected_group_index] = group;
} }
SelectGroup(i) => { SelectGroup(i) => {
self.selected_group_index = i; self.selected_group_index = i;
let index: u32; let index;
{ {
let state = self.state.lock().unwrap(); let state = self.state.lock();
index = state.word_groups[i].id; index = state.word_groups[i].id;
} }
self.update_words_include(index) self.update_words_include(index)
@@ -234,7 +230,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
return Task::none(); return Task::none();
} }
{ {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
if let Some(group) = state.word_groups.get(self.selected_group_index) { if let Some(group) = state.word_groups.get(self.selected_group_index) {
let remove_group_id = group.id; let remove_group_id = group.id;
@@ -277,7 +273,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
self.groups_panel(), self.groups_panel(),
row![horizontal().width(8), self.words_list(),], row![horizontal().width(8), self.words_list(),],
row![ row![
button("Добавить слово").style(jl_button).on_press(NewWord), self.add_word_button(),
horizontal().width(Fill), horizontal().width(Fill),
button("Импорт").style(text).on_press(ToImport), button("Импорт").style(text).on_press(ToImport),
] ]
@@ -294,7 +290,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
impl DictionaryState { impl DictionaryState {
pub fn new(state: Arc<Mutex<AppState>>) -> Self { pub fn new(state: Arc<Mutex<AppState>>) -> Self {
let len = state.lock().unwrap().dictionary.len(); let len = state.lock().dictionary.len();
let mut result = DictionaryState { let mut result = DictionaryState {
include_map: vec![false; len], include_map: vec![false; len],
@@ -314,11 +310,11 @@ impl DictionaryState {
} }
fn save_word(&mut self, i: usize) { fn save_word(&mut self, i: usize) {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let connection = &state.connection; let connection = &state.connection;
let word = &mut state.dictionary.get(i).unwrap().clone(); let word = &mut state.dictionary[i].clone();
update_word(word, &connection); update_word(word, connection);
state.dictionary[i] = word.clone(); state.dictionary[i] = word.clone();
} }
@@ -336,7 +332,7 @@ impl DictionaryState {
let time = Instant::now(); let time = Instant::now();
let mut col = Column::new().width(Fill); let mut col = Column::new().width(Fill);
let state = self.state.lock().unwrap(); let state = self.state.lock();
let group_id = state.word_groups[self.selected_group_index].id; let group_id = state.word_groups[self.selected_group_index].id;
let dict = &state.dictionary; let dict = &state.dictionary;
@@ -353,13 +349,12 @@ impl DictionaryState {
continue; continue;
} }
if !self.search.is_empty() { if !self.search.is_empty()
if word.key.contains(&self.search) == false && !word.key.contains(&self.search)
&& word.value.contains(&self.search) == false && !word.value.contains(&self.search)
&& word.tags.contains(&self.search) == false && !word.tags.contains(&self.search)
{ {
continue; continue;
}
} }
let word_line_data = WordLineState { let word_line_data = WordLineState {
@@ -424,7 +419,7 @@ impl DictionaryState {
let line_button = || { let line_button = || {
let action = WordAction(index); let action = WordAction(index);
if data.id == 0 { if !data.id.is_valid() {
return button("-").on_press(action).style(|_x, _status| Style { return button("-").on_press(action).style(|_x, _status| Style {
background: None, background: None,
text_color: Color::BLACK, text_color: Color::BLACK,
@@ -449,7 +444,7 @@ impl DictionaryState {
} }
fn filters(&self) -> iced::Element<'_, DictionaryMessage> { fn filters(&self) -> iced::Element<'_, DictionaryMessage> {
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
iced::widget::column![ iced::widget::column![
text_input("Поиск", &self.search) text_input("Поиск", &self.search)
@@ -505,7 +500,7 @@ impl DictionaryState {
fn update_tags(&mut self) { fn update_tags(&mut self) {
let mut tags_list: HashSet<String> = HashSet::new(); let mut tags_list: HashSet<String> = HashSet::new();
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
dict.iter().for_each(|element| { dict.iter().for_each(|element| {
split_with_coma(element.tags.as_str()) split_with_coma(element.tags.as_str())
@@ -533,7 +528,7 @@ impl DictionaryState {
}); });
} }
fn update_words_include(&mut self, group_id: u32) { fn update_words_include(&mut self, group_id: crate::lang::Id) {
let include_tags = self let include_tags = self
.tag_map .tag_map
.iter() .iter()
@@ -546,14 +541,16 @@ impl DictionaryState {
return; return;
} }
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
let time = Instant::now(); let time = Instant::now();
self.include_map = dict self.include_map = dict
.iter() .iter()
.map(|word| (split_with_coma(word.tags.as_str()), word.group_id)) .map(|word| (split_with_coma(word.tags.as_str()), word.group_id))
.map(|(tags, word_group_id)| { .map(|(tags, word_group_id)| {
tags.iter().all(|t| include_tags.contains(t)) && tags.len() != 0 && word_group_id == group_id !tags.is_empty()
&& tags.iter().all(|t| include_tags.contains(t))
&& word_group_id == group_id
}) })
.collect(); .collect();
@@ -564,17 +561,15 @@ impl DictionaryState {
let mut row = Row::new(); let mut row = Row::new();
row = row.push(button("+").style(text).on_press(CreateGroup)); row = row.push(button("+").style(text).on_press(CreateGroup));
let state = &self.state.lock().unwrap(); let state = &self.state.lock();
let groups = &state.word_groups; let groups = &state.word_groups;
let mut index = 0; for (index, group) in groups.iter().enumerate() {
for group in groups {
row = row.push( row = row.push(
button(text!("{}", group.name.clone())) button(text!("{}", group.name.clone()))
.style(text) .style(text)
.on_press(SelectGroup(index)), .on_press(SelectGroup(index)),
); );
index = index + 1;
} }
let group = state.word_groups[self.selected_group_index].clone(); let group = state.word_groups[self.selected_group_index].clone();
@@ -602,6 +597,18 @@ impl DictionaryState {
space().into() space().into()
} }
} }
fn add_word_button(&self) -> iced::Element<'_, DictionaryMessage> {
let state = self.state.lock();
let group_id = state.word_groups[self.selected_group_index].id;
let button = button("Добавить слово").style(jl_button);
if group_id.is_valid() {
return button.on_press(NewWord).into();
}
button.into()
}
} }
pub fn split_with_coma(ts: &str) -> Vec<String> { pub fn split_with_coma(ts: &str) -> Vec<String> {
@@ -615,7 +622,7 @@ pub fn app_data_dir() -> PathBuf {
let mut dir = dirs::data_dir().unwrap(); let mut dir = dirs::data_dir().unwrap();
dir.push("jap_learn"); dir.push("jap_learn");
if !dir.exists() { if !dir.exists() {
fs::create_dir(dir.clone()).unwrap(); fs::create_dir_all(dir.clone()).unwrap();
} }
dir dir
@@ -627,6 +634,6 @@ struct WordLineState {
key: String, key: String,
value: String, value: String,
tags: String, tags: String,
id: u32, id: crate::lang::Id,
index: usize, index: usize,
} }
+20 -19
View File
@@ -1,3 +1,4 @@
use crate::RootMessage;
use crate::dictionary::split_with_coma; use crate::dictionary::split_with_coma;
use crate::dictionary_test::DictionaryQuizMessage::*; use crate::dictionary_test::DictionaryQuizMessage::*;
use crate::lang::WordData; use crate::lang::WordData;
@@ -5,12 +6,11 @@ use crate::navigation::Page::PreviousPage;
use crate::navigation::*; use crate::navigation::*;
use crate::quiz::Score; use crate::quiz::Score;
use crate::styling::*; use crate::styling::*;
use crate::RootMessage; use iced::Background::Color;
use iced::border::Radius; use iced::border::Radius;
use iced::widget::container::Style; use iced::widget::container::Style;
use iced::widget::{button, container, row, space, text, text_input, Row}; use iced::widget::{Row, button, container, row, space, text, text_input};
use iced::Background::Color; use iced::{Border, Element, Fill, Task, Theme, alignment};
use iced::{alignment, Border, Element, Fill, Task, Theme};
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -35,15 +35,14 @@ pub enum DictionaryQuizMessage {
} }
impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState { impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
fn navigate(&self, message: &DictionaryQuizMessage) -> Option<Page> { fn navigate(&mut self, message: &DictionaryQuizMessage) -> Option<Page> {
match message { match message {
Back => Some(PreviousPage), Back => Some(PreviousPage),
_ => None, _ => None,
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: DictionaryQuizMessage) -> Task<RootMessage> { fn update(&mut self, message: DictionaryQuizMessage) -> Task<RootMessage> {
match message { match message {
@@ -95,12 +94,12 @@ impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
] ]
.spacing(DEFAULT_SPACING), .spacing(DEFAULT_SPACING),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.align_x(alignment::Horizontal::Center), .align_x(alignment::Horizontal::Center),
) )
.center_y(Fill) .center_y(Fill)
.center_x(Fill) .center_x(Fill)
.into() .into()
} }
} }
@@ -120,7 +119,6 @@ impl DictionaryQuizState {
} }
} }
fn submit(&mut self) { fn submit(&mut self) {
if self.view == "---" { if self.view == "---" {
self.show_next(); self.show_next();
@@ -151,7 +149,7 @@ impl DictionaryQuizState {
if self.answer == self.correct if self.answer == self.correct
|| split_with_coma(self.correct.as_str()).contains(&self.answer) || split_with_coma(self.correct.as_str()).contains(&self.answer)
{ {
if self.is_help == false { if !self.is_help {
self.score.correct += 1; self.score.correct += 1;
} }
self.show_next() self.show_next()
@@ -173,11 +171,14 @@ impl DictionaryQuizState {
self.is_help = false; self.is_help = false;
self.answer = String::new(); self.answer = String::new();
if self.current_set.is_empty() { let next: WordData = match self.current_set.pop() {
self.update_set(); Some(word) => word,
} None => {
self.update_set();
self.current_set.pop().expect("Empty set")
}
};
let next = self.current_set.pop().unwrap();
if self.reverse { if self.reverse {
self.view = next.value.clone(); self.view = next.value.clone();
self.correct = next.key.clone(); self.correct = next.key.clone();
@@ -208,7 +209,7 @@ impl DictionaryQuizState {
} }
fn appeal_button(&self) -> Element<'_, DictionaryQuizMessage> { fn appeal_button(&self) -> Element<'_, DictionaryQuizMessage> {
if self.is_help && self.no_typing == false { if self.is_help && !self.no_typing {
return button("Апелляция").style(jl_button).on_press(Appeal).into(); return button("Апелляция").style(jl_button).on_press(Appeal).into();
} }
space().into() space().into()
+13 -13
View File
@@ -9,7 +9,8 @@ use iced::alignment::Horizontal::Center;
use iced::widget::space::horizontal; use iced::widget::space::horizontal;
use iced::widget::*; use iced::widget::*;
use iced::{Element, Fill, FillPortion, Task}; use iced::{Element, Fill, FillPortion, Task};
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
#[derive(Clone)] #[derive(Clone)]
pub struct HistoryState { pub struct HistoryState {
@@ -18,13 +19,12 @@ pub struct HistoryState {
} }
impl NavigatedPage<HistoryMessage> for HistoryState { impl NavigatedPage<HistoryMessage> for HistoryState {
fn navigate(&self, message: &HistoryMessage) -> Option<Page> { fn navigate(&mut self, message: &HistoryMessage) -> Option<Page> {
match message { match message {
Back => Some(Page::PreviousPage), Back => Some(Page::PreviousPage),
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, _: HistoryMessage) -> Task<RootMessage> { fn update(&mut self, _: HistoryMessage) -> Task<RootMessage> {
Task::none() Task::none()
} }
@@ -38,17 +38,17 @@ impl NavigatedPage<HistoryMessage> for HistoryState {
.width(FillPortion(5)), .width(FillPortion(5)),
horizontal().width(FillPortion(1)) horizontal().width(FillPortion(1))
] ]
.height(Fill) .height(Fill)
.width(Fill) .width(Fill)
.into(), .into(),
Back, Back,
) )
} }
} }
impl HistoryState { impl HistoryState {
pub fn new(id: u32, state: Arc<Mutex<AppState>>) -> Self { pub fn new(id: crate::lang::Id, state: Arc<Mutex<AppState>>) -> Self {
let state = state.lock().unwrap(); let state = state.lock();
let history = get_history_of_set(id); let history = get_history_of_set(id);
let words = history let words = history
.iter() .iter()
@@ -68,8 +68,6 @@ impl HistoryState {
} }
} }
fn history_lines(&self) -> Column<'_, HistoryMessage> { fn history_lines(&self) -> Column<'_, HistoryMessage> {
let mut column = Column::new(); let mut column = Column::new();
for (item, index) in self.list.iter().zip(0..self.list.len()) { for (item, index) in self.list.iter().zip(0..self.list.len()) {
@@ -86,11 +84,13 @@ impl HistoryState {
.align_x(Center), .align_x(Center),
iced::widget::column![ iced::widget::column![
text!("{} ➞ {}", item.before, item.after), text!("{} ➞ {}", item.before, item.after),
text!("{}", item.timestamp.with_timezone(&Local).format("%d.%m %H:%M")) text!(
"{}",
item.timestamp.with_timezone(&Local).format("%d.%m %H:%M")
)
] ]
.spacing(5) .spacing(5)
.align_x(Center) .align_x(Center)
] ]
.spacing(5), .spacing(5),
); );
+45 -42
View File
@@ -21,7 +21,8 @@ use rusqlite::Connection;
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, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
use tokio::task::spawn_blocking; use tokio::task::spawn_blocking;
use zip::ZipArchive; use zip::ZipArchive;
@@ -62,8 +63,8 @@ pub enum ImportMessage {
} }
impl NavigatedPage<ImportMessage> for ImportState { impl NavigatedPage<ImportMessage> for ImportState {
fn navigate(&self, message: &ImportMessage) -> Option<Page> { fn navigate(&mut self, message: &ImportMessage) -> Option<Page> {
if let Some(_) = self.progress { if self.progress.is_some() {
return None; return None;
} }
@@ -80,10 +81,12 @@ impl NavigatedPage<ImportMessage> for ImportState {
Back => {} Back => {}
UpdateFile(path) => { UpdateFile(path) => {
self.path = Some(path); self.path = Some(path);
self.import_data = None;
return self.load_package(); return self.load_package();
} }
SelectFile => return Self::select_import_file(), SelectFile => return Self::select_import_file(),
UpdateImport(import) => { UpdateImport(import) => {
self.selected_index = 0;
self.import_data = Some(import); self.import_data = Some(import);
} }
NextGroup => { NextGroup => {
@@ -128,12 +131,7 @@ impl NavigatedPage<ImportMessage> for ImportState {
} }
ImportFinished => { ImportFinished => {
self.progress = None; self.progress = None;
let group = self let group = &mut self.import_data.as_mut().unwrap().0[self.selected_index];
.import_data.as_mut()
.unwrap()
.0
.get_mut(self.selected_index)
.unwrap();
group.imported = true; group.imported = true;
} }
} }
@@ -144,7 +142,7 @@ impl NavigatedPage<ImportMessage> for ImportState {
back_overlay( back_overlay(
{ {
if let Some(value) = &self.progress { if let Some(value) = &self.progress {
column![progress_bar(0f32..=1f32, *value.lock().unwrap()),] column![progress_bar(0f32..=1f32, *value.lock()),]
.spacing(QUARTER_SPACING) .spacing(QUARTER_SPACING)
.into() .into()
} else { } else {
@@ -200,7 +198,9 @@ impl ImportState {
fn import_button(&self, group: &ImportGroup) -> Element<'_, ImportMessage> { fn import_button(&self, group: &ImportGroup) -> Element<'_, ImportMessage> {
if group.imported { if group.imported {
return container(text!("Группа слов успешно импортирована")).padding(HALF_SPACING).align_x(Center) return container(text!("Группа слов успешно импортирована"))
.padding(HALF_SPACING)
.align_x(Center)
.style(success) .style(success)
.width(Fill) .width(Fill)
.into(); .into();
@@ -254,7 +254,7 @@ impl ImportState {
} }
fn property_selector(&self) -> Element<'_, ImportMessage> { fn property_selector(&self) -> Element<'_, ImportMessage> {
if self.selected_property == None { if self.selected_property.is_none() {
return space().into(); return space().into();
} }
column![ column![
@@ -360,7 +360,7 @@ impl ImportState {
spawn_blocking(move || { spawn_blocking(move || {
Self::extract_import_file(path)?; Self::extract_import_file(path)?;
let data = Self::read_import_file()?; let data = Self::read_import_file()?;
return Ok(data); Ok(data)
}) })
.await .await
.unwrap() .unwrap()
@@ -379,15 +379,17 @@ impl ImportState {
let file = File::open(path).map_err(|_| ())?; let file = File::open(path).map_err(|_| ())?;
let reader = BufReader::new(file); let reader = BufReader::new(file);
let mut archive = ZipArchive::new(reader).map_err(|_| ())?; let mut archive = ZipArchive::new(reader).map_err(|_| ())?;
let db_file = archive.by_name("collection.anki2"); let temp_file_path = app_data_dir().join("import");
if let Ok(mut file) = db_file { let mut temp_file = OpenOptions::new()
let temp_file_path = app_data_dir().join("import"); .write(true)
let mut temp_file = OpenOptions::new() .create(true)
.write(true) .truncate(true)
.create(true) .open(&temp_file_path)
.truncate(true) .map_err(|_| ())?;
.open(&temp_file_path) if let Ok(mut file) = archive.by_name("collection.anki21") {
.map_err(|_| ())?; std::io::copy(&mut file, &mut temp_file).map_err(|_| ())?;
Ok(())
} else if let Ok(mut file) = archive.by_name("collection.anki2") {
std::io::copy(&mut file, &mut temp_file).map_err(|_| ())?; std::io::copy(&mut file, &mut temp_file).map_err(|_| ())?;
Ok(()) Ok(())
} else { } else {
@@ -402,7 +404,7 @@ impl ImportState {
} }
fn setup_mapping(&mut self, property_name: String) { fn setup_mapping(&mut self, property_name: String) {
let group = self.import_data.as_mut().unwrap(); let group = self.import_data.as_mut().unwrap();
let group = group.0.get_mut(self.selected_index).unwrap(); let group = &mut group.0[self.selected_index];
group group
.mapping .mapping
.insert(self.selected_property.clone().unwrap(), property_name); .insert(self.selected_property.clone().unwrap(), property_name);
@@ -411,7 +413,7 @@ impl ImportState {
} }
fn remove_mapping(&mut self, property_name: String) { fn remove_mapping(&mut self, property_name: String) {
let group = self.import_data.as_mut().unwrap(); let group = self.import_data.as_mut().unwrap();
let group = group.0.get_mut(self.selected_index).unwrap(); let group = &mut group.0[self.selected_index];
let remove_key = group let remove_key = group
.mapping .mapping
.keys() .keys()
@@ -439,11 +441,11 @@ impl ImportState {
let map_indices = Self::get_mapping_indices(&group); let map_indices = Self::get_mapping_indices(&group);
let mut group_entity = WordGroup { let mut group_entity = WordGroup {
id: 0, id: 0.into(),
name: group.name.clone(), name: group.name.clone(),
}; };
{ {
let state = state.lock().unwrap(); let state = state.lock();
add_group(&mut group_entity, &state.connection); add_group(&mut group_entity, &state.connection);
} }
@@ -452,11 +454,11 @@ impl ImportState {
let mut word = WordData::new(); let mut word = WordData::new();
word.tags = import.tags.trim().replace(" ", ", "); word.tags = import.tags.trim().replace(" ", ", ");
word.group_id = group_id.clone(); word.group_id = group_id;
for (dest, indices) in &map_indices { for (dest, indices) in &map_indices {
let collected_string = Self::collect_strings( let collected_string = Self::collect_strings(
&import.fields, &import.fields,
&indices, indices,
&separator, &separator,
skip_empty, skip_empty,
); );
@@ -476,18 +478,17 @@ impl ImportState {
} }
} }
println!("{word:?}");
words_list.push(word); words_list.push(word);
} }
let mut state = state.lock().unwrap(); let mut state = state.lock();
let connection = &mut state.connection; let connection = &mut state.connection;
let mut index = 0; let mut index = 0;
let total_len = words_list.len() as f32 / 256.0; let total_len = words_list.len() as f32 / 1024.0;
for word in &mut words_list.chunks_mut(256) { for word in &mut words_list.chunks_mut(1024) {
add_words(word, connection); add_words(word, connection);
index += 1; index += 1;
let mut progress = progress.lock().unwrap(); let mut progress = progress.lock();
*progress = index as f32 / total_len; *progress = index as f32 / total_len;
} }
@@ -511,29 +512,31 @@ impl ImportState {
.iter() .iter()
.map(|name| (name.clone(), Vec::<usize>::with_capacity(1))) .map(|name| (name.clone(), Vec::<usize>::with_capacity(1)))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for key in group.mapping.keys() { for (key, endpoint) in &group.mapping {
let endpoint = group.mapping.get(key).unwrap(); let property_index = group
let property_index = group.fields.iter().position(|f| f == key).unwrap(); .fields
.iter()
.position(|f| f == key)
.expect("Unknown property");
let group_index = result let group_index = result
.iter() .iter()
.position(|(name, _)| name == endpoint) .position(|(name, _)| name == endpoint)
.unwrap(); .unwrap();
result.get_mut(group_index).unwrap().1.push(property_index); result[group_index].1.push(property_index);
} }
result result
} }
fn collect_strings( fn collect_strings(
properties: &Vec<String>, properties: &[String],
indices: &Vec<usize>, indices: &[usize],
separator: &str, separator: &str,
skip_empty: bool, skip_empty: bool,
) -> String { ) -> String {
let mut working_words = Vec::with_capacity(indices.len()); let mut working_words = Vec::with_capacity(indices.len());
for i in 0..indices.len() { for index in indices {
let index = indices[i]; let str = &properties[*index];
let str = properties.get(index).unwrap();
if skip_empty && str.is_empty() { if skip_empty && str.is_empty() {
continue; continue;
} }
+212 -127
View File
@@ -1,25 +1,80 @@
use crate::data_provider::card_stats::{
add_stat_list, delete_stat, load_stats_of_set, update_stat_score,
};
use crate::data_provider::history::{push_note, HistoryItem};
use crate::repetitions::CardSetSettings;
use crate::AppState; use crate::AppState;
use crate::data_provider::card_stats::{delete_stat, load_stats_of_deck, update_stat_score};
use crate::data_provider::history::{HistoryItem, push_note};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use rand::distr::weighted::WeightedIndex;
use rand::distr::Distribution; use rand::distr::Distribution;
use rand::distr::weighted::WeightedIndex;
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
use rand::rng; use rand::rng;
use rand::rngs::ThreadRng; use rand::rngs::ThreadRng;
use serde::{Deserialize, Serialize}; use rayon::iter::IndexedParallelIterator;
use std::cmp::min; use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use rhai::{Engine, Scope};
use rusqlite::ToSql;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
use std::cmp::PartialEq;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Arc, Mutex}; use std::fmt::{Display, Formatter};
use std::num::ParseIntError;
use std::str::FromStr;
use std::sync::Arc;
use parking_lot::Mutex;
use std::time::Instant; use std::time::Instant;
const MAX_HISTORY_LEN: usize = 20; const MAX_HISTORY_LEN: usize = 20;
const MAX_HISTORY_LEN_PART: f32 = 0.33; const MAX_HISTORY_LEN_PART: f32 = 0.33;
const MAX_SCORE: u8 = 25; const MAX_SCORE: u8 = 25;
const FADE_PER_DAY: f32 = 0.95; const FADE_PER_DAY: f32 = 0.95;
#[derive(Clone, PartialEq, Eq, Debug, Hash, Copy)]
pub struct Id(u32);
pub const INVALID_ID: Id = Id(0);
impl FromStr for Id {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Id(s.parse::<u32>()?))
}
}
impl From<u32> for Id {
fn from(value: u32) -> Self {
Id(value)
}
}
impl From<Id> for u32 {
fn from(value: Id) -> Self {
value.0
}
}
impl Display for Id {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromSql for Id {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Integer(i) => Ok(Id(i as u32)),
_ => Err(FromSqlError::InvalidType),
}
}
}
impl ToSql for Id {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0 as i64))
}
}
impl Id {
pub(crate) fn is_valid(self) -> bool {
self.0 != 0
}
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct KanaSet { pub struct KanaSet {
name: String, name: String,
@@ -27,13 +82,11 @@ pub struct KanaSet {
pub(crate) dictionary: Vec<Vec<(String, String)>>, pub(crate) dictionary: Vec<Vec<(String, String)>>,
pub(crate) include_map: [bool; 10], pub(crate) include_map: [bool; 10],
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum KanaType { pub enum KanaType {
Hiragana, Hiragana,
Katakana, Katakana,
} }
impl KanaSet { impl KanaSet {
pub fn hiragana() -> Self { pub fn hiragana() -> Self {
Self { Self {
@@ -199,14 +252,6 @@ impl KanaSet {
} }
} }
/* pub fn next(&mut self) -> (String, String) {
let current_set = self.list();
let mut rand = rand::rng();
let index: u32 = rand.random();
current_set[index as usize % current_set.len()].clone()
}*/
pub fn list(&self) -> Vec<(String, String)> { pub fn list(&self) -> Vec<(String, String)> {
let mut current_set: Vec<(String, String)> = Vec::new(); let mut current_set: Vec<(String, String)> = Vec::new();
@@ -221,7 +266,6 @@ impl KanaSet {
current_set current_set
} }
} }
impl Default for KanaSet { impl Default for KanaSet {
fn default() -> Self { fn default() -> Self {
KanaSet::hiragana() KanaSet::hiragana()
@@ -232,45 +276,40 @@ impl PartialEq<Self> for KanaSet {
self.name == other.name self.name == other.name
} }
} }
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WordData { pub struct WordData {
pub id: u32, pub id: Id,
pub key: String, pub key: String,
pub value: String, pub value: String,
pub tags: String, pub tags: String,
pub additional: HashMap<String, String>, pub additional: HashMap<String, String>,
pub group_id: u32, pub group_id: Id,
} }
impl WordData { impl WordData {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
id: 0, id: INVALID_ID,
key: String::new(), key: String::new(),
value: String::new(), value: String::new(),
tags: String::new(), tags: String::new(),
additional: Default::default(), additional: Default::default(),
group_id: 1, group_id: 1.into(),
} }
} }
} }
#[derive(Clone)] #[derive(Clone)]
pub struct WordGroup { pub struct WordGroup {
pub id: u32, pub id: Id,
pub name: String, pub name: String,
} }
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct CardStatistics { pub struct CardStatistics {
pub id: u32, pub id: Id,
pub word_id: u32, pub word_id: Id,
pub set_id: u32, pub set_id: Id,
pub last_open: DateTime<Utc>, pub last_open: DateTime<Utc>,
pub score: u8, pub score: u8,
} }
impl CardStatistics { impl CardStatistics {
pub fn update(&mut self, status: WordOpenMode) { pub fn update(&mut self, status: WordOpenMode) {
match status { match status {
@@ -286,11 +325,7 @@ impl CardStatistics {
} }
} }
if self.score < 1 { self.score = self.score.clamp(1, MAX_SCORE);
self.score = 1
} else if self.score > MAX_SCORE {
self.score = MAX_SCORE
}
self.last_open = Utc::now(); self.last_open = Utc::now();
} }
@@ -301,7 +336,6 @@ impl CardStatistics {
(self.score as f32 * multiplier).max(1.0) (self.score as f32 * multiplier).max(1.0)
} }
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub enum WordOpenMode { pub enum WordOpenMode {
Easy, Easy,
@@ -309,51 +343,29 @@ pub enum WordOpenMode {
Hard, Hard,
None, None,
} }
#[derive(Clone)] #[derive(Clone)]
pub struct CardSet { pub struct DeckData {
words: Vec<WordData>, words: Vec<WordData>,
set: Vec<CardStatistics>, set: Vec<CardStatistics>,
current_word_index: Option<usize>, current_word_index: Option<usize>,
state: Arc<Mutex<AppState>>, state: Arc<Mutex<AppState>>,
order_module: OrderModule, order_module: OrderModule,
settings: CardSetSettings, settings: DeckSettings,
} }
impl DeckData {
impl CardSet { pub fn new(settings: &DeckSettings, state: Arc<Mutex<AppState>>) -> Self {
pub fn new(settings: &CardSetSettings, state: Arc<Mutex<AppState>>) -> Self {
let state_for = state.clone(); let state_for = state.clone();
let state_locked = state.lock().unwrap(); let state_locked = state.lock();
let mut current_set = load_stats_of_set(&settings, &state_locked.connection); let mut current_set = load_stats_of_deck(settings, &state_locked.connection);
let last_list = settings.get_word_list(&state_locked); let last_list: Vec<_> = settings
let saved_ids = current_set.iter().map(|l| l.word_id).collect::<Vec<u32>>(); .get_word_list(&state_locked)
let word_ids = last_list.iter().map(|l| l.id).collect::<Vec<u32>>();
let new_stats: &mut Vec<CardStatistics> = &mut last_list
.iter() .iter()
.filter(|word| !saved_ids.contains(&word.id)) .map(|w| &state_locked.dictionary[*w])
.map(|word| CardStatistics { .cloned()
id: 0,
word_id: word.id.clone(),
last_open: Utc::now(),
score: 1,
set_id: settings.id.clone(),
})
.collect(); .collect();
let word_ids = last_list.iter().map(|l| l.id).collect::<Vec<Id>>();
let time = Instant::now();
if !new_stats.is_empty() {
add_stat_list(new_stats, &state_locked.connection);
current_set.append(new_stats);
}
println!(
"Added {} stats: {}",
new_stats.len(),
time.elapsed().as_millis()
);
let mut index = 0; let mut index = 0;
for stat in current_set.clone() { for stat in current_set.clone() {
if !word_ids.contains(&stat.word_id) { if !word_ids.contains(&stat.word_id) {
@@ -370,20 +382,19 @@ impl CardSet {
current_word_index: None, current_word_index: None,
state: state_for, state: state_for,
order_module: match settings.open_mode { order_module: match settings.open_mode {
SetOrderMode::Default => OrderModule::SemiRandomSRS(SemiRandomSRSModule::new()), OrderMode::Default => OrderModule::SemiRandomSRS(SemiRandomSRSModule::new()),
SetOrderMode::TrainWorstFirst => { OrderMode::TrainWorstFirst => {
OrderModule::WorstWordsSRS(WorstWordsSRSModule::new()) OrderModule::WorstWordsSRS(WorstWordsSRSModule::new())
} }
SetOrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()), OrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()),
}, },
settings: settings.clone(), settings: settings.clone(),
} }
} }
pub fn next(&mut self) -> (WordData, CardStatistics) { pub fn next(&mut self) -> (WordData, CardStatistics) {
let index = match self.order_module.clone() { let index = match self.order_module.clone() {
OrderModule::SemiRandomSRS(mut module) => { OrderModule::SemiRandomSRS(mut module) => {
if module.initialized == false { if !module.initialized {
module.init(self) module.init(self)
} }
let index = module.next(self); let index = module.next(self);
@@ -391,7 +402,7 @@ impl CardSet {
index index
} }
OrderModule::RandomSRS(mut module) => { OrderModule::RandomSRS(mut module) => {
if module.initialized == false { if !module.initialized {
module.init(self) module.init(self)
} }
let index = module.next(self); let index = module.next(self);
@@ -399,7 +410,7 @@ impl CardSet {
index index
} }
OrderModule::WorstWordsSRS(mut module) => { OrderModule::WorstWordsSRS(mut module) => {
if module.initialized == false { if !module.initialized {
module.init(self) module.init(self)
} }
let index = module.next(self); let index = module.next(self);
@@ -411,9 +422,8 @@ impl CardSet {
self.current_word_index = Some(index); self.current_word_index = Some(index);
(self.words[index].clone(), self.set[index].clone()) (self.words[index].clone(), self.set[index].clone())
} }
pub fn open(&mut self, status: WordOpenMode) { pub fn open(&mut self, status: WordOpenMode) {
if let None = self.current_word_index { if self.current_word_index.is_none() {
return; return;
} }
let index = self.current_word_index.unwrap(); let index = self.current_word_index.unwrap();
@@ -437,50 +447,50 @@ impl CardSet {
self.order_module = OrderModule::WorstWordsSRS(module); self.order_module = OrderModule::WorstWordsSRS(module);
} }
} }
update_stat_score(word, &self.state.lock().unwrap().connection); update_stat_score(word, &self.state.lock().connection);
push_note( push_note(
self.settings.id, self.settings.id,
HistoryItem { HistoryItem {
timestamp: Utc::now(), timestamp: Utc::now(),
word_id: word.word_id, word_id: word.word_id,
mode: WordOpenMode::Easy, mode: status,
before: old_score, before: old_score,
after: new_score, after: new_score,
}, },
) )
} }
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.set.len() self.set.len()
} }
} }
#[derive(Clone, PartialEq, Copy, Eq)] #[derive(Clone, PartialEq, Copy, Eq)]
pub enum SetOrderMode { pub enum OrderMode {
Default, Default,
TrainWorstFirst, TrainWorstFirst,
FullRandom, FullRandom,
} }
#[derive(Clone, Copy, Eq, PartialEq, Default)]
pub enum AppendMode {
Full,
#[default]
Manual,
}
#[derive(Clone)] #[derive(Clone)]
enum OrderModule { enum OrderModule {
SemiRandomSRS(SemiRandomSRSModule), SemiRandomSRS(SemiRandomSRSModule),
RandomSRS(RandomSRSModule), RandomSRS(RandomSRSModule),
WorstWordsSRS(WorstWordsSRSModule), WorstWordsSRS(WorstWordsSRSModule),
} }
trait SRSModule { trait SRSModule {
fn next(&mut self, set: &mut CardSet) -> usize; fn next(&mut self, set: &mut DeckData) -> usize;
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: CardStatistics); fn open(&mut self, status: WordOpenMode, index: usize, updated_word: CardStatistics);
fn init(&mut self, set: &mut CardSet); fn init(&mut self, set: &mut DeckData);
} }
#[derive(Clone)] #[derive(Clone)]
struct RandomSRSModule { struct RandomSRSModule {
basket: Vec<usize>, basket: Vec<usize>,
initialized: bool, initialized: bool,
} }
impl RandomSRSModule { impl RandomSRSModule {
fn new() -> RandomSRSModule { fn new() -> RandomSRSModule {
Self { Self {
@@ -489,26 +499,26 @@ impl RandomSRSModule {
} }
} }
} }
impl SRSModule for RandomSRSModule { impl SRSModule for RandomSRSModule {
fn next(&mut self, set: &mut CardSet) -> usize { fn next(&mut self, set: &mut DeckData) -> usize {
if self.basket.is_empty() { match self.basket.pop() {
self.basket = (0..set.words.len()).collect::<Vec<usize>>(); Some(index) => index,
self.basket.shuffle(&mut rand::rng()) None => {
self.basket = (0..set.words.len()).collect::<Vec<usize>>();
self.basket.shuffle(&mut rand::rng());
self.basket.pop().expect("empty basket")
}
} }
self.basket.pop().unwrap()
} }
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {} fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
fn init(&mut self, set: &mut CardSet) { fn init(&mut self, set: &mut DeckData) {
self.initialized = true; self.initialized = true;
self.basket = (0..set.words.len()).collect::<Vec<usize>>(); self.basket = (0..set.words.len()).collect::<Vec<usize>>();
self.basket.shuffle(&mut rand::rng()) self.basket.shuffle(&mut rand::rng())
} }
} }
#[derive(Clone)] #[derive(Clone)]
struct SemiRandomSRSModule { struct SemiRandomSRSModule {
history: Vec<usize>, history: Vec<usize>,
@@ -516,7 +526,6 @@ struct SemiRandomSRSModule {
generator: ThreadRng, generator: ThreadRng,
initialized: bool, initialized: bool,
} }
impl SemiRandomSRSModule { impl SemiRandomSRSModule {
fn new() -> SemiRandomSRSModule { fn new() -> SemiRandomSRSModule {
SemiRandomSRSModule { SemiRandomSRSModule {
@@ -527,9 +536,8 @@ impl SemiRandomSRSModule {
} }
} }
} }
impl SRSModule for SemiRandomSRSModule { impl SRSModule for SemiRandomSRSModule {
fn next(&mut self, set: &mut CardSet) -> usize { fn next(&mut self, set: &mut DeckData) -> usize {
let index = self.last_weights.sample(&mut self.generator); let index = self.last_weights.sample(&mut self.generator);
if self.history.contains(&index) { if self.history.contains(&index) {
@@ -543,15 +551,13 @@ impl SRSModule for SemiRandomSRSModule {
index index
} }
fn open(&mut self, _: WordOpenMode, index: usize, word: CardStatistics) { fn open(&mut self, _: WordOpenMode, index: usize, word: CardStatistics) {
let new_weight = (100.0 / word.calculated_score()).powf(2.0); let new_weight = (100.0 / word.calculated_score()).powf(2.0);
self.last_weights self.last_weights
.update_weights(&[(index, &new_weight)]) .update_weights(&[(index, &new_weight)])
.unwrap(); .expect("update weights error");
} }
fn init(&mut self, set: &mut DeckData) {
fn init(&mut self, set: &mut CardSet) {
self.initialized = true; self.initialized = true;
let weights = set let weights = set
.set .set
@@ -561,16 +567,11 @@ impl SRSModule for SemiRandomSRSModule {
self.last_weights = WeightedIndex::new(weights).unwrap(); self.last_weights = WeightedIndex::new(weights).unwrap();
} }
} }
impl SemiRandomSRSModule { impl SemiRandomSRSModule {
fn history_len(&self, set: &CardSet) -> usize { fn history_len(&self, set: &DeckData) -> usize {
min( ((set.len() as f32 * MAX_HISTORY_LEN_PART) as usize).clamp(1, MAX_HISTORY_LEN)
MAX_HISTORY_LEN,
(set.len() as f32 * MAX_HISTORY_LEN_PART) as usize,
)
} }
} }
#[derive(Clone)] #[derive(Clone)]
struct WorstWordsSRSModule { struct WorstWordsSRSModule {
initialized: bool, initialized: bool,
@@ -580,29 +581,29 @@ struct WorstWordsSRSModule {
queue: Vec<usize>, queue: Vec<usize>,
rounds_count: u8, rounds_count: u8,
} }
impl SRSModule for WorstWordsSRSModule { impl SRSModule for WorstWordsSRSModule {
fn next(&mut self, set: &mut CardSet) -> usize { fn next(&mut self, set: &mut DeckData) -> usize {
if self.rounds_remaining == 0 { if self.rounds_remaining == 0 {
self.fill_pool(set); self.fill_pool(set);
self.rounds_remaining = self.rounds_count; self.rounds_remaining = self.rounds_count;
} }
if self.queue.is_empty() { match self.queue.pop() {
self.queue.append(&mut self.pool.clone()); Some(index) => index,
self.rounds_remaining -= 1; None => {
self.queue.append(&mut self.pool.clone());
self.rounds_remaining -= 1;
self.queue.pop().expect("empty queue")
}
} }
self.queue.pop().unwrap()
} }
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {} fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
fn init(&mut self, _: &mut CardSet) { fn init(&mut self, _: &mut DeckData) {
self.initialized = true; self.initialized = true;
} }
} }
impl WorstWordsSRSModule { impl WorstWordsSRSModule {
fn new() -> WorstWordsSRSModule { fn new() -> WorstWordsSRSModule {
WorstWordsSRSModule { WorstWordsSRSModule {
@@ -614,8 +615,7 @@ impl WorstWordsSRSModule {
queue: vec![], queue: vec![],
} }
} }
fn fill_pool(&mut self, set: &DeckData) {
fn fill_pool(&mut self, set: &CardSet) {
let mut sorted = set let mut sorted = set
.set .set
.clone() .clone()
@@ -631,3 +631,88 @@ impl WorstWordsSRSModule {
self.pool = worst; self.pool = worst;
} }
} }
#[derive(Clone)]
pub struct DeckSettings {
pub id: Id,
pub name: String,
pub forward: String,
pub backward: String,
pub filter: String,
pub count: Option<usize>,
pub worst_words_list: Option<Vec<WordData>>,
pub open_mode: OrderMode,
}
impl DeckSettings {
pub(crate) fn with_name(name: String) -> DeckSettings {
DeckSettings {
id: 0.into(),
name,
forward: "".to_string(),
backward: "".to_string(),
filter: "true".to_string(),
count: None,
worst_words_list: None,
open_mode: OrderMode::Default,
}
}
pub fn check_filter(&self) -> bool {
let time = Instant::now();
let engine = Engine::new();
let ast = engine.compile(&self.filter);
println!("Compile time is {:?}", time.elapsed());
ast.is_ok()
}
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
let time = Instant::now();
let mut list = vec![];
let engine = Engine::new();
let ast = engine.compile(&self.filter);
if ast.is_err() {
return list;
}
let ast = ast.unwrap();
let groups = &state.word_groups;
list = state
.dictionary
.par_iter()
.enumerate()
.filter(|(_, word)| {
let mut more = rhai::Map::new();
for iced in &word.additional {
more.insert(iced.0.clone().into(), iced.1.clone().into());
}
let mut scope = Scope::new();
scope
.push_constant("id", word.id.0)
.push_constant("key", word.key.clone())
.push_constant("value", word.value.clone())
.push_constant("tags", word.tags.clone())
.push_constant("more", more)
.push_constant(
"group",
groups
.iter()
.find(|g| g.id == word.group_id)
.cloned()
.unwrap()
.name,
);
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
result.is_ok() && result.unwrap()
})
.map(|(index, _)| index)
.collect();
println!("Collecting available words is {:?}", time.elapsed());
list
}
pub fn require_speech(&self) -> bool {
self.forward == "speech" || self.backward == "speech"
}
}
+44 -31
View File
@@ -3,39 +3,38 @@ mod data_provider;
mod dictionary; mod dictionary;
mod dictionary_test; mod dictionary_test;
mod history; mod history;
pub mod import;
mod lang; mod lang;
pub mod navigation; pub mod navigation;
mod quiz; mod quiz;
mod randomizer; mod randomizer;
mod repetition; mod repetition;
mod repetition_settings;
mod repetitions; mod repetitions;
mod selector; mod selector;
pub mod styling; pub mod styling;
mod sync; mod sync;
mod word; mod word;
mod writing; mod writing;
mod repetition_settings;
pub mod import;
use crate::RootMessage::Keyboard;
use crate::data_provider::card_sets::load_sets; use crate::data_provider::card_sets::load_sets;
use crate::data_provider::settings::get_setting; use crate::data_provider::settings::get_setting;
use crate::data_provider::sqlite::default_connection; use crate::data_provider::sqlite::default_connection;
use crate::data_provider::words::{load_word_groups, load_words}; use crate::data_provider::words::{load_word_groups, load_words};
use crate::lang::{WordData, WordGroup}; use crate::lang::{DeckSettings, Id, WordData, WordGroup};
use crate::navigation::{AppSettings, RootMessage, ScreenState}; use crate::navigation::{AppSettings, RootMessage, ScreenState};
use crate::quiz::*; use crate::quiz::*;
use crate::repetitions::CardSetSettings;
use crate::RootMessage::Keyboard;
use chrono::NaiveDate; use chrono::NaiveDate;
use iced::{keyboard, Subscription, Theme}; use hashbrown::HashMap;
use iced::{window, Font}; use iced::{Font, window};
use iced_core::window::Position; use iced::{Subscription, Theme, keyboard};
use iced_core::Size; use iced_core::Size;
use rusqlite::Connection; use iced_core::window::Position;
use std::collections::HashMap; #[cfg(target_os = "linux")]
use iced_core::window::settings::PlatformSpecific; use iced_core::window::settings::PlatformSpecific;
use mimalloc::MiMalloc; use mimalloc::MiMalloc;
use rusqlite::Connection;
#[global_allocator] #[global_allocator]
static GLOBAL: MiMalloc = MiMalloc; static GLOBAL: MiMalloc = MiMalloc;
@@ -43,7 +42,8 @@ const USER_FONT: Font = Font::with_name("Noto Sans JP");
fn main() -> iced::Result { fn main() -> iced::Result {
println!("Welcome to JapLearn"); println!("Welcome to JapLearn");
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view).window(window_settings()) iced::application(ScreenState::boot, ScreenState::update, ScreenState::view)
.window(window_settings())
.subscription(subscription) .subscription(subscription)
.title("JapLearn") .title("JapLearn")
.settings(iced::Settings { .settings(iced::Settings {
@@ -52,51 +52,58 @@ fn main() -> iced::Result {
}) })
.font(include_bytes!("../noto.ttf")) .font(include_bytes!("../noto.ttf"))
.default_font(USER_FONT) .default_font(USER_FONT)
.theme(Theme::GruvboxDark).run() .theme(Theme::GruvboxDark)
.run()
} }
fn window_settings() -> window::Settings { fn window_settings() -> window::Settings {
let mut settings = window::Settings{ let mut settings = window::Settings {
position: Position::Centered, position: Position::Centered,
min_size: Some(Size::new(700.0_f32.into(), 700.0_f32.into())), min_size: Some(Size::new(700.0_f32, 700.0_f32)),
.. Default::default() ..Default::default()
}; };
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
{ {
settings.platform_specific = settings.platform_specific = PlatformSpecific {
PlatformSpecific { application_id: "JapLearn".to_string(),
application_id: "JapLearn".to_string(), override_redirect: false,
override_redirect: false };
};
} }
settings settings
} }
fn subscription(_state: &ScreenState) -> Subscription<RootMessage> { fn subscription(_state: &ScreenState) -> Subscription<RootMessage> {
keyboard::listen().map(|e| Keyboard(e)) keyboard::listen().map(Keyboard)
} }
pub struct AppState { pub struct AppState {
pub dictionary: Vec<WordData>, pub dictionary: Vec<WordData>,
pub card_sets: Vec<CardSetSettings>, pub decks: Vec<DeckSettings>,
pub word_groups: Vec<WordGroup>, pub word_groups: Vec<WordGroup>,
pub connection: Connection, pub connection: Connection,
pub sync_data: AppSettings, pub sync_data: AppSettings,
pub activity: HashMap<u32, Vec<(NaiveDate, u32)>> pub activity: HashMap<Id, Vec<(NaiveDate, u32)>>,
}
impl Default for AppState {
fn default() -> Self {
Self::new()
}
} }
impl AppState { impl AppState {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
dictionary: vec![], dictionary: vec![],
card_sets: vec![], decks: vec![],
word_groups: vec![], word_groups: vec![],
connection: default_connection(), connection: default_connection(),
sync_data: AppSettings { key: None, auto_web_fetch: false }, sync_data: AppSettings {
key: None,
auto_web_fetch: false,
},
activity: Default::default(), activity: Default::default(),
} }
} }
@@ -109,13 +116,19 @@ fn fill_state(state: &mut AppState) {
let setting = load_settings(&state.connection); let setting = load_settings(&state.connection);
state.dictionary = list; state.dictionary = list;
state.card_sets = sets; state.decks = sets;
state.word_groups = groups; state.word_groups = groups;
state.sync_data = setting state.sync_data = setting
} }
fn load_settings(connection: &Connection) -> AppSettings { fn load_settings(connection: &Connection) -> AppSettings {
let key = get_setting("SYNC_KEY".to_string(), connection); let key = get_setting("SYNC_KEY".to_string(), connection);
let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection).unwrap_or("false".to_string()).parse::<bool>().unwrap(); let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection)
AppSettings { key, auto_web_fetch: fetch } .unwrap_or("false".to_string())
.parse::<bool>()
.unwrap();
AppSettings {
key,
auto_web_fetch: fetch,
}
} }
+45 -29
View File
@@ -1,9 +1,13 @@
use crate::data_provider::history::{get_history_of_set, history_dir}; use crate::data_provider::history::{get_history_of_set, history_dir};
use crate::data_provider::sqlite::{create_db, default_connection}; use crate::data_provider::sqlite::{create_db, default_connection};
use crate::data_provider::web_api::{get_local_version, get_web_version, load_data, set_local_version}; use crate::data_provider::web_api::{
use crate::dictionary::{app_data_dir, DictionaryMessage, DictionaryState}; get_local_version, get_web_version, load_data, set_local_version,
};
use crate::dictionary::{DictionaryMessage, DictionaryState, app_data_dir};
use crate::dictionary_test::{DictionaryQuizMessage, DictionaryQuizState}; use crate::dictionary_test::{DictionaryQuizMessage, DictionaryQuizState};
use crate::history::{HistoryMessage, HistoryState}; use crate::history::{HistoryMessage, HistoryState};
use crate::import::{ImportMessage, ImportState};
use crate::lang::Id;
use crate::message_navigation; use crate::message_navigation;
use crate::navigation::Page::*; use crate::navigation::Page::*;
use crate::navigation::RootMessage::{DataLoaded, Keyboard, UpdateData}; use crate::navigation::RootMessage::{DataLoaded, Keyboard, UpdateData};
@@ -21,13 +25,14 @@ use crate::word::{WordMessage, WordState};
use crate::writing::{WritingMessage, WritingState}; use crate::writing::{WritingMessage, WritingState};
use crate::{AppState, fill_state}; use crate::{AppState, fill_state};
use chrono::NaiveDate; use chrono::NaiveDate;
use hashbrown::HashMap;
use iced::keyboard::Event; use iced::keyboard::Event;
use iced::{Element, Task}; use iced::{Element, Task};
use reqwest::Error; use reqwest::Error;
use std::collections::HashMap; use rusqlite::Connection;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
use std::time::Instant; use std::time::Instant;
use crate::import::{ImportMessage, ImportState};
impl Default for ScreenState { impl Default for ScreenState {
fn default() -> Self { fn default() -> Self {
@@ -57,7 +62,7 @@ pub enum RootMessage {
RepetitionSettings(RepetitionSettingsMessage), RepetitionSettings(RepetitionSettingsMessage),
Import(ImportMessage), Import(ImportMessage),
Keyboard(Event), Keyboard(Event),
DataLoaded(HashMap<u32, Vec<(NaiveDate, u32)>>), DataLoaded(HashMap<Id, Vec<(NaiveDate, u32)>>),
None, None,
UpdateData, UpdateData,
} }
@@ -93,13 +98,15 @@ impl ScreenState {
let reading_additional_task = Task::perform(Self::load_additional_data(), |data| data); let reading_additional_task = Task::perform(Self::load_additional_data(), |data| data);
let final_task; let final_task;
let state_guard = state.app_state.lock().unwrap(); let state_guard = state.app_state.lock();
if state_guard.sync_data.auto_web_fetch { if state_guard.sync_data.auto_web_fetch {
let key = state_guard.sync_data.key.clone().unwrap(); let key = state_guard.sync_data.key.clone().unwrap();
final_task = Task::batch([ final_task = Task::batch([
reading_additional_task, reading_additional_task,
Task::perform(Self::load_web_backup(key), |result| { Task::perform(Self::load_web_backup(key), |result| {
if let Ok(update) = result && update { if let Ok(update) = result
&& update
{
UpdateData UpdateData
} else { } else {
RootMessage::None RootMessage::None
@@ -118,23 +125,25 @@ impl ScreenState {
async fn load_additional_data() -> RootMessage { async fn load_additional_data() -> RootMessage {
let directory = history_dir(); let directory = history_dir();
let mut map = HashMap::new(); let mut map = HashMap::new();
for file in directory.read_dir().unwrap() { for file in directory.read_dir().unwrap().flatten() {
if let Ok(file) = file { let mut vec = vec![];
let mut vec = vec![]; let history_file_name = match file.file_name().into_string() {
let history_file_name = file.file_name().into_string().unwrap(); Err(_) => continue,
let id = history_file_name[4..history_file_name.len() - 12] Ok(v) => v,
.parse::<u32>() };
.unwrap();
let history = get_history_of_set(id); let id: Id = history_file_name[4..history_file_name.len() - 12]
let by_date = history.chunk_by(|x, x1| { .parse::<Id>()
x.timestamp.naive_local().date() == x1.timestamp.naive_local().date() .unwrap();
});
for group in by_date { let history = get_history_of_set(id);
vec.push((group[0].timestamp.naive_local().date(), group.len() as u32)); let by_date = history.chunk_by(|x, x1| {
} x.timestamp.naive_local().date() == x1.timestamp.naive_local().date()
map.insert(id, vec); });
for group in by_date {
vec.push((group[0].timestamp.naive_local().date(), group.len() as u32));
} }
map.insert(id, vec);
} }
DataLoaded(map) DataLoaded(map)
} }
@@ -142,11 +151,12 @@ impl ScreenState {
async fn load_web_backup(string: String) -> Result<bool, Error> { async fn load_web_backup(string: String) -> Result<bool, Error> {
let local = get_local_version().await; let local = get_local_version().await;
let web = get_web_version(string.as_str()).await?; let web = get_web_version(string.as_str()).await?;
println!("{} {}", local, web);
if web > local { if web > local {
println!("Web version is newer than local version"); println!("Web version is newer than local version");
load_data(string, true).await; load_data(string, true).await;
set_local_version(web).await; set_local_version(web).await;
}else { } else {
return Ok(false); return Ok(false);
} }
Ok(true) Ok(true)
@@ -160,13 +170,16 @@ impl ScreenState {
} }
if let DataLoaded(data) = message { if let DataLoaded(data) = message {
self.app_state.lock().unwrap().activity = data; self.app_state.lock().activity = data;
return Task::none(); return Task::none();
} }
if let UpdateData = message{ if let UpdateData = message {
println!("Loading data"); println!("Loading data");
let mut state = self.app_state.lock().unwrap(); let mut state = self.app_state.lock();
if cfg!(windows) {
state.connection = Connection::open_in_memory().unwrap();
}
let path = app_data_dir(); let path = app_data_dir();
let db_file = path.join("data.db"); let db_file = path.join("data.db");
let temp_db_file = path.join("data.db.tmp"); let temp_db_file = path.join("data.db.tmp");
@@ -295,7 +308,10 @@ macro_rules! message_navigation {
($msg:expr, $stack:expr, $state:expr) => { ($msg:expr, $stack:expr, $state:expr) => {
if let Some(new_page) = $state.navigate(&$msg) { if let Some(new_page) = $state.navigate(&$msg) {
if let Page::PreviousPage = new_page { if let Page::PreviousPage = new_page {
$stack.pop(); if $stack.len() > 1 {
$stack.pop();
}
return (Task::<RootMessage>::none(), true); return (Task::<RootMessage>::none(), true);
} else { } else {
$stack.push(new_page); $stack.push(new_page);
@@ -323,7 +339,7 @@ macro_rules! state_navigate_handle {
} }
pub trait NavigatedPage<T> { pub trait NavigatedPage<T> {
fn navigate(&self, message: &T) -> Option<Page>; fn navigate(&mut self, message: &T) -> Option<Page>;
fn navigated(&mut self); fn navigated(&mut self);
fn update(&mut self, message: T) -> Task<RootMessage>; fn update(&mut self, message: T) -> Task<RootMessage>;
fn view(&self) -> Element<'_, T>; fn view(&self) -> Element<'_, T>;
+25 -23
View File
@@ -5,7 +5,7 @@ use crate::quiz::QuizMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::{RootMessage, USER_FONT}; use crate::{RootMessage, USER_FONT};
use iced::widget::*; use iced::widget::*;
use iced::{alignment, Element, Fill, Task}; use iced::{Element, Fill, Task, alignment};
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -20,7 +20,7 @@ pub struct QuizState {
} }
impl NavigatedPage<QuizMessage> for QuizState { impl NavigatedPage<QuizMessage> for QuizState {
fn navigate(&self, message: &QuizMessage) -> Option<Page> { fn navigate(&mut self, message: &QuizMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -28,8 +28,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: QuizMessage) -> Task<RootMessage> { fn update(&mut self, message: QuizMessage) -> Task<RootMessage> {
match message { match message {
@@ -42,7 +41,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
} }
self.current_roman = content; self.current_roman = content;
if self.correct_roman == self.current_roman { if self.correct_roman == self.current_roman {
if self.is_help == false { if !self.is_help {
self.score.correct += 1; self.score.correct += 1;
} }
@@ -55,13 +54,11 @@ impl NavigatedPage<QuizMessage> for QuizState {
self.update_showed() self.update_showed()
} }
} }
Back => todo!(), Back => {}
} }
Task::none() Task::none()
} }
fn view(&self) -> Element<'_, QuizMessage> { fn view(&self) -> Element<'_, QuizMessage> {
container( container(
iced::widget::column![ iced::widget::column![
@@ -84,27 +81,32 @@ impl NavigatedPage<QuizMessage> for QuizState {
.size(28) .size(28)
.width(150) .width(150)
.on_input(ContentChanged), .on_input(ContentChanged),
row![ score_display(&self.score),
text!("{}", self.score.total.to_string()).size(25),
text!("{}", self.score.correct.to_string())
.size(25)
.color(iced::Color::from_rgb8(60, 170, 60)),
text!("{}", self.score.fail.to_string())
.color(iced::Color::from_rgb8(255, 79, 0))
.size(25),
]
.spacing(DEFAULT_SPACING),
button("Закончить").style(jl_button).on_press(Back), button("Закончить").style(jl_button).on_press(Back),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.align_x(alignment::Horizontal::Center), .align_x(alignment::Horizontal::Center),
) )
.center_y(Fill) .center_y(Fill)
.center_x(Fill) .center_x(Fill)
.into() .into()
} }
} }
fn score_display<'a, T: 'a>(score: &Score) -> Element<'a, T> {
row![
text!("{}", score.total.to_string()).size(25),
text!("{}", score.correct.to_string())
.size(25)
.color(iced::Color::from_rgb8(60, 170, 60)),
text!("{}", score.fail.to_string())
.color(iced::Color::from_rgb8(255, 79, 0))
.size(25),
]
.spacing(DEFAULT_SPACING)
.into()
}
impl QuizState { impl QuizState {
pub(crate) fn new() -> QuizState { pub(crate) fn new() -> QuizState {
QuizState { QuizState {
+9 -11
View File
@@ -1,9 +1,9 @@
use crate::RootMessage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::randomizer::RandomizerMessage::{Back, Edit, Start}; use crate::randomizer::RandomizerMessage::{Back, Edit, Start};
use crate::styling::{back_overlay, jl_button, HALF_SPACING}; use crate::styling::{HALF_SPACING, back_overlay, jl_button};
use crate::RootMessage;
use iced::widget::{button, text_editor};
use iced::Task; use iced::Task;
use iced::widget::{button, text_editor};
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -20,15 +20,14 @@ pub enum RandomizerMessage {
} }
impl NavigatedPage<RandomizerMessage> for RandomizerState { impl NavigatedPage<RandomizerMessage> for RandomizerState {
fn navigate(&self, message: &RandomizerMessage) -> Option<Page> { fn navigate(&mut self, message: &RandomizerMessage) -> Option<Page> {
if let Back = message { if let Back = message {
return Some(Page::PreviousPage); return Some(Page::PreviousPage);
} }
None None
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: RandomizerMessage) -> Task<RootMessage> { fn update(&mut self, message: RandomizerMessage) -> Task<RootMessage> {
match message { match message {
Edit(action) => { Edit(action) => {
@@ -59,11 +58,12 @@ impl NavigatedPage<RandomizerMessage> for RandomizerState {
.placeholder("Каждый элемент с новой строки"), .placeholder("Каждый элемент с новой строки"),
button("Перемешать").style(jl_button).on_press(Start), button("Перемешать").style(jl_button).on_press(Start),
] ]
.spacing(HALF_SPACING) .spacing(HALF_SPACING)
.into(), .into(),
Back, Back,
) )
}} }
}
impl Default for RandomizerState { impl Default for RandomizerState {
fn default() -> Self { fn default() -> Self {
@@ -78,6 +78,4 @@ impl RandomizerState {
list: vec![], list: vec![],
} }
} }
} }
+26 -29
View File
@@ -1,8 +1,8 @@
use crate::data_provider::voice::get_voice; use crate::data_provider::voice::get_voice;
use crate::lang::{CardSet, CardStatistics, WordData, WordOpenMode}; use crate::lang::Id;
use crate::lang::{CardStatistics, DeckData, DeckSettings, WordData, WordOpenMode};
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{KeyPressedPage, NavigatedPage, Page}; use crate::navigation::{KeyPressedPage, NavigatedPage, Page};
use crate::repetitions::CardSetSettings;
use crate::styling::*; use crate::styling::*;
use crate::{AppState, RootMessage}; use crate::{AppState, RootMessage};
use chrono::Local; use chrono::Local;
@@ -13,23 +13,24 @@ use iced::widget::{Column, button, column, container, row, rule, space, text, to
use iced::{Element, Fill, Task, Theme, alignment, keyboard}; use iced::{Element, Fill, Task, Theme, alignment, keyboard};
use rodio::MixerDeviceSink; use rodio::MixerDeviceSink;
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
use tokio::task::spawn_blocking; use tokio::task::spawn_blocking;
pub struct RepetitionState { pub struct RepetitionState {
state: Arc<Mutex<AppState>>, state: Arc<Mutex<AppState>>,
pub settings: CardSetSettings, pub settings: DeckSettings,
pub set: CardSet, pub set: DeckData,
current_word: WordData, current_word: WordData,
current_statistic: CardStatistics, current_statistic: CardStatistics,
open: bool, open: bool,
can_play: bool, can_play: bool,
sink: Arc<MixerDeviceSink>, sink: Arc<MixerDeviceSink>,
opened: HashSet<u32>, opened: HashSet<Id>,
} }
impl NavigatedPage<RepetitionMessage> for RepetitionState { impl NavigatedPage<RepetitionMessage> for RepetitionState {
fn navigate(&self, message: &RepetitionMessage) -> Option<Page> { fn navigate(&mut self, message: &RepetitionMessage) -> Option<Page> {
if let RepetitionMessage::Back = message { if let RepetitionMessage::Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -37,8 +38,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: RepetitionMessage) -> Task<RootMessage> { fn update(&mut self, message: RepetitionMessage) -> Task<RootMessage> {
match message { match message {
RepetitionMessage::Back => {} RepetitionMessage::Back => {}
@@ -88,17 +88,17 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
(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)
.into(), .into(),
RepetitionMessage::Back, RepetitionMessage::Back,
) )
} }
} }
impl RepetitionState { impl RepetitionState {
pub(crate) fn new(set: CardSetSettings, state: Arc<Mutex<AppState>>) -> RepetitionState { pub(crate) fn new(set: DeckSettings, state: Arc<Mutex<AppState>>) -> RepetitionState {
let mut card_set = CardSet::new(&set, state.clone()); let mut card_set = DeckData::new(&set, state.clone());
let (word, stat) = card_set.next(); let (word, stat) = card_set.next();
let sink_handle = rodio::DeviceSinkBuilder::open_default_sink().unwrap(); let sink_handle = rodio::DeviceSinkBuilder::open_default_sink().unwrap();
@@ -117,8 +117,6 @@ impl RepetitionState {
} }
impl RepetitionState { impl RepetitionState {
fn next(&mut self) -> Task<RootMessage> { fn next(&mut self) -> Task<RootMessage> {
if self.open { if self.open {
self.answer(WordOpenMode::None) self.answer(WordOpenMode::None)
@@ -151,7 +149,7 @@ impl RepetitionState {
} }
fn increment_counter(&mut self) { fn increment_counter(&mut self) {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
let id = self.settings.id; let id = self.settings.id;
let activity = state.activity.get_mut(&id); let activity = state.activity.get_mut(&id);
@@ -169,7 +167,6 @@ impl RepetitionState {
} }
} }
fn draw_forward(&self) -> Element<'_, RepetitionMessage> { fn draw_forward(&self) -> Element<'_, RepetitionMessage> {
self.draw_card_view(self.settings.forward.as_str()) self.draw_card_view(self.settings.forward.as_str())
} }
@@ -294,18 +291,18 @@ impl KeyPressedPage for RepetitionState {
text: _, text: _,
repeat: _, repeat: _,
} = message } = message
&& let Code(code) = pk
{ {
if let Code(code) = pk { return match code {
return match code { keyboard::key::Code::Space => self.next(),
keyboard::key::Code::Space => self.next(), keyboard::key::Code::Digit1 => self.answer(WordOpenMode::None),
keyboard::key::Code::Digit1 => self.answer(WordOpenMode::None), keyboard::key::Code::Digit2 => self.answer(WordOpenMode::Hard),
keyboard::key::Code::Digit2 => self.answer(WordOpenMode::Hard), keyboard::key::Code::Digit3 => self.answer(WordOpenMode::Ok),
keyboard::key::Code::Digit3 => self.answer(WordOpenMode::Ok), keyboard::key::Code::Digit4 => self.answer(WordOpenMode::Easy),
keyboard::key::Code::Digit4 => self.answer(WordOpenMode::Easy), _ => Task::none(),
_ => Task::none(), };
};
}
} }
Task::none() Task::none()
} }
} }
@@ -322,7 +319,7 @@ pub enum RepetitionMessage {
async fn play_sound(sink: Arc<MixerDeviceSink>, text: String) { async fn play_sound(sink: Arc<MixerDeviceSink>, text: String) {
let data = get_voice(text.as_str()).await; let data = get_voice(text.as_str()).await;
spawn_blocking(move || { spawn_blocking(move || {
rodio::play(&sink.mixer(), data).unwrap().sleep_until_end(); rodio::play(sink.mixer(), data).unwrap().sleep_until_end();
}) })
.await .await
.unwrap(); .unwrap();
+41 -28
View File
@@ -1,43 +1,50 @@
use crate::data_provider::card_sets::{delete_set, update_card_set}; use crate::AppState;
use crate::data_provider::card_sets::{delete_set, update_deck};
use crate::lang::DeckSettings;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::repetition_settings::RepetitionSettingsMessage::*; use crate::repetition_settings::RepetitionSettingsMessage::*;
use crate::repetitions::CardSetSettings;
use crate::styling::*; use crate::styling::*;
use crate::AppState;
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::text_input::Catalog;
use iced::widget::{button, column, row, scrollable, space, text, text_input}; use iced::widget::{button, column, row, scrollable, space, text, text_input};
use iced::{Element, Task}; use iced::{Element, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use iced_core::Padding; use iced_core::{Padding, Theme, color};
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
use std::time::Duration; use std::time::Duration;
pub struct RepetitionSettingsState { pub struct RepetitionSettingsState {
set: CardSetSettings, set: DeckSettings,
index: usize, index: usize,
state: Arc<Mutex<AppState>>, state: Arc<Mutex<AppState>>,
real_delete: bool, real_delete: bool,
correct_filter: bool,
} }
impl RepetitionSettingsState { impl RepetitionSettingsState {
pub(crate) fn new(index: usize, p1: Arc<Mutex<AppState>>) -> RepetitionSettingsState { pub(crate) fn new(index: usize, state: Arc<Mutex<AppState>>) -> RepetitionSettingsState {
let set; let set;
{ {
let local_state = p1.lock().unwrap(); let local_state = state.lock();
set = local_state.card_sets[index].clone(); set = local_state.decks[index].clone();
} }
let filter_state = set.check_filter();
RepetitionSettingsState { RepetitionSettingsState {
index, index,
set, set,
state: p1, state,
real_delete: false, real_delete: false,
correct_filter: filter_state,
} }
} }
} }
impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState { impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
fn navigate(&self, message: &RepetitionSettingsMessage) -> Option<Page> { fn navigate(&mut self, message: &RepetitionSettingsMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -45,15 +52,14 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: RepetitionSettingsMessage) -> Task<RootMessage> { fn update(&mut self, message: RepetitionSettingsMessage) -> Task<RootMessage> {
match message { match message {
Back => {} Back => {}
Save => { Save => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
update_card_set(&mut self.set, &state.connection); update_deck(&mut self.set, &state.connection);
state.card_sets[self.index] = self.set.clone(); state.decks[self.index] = self.set.clone();
} }
SetName(new) => { SetName(new) => {
self.set.name = new; self.set.name = new;
@@ -66,25 +72,26 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
} }
SetFilter(new) => { SetFilter(new) => {
self.set.filter = new; self.set.filter = new;
self.correct_filter = self.set.check_filter();
} }
TryFilter => { TryFilter => {
let state = self.state.lock().unwrap(); let state = self.state.lock();
let count = self.set.get_word_list(&state).len(); let count = self.set.get_word_list(&state).len();
self.set.count = Some(count); self.set.count = Some(count);
} }
DeleteSet => { DeleteSet => {
if self.real_delete == false { if !self.real_delete {
self.real_delete = true; self.real_delete = true;
return Task::future(async { return Task::future(async {
tokio::time::sleep(Duration::from_millis(3000)).await; tokio::time::sleep(Duration::from_millis(3000)).await;
return RootMessage::RepetitionSettings(RevertDeleteSet); RootMessage::RepetitionSettings(RevertDeleteSet)
}); });
} }
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
delete_set(&self.set, &state.connection); delete_set(&self.set, &state.connection);
state.card_sets.remove(self.index); state.decks.remove(self.index);
return Task::done(RootMessage::RepetitionSettings(Back)); return Task::done(RootMessage::RepetitionSettings(Back));
}, }
RevertDeleteSet => self.real_delete = false, RevertDeleteSet => self.real_delete = false,
} }
Task::none() Task::none()
@@ -112,7 +119,15 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Фильтр"), text!("Фильтр"),
text_input("", &self.set.filter).on_input(SetFilter), text_input("", &self.set.filter)
.style(|x, status| {
let mut primary = Theme::default()(x, status);
if !self.correct_filter {
primary.border.color = color!(255, 255, 0);
}
primary
})
.on_input(SetFilter),
button("Проверить фильтр") button("Проверить фильтр")
.style(jl_button) .style(jl_button)
.on_press(TryFilter), .on_press(TryFilter),
@@ -142,17 +157,15 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
] ]
.spacing(DEFAULT_SPACING), .spacing(DEFAULT_SPACING),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.into(), .into(),
Back, Back,
) )
} }
} }
impl RepetitionSettingsState { impl RepetitionSettingsState {
fn count_view(&self, set: &DeckSettings) -> Element<'_, RepetitionSettingsMessage> {
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionSettingsMessage> {
if let Some(count) = set.count { if let Some(count) = set.count {
return text!("Количество слов: {}", count).into(); return text!("Количество слов: {}", count).into();
} }
+391 -267
View File
@@ -1,7 +1,7 @@
use crate::data_provider::card_sets::{delete_set, update_card_set}; use crate::data_provider::card_sets::update_deck;
use crate::data_provider::card_stats::load_stats_of_set; use crate::data_provider::card_stats::{add_stat_list, load_stats_of_deck};
use crate::history::HistoryState; use crate::history::HistoryState;
use crate::lang::{SetOrderMode, WordData}; use crate::lang::{AppendMode, CardStatistics, DeckSettings, Id, OrderMode};
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings}; use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::repetition::RepetitionState; use crate::repetition::RepetitionState;
@@ -9,117 +9,220 @@ use crate::repetition_settings::RepetitionSettingsState;
use crate::repetitions::RepetitionsMessage::*; use crate::repetitions::RepetitionsMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::{AppState, RootMessage}; use crate::{AppState, RootMessage};
use chrono::{Days, Local}; use chrono::{Days, Local, Utc};
use iced::widget::button::{danger, Status}; use hashbrown::{HashMap, HashSet};
pub use iced::widget::button::{Catalog, Style}; pub use iced::widget::button::{Catalog, Style};
use iced::widget::container::bordered_box; use iced::widget::button::{Status, danger};
use iced::widget::tooltip::Position::Top; use iced::widget::tooltip::Position::Top;
use iced::widget::{button, column, container, lazy, radio, row, scrollable, space, svg, text, text_input, tooltip, Column, Row}; use iced::widget::{
Column, Row, button, column, container, lazy, radio, row, scrollable, space, svg, text,
text_input, tooltip,
};
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::Padding;
use iced_core::border::Radius; use iced_core::border::Radius;
use iced_core::svg::Handle; use iced_core::svg::Handle;
use iced_core::Padding; use std::ops::Deref;
use rhai::{Engine, Scope}; use std::sync::Arc;
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
#[derive(Clone)] #[derive(Clone)]
pub struct RepetitionsState { pub struct RepetitionsState {
selected_set: Option<usize>, word_id_index_map: HashMap<Id, usize>,
correct_filters: Vec<bool>, selected_deck_index: Option<usize>,
pub state: Arc<Mutex<AppState>>, decks: Vec<DeckViewData>,
state: Arc<Mutex<AppState>>,
} }
impl NavigatedPage<RepetitionsMessage> for RepetitionsState { impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
fn navigate(&self, message: &RepetitionsMessage) -> Option<Page> { fn navigate(&mut self, message: &RepetitionsMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else if let GoToHistory = message { } else if let GoToHistory = message {
let card_set; Some(History(HistoryState::new(
{ self.selected_deck().unwrap().id,
card_set = self.state.lock().unwrap().card_sets[self.selected_set.unwrap()].id; self.state.clone(),
} )))
Some(History(HistoryState::new(card_set, self.state.clone())))
} else if let GoToRepetition = message { } else if let GoToRepetition = message {
let clone = self.state.clone(); let clone = self.state.clone();
let card_set;
{ let selected_set = self.selected_deck_mut().unwrap();
card_set = self.state.lock().unwrap().card_sets[self.selected_set.unwrap()].clone(); if selected_set.append_mode == AppendMode::Full {
Self::append_all_words(&mut clone.lock(), selected_set);
selected_set.existing_words_indices = selected_set.available_words_indices.clone();
} else {
if selected_set
.available_words_indices
.as_ref()
.unwrap()
.is_empty()
|| selected_set
.existing_words_indices
.as_ref()
.unwrap()
.is_empty()
{
return None;
}
} }
Some(Repetition(RepetitionState::new(card_set, clone)))
Some(Repetition(RepetitionState::new(
selected_set.general_settings.clone(),
clone,
)))
} else if let GoToSettings = message { } else if let GoToSettings = message {
Some(RepetitionSettings(RepetitionSettingsState::new( Some(RepetitionSettings(RepetitionSettingsState::new(
self.selected_set.unwrap(), self.selected_deck().unwrap().index.unwrap(),
self.state.clone(), self.state.clone(),
))) )))
} else { } else {
None None
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {
self.selected_set = None; let index = self.selected_deck_index.unwrap();
let state = self.state.lock();
if let Some(global_deck) = state.decks.get(index) {
if global_deck.id != self.selected_deck().unwrap().id {
drop(state);
self.decks.remove(index);
self.clear_selection();
}
} else {
drop(state);
self.decks.remove(index);
self.clear_selection()
}
} }
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> { fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
let mut state = self.state.lock().unwrap();
match message { match message {
Next => {} Next => {}
Back => {} Back => {}
GoToRepetition => {} GoToRepetition => {}
GoToHistory => {} GoToHistory => {}
GoToSettings => {} GoToSettings => {}
CreateSet => { CreateSet => {
let index = state.card_sets.len() + 1; let index = self.decks.len() + 1;
state self.decks.push(DeckViewData {
.card_sets general_settings: DeckSettings::with_name(format!("Колода #{}", index)),
.push(CardSetSettings::with_name(format!("Card set #{}", index))); existing_words_indices: None,
self.correct_filters.push(true); available_words_indices: None,
append_mode: Default::default(),
index: None,
});
} }
DeleteSet => { DeleteSet => {
let set = state.card_sets.remove(self.selected_set.unwrap()); let index = self.selected_deck_index.unwrap();
self.correct_filters.remove(self.selected_set.unwrap()); self.clear_selection();
self.selected_set = None; let deck = self.decks.remove(index);
delete_set(&set, &state.connection); if deck.id.is_valid() {
let mut state = self.state.lock();
state.decks.remove(index);
self.decks = self
.decks
.clone()
.into_iter()
.map(|mut deck| {
deck.index = state.decks.iter().position(|d| d.id == deck.id);
deck
})
.collect();
}
}
SetName(value) => {
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.name = value;
} }
SelectSet(index) => { SelectSet(index) => {
self.selected_set = Some(index); self.select_deck(index);
let mut set = state.card_sets.get(index).unwrap().clone(); let deck = self.selected_deck().unwrap();
set.update_worst_words(&state); if deck.existing_words_indices.is_none() {
state.card_sets[index] = set; let state = self.state.lock();
} let added: Vec<_> = load_stats_of_deck(deck, &state.connection)
SetName(new) => { .iter()
state.card_sets[self.selected_set.unwrap()].name = new; .map(|c| self.word_id_index_map[&c.word_id])
.collect();
let total = deck.get_word_list(&state);
drop(state);
let deck = self.selected_deck_mut().unwrap();
deck.existing_words_indices = Some(added);
deck.available_words_indices = Some(total);
}
} }
Save => { Save => {
for i in 0..state.card_sets.len() { let mut deck = self.selected_deck().unwrap().clone();
self.correct_filters[i] = state.card_sets[i].check_filter(); let mut state = self.state.lock();
{
update_deck(&mut deck.general_settings, &state.connection);
if let Some(index) = deck.index {
state.decks[index] = deck.general_settings.clone();
} else {
state.decks.push(deck.general_settings.clone());
deck.index = Some(state.decks.len() - 1);
self.decks[self.selected_deck_index.unwrap()] = deck.clone();
}
} }
let set = &mut state.card_sets[self.selected_set.unwrap()].clone();
update_card_set(set, &state.connection);
state.card_sets[self.selected_set.unwrap()] = set.clone();
} }
SetForward(new) => { SetForward(value) => {
state.card_sets[self.selected_set.unwrap()].forward = new; let deck = self.selected_deck_mut().unwrap();
deck.general_settings.forward = value;
} }
SetBackward(new) => { SetBackward(value) => {
state.card_sets[self.selected_set.unwrap()].backward = new; let deck = self.selected_deck_mut().unwrap();
deck.general_settings.backward = value;
} }
SetFilter(new) => { SetFilter(value) => {
state.card_sets[self.selected_set.unwrap()].filter = new; let deck = self.selected_deck_mut().unwrap();
deck.general_settings.filter = value;
} }
TryFilter => { TryFilter => {
let set = state.card_sets.get(self.selected_set.unwrap()).unwrap(); let state = self.state.lock();
let count = set.get_word_list(&state).len(); let deck = self.selected_deck().unwrap();
state.card_sets[self.selected_set.unwrap()].count = Some(count); let count = deck.get_word_list(&state).len();
drop(state);
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.count = Some(count);
} }
SetOpenMode(mode) => { SetOpenMode(mode) => {
state let deck = self.selected_deck_mut().unwrap();
.card_sets deck.general_settings.open_mode = mode;
.get_mut(self.selected_set.unwrap()) }
.unwrap() SetAppendMode(mode) => {
.open_mode = mode; let deck = self.selected_deck_mut().unwrap();
deck.append_mode = mode;
}
AppendWords(count) => {
let adding: Vec<usize>;
{
{
let deck = self.selected_deck().unwrap();
let existing_words_indices = deck.existing_words_indices.as_ref().unwrap();
let mut created_set = HashSet::with_capacity(existing_words_indices.len());
existing_words_indices.iter().for_each(|c| {
created_set.insert(c);
});
adding = deck
.available_words_indices
.as_ref()
.unwrap()
.iter()
.filter(|c| !created_set.contains(c))
.take(count)
.cloned()
.collect();
}
let deck = self.selected_deck_mut().unwrap();
deck.existing_words_indices
.as_mut()
.unwrap()
.append(&mut adding.clone());
}
let deck = self.selected_deck().unwrap();
let mut state = self.state.lock();
Self::append_words(&mut state, &deck.general_settings, adding.into_iter());
} }
} }
Task::none() Task::none()
@@ -129,7 +232,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
back_overlay( back_overlay(
row![ row![
column![ column![
scrollable(self.sets_list()).height(Fill), scrollable(self.decks_list()).height(Fill),
button("Добавить") button("Добавить")
.style(jl_button) .style(jl_button)
.width(Fill) .width(Fill)
@@ -137,34 +240,65 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.width(Length::FillPortion(1)), .width(Length::FillPortion(1)),
self.selected_set_view(), self.selected_deck_view(),
] ]
.align_y(Center) .align_y(Center)
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.width(Fill) .width(Fill)
.height(Fill) .height(Fill)
.into(), .into(),
Back, Back,
) )
} }
} }
impl RepetitionsState { impl RepetitionsState {
pub(crate) fn new(state: Arc<Mutex<AppState>>) -> RepetitionsState { pub(crate) fn new(state: Arc<Mutex<AppState>>) -> RepetitionsState {
let count = state.lock().unwrap().card_sets.len(); let state_ = state.lock();
let mut map = HashMap::with_capacity(state_.dictionary.len());
state_
.dictionary
.iter()
.enumerate()
.for_each(|(index, word)| {
map.insert(word.id, index);
});
let decks = Self::get_decks_from_state(&state_);
drop(state_);
RepetitionsState { RepetitionsState {
selected_set: None, word_id_index_map: map,
correct_filters: vec![true; count], selected_deck_index: None,
decks,
state, state,
} }
} }
fn get_decks_from_state(state: &AppState) -> Vec<DeckViewData> {
state
.decks
.iter()
.enumerate()
.map(|(index, deck)| DeckViewData {
general_settings: deck.clone(),
existing_words_indices: None,
available_words_indices: None,
append_mode: Default::default(),
index: Some(index),
})
.collect()
}
} }
impl RepetitionsState { impl RepetitionsState {
fn launch_delete_button(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
fn launch_delete_button(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> { if deck.id.is_valid() {
if set.id != 0 { if deck.append_mode == AppendMode::Manual
&& deck.existing_words_indices.as_ref().unwrap().is_empty()
{
return text!("Добавьте карточки или измените фильтр").into();
}
return row![ return row![
space().width(Fill), space().width(Fill),
button(text!("Начать повторение").width(200).center()) button(text!("Начать повторение").width(200).center())
@@ -175,24 +309,15 @@ impl RepetitionsState {
} }
button("Удалить").style(danger).on_press(DeleteSet).into() button("Удалить").style(danger).on_press(DeleteSet).into()
} }
fn selected_deck_view(&self) -> Element<'_, RepetitionsMessage> {
fn selected_set_view(&self) -> Element<'_, RepetitionsMessage> { if let Some(deck) = &self.selected_deck() {
if let Some(index) = self.selected_set {
let set;
{
let state = self.state.lock().unwrap();
if state.card_sets.len() <= index {
return space().width(Length::FillPortion(3)).into();
}
set = state.card_sets[index].clone();
}
return column![ return column![
scrollable( scrollable(
column![ column![
column![ column![
text!("Название набора"), text!("Название набора"),
row![ row![
text_input("", &set.name).on_input(SetName), 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),
@@ -201,41 +326,57 @@ impl RepetitionsState {
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
{ {
if set.id == 0 { if !deck.id.is_valid() {
column![ column![
column![ column![
text!("Передняя сторона"), text!("Передняя сторона"),
text_input("", &set.forward).on_input(SetForward), text_input("", &deck.forward).on_input(SetForward),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Задняя сторона"), text!("Задняя сторона"),
text_input("", &set.backward).on_input(SetBackward), text_input("", &deck.backward).on_input(SetBackward),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Фильтр"), text!("Фильтр"),
text_input("", &set.filter).on_input(SetFilter), text_input("", &deck.filter).on_input(SetFilter),
button("Проверить фильтр") button("Проверить фильтр")
.style(jl_button) .style(jl_button)
.on_press(TryFilter), .on_press(TryFilter),
self.count_view(&set), self.count_view(deck),
] ]
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
} else { } else {
self.filled_set_data_view(&set) column![
self.filled_deck_data_view(deck),
self.word_append_panel(deck),
radio(
"Обычный режим",
OrderMode::Default,
Some(deck.open_mode),
SetOpenMode
),
radio(
"Начать с плохих слов",
OrderMode::TrainWorstFirst,
Some(deck.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
OrderMode::FullRandom,
Some(deck.open_mode),
SetOpenMode
),
button("История").style(jl_button).on_press(GoToHistory),
]
.spacing(HALF_SPACING)
} }
}, },
radio( // self.words_words_view(&set),
"Обычный режим",
SetOrderMode::Default,
Some(set.open_mode),
SetOpenMode
),
self.words_words_view(&set),
button("История").style(jl_button).on_press(GoToHistory),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.padding(Padding { .padding(Padding {
@@ -248,40 +389,36 @@ impl RepetitionsState {
.height(Fill), .height(Fill),
row![ row![
button("Сохранить").style(jl_button).on_press(Save), button("Сохранить").style(jl_button).on_press(Save),
self.launch_delete_button(&set) self.launch_delete_button(deck)
] ]
.spacing(DEFAULT_SPACING), .spacing(DEFAULT_SPACING)
.align_y(Center),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.width(Length::FillPortion(3)) .width(Length::FillPortion(2))
.into(); .into();
} }
space().width(Length::FillPortion(3)).into() space().width(Length::FillPortion(2)).into()
} }
fn filled_deck_data_view(&self, deck: &DeckSettings) -> Column<'_, RepetitionsMessage> {
fn filled_set_data_view(&self, set: &CardSetSettings) -> Column<'_, RepetitionsMessage> { column![self.activity_bar(deck), self.count_comparator_view()]
column![self.activity_bar(set)].align_x(Center) .align_x(Center)
.width(Fill) .width(Fill)
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.into()
} }
fn activity_bar(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> { fn activity_bar(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
const MAX_DAY_COUNT: f32 = 128.0; const MAX_DAY_COUNT: f32 = 128.0;
let state = self.state.lock().unwrap(); let state = self.state.lock();
let history = state.activity.get(&set.id); let history = state.activity.get(&deck.id);
let mut counts: Vec<u32> = vec![0; 30 * 7]; let mut counts: Vec<u32> = vec![0; 30 * 7];
let now = Local::now().date_naive(); let now = Local::now().date_naive();
if let Some(history) = history { if let Some(history) = history {
for (date, activity) in history { for (date, activity) in history {
let distance = now - *date; let distance = now - *date;
let index = counts.len() as i64 - distance.num_days() - 1; let index = counts.len() as i64 - distance.num_days() - 1;
if index == 210 {
println!("invalid index")
}
if index < 0 { if index < 0 {
continue; continue;
} }
@@ -300,8 +437,7 @@ impl RepetitionsState {
}) })
.spacing(QUARTER_SPACING); .spacing(QUARTER_SPACING);
let mut iter = counts.iter();
let mut iter = counts.into_iter();
for i in 0..30 { for i in 0..30 {
let mut column = Column::new().spacing(QUARTER_SPACING); let mut column = Column::new().spacing(QUARTER_SPACING);
@@ -309,13 +445,17 @@ impl RepetitionsState {
let value = *iter.next().unwrap() as f32; let value = *iter.next().unwrap() as f32;
let k = (value / MAX_DAY_COUNT).min(1.0) * 0.9 + 0.1; let k = (value / MAX_DAY_COUNT).min(1.0) * 0.9 + 0.1;
let date = now.clone().checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1)).unwrap(); let date = (*now)
.checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1))
.unwrap();
column = column.push(tooltip( column = column.push(tooltip(
iced::widget::container(space().height(15).width(15)).style( iced::widget::container(space().height(15).width(15)).style(
move |x: &Theme| container::Style { move |x: &Theme| container::Style {
text_color: None, text_color: None,
background: Some(Background::Color(x.palette().primary.scale_alpha(k))), background: Some(Background::Color(
x.palette().primary.scale_alpha(k),
)),
border: Border { border: Border {
color: Default::default(), color: Default::default(),
width: 0.0, width: 0.0,
@@ -332,67 +472,81 @@ impl RepetitionsState {
row = row.push(column); row = row.push(column);
} }
scrollable(column!["Карта активности", row].spacing(QUARTER_SPACING).align_x(Center)) scrollable(
}).into() column!["Карта активности", row]
.spacing(QUARTER_SPACING)
} .align_x(Center),
fn words_words_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
column![
text!("Худшие слова"),
container(scrollable(self.worst_words_list(&set)).height(200)).style(bordered_box),
radio(
"Начать с плохих слов",
SetOrderMode::TrainWorstFirst,
Some(set.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
SetOrderMode::FullRandom,
Some(set.open_mode),
SetOpenMode
) )
] })
.spacing(DEFAULT_SPACING)
.into() .into()
} }
fn word_append_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
fn worst_words_list(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> { column![
let mut column = Column::new(); text!("Режим добавления карточек"),
row![
for word in set.worst_words_list.clone().unwrap() { radio(
column = column.push(text!("{} | {}", &word.key, &word.value)); "Добавлять все доступные",
AppendMode::Full,
Some(deck.append_mode),
SetAppendMode
),
radio(
"Добавлять вручную",
AppendMode::Manual,
Some(deck.append_mode),
SetAppendMode
)
]
.spacing(HALF_SPACING),
self.adder_panel(deck),
]
.spacing(HALF_SPACING)
.into()
}
fn adder_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
match deck.append_mode {
AppendMode::Full => space().into(),
AppendMode::Manual => row![
button("+5").on_press(AppendWords(5)),
button("+10").on_press(AppendWords(10)),
button("+15").on_press(AppendWords(15)),
button("+20").on_press(AppendWords(20))
]
.spacing(HALF_SPACING)
.into(),
} }
column.into()
} }
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> { fn count_comparator_view(&self) -> Element<'_, RepetitionsMessage> {
if let Some(count) = set.count { let selected_deck = self.selected_deck().unwrap();
let now = selected_deck.existing_words_indices.as_ref().unwrap().len();
let available = selected_deck
.available_words_indices
.as_ref()
.unwrap()
.len();
text!("{} слова добавлено из {}", now, available).into()
}
fn count_view(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
if let Some(count) = deck.count {
return text!("Количество слов: {}", count).into(); return text!("Количество слов: {}", count).into();
} }
space().into() space().into()
} }
fn decks_list(&self) -> Column<'_, RepetitionsMessage> {
fn sets_list(&self) -> Column<'_, RepetitionsMessage> {
let mut column = Column::new(); let mut column = Column::new();
let mut i = 0;
let sets = &self.state.lock().unwrap().card_sets; for (i, deck) in self.decks.iter().enumerate() {
for set in sets {
column = column.push( column = column.push(
button(text!("{}", set.name.clone())) button(text!("{}", &deck.name))
.on_press_with(move || SelectSet(i.clone())) .on_press_with(move || SelectSet(i))
.style(move |_x: &Theme, status: Status| Style { .style(move |_x: &Theme, status: Status| Style {
background: if status == Status::Hovered { background: if status == Status::Hovered {
Some(Background::Color(Color::WHITE.scale_alpha(0.2))) Some(Background::Color(Color::WHITE.scale_alpha(0.2)))
} else { } else {
None None
}, },
text_color: if self.correct_filters[i.clone()] { text_color: _x.palette().primary,
_x.palette().primary
} else {
_x.palette().warning
},
border: Border { border: Border {
color: Default::default(), color: Default::default(),
width: 0.0, width: 0.0,
@@ -402,13 +556,69 @@ impl RepetitionsState {
snap: false, snap: false,
}), }),
); );
i += 1;
} }
column column
} }
} }
impl RepetitionsState {
fn append_all_words(state: &mut AppState, deck: &DeckViewData) {
let existing = deck.existing_words_indices.as_ref().unwrap();
let mut created_set = HashSet::with_capacity(existing.len());
existing.iter().for_each(|c| {
created_set.insert(c);
});
let required = deck
.available_words_indices
.as_ref()
.unwrap()
.iter()
.filter(|i| !created_set.contains(i))
.cloned();
Self::append_words(state, deck, required);
}
fn append_words(
state: &mut AppState,
deck: &DeckSettings,
indices: impl Iterator<Item = usize>,
) {
let words = &state.dictionary;
let stats = &mut indices
.map(|i| {
let word = &words[i];
CardStatistics {
id: 0.into(),
word_id: word.id,
last_open: Utc::now(),
score: 1,
set_id: deck.id,
}
})
.collect::<Vec<_>>();
if !stats.is_empty() {
add_stat_list(stats, &mut state.connection);
}
}
fn select_deck(&mut self, index: usize) {
if self.decks.get(index).is_some() {
self.selected_deck_index = Some(index);
}
}
fn selected_deck(&self) -> Option<&DeckViewData> {
self.decks.get(self.selected_deck_index?)
}
fn selected_deck_mut(&mut self) -> Option<&mut DeckViewData> {
self.decks.get_mut(self.selected_deck_index?)
}
fn clear_selection(&mut self) {
self.selected_deck_index = None;
}
}
#[derive(Clone)] #[derive(Clone)]
pub enum RepetitionsMessage { pub enum RepetitionsMessage {
Next, Next,
@@ -423,111 +633,25 @@ pub enum RepetitionsMessage {
SetBackward(String), SetBackward(String),
SetFilter(String), SetFilter(String),
TryFilter, TryFilter,
SetOpenMode(SetOrderMode), SetOpenMode(OrderMode),
SetAppendMode(AppendMode),
GoToHistory, GoToHistory,
GoToSettings, GoToSettings,
AppendWords(usize),
} }
#[derive(Clone)] #[derive(Clone)]
pub struct CardSetSettings { struct DeckViewData {
pub id: u32, general_settings: DeckSettings,
pub name: String, existing_words_indices: Option<Vec<usize>>,
pub forward: String, available_words_indices: Option<Vec<usize>>,
pub backward: String, append_mode: AppendMode,
pub filter: String, index: Option<usize>,
pub count: Option<usize>,
pub worst_words_list: Option<Vec<WordData>>,
pub open_mode: SetOrderMode,
} }
impl Deref for DeckViewData {
type Target = DeckSettings;
impl CardSetSettings { fn deref(&self) -> &Self::Target {
fn with_name(name: String) -> CardSetSettings { &self.general_settings
CardSetSettings {
id: 0,
name,
forward: "".to_string(),
backward: "".to_string(),
filter: "true".to_string(),
count: None,
worst_words_list: None,
open_mode: SetOrderMode::Default,
}
}
fn check_filter(&self) -> bool {
let engine = Engine::new();
let ast = engine.compile(&self.filter);
ast.is_ok()
}
pub fn get_word_list(&self, state: &AppState) -> Vec<WordData> {
let mut list = vec![];
let engine = Engine::new();
let ast = engine.compile(&self.filter);
if ast.is_err() {
return list;
}
let ast = ast.unwrap();
let groups = &state.word_groups;
for word in &state.dictionary {
let mut more = rhai::Map::new();
for iced in &word.additional {
more.insert(iced.0.clone().into(), iced.1.clone().into());
}
let mut scope = Scope::new();
scope
.push_constant("key", word.key.clone())
.push_constant("value", word.value.clone())
.push_constant("tags", word.tags.clone())
.push_constant("more", more)
.push_constant(
"group",
groups
.iter()
.find(|g| g.id == word.group_id)
.cloned()
.unwrap()
.name,
);
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
if result.is_ok() && result.unwrap() {
list.push(word.clone());
}
}
list
}
pub fn require_speech(&self) -> bool {
self.forward == "speech" || self.backward == "speech"
}
fn update_worst_words(&mut self, state: &AppState) {
if let Some(_) = self.worst_words_list {
return;
}
let connection = &state.connection;
let mut stats = load_stats_of_set(self, connection);
stats.sort_by_key(|s| s.calculated_score() as i32);
let avg = stats.iter().map(|s| s.calculated_score()).sum::<f32>() / stats.len() as f32;
let avg = avg * 0.7;
let bad: Vec<WordData> = stats
.iter()
.take_while(|word| word.calculated_score() < avg)
.map(|stat| {
state.dictionary[state
.dictionary
.binary_search_by_key(&stat.word_id, |x| x.id)
.unwrap()]
.clone()
})
.collect();
self.worst_words_list = Some(bad.clone());
} }
} }
+7 -10
View File
@@ -15,7 +15,8 @@ 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;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
pub struct SelectorState { pub struct SelectorState {
pub set: KanaSet, pub set: KanaSet,
@@ -36,7 +37,7 @@ pub enum SelectorMessage {
} }
impl NavigatedPage<SelectorMessage> for SelectorState { impl NavigatedPage<SelectorMessage> for SelectorState {
fn navigate(&self, message: &SelectorMessage) -> Option<Page> { fn navigate(&mut self, message: &SelectorMessage) -> Option<Page> {
if let SelectorMessage::Goto = message { if let SelectorMessage::Goto = message {
return if self.is_writing { return if self.is_writing {
let writing = WritingState::new(&self.set); let writing = WritingState::new(&self.set);
@@ -62,8 +63,7 @@ impl NavigatedPage<SelectorMessage> for SelectorState {
None None
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: SelectorMessage) -> Task<RootMessage> { fn update(&mut self, message: SelectorMessage) -> Task<RootMessage> {
match message { match message {
SelectorMessage::Change => match self.set.chars_type { SelectorMessage::Change => match self.set.chars_type {
@@ -105,10 +105,10 @@ impl NavigatedPage<SelectorMessage> for SelectorState {
.on_press(SelectorMessage::Goto) .on_press(SelectorMessage::Goto)
.style(cta_button), .style(cta_button),
] ]
.spacing(DEFAULT_SPACING), .spacing(DEFAULT_SPACING),
) )
.padding(10) .padding(10)
.into() .into()
} }
} }
@@ -121,7 +121,6 @@ impl SelectorState {
} }
} }
fn nav_style(theme: &Theme, status: Status) -> Style { fn nav_style(theme: &Theme, status: Status) -> Style {
let mut basic = button::text(theme, status); let mut basic = button::text(theme, status);
basic.background = if status == Status::Hovered { basic.background = if status == Status::Hovered {
@@ -133,8 +132,6 @@ impl SelectorState {
basic basic
} }
fn rows_selector(&self) -> Element<'_, SelectorMessage> { fn rows_selector(&self) -> Element<'_, SelectorMessage> {
let mut row = Row::new(); let mut row = Row::new();
+2 -2
View File
@@ -1,10 +1,10 @@
use crate::repetitions::Style; use crate::repetitions::Style;
use iced::Element;
use iced::border::Radius; use iced::border::Radius;
use iced::widget::button::*; use iced::widget::button::*;
use iced::widget::{button, container}; use iced::widget::{button, container};
use iced::Element;
use iced_core::alignment::Horizontal::Left;
use iced_core::Length::Fill; use iced_core::Length::Fill;
use iced_core::alignment::Horizontal::Left;
use iced_core::{Border, Theme}; use iced_core::{Border, Theme};
pub const HALF_SPACING: f32 = DEFAULT_SPACING / 2.0; pub const HALF_SPACING: f32 = DEFAULT_SPACING / 2.0;
+24 -21
View File
@@ -4,15 +4,15 @@ use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::styling::*; use crate::styling::*;
use crate::sync::SyncMessage::*; use crate::sync::SyncMessage::*;
use crate::{fill_state, AppState, RootMessage}; use crate::{AppState, RootMessage, fill_state};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::container::rounded_box; use iced::widget::container::rounded_box;
use iced::widget::{button, column, container, progress_bar, row, space, text, toggler}; use iced::widget::{button, column, container, progress_bar, row, space, text, toggler};
use iced::{Center, Element, Fill, Font, Length, Task}; use iced::{Center, Element, Fill, Font, Length, Task};
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
use std::time::Duration; use std::time::Duration;
#[derive(Clone)] #[derive(Clone)]
pub enum SyncMessage { pub enum SyncMessage {
Back, Back,
@@ -38,7 +38,7 @@ pub struct SyncState {
} }
impl NavigatedPage<SyncMessage> for SyncState { impl NavigatedPage<SyncMessage> for SyncState {
fn navigate(&self, message: &SyncMessage) -> Option<Page> { fn navigate(&mut self, message: &SyncMessage) -> Option<Page> {
if let Back = message if let Back = message
&& !self.frozen && !self.frozen
{ {
@@ -53,7 +53,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
match message { match message {
Back => {} Back => {}
CopyKey => { CopyKey => {
let state = self.state.lock().unwrap(); let state = self.state.lock();
let key = state.sync_data.key.clone().unwrap(); let key = state.sync_data.key.clone().unwrap();
return iced::clipboard::write(key) return iced::clipboard::write(key)
.map(|_val: String| RootMessage::Sync(KeyCopied)); .map(|_val: String| RootMessage::Sync(KeyCopied));
@@ -67,17 +67,17 @@ impl NavigatedPage<SyncMessage> for SyncState {
} }
KeyCopied => {} KeyCopied => {}
IdReceived(new_id) => { IdReceived(new_id) => {
if validate_id(&new_id) == false { if !validate_id(&new_id) {
return Task::none(); return Task::none();
} }
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data.key = Some(new_id.clone()); state.sync_data.key = Some(new_id.clone());
set_setting("SYNC_KEY".to_string(), new_id, &state.connection); set_setting("SYNC_KEY".to_string(), new_id, &state.connection);
} }
Send => { Send => {
self.prepare_to_db_interaction(); self.prepare_to_db_interaction();
let id = self.state.lock().unwrap().sync_data.key.clone().unwrap(); let id = self.state.lock().sync_data.key.clone().unwrap();
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 },
@@ -89,7 +89,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
return tasks; return tasks;
} }
GetLast => { GetLast => {
let id = self.state.lock().unwrap().sync_data.key.clone().unwrap(); let id = self.state.lock().sync_data.key.clone().unwrap();
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 },
@@ -117,26 +117,29 @@ impl NavigatedPage<SyncMessage> for SyncState {
let mut updated_state = AppState::new(); let mut updated_state = AppState::new();
fill_state(&mut updated_state); fill_state(&mut updated_state);
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data = updated_state.sync_data; state.sync_data = updated_state.sync_data;
state.connection = updated_state.connection; state.connection = updated_state.connection;
state.card_sets = updated_state.card_sets; state.decks = updated_state.decks;
state.dictionary = updated_state.dictionary; state.dictionary = updated_state.dictionary;
state.word_groups = updated_state.word_groups; state.word_groups = updated_state.word_groups;
} }
Disable => {} Disable => {}
DisableSync => { DisableSync => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data.key = None; state.sync_data.key = None;
delete_settings("SYNC_KEY".to_string(), &state.connection); delete_settings("SYNC_KEY".to_string(), &state.connection);
delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection); delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection);
} }
SwitchAutoSync => { SwitchAutoSync => {
self.auto_fetch = !self.auto_fetch; self.auto_fetch = !self.auto_fetch;
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data.auto_web_fetch = self.auto_fetch; state.sync_data.auto_web_fetch = self.auto_fetch;
set_setting("AUTO_WEB_FETCH".to_string(), self.auto_fetch.to_string(), &state.connection); set_setting(
"AUTO_WEB_FETCH".to_string(),
self.auto_fetch.to_string(),
&state.connection,
);
} }
} }
Task::none() Task::none()
@@ -157,7 +160,7 @@ impl SyncState {
pub fn new(state: Arc<Mutex<AppState>>) -> SyncState { pub fn new(state: Arc<Mutex<AppState>>) -> SyncState {
let auto_fetch; let auto_fetch;
{ {
auto_fetch = state.lock().unwrap().sync_data.auto_web_fetch; auto_fetch = state.lock().sync_data.auto_web_fetch;
} }
Self { Self {
auto_fetch, auto_fetch,
@@ -167,8 +170,6 @@ impl SyncState {
} }
} }
fn sync_column(&self) -> Element<'_, SyncMessage> { fn sync_column(&self) -> Element<'_, SyncMessage> {
let network_view: Element<'_, SyncMessage> = if self.frozen { let network_view: Element<'_, SyncMessage> = if self.frozen {
progress_bar(0.0..=5.0, self.progress).into() progress_bar(0.0..=5.0, self.progress).into()
@@ -176,7 +177,7 @@ impl SyncState {
space().into() space().into()
}; };
{ {
if let Some(key) = self.state.lock().unwrap().sync_data.key.clone() { if let Some(key) = self.state.lock().sync_data.key.clone() {
column![ column![
text!("Ваш ключ синхронизации"), text!("Ваш ключ синхронизации"),
container( container(
@@ -198,7 +199,9 @@ impl SyncState {
button("↓ Скачать").style(jl_button).on_press(GetLast) button("↓ Скачать").style(jl_button).on_press(GetLast)
] ]
.spacing(DEFAULT_SPACING), .spacing(DEFAULT_SPACING),
toggler(self.auto_fetch).label("Автоматическая синхронизация").on_toggle(|_| SwitchAutoSync), toggler(self.auto_fetch)
.label("Автоматическая синхронизация")
.on_toggle(|_| SwitchAutoSync),
container(network_view).width(Fill), container(network_view).width(Fill),
button("Отключить синхронизацию") button("Отключить синхронизацию")
.style(danger) .style(danger)
@@ -231,7 +234,7 @@ impl SyncState {
} }
self.frozen = true; self.frozen = true;
self.progress = 0.0; self.progress = 0.0;
let state = self.state.lock().unwrap(); let state = self.state.lock();
state state
.connection .connection
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
+12 -18
View File
@@ -8,7 +8,8 @@ use crate::{AppState, RootMessage};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::{button, column, row, rule, scrollable, text, text_input}; use iced::widget::{button, column, row, rule, scrollable, text, text_input};
use iced::{Element, Fill, Task}; use iced::{Element, Fill, Task};
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use parking_lot::Mutex;
#[derive(Clone)] #[derive(Clone)]
pub struct WordState { pub struct WordState {
@@ -18,7 +19,7 @@ pub struct WordState {
} }
impl NavigatedPage<WordMessage> for WordState { impl NavigatedPage<WordMessage> for WordState {
fn navigate(&self, message: &WordMessage) -> Option<Page> { fn navigate(&mut self, message: &WordMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -31,13 +32,13 @@ impl NavigatedPage<WordMessage> for WordState {
match message { match message {
Back => {} Back => {}
Save => { Save => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.dictionary[self.index] = self.word.clone(); state.dictionary[self.index] = self.word.clone();
update_word(&mut self.word, &state.connection); update_word(&mut self.word, &state.connection);
return Task::done(RootMessage::Word(Back)); return Task::done(RootMessage::Word(Back));
} }
Delete => { Delete => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.dictionary.remove(self.index); state.dictionary.remove(self.index);
delete_word(&self.word, &state.connection); delete_word(&self.word, &state.connection);
return Task::done(RootMessage::Word(Back)); return Task::done(RootMessage::Word(Back));
@@ -49,11 +50,9 @@ impl NavigatedPage<WordMessage> for WordState {
SetValue(n) => { SetValue(n) => {
self.word.value = n; self.word.value = n;
} }
SetAdditional(key, value) => match key.as_str() { SetAdditional(key, value) => {
_ => { self.word.additional.insert(key, value.clone());
self.word.additional.insert(key, value.clone()); }
}
},
AddAdditional(key) => { AddAdditional(key) => {
self.word.additional.insert(key, "".to_string()); self.word.additional.insert(key, "".to_string());
} }
@@ -145,23 +144,18 @@ impl WordState {
} }
} }
fn reading_field(&self, value: &String) -> Element<'_, WordMessage> { fn reading_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "Чтение слова".to_string(), "reading".to_string()) self.additional_field(value, "Чтение слова".to_string(), "reading".to_string())
} }
fn description_field(&self, value: &String) -> Element<'_, WordMessage> { fn description_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "Описание".to_string(), "description".to_string()) self.additional_field(value, "Описание".to_string(), "description".to_string())
} }
fn context_field(&self, value: &String) -> Element<'_, WordMessage> { fn context_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "В контексте".to_string(), "context".to_string()) self.additional_field(value, "В контексте".to_string(), "context".to_string())
} }
fn additional_field( fn additional_field(&self, value: &str, name: String, id: String) -> Element<'_, WordMessage> {
&self,
value: &String,
name: String,
id: String,
) -> Element<'_, WordMessage> {
column![ column![
text!("{}", name), text!("{}", name),
row![ row![
+16 -21
View File
@@ -1,10 +1,10 @@
use crate::RootMessage;
use crate::lang::KanaSet; use crate::lang::KanaSet;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::styling::*; use crate::styling::*;
use crate::RootMessage;
use iced::widget::*; use iced::widget::*;
use iced::{alignment, Element, Fill, Task}; use iced::{Element, Fill, Task, alignment};
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -19,7 +19,7 @@ pub struct WritingState {
} }
impl NavigatedPage<WritingMessage> for WritingState { impl NavigatedPage<WritingMessage> for WritingState {
fn navigate(&self, message: &WritingMessage) -> Option<Page> { fn navigate(&mut self, message: &WritingMessage) -> Option<Page> {
if let WritingMessage::Back = message { if let WritingMessage::Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -27,11 +27,10 @@ impl NavigatedPage<WritingMessage> for WritingState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: WritingMessage) -> Task<RootMessage> { fn update(&mut self, message: WritingMessage) -> Task<RootMessage> {
match message { match message {
WritingMessage::Back => todo!(), WritingMessage::Back => {}
WritingMessage::Next => self.next(), WritingMessage::Next => self.next(),
WritingMessage::SwitchShowMode(b) => self.show_all = b, WritingMessage::SwitchShowMode(b) => self.show_all = b,
} }
@@ -56,13 +55,13 @@ impl NavigatedPage<WritingMessage> for WritingState {
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
.align_x(alignment::Horizontal::Center), .align_x(alignment::Horizontal::Center),
) )
.center_x(Fill) .center_x(Fill)
.center_y(Fill) .center_y(Fill)
.padding(10) .padding(10)
.into() .into()
} }
} }
@@ -83,8 +82,6 @@ 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 = "".to_string();
@@ -97,24 +94,22 @@ impl WritingState {
} }
if self.show_all { if self.show_all {
if self.set.is_empty() == false && self.kana_total.is_empty() == false { if !self.set.is_empty() && !self.kana_total.is_empty() {
self.set.clear(); self.set.clear();
} }
for pair in &self.set { for pair in &self.set {
self.kana = "---".to_string(); self.kana = "---".to_string();
self.roman_total += &*format!("{} ", &pair.1.clone()).to_string(); self.roman_total += &*format!("{} ", pair.1.clone()).to_string();
self.kana_total += &*format!("{} ", &pair.0).to_string(); self.kana_total += &*format!("{} ", pair.0).to_string();
} }
} else { } else {
let current = self.set.pop().unwrap(); let current = self.set.pop().unwrap();
self.kana_total += &*format!("{} ", &current.0).to_string(); self.kana_total += &*format!("{} ", current.0).to_string();
self.roman_total += &*format!("{} ", &current.1.clone()).to_string(); self.roman_total += &*format!("{} ", current.1.clone()).to_string();
self.kana = current.1; self.kana = current.1;
} }
} }
fn answers(&self) -> Element<'_, WritingMessage> { fn answers(&self) -> Element<'_, WritingMessage> {
if self.set.is_empty() { if self.set.is_empty() {
text!("{}", self.kana_total).size(36).into() text!("{}", self.kana_total).size(36).into()