Compare commits
60
Commits
6387afba93
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
142c2d3d10 | ||
|
|
27bdcf41b0 | ||
|
|
5817bfcd46 | ||
|
|
a36613b238 | ||
|
|
496f246125 | ||
|
|
7ad44110c3 | ||
|
|
0b23da9eda | ||
|
|
5b2b48c88f | ||
|
|
632f0c341b | ||
|
|
65991f742e | ||
|
|
79c42d0feb | ||
|
|
4b9e257cdf | ||
|
|
6628d79307 | ||
|
|
936efd0e99 | ||
|
|
8603e9b981 | ||
|
|
824a868d73 | ||
|
|
8b673e52da | ||
|
|
b210b2013d | ||
|
|
48cd68d1c7 | ||
|
|
a5526dc5e9 | ||
|
|
1d4b37e381 | ||
|
|
96a58c61bc | ||
|
|
1847d4f44f | ||
|
|
b1902b35cb | ||
|
|
5d12f3b02a | ||
|
|
0e867a33ce | ||
|
|
ccfb302770 | ||
|
|
0de809fcce | ||
|
|
e5622c70de | ||
|
|
cbf49412ec | ||
|
|
f61f93717c | ||
|
|
be64b1da2d | ||
|
|
2568b9f292 | ||
|
|
05c82bee02 | ||
|
|
5d305affd3 | ||
|
|
d59776d713 | ||
|
|
adb6388ee2 | ||
|
|
8fe4f3b8f4 | ||
|
|
47bc83d4ae | ||
|
|
097c3c033c | ||
|
|
c30be42822 | ||
|
|
ace54b10e1 | ||
|
|
f66bf69ef5 | ||
|
|
1ad991667b | ||
|
|
444352c007 | ||
|
|
2069bdf5b3 | ||
|
|
28730c0fda | ||
|
|
7715aaff3b | ||
|
|
a20c72eb9d | ||
|
|
58bdaac7fe | ||
|
|
4a71f31e6f | ||
|
|
6e3f58d21c | ||
|
|
3663765284 | ||
|
|
294f0e8b98 | ||
|
|
2e04450c76 | ||
|
|
242b56fc21 | ||
|
|
7f9aa11d6e | ||
|
|
92b019b072 | ||
|
|
9c93ca4408 | ||
|
|
e2f367f3aa |
No files matched your search
Generated
+67
-641
File diff suppressed because it is too large.
Load diff
+9
-17
@@ -1,23 +1,23 @@
|
||||
[package]
|
||||
name = "jap_learn"
|
||||
version = "0.1.3"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
iced = { version = "0.14.0", features = ["tokio", "svg", "lazy"]}
|
||||
iced = { version = "0.14.0", features = ["tokio", "svg", "lazy", "crisp", "tiny-skia", "wayland", "wgpu"], default-features = false}
|
||||
iced_core = "0.14.0"
|
||||
rand = "0.10.2"
|
||||
dirs = "6.0.0"
|
||||
rand = "0.10.3"
|
||||
dirs = "7.0.0"
|
||||
serde_json = "1.0.151"
|
||||
rhai = { version = "1.26.0", features = ["sync"] }
|
||||
rhai = { version = "1.26.1", features = ["sync"] }
|
||||
chrono = "0.4.45"
|
||||
rusqlite = { version = "0.40.2", features = ["chrono", "bundled"] }
|
||||
reqwest = { version = "0.13.4", features = ["json", "stream", "multipart"] }
|
||||
reqwest = { version = "0.13.5", features = ["json", "stream", "multipart"] }
|
||||
rodio = "0.22.2"
|
||||
sha2 = "0.11.0"
|
||||
tokio = { version = "1.53.1", features = ["rt", "rt-multi-thread", "macros"] }
|
||||
tokio = { version = "1.53.2", features = ["rt", "rt-multi-thread", "macros"] }
|
||||
hex = "0.4.3"
|
||||
zstd = "0.13.3"
|
||||
zstd = "0.14.1"
|
||||
zip = "8.6.0"
|
||||
rfd = "0.17.2"
|
||||
mimalloc = "0.1.52"
|
||||
@@ -27,7 +27,7 @@ parking_lot = "0.12.5"
|
||||
env_logger = "0.11.11"
|
||||
log = "0.4.34"
|
||||
fsrs = "6.6.2"
|
||||
litemap = { version = "0.8.3", features = ["serde"] }
|
||||
litemap = { version = "0.8.3" }
|
||||
|
||||
[profile.super-release]
|
||||
inherits = "release"
|
||||
@@ -40,11 +40,3 @@ panic = "abort"
|
||||
[dev-dependencies]
|
||||
criterion = { version = "0.8.2", features = ["html_reports"] }
|
||||
rustc-hash = "2.1.3"
|
||||
|
||||
[[bench]]
|
||||
name = "map_bench"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "repo_cache_bench"
|
||||
harness = false
|
||||
@@ -1,126 +0,0 @@
|
||||
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);
|
||||
@@ -1,325 +0,0 @@
|
||||
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
|
||||
use hashbrown::HashMap as HashbrownMap;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::hint::black_box;
|
||||
|
||||
// Тестовая структура (аналог вашей сущности)
|
||||
#[derive(Debug, Clone)]
|
||||
struct Entity {
|
||||
id: i64,
|
||||
data: [u8; 64], // 64 байта данных для реалистичности
|
||||
}
|
||||
|
||||
impl Entity {
|
||||
fn new(id: i64) -> Self {
|
||||
Self {
|
||||
id,
|
||||
data: [id as u8; 64],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== ТЕСТОВЫЕ ФУНКЦИИ ==========
|
||||
|
||||
fn bench_vec_insert_sorted(vec: &mut Vec<Entity>, entities: &[Entity]) {
|
||||
vec.clear();
|
||||
for entity in entities {
|
||||
vec.push(entity.clone());
|
||||
}
|
||||
// Vec уже отсортирован, так как ID монотонно возрастают
|
||||
}
|
||||
|
||||
fn bench_vec_search_separated<'a>(ids: &[i64], vec: &'a [Entity], id: i64) -> Option<&'a Entity> {
|
||||
match ids.binary_search(&id) {
|
||||
Ok(index) => Some(&vec[index]),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_vec_search(vec: &Vec<Entity>, id: i64) -> Option<&Entity> {
|
||||
match vec.binary_search_by(|probe| probe.id.cmp(&id)) {
|
||||
Ok(index) => Some(&vec[index]),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_btreemap_insert(map: &mut BTreeMap<i64, Entity>, entities: &[Entity]) {
|
||||
map.clear();
|
||||
for entity in entities {
|
||||
map.insert(entity.id, entity.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_btreemap_search(map: &BTreeMap<i64, Entity>, id: i64) -> Option<&Entity> {
|
||||
map.get(&id)
|
||||
}
|
||||
|
||||
fn bench_hashmap_insert(map: &mut HashMap<i64, Entity>, entities: &[Entity]) {
|
||||
map.clear();
|
||||
for entity in entities {
|
||||
map.insert(entity.id, entity.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_hashmap_search(map: &HashMap<i64, Entity>, id: i64) -> Option<&Entity> {
|
||||
map.get(&id)
|
||||
}
|
||||
|
||||
fn bench_hashbrown_insert(map: &mut HashbrownMap<i64, Entity>, entities: &[Entity]) {
|
||||
map.clear();
|
||||
for entity in entities {
|
||||
map.insert(entity.id, entity.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_hashbrown_search(map: &HashbrownMap<i64, Entity>, id: i64) -> Option<&Entity> {
|
||||
map.get(&id)
|
||||
}
|
||||
|
||||
fn bench_fxhashmap_insert(map: &mut FxHashMap<i64, Entity>, entities: &[Entity]) {
|
||||
map.clear();
|
||||
for entity in entities {
|
||||
map.insert(entity.id, entity.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn bench_fxhashmap_search(map: &FxHashMap<i64, Entity>, id: i64) -> Option<&Entity> {
|
||||
map.get(&id)
|
||||
}
|
||||
|
||||
// ========== ГЕНЕРАЦИЯ ДАННЫХ ==========
|
||||
|
||||
fn generate_entities(count: usize) -> Vec<Entity> {
|
||||
(0..count).map(|i| Entity::new(i as i64)).collect()
|
||||
}
|
||||
|
||||
fn generate_search_ids(count: usize, max_id: i64) -> Vec<i64> {
|
||||
// 70% попаданий, 30% промахов (реалистичный сценарий)
|
||||
let mut ids = Vec::with_capacity(count);
|
||||
for i in 0..count {
|
||||
if i % 10 < 7 {
|
||||
// Попадание
|
||||
ids.push((i as i64 * 13) % max_id);
|
||||
} else {
|
||||
// Промах (несуществующий ID)
|
||||
ids.push(max_id + i as i64);
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
// ========== БЕНЧМАРКИ ==========
|
||||
|
||||
fn bench_insert(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("insert");
|
||||
|
||||
for size in [10_000, 100_000, 500_000] {
|
||||
let entities = generate_entities(size);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("Vec (sorted)", size),
|
||||
&entities,
|
||||
|b, entities| {
|
||||
let mut vec = Vec::with_capacity(size);
|
||||
b.iter(|| {
|
||||
bench_vec_insert_sorted(&mut vec, black_box(entities));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("BTreeMap", size),
|
||||
&entities,
|
||||
|b, entities| {
|
||||
let mut map = BTreeMap::new();
|
||||
b.iter(|| {
|
||||
bench_btreemap_insert(&mut map, black_box(entities));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("HashMap (std)", size),
|
||||
&entities,
|
||||
|b, entities| {
|
||||
let mut map = HashMap::new();
|
||||
b.iter(|| {
|
||||
bench_hashmap_insert(&mut map, black_box(entities));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("HashMap (hashbrown)", size),
|
||||
&entities,
|
||||
|b, entities| {
|
||||
let mut map = HashbrownMap::new();
|
||||
b.iter(|| {
|
||||
bench_hashbrown_insert(&mut map, black_box(entities));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("FxHashMap", size),
|
||||
&entities,
|
||||
|b, entities| {
|
||||
let mut map = FxHashMap::default();
|
||||
b.iter(|| {
|
||||
bench_fxhashmap_insert(&mut map, black_box(entities));
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn bench_search(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("search");
|
||||
|
||||
for size in [10_000, 100_000, 500_000] {
|
||||
let entities = generate_entities(size);
|
||||
let entity_ids = entities.iter().map(|entity| entity.id).collect::<Vec<_>>();
|
||||
let search_ids = generate_search_ids(1000, size as i64);
|
||||
|
||||
// Подготовка коллекций
|
||||
let mut vec = Vec::with_capacity(size);
|
||||
bench_vec_insert_sorted(&mut vec, &entities);
|
||||
|
||||
let mut btreemap = BTreeMap::new();
|
||||
bench_btreemap_insert(&mut btreemap, &entities);
|
||||
|
||||
let mut hashmap = HashMap::new();
|
||||
bench_hashmap_insert(&mut hashmap, &entities);
|
||||
|
||||
let mut hashbrown = HashbrownMap::new();
|
||||
bench_hashbrown_insert(&mut hashbrown, &entities);
|
||||
|
||||
let mut fxhashmap = FxHashMap::default();
|
||||
bench_fxhashmap_insert(&mut fxhashmap, &entities);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("Vec (binary search)", size),
|
||||
&search_ids,
|
||||
|b, ids| {
|
||||
b.iter(|| {
|
||||
for &id in ids {
|
||||
black_box(bench_vec_search_separated(&entity_ids, &vec, black_box(id)));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("Vec (binary search) separated", size),
|
||||
&search_ids,
|
||||
|b, ids| {
|
||||
b.iter(|| {
|
||||
for &id in ids {
|
||||
black_box(bench_vec_search(&vec, black_box(id)));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(BenchmarkId::new("BTreeMap", size), &search_ids, |b, ids| {
|
||||
b.iter(|| {
|
||||
for &id in ids {
|
||||
black_box(bench_btreemap_search(&btreemap, black_box(id)));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("HashMap (std)", size),
|
||||
&search_ids,
|
||||
|b, ids| {
|
||||
b.iter(|| {
|
||||
for &id in ids {
|
||||
black_box(bench_hashmap_search(&hashmap, black_box(id)));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("HashMap (hashbrown)", size),
|
||||
&search_ids,
|
||||
|b, ids| {
|
||||
b.iter(|| {
|
||||
for &id in ids {
|
||||
black_box(bench_hashbrown_search(&hashbrown, black_box(id)));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
group.bench_with_input(
|
||||
BenchmarkId::new("FxHashMap", size),
|
||||
&search_ids,
|
||||
|b, ids| {
|
||||
b.iter(|| {
|
||||
for &id in ids {
|
||||
black_box(bench_fxhashmap_search(&fxhashmap, black_box(id)));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
fn bench_memory_efficiency(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("memory_efficiency");
|
||||
|
||||
let size = 100_000;
|
||||
let entities = generate_entities(size);
|
||||
|
||||
group.bench_function("Vec memory", |b| {
|
||||
b.iter(|| {
|
||||
let mut vec = Vec::with_capacity(size);
|
||||
bench_vec_insert_sorted(&mut vec, black_box(&entities));
|
||||
black_box(vec);
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_function("BTreeMap memory", |b| {
|
||||
b.iter(|| {
|
||||
let mut map = BTreeMap::new();
|
||||
bench_btreemap_insert(&mut map, black_box(&entities));
|
||||
black_box(map);
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_function("HashMap (std) memory", |b| {
|
||||
b.iter(|| {
|
||||
let mut map = HashMap::new();
|
||||
bench_hashmap_insert(&mut map, black_box(&entities));
|
||||
black_box(map);
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_function("HashMap (hashbrown) memory", |b| {
|
||||
b.iter(|| {
|
||||
let mut map = HashbrownMap::new();
|
||||
bench_hashbrown_insert(&mut map, black_box(&entities));
|
||||
black_box(map);
|
||||
});
|
||||
});
|
||||
|
||||
group.bench_function("FxHashMap memory", |b| {
|
||||
b.iter(|| {
|
||||
let mut map = FxHashMap::default();
|
||||
bench_fxhashmap_insert(&mut map, black_box(&entities));
|
||||
black_box(map);
|
||||
});
|
||||
});
|
||||
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench_insert, bench_search, bench_memory_efficiency);
|
||||
criterion_main!(benches);
|
||||
@@ -1,4 +1,6 @@
|
||||
create table custom_fields(
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT not null
|
||||
create table custom_fields
|
||||
(
|
||||
id integer primary key,
|
||||
name text not null,
|
||||
identifier text not null
|
||||
);
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
create table decks
|
||||
(
|
||||
id INTEGER
|
||||
id integer
|
||||
primary key autoincrement,
|
||||
name TEXT not null,
|
||||
forward TEXT not null,
|
||||
backward TEXT not null,
|
||||
filter TEXT not null
|
||||
name text not null,
|
||||
forward text not null,
|
||||
backward text not null,
|
||||
filter text not null
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
create table exams(
|
||||
id integer primary key,
|
||||
timestamp integer,
|
||||
deck_id integer not null references decks on delete cascade
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
create table exam_entries
|
||||
(
|
||||
id integer primary key,
|
||||
exam_id integer not null references exams on delete cascade,
|
||||
word_id integer not null references words on delete cascade,
|
||||
status integer default null
|
||||
);
|
||||
+8
-8
@@ -1,12 +1,12 @@
|
||||
create table history
|
||||
(
|
||||
id INTEGER
|
||||
id integer
|
||||
primary key autoincrement,
|
||||
deck_id INTEGER not null references decks on delete cascade,
|
||||
word_id INTEGER not null references words on delete cascade,
|
||||
timestamp INTEGER not null,
|
||||
answer INTEGER not null,
|
||||
before INTEGER not null,
|
||||
after INTEGER not null,
|
||||
fsrs INTEGER not null
|
||||
deck_id integer not null references decks on delete cascade,
|
||||
word_id integer not null references words on delete cascade,
|
||||
timestamp integer not null,
|
||||
answer integer not null,
|
||||
before integer not null,
|
||||
after integer not null,
|
||||
fsrs integer not null
|
||||
);
|
||||
+8
-8
@@ -1,16 +1,16 @@
|
||||
create table states
|
||||
(
|
||||
id INTEGER
|
||||
id integer
|
||||
primary key autoincrement,
|
||||
word_id INTEGER not null
|
||||
word_id integer not null
|
||||
references words
|
||||
on delete cascade,
|
||||
deck_id INTEGER not null
|
||||
deck_id integer not null
|
||||
references decks
|
||||
on delete cascade,
|
||||
score INTEGER default 1 not null,
|
||||
last_opened INTEGER not null,
|
||||
fsrs_opened INTEGER not null,
|
||||
fsrs_memory INTEGER not null,
|
||||
fsrs_open_day INTEGER not null
|
||||
score integer default 1 not null,
|
||||
last_opened integer not null,
|
||||
fsrs_opened integer not null,
|
||||
fsrs_memory integer not null,
|
||||
fsrs_open_day integer not null
|
||||
);
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
create table word_groups
|
||||
(
|
||||
id INTEGER
|
||||
id integer
|
||||
primary key autoincrement,
|
||||
name TEXT not null
|
||||
name text not null
|
||||
);
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
create table words
|
||||
(
|
||||
id INTEGER
|
||||
id integer
|
||||
primary key autoincrement,
|
||||
key TEXT not null,
|
||||
value TEXT not null,
|
||||
tags TEXT not null,
|
||||
more TEXT,
|
||||
key text not null,
|
||||
value text not null,
|
||||
tags text not null,
|
||||
more text,
|
||||
group_id integer default 1 not null
|
||||
constraint words_word_groups_id_fk
|
||||
references word_groups
|
||||
|
||||
+12
-1
@@ -1,5 +1,6 @@
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::data_provider::card_states::CardStateRepository;
|
||||
use crate::data_provider::custom_fields::CustomFieldRepository;
|
||||
use crate::data_provider::decks::DeckRepository;
|
||||
use crate::data_provider::history::HistoryRepository;
|
||||
use crate::data_provider::settings::get_setting;
|
||||
@@ -17,6 +18,7 @@ use log::info;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use rusqlite::Connection;
|
||||
use std::sync::Arc;
|
||||
use crate::data_provider::exam::{ExamEntryRepository, ExamRepository};
|
||||
|
||||
pub const USER_FONT: Font = Font::with_name("Noto Sans JP");
|
||||
|
||||
@@ -65,9 +67,12 @@ pub struct AppState {
|
||||
pub decks: DeckRepository,
|
||||
pub word_groups: WordGroupRepository,
|
||||
pub card_states: CardStateRepository,
|
||||
pub custom_fields: CustomFieldRepository,
|
||||
pub connection: Arc<Mutex<SqliteConnection>>,
|
||||
pub sync_data: Arc<RwLock<AppSettings>>,
|
||||
pub history: HistoryRepository,
|
||||
pub exam: ExamRepository,
|
||||
pub exam_entries: ExamEntryRepository
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
@@ -85,6 +90,9 @@ impl AppState {
|
||||
word_groups: WordGroupRepository::new(connection.clone()),
|
||||
card_states: CardStateRepository::new(connection.clone()),
|
||||
history: HistoryRepository::new(connection.clone()),
|
||||
exam: ExamRepository::new(connection.clone()),
|
||||
custom_fields: CustomFieldRepository::new(connection.clone()),
|
||||
exam_entries: ExamEntryRepository::new(connection.clone()),
|
||||
sync_data: Arc::new(RwLock::new(AppSettings {
|
||||
key: None,
|
||||
auto_web_fetch: false,
|
||||
@@ -103,7 +111,10 @@ pub fn fill_state(state: &mut AppState) {
|
||||
state.dictionary.write().start().unwrap();
|
||||
state.decks.write().start().unwrap();
|
||||
state.history.write().start().unwrap();
|
||||
|
||||
state.card_states.write().start().unwrap();
|
||||
state.custom_fields.write().start().unwrap();
|
||||
state.exam.write().start().unwrap();
|
||||
state.exam_entries.write().start().unwrap();
|
||||
state.sync_data = Arc::new(RwLock::new(setting))
|
||||
}
|
||||
|
||||
|
||||
+94
-97
@@ -1,104 +1,92 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use chrono::Utc;
|
||||
use crate::app::AppState;
|
||||
use crate::core::srs::OrderModule::{Fsrs, RandomSRS, SemiRandomSRS, WorstWordsSRS};
|
||||
use crate::core::srs::{
|
||||
OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule,
|
||||
FsrsModule, OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule,
|
||||
WordOpenMode, WorstWordsSRSModule,
|
||||
};
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::*;
|
||||
use crate::data_provider::card_states::{CardStateRepositoryInner};
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::data_provider::card_states::CardStateRepositoryInner;
|
||||
use crate::notification::MaybeError;
|
||||
use chrono::Utc;
|
||||
use litemap::LiteMap;
|
||||
use log::info;
|
||||
use rhai::{Engine, Scope};
|
||||
use crate::data::repositories::Repository;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DeckData {
|
||||
pub(crate) words: Vec<EntityHandle<WordData>>,
|
||||
pub(crate) set: Vec<EntityHandle<CardState>>,
|
||||
pub(crate) states: Vec<EntityHandle<CardState>>,
|
||||
current_word_index: Option<usize>,
|
||||
state: AppState,
|
||||
order_module: OrderModule,
|
||||
open_mode: OrderMode,
|
||||
settings: DeckSettings,
|
||||
}
|
||||
|
||||
struct DisplayStyle {
|
||||
properties: LiteMap<String, String>,
|
||||
}
|
||||
|
||||
impl DeckData {
|
||||
pub fn new(
|
||||
settings: &DeckSettings,
|
||||
state: AppState,
|
||||
) -> Result<Self, NotificationData> {
|
||||
todo!()
|
||||
// let state_for = state.clone();
|
||||
//
|
||||
// let stats = state (settings, &state.connection.read())?;
|
||||
// let words = stats
|
||||
// .iter()
|
||||
// .map(|stat| {
|
||||
// state
|
||||
// .dictionary
|
||||
// .binary_search_by_key(&stat.word_id, |w| w.id)
|
||||
// .expect("No word found in dictionary")
|
||||
// })
|
||||
// .map(|index| &state.dictionary[index])
|
||||
// .cloned()
|
||||
// .collect();
|
||||
//
|
||||
// Ok(Self {
|
||||
// set: stats,
|
||||
// words,
|
||||
// current_word_index: None,
|
||||
// state: state_for,
|
||||
// order_module: Fsrs(FsrsModule::new()),
|
||||
// open_mode: settings.open_mode,
|
||||
// settings: settings.clone(),
|
||||
// })
|
||||
pub fn new(settings: &DeckSettings, open_mode: OrderMode, state: AppState) -> Self {
|
||||
let states_repo = state.card_states.read();
|
||||
let mut query = states_repo.deck_states(settings.id);
|
||||
let words = query
|
||||
.iter(&states_repo)
|
||||
.map(|card_state| EntityHandle::from_id(card_state.word_id))
|
||||
.collect();
|
||||
let states = query.handles().collect::<Vec<EntityHandle<CardState>>>();
|
||||
let fsrs = Fsrs(FsrsModule::new(
|
||||
Self::set_links(states.as_slice(), &states_repo).as_slice(),
|
||||
));
|
||||
drop(states_repo);
|
||||
Self {
|
||||
states,
|
||||
words,
|
||||
current_word_index: None,
|
||||
state,
|
||||
order_module: fsrs,
|
||||
open_mode,
|
||||
settings: settings.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next(&mut self) -> (EntityHandle<WordData>, EntityHandle<CardState>) {
|
||||
if self.fsrs_finished() {
|
||||
self.switch_order_engine()
|
||||
}
|
||||
let repo = self.state.card_states.read();
|
||||
let links = Self::set_links(self.set.as_slice(), &repo);
|
||||
let links = Self::set_links(self.states.as_slice(), &repo);
|
||||
let index = match self.order_module {
|
||||
SemiRandomSRS(ref mut module) => {
|
||||
if !module.initialized {
|
||||
module.init(links.as_slice());
|
||||
}
|
||||
module.next(links.as_slice())
|
||||
}
|
||||
SemiRandomSRS(ref mut module) => module.next(links.as_slice()),
|
||||
|
||||
RandomSRS(ref mut module) => {
|
||||
if !module.initialized {
|
||||
module.init(links.as_slice())
|
||||
}
|
||||
module.next(links.as_slice())
|
||||
}
|
||||
WorstWordsSRS(ref mut module) => {
|
||||
if !module.initialized {
|
||||
module.init(links.as_slice())
|
||||
}
|
||||
module.next(links.as_slice())
|
||||
}
|
||||
Fsrs(ref mut module) => {
|
||||
if !module.initialized {
|
||||
module.init(links.as_slice())
|
||||
}
|
||||
module.next(links.as_slice())
|
||||
}
|
||||
RandomSRS(ref mut module) => module.next(links.as_slice()),
|
||||
WorstWordsSRS(ref mut module) => module.next(links.as_slice()),
|
||||
Fsrs(ref mut module) => module.next(links.as_slice()),
|
||||
};
|
||||
|
||||
self.current_word_index = Some(index);
|
||||
(self.words[index].clone(), self.set[index].clone())
|
||||
(self.words[index], self.states[index])
|
||||
}
|
||||
|
||||
fn set_links<'a>(set: &[EntityHandle<CardState>], repo: &'a CardStateRepositoryInner) -> Vec<&'a CardState> {
|
||||
set.iter().map(|h| repo.get_ref_static(*h).unwrap()).collect::<Vec<_>>()
|
||||
fn set_links<'a>(
|
||||
set: &[EntityHandle<CardState>],
|
||||
repo: &'a CardStateRepositoryInner,
|
||||
) -> Vec<&'a CardState> {
|
||||
set.iter()
|
||||
.map(|h| repo.get_ref_static(*h).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
pub fn open(&mut self, status: WordOpenMode) -> MaybeError {
|
||||
if let Some(index) = self.current_word_index {
|
||||
let mut repo = self.state.card_states.write();
|
||||
let card_state_handle = &mut self.set[index];
|
||||
let card_state_handle = &mut self.states[index];
|
||||
let card_state = repo.get_mut(card_state_handle).unwrap();
|
||||
let old_score = card_state.score;
|
||||
card_state.update(status);
|
||||
@@ -121,16 +109,6 @@ impl DeckData {
|
||||
}
|
||||
}
|
||||
|
||||
if let Fsrs(ref fsrs) = self.order_module
|
||||
&& fsrs.finished()
|
||||
{
|
||||
self.order_module = match self.open_mode {
|
||||
OrderMode::Default => SemiRandomSRS(SemiRandomSRSModule::new()),
|
||||
OrderMode::TrainWorstFirst => WorstWordsSRS(WorstWordsSRSModule::new()),
|
||||
OrderMode::FullRandom => RandomSRS(RandomSRSModule::new()),
|
||||
}
|
||||
}
|
||||
|
||||
let word_id = card_state.word_id;
|
||||
repo.save(card_state_handle)?;
|
||||
|
||||
@@ -140,28 +118,39 @@ impl DeckData {
|
||||
timestamp: Utc::now(),
|
||||
deck_id: self.settings.id,
|
||||
word_id,
|
||||
answer: status.clone(),
|
||||
answer: status,
|
||||
before: old_score,
|
||||
after: new_score,
|
||||
fsrs,
|
||||
})?;
|
||||
todo!("Implement history pushing")
|
||||
// let _ = push_note(
|
||||
// self.settings.id,
|
||||
// HistoryNote {
|
||||
// timestamp: Utc::now(),
|
||||
// word_id: word.word_id,
|
||||
// answer: status,
|
||||
// before: old_score,
|
||||
// after: new_score,
|
||||
// },
|
||||
// );
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn switch_order_engine(&mut self) {
|
||||
let repo = self.state.card_states.read();
|
||||
let links = Self::set_links(self.states.as_slice(), &repo);
|
||||
self.order_module = match self.open_mode {
|
||||
OrderMode::Default => SemiRandomSRS(SemiRandomSRSModule::new(links.as_slice())),
|
||||
OrderMode::TrainWorstFirst => WorstWordsSRS(WorstWordsSRSModule::new(links.as_slice())),
|
||||
OrderMode::FullRandom => RandomSRS(RandomSRSModule::new(links.as_slice())),
|
||||
}
|
||||
}
|
||||
|
||||
fn fsrs_finished(&self) -> bool {
|
||||
if let Fsrs(ref fsrs) = self.order_module
|
||||
&& fsrs.finished()
|
||||
{
|
||||
info!("Fsrs finished. Infinite mode enabled");
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.set.len()
|
||||
self.states.len()
|
||||
}
|
||||
|
||||
pub fn list(deck: &DeckSettings, state: &AppState) -> Vec<EntityHandle<WordData>> {
|
||||
@@ -173,23 +162,31 @@ impl DeckData {
|
||||
if let Ok(ast) = ast {
|
||||
let groups = state.word_groups.read().iter().cloned().collect::<Vec<_>>();
|
||||
let dictionary = &state.dictionary.read();
|
||||
let fields: HashMap<Id, String> = HashMap::from_iter(
|
||||
state
|
||||
.custom_fields
|
||||
.read()
|
||||
.iter()
|
||||
.map(|f| (f.id, f.identifier.clone())),
|
||||
);
|
||||
let query = dictionary.query_par(Arc::new(move |word| {
|
||||
let mut more = rhai::Map::new();
|
||||
for iced in &word.additional {
|
||||
more.insert(iced.0.clone().into(), iced.1.clone().into());
|
||||
for kv in &word.additional {
|
||||
more.insert(fields[kv.0].clone().into(), kv.1.clone().into());
|
||||
}
|
||||
let mut scope = Scope::new();
|
||||
let group_name = groups[groups.binary_search_by_key(&word.group_id, |g| g.id).unwrap()].name.clone();
|
||||
let group_name = groups[groups
|
||||
.binary_search_by_key(&word.group_id, |g| g.id)
|
||||
.unwrap()]
|
||||
.name
|
||||
.clone();
|
||||
scope
|
||||
.push_constant("id", word.id.0 as i64)
|
||||
.push_constant("key", word.key.clone())
|
||||
.push_constant("value", word.value.clone())
|
||||
.push_constant("tags", word.tags.clone())
|
||||
.push_constant("more", more)
|
||||
.push_constant(
|
||||
"group",
|
||||
group_name,
|
||||
);
|
||||
.push_constant("group", group_name);
|
||||
|
||||
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
|
||||
if let Ok(result) = result {
|
||||
@@ -199,7 +196,7 @@ impl DeckData {
|
||||
}));
|
||||
|
||||
info!("Collecting available words is {:?}", time.elapsed());
|
||||
let handles =query.handles().collect();
|
||||
let handles = query.handles().collect();
|
||||
drop(query);
|
||||
handles
|
||||
} else {
|
||||
|
||||
+59
-102
@@ -31,24 +31,21 @@ pub enum OrderModule {
|
||||
Fsrs(FsrsModule),
|
||||
}
|
||||
pub trait SRSModule {
|
||||
fn new(set: &[&CardState]) -> Self;
|
||||
fn next(&mut self, set: &[&CardState]) -> usize;
|
||||
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &mut CardState);
|
||||
fn init(&mut self, set: &[&CardState]);
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct RandomSRSModule {
|
||||
basket: Vec<usize>,
|
||||
pub(crate) initialized: bool,
|
||||
}
|
||||
impl RandomSRSModule {
|
||||
pub(crate) fn new() -> RandomSRSModule {
|
||||
Self {
|
||||
basket: vec![],
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl SRSModule for RandomSRSModule {
|
||||
fn new(set: &[&CardState]) -> Self {
|
||||
let mut basket = (0..set.len()).collect::<Vec<usize>>();
|
||||
basket.shuffle(&mut rand::rng());
|
||||
Self { basket }
|
||||
}
|
||||
|
||||
fn next(&mut self, set: &[&CardState]) -> usize {
|
||||
match self.basket.pop() {
|
||||
Some(index) => index,
|
||||
@@ -61,31 +58,26 @@ impl SRSModule for RandomSRSModule {
|
||||
}
|
||||
|
||||
fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {}
|
||||
|
||||
fn init(&mut self, set: &[&CardState]) {
|
||||
self.initialized = true;
|
||||
self.basket = (0..set.len()).collect::<Vec<usize>>();
|
||||
self.basket.shuffle(&mut rand::rng())
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct SemiRandomSRSModule {
|
||||
history: Vec<usize>,
|
||||
last_weights: WeightedIndex<f32>,
|
||||
generator: ThreadRng,
|
||||
pub(crate) initialized: bool,
|
||||
}
|
||||
impl SemiRandomSRSModule {
|
||||
pub(crate) fn new() -> SemiRandomSRSModule {
|
||||
SemiRandomSRSModule {
|
||||
history: vec![],
|
||||
last_weights: WeightedIndex::new([1.0]).unwrap(),
|
||||
generator: rng(),
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl SRSModule for SemiRandomSRSModule {
|
||||
fn new(set: &[&CardState]) -> Self {
|
||||
let weights = set
|
||||
.iter()
|
||||
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
|
||||
.collect::<Vec<f32>>();
|
||||
|
||||
Self {
|
||||
generator: rng(),
|
||||
last_weights: WeightedIndex::new(weights).expect("Incorrect weights update"),
|
||||
history: vec![],
|
||||
}
|
||||
}
|
||||
fn next(&mut self, set: &[&CardState]) -> usize {
|
||||
let index = self.last_weights.sample(&mut self.generator);
|
||||
|
||||
@@ -106,14 +98,6 @@ impl SRSModule for SemiRandomSRSModule {
|
||||
.update_weights(&[(index, &new_weight)])
|
||||
.expect("update weights error");
|
||||
}
|
||||
fn init(&mut self, set: &[&CardState]) {
|
||||
self.initialized = true;
|
||||
let weights = set
|
||||
.iter()
|
||||
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
|
||||
.collect::<Vec<f32>>();
|
||||
self.last_weights = WeightedIndex::new(weights).expect("Incorrect weights update");
|
||||
}
|
||||
}
|
||||
impl SemiRandomSRSModule {
|
||||
fn history_len(&self, set: &[&CardState]) -> usize {
|
||||
@@ -122,7 +106,6 @@ impl SemiRandomSRSModule {
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct WorstWordsSRSModule {
|
||||
pub(crate) initialized: bool,
|
||||
pool_size: usize,
|
||||
rounds_remaining: u8,
|
||||
pool: Vec<usize>,
|
||||
@@ -130,6 +113,16 @@ pub struct WorstWordsSRSModule {
|
||||
rounds_count: u8,
|
||||
}
|
||||
impl SRSModule for WorstWordsSRSModule {
|
||||
fn new(_: &[&CardState]) -> Self {
|
||||
WorstWordsSRSModule {
|
||||
pool_size: PARTIAL_POOL_SIZE,
|
||||
rounds_count: 2,
|
||||
rounds_remaining: 0,
|
||||
pool: vec![],
|
||||
queue: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn next(&mut self, set: &[&CardState]) -> usize {
|
||||
if self.rounds_remaining == 0 {
|
||||
self.fill_pool(set);
|
||||
@@ -147,22 +140,8 @@ impl SRSModule for WorstWordsSRSModule {
|
||||
}
|
||||
|
||||
fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {}
|
||||
|
||||
fn init(&mut self, _: &[&CardState]) {
|
||||
self.initialized = true;
|
||||
}
|
||||
}
|
||||
impl WorstWordsSRSModule {
|
||||
pub(crate) fn new() -> WorstWordsSRSModule {
|
||||
WorstWordsSRSModule {
|
||||
initialized: false,
|
||||
pool_size: PARTIAL_POOL_SIZE,
|
||||
rounds_count: 2,
|
||||
rounds_remaining: 0,
|
||||
pool: vec![],
|
||||
queue: vec![],
|
||||
}
|
||||
}
|
||||
fn fill_pool(&mut self, set: &[&CardState]) {
|
||||
let mut sorted = set.iter().enumerate().collect::<Vec<_>>();
|
||||
sorted.sort_by_key(|c| c.1.score);
|
||||
@@ -177,21 +156,33 @@ impl WorstWordsSRSModule {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FsrsModule {
|
||||
today_set: Vec<usize>,
|
||||
solved: Vec<usize>,
|
||||
current_group: Vec<usize>,
|
||||
next_round: Vec<usize>,
|
||||
queue: Vec<usize>,
|
||||
rng: ThreadRng,
|
||||
fsrs: FSRS,
|
||||
pub(crate) initialized: bool,
|
||||
}
|
||||
|
||||
impl SRSModule for FsrsModule {
|
||||
fn next(&mut self, _: &[&CardState]) -> usize {
|
||||
if self.current_group.is_empty() {
|
||||
self.fill_partial_pool();
|
||||
}
|
||||
fn new(set: &[&CardState]) -> Self {
|
||||
let today = Local::now().date_naive();
|
||||
|
||||
let mut new = Self {
|
||||
queue: set
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| c.fsrs_open_day <= today)
|
||||
.map(|(index, _)| index)
|
||||
.collect(),
|
||||
next_round: vec![],
|
||||
rng: rng(),
|
||||
fsrs: FSRS::default(),
|
||||
};
|
||||
new.queue.shuffle(&mut new.rng);
|
||||
|
||||
new
|
||||
}
|
||||
|
||||
fn next(&mut self, _: &[&CardState]) -> usize {
|
||||
if self.queue.is_empty() {
|
||||
self.fill_queue();
|
||||
self.queue.shuffle(&mut self.rng);
|
||||
@@ -222,66 +213,32 @@ impl SRSModule for FsrsModule {
|
||||
let offset = ((rng().random::<f32>() - 0.5) * 3.0).round() as i32;
|
||||
next_day += TimeDelta::days(offset as i64);
|
||||
}
|
||||
|
||||
let first_time = updated_word.fsrs_memory.is_none();
|
||||
|
||||
updated_word.fsrs_memory = Some(next.memory);
|
||||
updated_word.fsrs_open_day = next_day;
|
||||
updated_word.fsrs_opened = updated_word.last_open.date_naive();
|
||||
|
||||
if updated_word.fsrs_open_day != today {
|
||||
self.solved.push(index);
|
||||
let index = self.current_group.iter().position(|x| *x == index).unwrap();
|
||||
self.current_group.remove(index);
|
||||
if (updated_word.fsrs_open_day == today && !first_time)
|
||||
|| (first_time && status != WordOpenMode::Easy)
|
||||
{
|
||||
self.next_round.push(index);
|
||||
}
|
||||
}
|
||||
|
||||
fn init(&mut self, set: &[&CardState]) {
|
||||
self.rng = rng();
|
||||
let today = Local::now().date_naive();
|
||||
self.today_set = set
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, c)| c.fsrs_open_day <= today)
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
self.today_set.shuffle(&mut self.rng);
|
||||
self.fill_partial_pool();
|
||||
self.initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl FsrsModule {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
today_set: vec![],
|
||||
current_group: vec![],
|
||||
queue: vec![],
|
||||
solved: vec![],
|
||||
rng: Default::default(),
|
||||
fsrs: FSRS::default(),
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
fn fill_partial_pool(&mut self) {
|
||||
self.current_group.extend(
|
||||
self.today_set
|
||||
.iter()
|
||||
.filter(|x| !self.solved.contains(*x))
|
||||
.take(PARTIAL_POOL_SIZE),
|
||||
);
|
||||
|
||||
self.queue.clear();
|
||||
self.queue.extend(self.current_group.clone());
|
||||
}
|
||||
|
||||
fn fill_queue(&mut self) {
|
||||
self.queue.extend(self.current_group.clone());
|
||||
self.queue.append(&mut self.next_round);
|
||||
}
|
||||
|
||||
pub fn finished(&self) -> bool {
|
||||
self.today_set.len() == self.solved.len()
|
||||
self.queue.is_empty() && self.next_round.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WordOpenMode {
|
||||
Easy,
|
||||
Ok,
|
||||
|
||||
+60
-15
@@ -1,5 +1,6 @@
|
||||
use crate::core::srs::{FADE_PER_DAY, MAX_SCORE, WordOpenMode};
|
||||
use crate::data::{INVALID_ID, Id};
|
||||
use crate::data_provider::history::HistoryRepositoryInner;
|
||||
use chrono::{DateTime, Local, NaiveDate, Utc};
|
||||
use fsrs::MemoryState;
|
||||
use litemap::LiteMap;
|
||||
@@ -10,7 +11,6 @@ use std::hash::{Hash, Hasher};
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use crate::data_provider::history::{HistoryRepository, HistoryRepositoryInner};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WordData {
|
||||
@@ -19,7 +19,7 @@ pub struct WordData {
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
pub tags: String,
|
||||
pub additional: LiteMap<String, String>,
|
||||
pub additional: LiteMap<Id, String>,
|
||||
}
|
||||
|
||||
impl EntityData for WordData {
|
||||
@@ -70,7 +70,7 @@ pub struct HistoryNote {
|
||||
pub answer: WordOpenMode,
|
||||
pub before: u8,
|
||||
pub after: u8,
|
||||
pub fsrs: bool
|
||||
pub fsrs: bool,
|
||||
}
|
||||
|
||||
impl EntityData for HistoryNote {
|
||||
@@ -86,22 +86,24 @@ impl EntityData for HistoryNote {
|
||||
impl HistoryRepositoryInner {
|
||||
pub fn activity_of_deck(&self, id: Id) -> Vec<(NaiveDate, u32)> {
|
||||
let mut query = self.query(Arc::new(move |note| note.deck_id == id));
|
||||
let values = query.iter(&self).collect::<Vec<_>>();
|
||||
let values = query.iter(self).collect::<Vec<_>>();
|
||||
let mut counts = vec![];
|
||||
if !values.is_empty() {
|
||||
let mut date = values[0].timestamp.with_timezone(&Local).date_naive();
|
||||
let mut count = 0;
|
||||
for note in values {
|
||||
let current_date = note.timestamp.with_timezone(&Local).date_naive();
|
||||
if date == current_date{
|
||||
if date == current_date {
|
||||
count += 1;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
counts.push((date, count));
|
||||
date = current_date;
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
if count != 0 {
|
||||
counts.push((date, count));
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
@@ -131,8 +133,8 @@ impl DeckSettings {
|
||||
DeckSettings {
|
||||
id: 0.into(),
|
||||
name,
|
||||
forward: "".to_string(),
|
||||
backward: "".to_string(),
|
||||
forward: String::new(),
|
||||
backward: String::new(),
|
||||
filter: "true".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -144,7 +146,7 @@ impl DeckSettings {
|
||||
ast.is_ok()
|
||||
}
|
||||
pub fn require_speech(&self) -> bool {
|
||||
self.forward == "speech" || self.backward == "speech"
|
||||
self.forward.contains("speech") || self.backward.contains("speech")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,9 +199,55 @@ impl CardState {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CustomField {
|
||||
pub id: Id,
|
||||
pub name: String,
|
||||
pub identifier: String,
|
||||
}
|
||||
|
||||
impl EntityData for CustomField {
|
||||
fn id(&self) -> Id {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn set_id(&mut self, id: Id) {
|
||||
self.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Exam {
|
||||
pub id: Id,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub deck_id: Id,
|
||||
}
|
||||
|
||||
impl EntityData for Exam {
|
||||
fn id(&self) -> Id {
|
||||
self.id
|
||||
}
|
||||
fn set_id(&mut self, id: Id) {
|
||||
self.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ExamEntry{
|
||||
pub id: Id,
|
||||
pub exam_id: Id,
|
||||
pub word_id: Id,
|
||||
pub status: Option<bool>
|
||||
}
|
||||
|
||||
impl EntityData for ExamEntry {
|
||||
fn id(&self) -> Id {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn set_id(&mut self, id: Id) {
|
||||
self.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EntityHandle<E> {
|
||||
@@ -210,13 +258,10 @@ pub struct EntityHandle<E> {
|
||||
|
||||
impl<T> Clone for EntityHandle<T> {
|
||||
fn clone(&self) -> Self {
|
||||
EntityHandle {
|
||||
id: self.id,
|
||||
index: self.index,
|
||||
_phantom: Default::default(),
|
||||
}
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Copy for EntityHandle<T> {}
|
||||
impl<T> EntityHandle<T> {
|
||||
pub fn new(id: Id, index: usize, real: bool) -> Self {
|
||||
|
||||
+99
-82
@@ -1,8 +1,9 @@
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::{CardState, EntityData, EntityHandle};
|
||||
use crate::data::entities::{EntityData, EntityHandle};
|
||||
use crate::data_provider::sqlite::SqliteConnection;
|
||||
use crate::helpers::into_result;
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use log::debug;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use rayon::iter::IndexedParallelIterator;
|
||||
use rayon::iter::IntoParallelRefIterator;
|
||||
@@ -11,6 +12,7 @@ use rusqlite::Connection;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::{Deref, Index, IndexMut};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
pub trait Repository<T, D>
|
||||
where
|
||||
@@ -29,13 +31,19 @@ where
|
||||
fn create_now(&mut self, new: T) -> Result<EntityHandle<T>, NotificationData>;
|
||||
fn save(&mut self, entity: &mut EntityHandle<T>) -> MaybeError;
|
||||
fn delete(&mut self, handle: EntityHandle<T>) -> MaybeError;
|
||||
fn find<F>(&self, predicate: F) -> Option<EntityHandle<T>> where F : Fn(&T) -> bool;
|
||||
fn find<F>(&self, predicate: F) -> Option<EntityHandle<T>>
|
||||
where
|
||||
F: Fn(&T) -> bool;
|
||||
fn init(&mut self) -> MaybeError;
|
||||
fn start(&mut self) -> MaybeError;
|
||||
fn reload(&mut self) -> MaybeError;
|
||||
fn shifts(&self) -> usize;
|
||||
fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T> where T: 'a;
|
||||
fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T> where T: 'a;
|
||||
fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T>
|
||||
where
|
||||
T: 'a;
|
||||
fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T>
|
||||
where
|
||||
T: 'a;
|
||||
}
|
||||
|
||||
struct QueryManger<T, R, D>
|
||||
@@ -86,9 +94,7 @@ where
|
||||
.filter(|(_, q)| {
|
||||
let query = q.lock();
|
||||
let rule = &query.rule;
|
||||
return rule(data);
|
||||
|
||||
false
|
||||
rule(data)
|
||||
})
|
||||
.map(|(i, _)| i)
|
||||
.collect()
|
||||
@@ -116,7 +122,10 @@ where
|
||||
}
|
||||
|
||||
impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Query<T, R, D> {
|
||||
pub fn iter<'a>(&mut self, data_repository_inner: &'a DataRepositoryInner<T, D>) -> impl Iterator<Item = &'a T>
|
||||
pub fn iter<'a>(
|
||||
&mut self,
|
||||
data_repository_inner: &'a DataRepositoryInner<T, D>,
|
||||
) -> impl Iterator<Item = &'a T>
|
||||
where
|
||||
T: 'a,
|
||||
{
|
||||
@@ -128,7 +137,10 @@ impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Qu
|
||||
.filter_map(move |e| data_repository_inner.get_ref(e))
|
||||
}
|
||||
|
||||
pub fn iter_with_handles<'a>(&mut self, data_repository_inner: &'a DataRepositoryInner<T, D>) -> impl Iterator<Item = (&'a T, EntityHandle<T>)>
|
||||
pub fn iter_with_handles<'a>(
|
||||
&mut self,
|
||||
data_repository_inner: &'a DataRepositoryInner<T, D>,
|
||||
) -> impl Iterator<Item = (&'a T, EntityHandle<T>)>
|
||||
where
|
||||
T: 'a,
|
||||
{
|
||||
@@ -137,9 +149,9 @@ impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Qu
|
||||
}
|
||||
self.cache
|
||||
.iter_mut()
|
||||
.filter_map(move |e| Some((data_repository_inner.get_ref(e)?, e.clone())))
|
||||
.filter_map(move |e| Some((data_repository_inner.get_ref(e)?, *e)))
|
||||
}
|
||||
|
||||
|
||||
pub fn for_each_mut<F>(&mut self, repo: &mut DataRepositoryInner<T, D>, mut f: F)
|
||||
where
|
||||
F: FnMut(&mut T),
|
||||
@@ -158,6 +170,7 @@ impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Qu
|
||||
where
|
||||
T: Send + Sync,
|
||||
{
|
||||
let time = Instant::now();
|
||||
self.cache.clear();
|
||||
if self.parallel {
|
||||
self.cache = data_repository
|
||||
@@ -186,18 +199,31 @@ impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Qu
|
||||
.map(|(i, entity)| EntityHandle::new(entity.id(), i, false))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
debug!(
|
||||
"Query for {} elements (filtered {}) takes {:?}",
|
||||
data_repository.len(),
|
||||
self.cache.len(),
|
||||
time.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
pub fn handles(&self) -> impl Iterator<Item = EntityHandle<T>> {
|
||||
self.cache.iter().cloned()
|
||||
}
|
||||
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.cache.len()
|
||||
}
|
||||
|
||||
pub fn get(&self, index: usize) -> Option<EntityHandle<T>> {
|
||||
self.cache.get(index).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Index<usize> for Query<T, R, D> {
|
||||
impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> Index<usize>
|
||||
for Query<T, R, D>
|
||||
{
|
||||
type Output = EntityHandle<T>;
|
||||
|
||||
fn index(&self, index: usize) -> &Self::Output {
|
||||
@@ -205,7 +231,9 @@ impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> In
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> IndexMut<usize> for Query<T, R, D> {
|
||||
impl<T: EntityData + Clone + Send + Sync, R: Repository<T, D>, D: DbLayer<T>> IndexMut<usize>
|
||||
for Query<T, R, D>
|
||||
{
|
||||
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
|
||||
&mut self.cache[index]
|
||||
}
|
||||
@@ -216,7 +244,10 @@ where
|
||||
D: BatchedDbLayer<T>,
|
||||
T: EntityData,
|
||||
{
|
||||
fn create_now_many(&mut self, entities: &mut [T]) -> Result<Vec<EntityHandle<T>>, NotificationData>;
|
||||
fn create_now_many(
|
||||
&mut self,
|
||||
entities: &mut [T],
|
||||
) -> Result<Vec<EntityHandle<T>>, NotificationData>;
|
||||
fn save_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError;
|
||||
fn delete_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError;
|
||||
}
|
||||
@@ -252,10 +283,10 @@ pub struct DataRepositoryInner<T: Clone + EntityData, D: DbLayer<T>> {
|
||||
shifts: usize,
|
||||
}
|
||||
|
||||
impl<T: Clone + EntityData, D: DbLayer<T> + Default> DataRepository<T, D> {
|
||||
impl<T: Clone + EntityData, D: DbLayer<T> + Default> DataRepository<T, D> {
|
||||
pub fn new(connection: Arc<Mutex<SqliteConnection>>) -> DataRepository<T, D> {
|
||||
Self{
|
||||
inner: Arc::new(RwLock::new(DataRepositoryInner{
|
||||
Self {
|
||||
inner: Arc::new(RwLock::new(DataRepositoryInner {
|
||||
cache: vec![],
|
||||
temporal: vec![],
|
||||
next_temporal: 0,
|
||||
@@ -269,7 +300,6 @@ impl<T: Clone + EntityData, D: DbLayer<T> + Default> DataRepository<T, D> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl<T: Clone + EntityData, D: DbLayer<T>> Deref for DataRepository<T, D> {
|
||||
type Target = Arc<RwLock<DataRepositoryInner<T, D>>>;
|
||||
|
||||
@@ -278,7 +308,9 @@ impl<T: Clone + EntityData, D: DbLayer<T>> Deref for DataRepository<T, D> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: EntityData + Clone, D: DbLayer<T>> DataRepositoryInner<T, D> {
|
||||
impl<T: EntityData + Clone + std::marker::Send + std::marker::Sync, D: DbLayer<T>>
|
||||
DataRepositoryInner<T, D>
|
||||
{
|
||||
pub fn query_par(
|
||||
&self,
|
||||
rule: Arc<dyn Fn(&T) -> bool + Send + Sync>,
|
||||
@@ -286,67 +318,41 @@ impl<T: EntityData + Clone, D: DbLayer<T>> DataRepositoryInner<T, D> {
|
||||
where
|
||||
T: Send + Sync,
|
||||
{
|
||||
let mut cache: Vec<EntityHandle<T>> = self
|
||||
.cache
|
||||
.par_iter()
|
||||
.enumerate()
|
||||
.filter(|(_, entity)| rule(entity))
|
||||
.map(|(i, entity)| EntityHandle::new(entity.id(), i, true))
|
||||
.collect();
|
||||
|
||||
cache.extend(
|
||||
self.temporal
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, entity)| rule(entity))
|
||||
.map(|(i, entity)| EntityHandle::new(entity.id(), i, false))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
Query {
|
||||
cache,
|
||||
let mut query = Query {
|
||||
cache: vec![],
|
||||
rule,
|
||||
parallel: true,
|
||||
_marker: PhantomData,
|
||||
shift_stamp: self.shifts,
|
||||
}
|
||||
};
|
||||
|
||||
query.load(self);
|
||||
|
||||
query
|
||||
}
|
||||
|
||||
pub fn query(
|
||||
&self,
|
||||
rule: Arc<dyn Fn(& T) -> bool + Send + Sync>,
|
||||
rule: Arc<dyn Fn(&T) -> bool + Send + Sync>,
|
||||
) -> Query<T, DataRepositoryInner<T, D>, D>
|
||||
where
|
||||
T: Send + Sync,
|
||||
{
|
||||
let mut cache: Vec<EntityHandle<T>> = self
|
||||
.cache
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, entity)| rule(entity))
|
||||
.map(|(i, entity)| EntityHandle::new(entity.id(), i, true))
|
||||
.collect();
|
||||
|
||||
cache.extend(
|
||||
self.temporal
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, entity)| rule(entity))
|
||||
.map(|(i, entity)| EntityHandle::new(entity.id(), i, false))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
Query {
|
||||
cache,
|
||||
let mut query = Query {
|
||||
cache: vec![],
|
||||
rule,
|
||||
parallel: false,
|
||||
_marker: PhantomData,
|
||||
shift_stamp: self.shifts,
|
||||
}
|
||||
};
|
||||
|
||||
query.load(self);
|
||||
|
||||
query
|
||||
}
|
||||
|
||||
|
||||
pub fn empty_query(&self) -> Query<T, DataRepositoryInner<T, D>, D> {
|
||||
Query{
|
||||
Query {
|
||||
cache: vec![],
|
||||
rule: Arc::new(|_| false),
|
||||
parallel: false,
|
||||
@@ -356,7 +362,7 @@ impl<T: EntityData + Clone, D: DbLayer<T>> DataRepositoryInner<T, D> {
|
||||
}
|
||||
|
||||
pub fn empty_query_par(&self) -> Query<T, DataRepositoryInner<T, D>, D> {
|
||||
Query{
|
||||
Query {
|
||||
cache: vec![],
|
||||
rule: Arc::new(|_| false),
|
||||
parallel: true,
|
||||
@@ -365,6 +371,10 @@ impl<T: EntityData + Clone, D: DbLayer<T>> DataRepositoryInner<T, D> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn full_query(&self) -> Query<T, DataRepositoryInner<T, D>, D> {
|
||||
self.query(Arc::new(|_| true))
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.cache.len() + self.temporal.len()
|
||||
}
|
||||
@@ -450,7 +460,7 @@ impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryIn
|
||||
}
|
||||
|
||||
fn save(&mut self, entity: &mut EntityHandle<T>) -> MaybeError {
|
||||
let original_state = entity.clone();
|
||||
let original_state = *entity;
|
||||
if entity.real() {
|
||||
let data = self.get_ref(entity).unwrap();
|
||||
self.data_layer
|
||||
@@ -458,12 +468,11 @@ impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryIn
|
||||
} else {
|
||||
let index = fast_position_of(self.temporal.as_slice(), entity).unwrap();
|
||||
let data = &mut self.temporal[index];
|
||||
self.data_layer
|
||||
.add_entity(data, &self.connection.lock())?;
|
||||
self.data_layer.add_entity(data, &self.connection.lock())?;
|
||||
entity.set_real(true);
|
||||
entity.id = data.id();
|
||||
entity.set_index(self.cache.len());
|
||||
self.query_manger.handle_save(original_state, entity, &data);
|
||||
self.query_manger.handle_save(original_state, entity, data);
|
||||
|
||||
let data = self.temporal.remove(index);
|
||||
self.cache.push(data);
|
||||
@@ -494,16 +503,16 @@ impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryIn
|
||||
|
||||
fn find<F>(&self, predicate: F) -> Option<EntityHandle<T>>
|
||||
where
|
||||
F: Fn(&T) -> bool
|
||||
F: Fn(&T) -> bool,
|
||||
{
|
||||
if let Some(index) = self.cache.iter().position(|entity| predicate(entity)){
|
||||
if let Some(index) = self.cache.iter().position(&predicate) {
|
||||
let value = &self.cache[index];
|
||||
return Some(EntityHandle::new(value.id(), index, true))
|
||||
return Some(EntityHandle::new(value.id(), index, true));
|
||||
}
|
||||
|
||||
if let Some(index) = self.temporal.iter().position(|entity| predicate(entity)){
|
||||
if let Some(index) = self.temporal.iter().position(predicate) {
|
||||
let value = &self.temporal[index];
|
||||
return Some(EntityHandle::new(value.id(), index, false))
|
||||
return Some(EntityHandle::new(value.id(), index, false));
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -535,16 +544,16 @@ impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryIn
|
||||
self.shifts
|
||||
}
|
||||
|
||||
fn iter<'a>(&'a self) -> impl Iterator<Item=&'a T>
|
||||
fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T>
|
||||
where
|
||||
T: 'a
|
||||
T: 'a,
|
||||
{
|
||||
self.cache.iter().chain(self.temporal.iter())
|
||||
}
|
||||
|
||||
fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item=&'a mut T>
|
||||
fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T>
|
||||
where
|
||||
T: 'a
|
||||
T: 'a,
|
||||
{
|
||||
self.cache.iter_mut().chain(self.temporal.iter_mut())
|
||||
}
|
||||
@@ -552,10 +561,18 @@ impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryIn
|
||||
impl<T: EntityData + Clone, D: BatchedDbLayer<T> + DbLayer<T>> BatchedRepository<T, D>
|
||||
for DataRepositoryInner<T, D>
|
||||
{
|
||||
fn create_now_many(&mut self, entities: &mut [T]) -> Result<Vec<EntityHandle<T>>, NotificationData> {
|
||||
self.data_layer.add_many_entities(entities, &mut self.connection.lock())?;
|
||||
fn create_now_many(
|
||||
&mut self,
|
||||
entities: &mut [T],
|
||||
) -> Result<Vec<EntityHandle<T>>, NotificationData> {
|
||||
self.data_layer
|
||||
.add_many_entities(entities, &mut self.connection.lock())?;
|
||||
let len = self.cache.len();
|
||||
let handles = entities.iter().enumerate().map(|(index, entity)| {EntityHandle::new(entity.id(), index + len, true)}).collect();
|
||||
let handles = entities
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, entity)| EntityHandle::new(entity.id(), index + len, true))
|
||||
.collect();
|
||||
self.cache.extend(entities.to_vec());
|
||||
Ok(handles)
|
||||
}
|
||||
@@ -594,7 +611,7 @@ impl<T: EntityData + Clone, D: BatchedDbLayer<T> + DbLayer<T>> BatchedRepository
|
||||
let start = self.cache.len();
|
||||
|
||||
for (i, (handle, data)) in temp.into_iter().zip(&mut temp_values).enumerate() {
|
||||
let old = handle.clone();
|
||||
let old = *handle;
|
||||
handle.id = data.id();
|
||||
handle.set_index(start + i);
|
||||
handle.set_real(true);
|
||||
@@ -658,7 +675,7 @@ where
|
||||
{
|
||||
let mut temp = Vec::with_capacity(handles.len() / 2);
|
||||
let mut cached = Vec::with_capacity(handles.len() / 2);
|
||||
handles.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
handles.sort_by_key(|a| a.id);
|
||||
handles.iter().for_each(|handle| {
|
||||
if handle.real() {
|
||||
cached.push(getter(handle))
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
use crate::data::entities::{CardState, DeckSettings};
|
||||
use crate::data::entities::CardState;
|
||||
use crate::data::repositories::{DataRepository, DataRepositoryInner, Query};
|
||||
use crate::data::Id;
|
||||
use crate::data_access_methods;
|
||||
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
|
||||
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use chrono::NaiveDate;
|
||||
use fsrs::MemoryState;
|
||||
use log::info;
|
||||
use rusqlite::{Connection, Error, Params, Row, params};
|
||||
use std::time::Instant;
|
||||
use crate::data::repositories::{DataRepository, DataRepositoryInner};
|
||||
use rusqlite::{Error, Params, Row};
|
||||
use std::sync::Arc;
|
||||
|
||||
data_access_methods!(
|
||||
CardStateDbLayer,
|
||||
CardStateRepository,
|
||||
CardStateRepositoryInner,
|
||||
CardState,
|
||||
CardStatesQuerySet,
|
||||
CardStateQuery
|
||||
);
|
||||
|
||||
pub type CardStateRepository = DataRepository<CardState, SqliteDbLayer<CardState, CardStatesQuerySet>>;
|
||||
pub type CardStateRepositoryInner = DataRepositoryInner<CardState, SqliteDbLayer<CardState, CardStatesQuerySet>>;
|
||||
#[derive(Clone)]
|
||||
pub struct CardStatesQuerySet;
|
||||
impl TableAccessQuerySet<CardState> for CardStatesQuerySet {
|
||||
@@ -19,11 +25,11 @@ impl TableAccessQuerySet<CardState> for CardStatesQuerySet {
|
||||
}
|
||||
|
||||
fn save() -> &'static str {
|
||||
"UPDATE states SET score = ?1, last_opened = ?2 WHERE id = ?3"
|
||||
"UPDATE states SET score = ?1, last_opened = ?2, fsrs_opened = ?3, fsrs_memory = ?4, fsrs_open_day = ?5 WHERE id = ?6"
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT INTO states (word_id, deck_id, score, last_opened, fsrs_opened, fsrs_memory, fsrs_open_day) VALUES (?1, ?2, ?3, ?4) RETURNING id"
|
||||
"INSERT INTO states (word_id, deck_id, score, last_opened, fsrs_opened, fsrs_memory, fsrs_open_day) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
@@ -58,38 +64,16 @@ impl TableAccessQuerySet<CardState> for CardStatesQuerySet {
|
||||
}
|
||||
|
||||
fn update_params(entity: &CardState) -> impl Params {
|
||||
(entity.score, entity.last_open.timestamp(), entity.id)
|
||||
(
|
||||
entity.score,
|
||||
entity.last_open.timestamp(),
|
||||
entity.fsrs_opened.to_epoch_days(),
|
||||
memory_to_i64(&entity.fsrs_memory),
|
||||
entity.fsrs_open_day.to_epoch_days(),
|
||||
entity.id,
|
||||
)
|
||||
}
|
||||
}
|
||||
pub fn load_stats_of_deck(
|
||||
set: &DeckSettings,
|
||||
connection: &Connection,
|
||||
) -> Result<Vec<CardState>, NotificationData> {
|
||||
let mut stmt = connection
|
||||
.prepare("SELECT id, word_id, score, last_opened, fsrs_opened, fsrs_memory, fsrs_open_day FROM states WHERE set_id = ?1")
|
||||
.expect("Failed to prepare state query");
|
||||
let iter = stmt
|
||||
.query_map((set.id,), |row| {
|
||||
Ok(CardState {
|
||||
id: row.get(0)?,
|
||||
word_id: row.get(1)?,
|
||||
deck_id: set.id,
|
||||
score: row.get(2)?,
|
||||
fsrs_opened: NaiveDate::from_epoch_days(row.get::<usize, i32>(4)?)
|
||||
.expect("Incorrect date encoding"),
|
||||
fsrs_memory: get_memory(row.get(5)?),
|
||||
last_open: row.get(3)?,
|
||||
fsrs_open_day: NaiveDate::from_epoch_days(row.get::<usize, i32>(6)?)
|
||||
.expect("Incorrect date encoding"),
|
||||
})
|
||||
})
|
||||
.map_err(|_| DbLoadError)?;
|
||||
|
||||
let mut buffer = Vec::with_capacity(512);
|
||||
iter.filter_map(|res| res.ok()).for_each(|i| buffer.push(i));
|
||||
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
fn get_memory(value: i64) -> Option<MemoryState> {
|
||||
if value == 0 {
|
||||
@@ -109,74 +93,11 @@ fn memory_to_i64(value: &Option<MemoryState>) -> i64 {
|
||||
value.stability.to_bits() as i64 | ((value.difficulty.to_bits() as i64) << 32)
|
||||
}
|
||||
|
||||
pub fn add_stat_list(stats: &mut [CardState], connection: &mut Connection) -> MaybeError {
|
||||
let time = Instant::now();
|
||||
let tx = connection
|
||||
.transaction()
|
||||
.expect("Failed to create transaction");
|
||||
let count = stats.len();
|
||||
|
||||
{
|
||||
let mut stmt = tx
|
||||
.prepare(
|
||||
"INSERT INTO states (word_id, set_id, score, last_opened, fsrs_opened, fsrs_memory, fsrs_open_day) VALUES (?1, ?2, ?3, ?4)",
|
||||
)
|
||||
.expect("Failed to prepare state query");
|
||||
|
||||
for stat in stats.iter() {
|
||||
stmt.execute(params![
|
||||
stat.word_id,
|
||||
stat.deck_id,
|
||||
stat.score,
|
||||
stat.last_open.timestamp(),
|
||||
stat.fsrs_opened.to_epoch_days(),
|
||||
memory_to_i64(&stat.fsrs_memory),
|
||||
stat.fsrs_open_day.to_epoch_days()
|
||||
])
|
||||
.map_err(|_| DbSaveError)?;
|
||||
}
|
||||
impl CardStateRepositoryInner {
|
||||
pub fn deck_states(
|
||||
&self,
|
||||
deck_id: Id,
|
||||
) -> Query<CardState, CardStateRepositoryInner, CardStateDbLayer> {
|
||||
self.query(Arc::new(move |state| state.deck_id == deck_id))
|
||||
}
|
||||
|
||||
let last_index: u32 = tx.last_insert_rowid() as u32;
|
||||
tx.commit().expect("Failed to commit");
|
||||
|
||||
let start_index = last_index - (count as u32) + 1;
|
||||
|
||||
for (index, id) in (start_index..=last_index).enumerate() {
|
||||
stats[index].id = id.into();
|
||||
}
|
||||
|
||||
info!("Added {} cards for {:?}", stats.len(), time.elapsed());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_stat_score(stat: &CardState, connection: &Connection) -> MaybeError {
|
||||
let time = Instant::now();
|
||||
|
||||
connection
|
||||
.execute(
|
||||
"UPDATE states SET score = ?1, last_opened = ?2 WHERE id = ?3",
|
||||
(&stat.score, &stat.last_open.timestamp(), &stat.id),
|
||||
)
|
||||
.map_err(|_| DbSaveError)?;
|
||||
info!("Updated stat: {}", time.elapsed().as_millis());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_stats(stat: &[CardState], connection: &Connection) -> MaybeError {
|
||||
if stat.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let ids = stat
|
||||
.iter()
|
||||
.map(|s| s.id.into())
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
connection
|
||||
.execute(
|
||||
format!("DELETE FROM states WHERE id in ({ids})").as_str(),
|
||||
(),
|
||||
)
|
||||
.map_err(|_| DbSaveError)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,40 +1,42 @@
|
||||
use crate::data::entities::{CustomField, WordGroup};
|
||||
use crate::data::repositories::DataRepository;
|
||||
use crate::data::entities::CustomField;
|
||||
use crate::data::repositories::{DataRepository, DataRepositoryInner};
|
||||
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
|
||||
use rusqlite::{Error, Params, Row};
|
||||
use crate::data_access_methods;
|
||||
|
||||
pub type CustomFieldRepository = DataRepository<CustomField, SqliteDbLayer<CustomField, CustomFieldsQuerySet>>;
|
||||
|
||||
data_access_methods!(CustomFieldDbLayer, CustomFieldRepository, CustomFieldRepositoryInner, CustomField, CustomFieldsQuerySet, CustomFieldQuery);
|
||||
#[derive(Clone)]
|
||||
pub struct CustomFieldsQuerySet;
|
||||
impl TableAccessQuerySet<WordGroup> for CustomFieldsQuerySet {
|
||||
impl TableAccessQuerySet<CustomField> for CustomFieldsQuerySet {
|
||||
fn load() -> &'static str {
|
||||
"SELECT id, name FROM custom_fields"
|
||||
"SELECT id, name, identifier FROM custom_fields"
|
||||
}
|
||||
|
||||
fn save() -> &'static str {
|
||||
"UPDATE custom_fields SET name = ?1 WHERE id = ?2"
|
||||
"UPDATE custom_fields SET name = ?1, identifier = ?2 WHERE id = ?3"
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT INTO word_groups (name) VALUES (?1) RETURNING id"
|
||||
"INSERT INTO custom_fields (name, identifier) VALUES (?1, ?2)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
"custom_fields"
|
||||
}
|
||||
|
||||
fn from_sql(row: &Row) -> Result<WordGroup, Error> {
|
||||
Ok(WordGroup {
|
||||
fn from_sql(row: &Row) -> Result<CustomField, Error> {
|
||||
Ok(CustomField {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
identifier: row.get(2)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn insert_params(entity: &WordGroup) -> impl Params {
|
||||
(&entity.name,)
|
||||
fn insert_params(entity: &CustomField) -> impl Params {
|
||||
(&entity.name, &entity.identifier)
|
||||
}
|
||||
|
||||
fn update_params(entity: &WordGroup) -> impl Params {
|
||||
(&entity.name, entity.id)
|
||||
fn update_params(entity: &CustomField) -> impl Params {
|
||||
(&entity.name, &entity.identifier, entity.id)
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ impl TableAccessQuerySet<DeckSettings> for DeckQuerySet {
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT INTO decks (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id"
|
||||
"INSERT INTO decks (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
@@ -52,4 +52,4 @@ impl TableAccessQuerySet<DeckSettings> for DeckQuerySet {
|
||||
entity.id,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use crate::data::entities::{Exam, ExamEntry};
|
||||
use crate::data::repositories::*;
|
||||
use crate::data_access_methods;
|
||||
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
|
||||
use rusqlite::{Error, Params, Row};
|
||||
|
||||
data_access_methods!(
|
||||
ExamDataLayer,
|
||||
ExamRepository,
|
||||
ExamRepositoryInner,
|
||||
Exam,
|
||||
ExamQuerySet,
|
||||
ExamQuery
|
||||
);
|
||||
|
||||
data_access_methods!(
|
||||
ExamEntryLayer,
|
||||
ExamEntryRepository,
|
||||
ExamEntryRepositoryInner,
|
||||
ExamEntry,
|
||||
ExamEntryQuerySet,
|
||||
ExamEntryQuery
|
||||
);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ExamQuerySet;
|
||||
|
||||
impl TableAccessQuerySet<Exam> for ExamQuerySet {
|
||||
fn load() -> &'static str {
|
||||
"SELECT id, timestamp, deck_id FROM exams"
|
||||
}
|
||||
|
||||
fn save() -> &'static str {
|
||||
"UPDATE exams set deck_id = $1, timestamp = $2 WHERE id = $3"
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT INTO exams (timestamp, deck_id) values ($1, $2)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
"exams"
|
||||
}
|
||||
|
||||
fn from_sql(row: &Row) -> Result<Exam, Error> {
|
||||
Ok(Exam {
|
||||
id: row.get(0)?,
|
||||
timestamp: row.get(1)?,
|
||||
deck_id: row.get(2)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn insert_params(entity: &Exam) -> impl Params {
|
||||
(entity.timestamp.timestamp(), entity.deck_id)
|
||||
}
|
||||
|
||||
fn update_params(entity: &Exam) -> impl Params {
|
||||
(entity.timestamp.timestamp(), entity.deck_id, entity.id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ExamEntryQuerySet;
|
||||
|
||||
impl TableAccessQuerySet<ExamEntry> for ExamEntryQuerySet {
|
||||
fn load() -> &'static str {
|
||||
"SELECT id, exam_id, word_id, status FROM exam_entries"
|
||||
}
|
||||
|
||||
fn save() -> &'static str {
|
||||
"UPDATE exam_entries set status = $1 WHERE id = $2"
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT into exam_entries (exam_id, word_id, status) VALUES ($1, $2, $3)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
"exam_entries"
|
||||
}
|
||||
|
||||
fn from_sql(row: &Row) -> Result<ExamEntry, Error> {
|
||||
Ok(ExamEntry {
|
||||
id: row.get(0)?,
|
||||
exam_id: row.get(1)?,
|
||||
word_id: row.get(2)?,
|
||||
status: row.get(3)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn insert_params(entity: &ExamEntry) -> impl Params {
|
||||
(entity.exam_id, entity.word_id, entity.status)
|
||||
}
|
||||
|
||||
fn update_params(entity: &ExamEntry) -> impl Params {
|
||||
(entity.status, entity.id)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@ use crate::data::repositories::{DataRepository, DataRepositoryInner};
|
||||
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
|
||||
use rusqlite::types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef};
|
||||
use rusqlite::{Error, Params, Row, ToSql};
|
||||
use crate::data_access_methods;
|
||||
|
||||
pub type HistoryRepository = DataRepository<HistoryNote, HistoryDataLayer>;
|
||||
pub type HistoryRepositoryInner = DataRepositoryInner<HistoryNote, HistoryDataLayer>;
|
||||
pub type HistoryDataLayer = SqliteDbLayer<HistoryNote, HistoryQuerySet>;
|
||||
data_access_methods!(HistoryDataLayer, HistoryRepository, HistoryRepositoryInner, HistoryNote, HistoryQuerySet, HistoryQuery);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HistoryQuerySet;
|
||||
@@ -21,13 +20,16 @@ impl TableAccessQuerySet<HistoryNote> for HistoryQuerySet {
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT INTO history (deck_id, state_id, timestamp, answer, before, after, fsrs) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) RETURNING rowid"
|
||||
"INSERT INTO history (deck_id, word_id, timestamp, answer, before, after, fsrs) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
"history"
|
||||
}
|
||||
|
||||
fn id_field() -> &'static str {
|
||||
"rowid"
|
||||
}
|
||||
fn from_sql(row: &Row) -> Result<HistoryNote, Error> {
|
||||
Ok(HistoryNote {
|
||||
id: row.get(0)?,
|
||||
@@ -45,7 +47,7 @@ impl TableAccessQuerySet<HistoryNote> for HistoryQuerySet {
|
||||
(
|
||||
entity.deck_id,
|
||||
entity.word_id,
|
||||
entity.timestamp,
|
||||
entity.timestamp.timestamp(),
|
||||
entity.answer,
|
||||
entity.before,
|
||||
entity.after,
|
||||
@@ -57,7 +59,7 @@ impl TableAccessQuerySet<HistoryNote> for HistoryQuerySet {
|
||||
(
|
||||
entity.deck_id,
|
||||
entity.word_id,
|
||||
entity.timestamp,
|
||||
entity.timestamp.timestamp(),
|
||||
entity.answer,
|
||||
entity.before,
|
||||
entity.after,
|
||||
@@ -74,7 +76,7 @@ impl FromSql for WordOpenMode {
|
||||
2 => Ok(WordOpenMode::Ok),
|
||||
3 => Ok(WordOpenMode::Easy),
|
||||
_ => Ok(WordOpenMode::None),
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(WordOpenMode::None)
|
||||
}
|
||||
@@ -86,7 +88,7 @@ impl ToSql for WordOpenMode {
|
||||
WordOpenMode::Easy => 3,
|
||||
WordOpenMode::Ok => 2,
|
||||
WordOpenMode::Hard => 1,
|
||||
WordOpenMode::None => 0
|
||||
WordOpenMode::None => 0,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
use crate::helpers::into_result;
|
||||
use crate::notification::NotificationData;
|
||||
use crate::notification::NotificationData::IncorrectAnkiFile;
|
||||
use hashbrown::HashMap;
|
||||
use crate::pages::import::AnkiSchema;
|
||||
use log::info;
|
||||
use rusqlite::Connection;
|
||||
use serde_json::Value;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ImportData(pub(crate) Vec<ImportGroup>);
|
||||
@@ -15,7 +16,7 @@ pub struct ImportGroup {
|
||||
pub name: String,
|
||||
pub fields: Vec<String>,
|
||||
pub length: u64,
|
||||
pub mapping: HashMap<String, String>,
|
||||
pub mapping: BTreeMap<String, String>,
|
||||
pub imported: bool,
|
||||
}
|
||||
|
||||
@@ -25,7 +26,17 @@ pub struct ImportNote {
|
||||
pub fields: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationData> {
|
||||
pub fn load_groups(
|
||||
connection: &Connection,
|
||||
schema: AnkiSchema,
|
||||
) -> Result<ImportData, NotificationData> {
|
||||
match schema {
|
||||
AnkiSchema::Old => load_old_schema(connection),
|
||||
AnkiSchema::Beta => load_new_schema(connection),
|
||||
}
|
||||
}
|
||||
|
||||
fn load_old_schema(connection: &Connection) -> Result<ImportData, NotificationData> {
|
||||
let json_models: String = connection
|
||||
.query_one("select models from col", (), |row| row.get(0))
|
||||
.map_err(|_| IncorrectAnkiFile)?;
|
||||
@@ -45,7 +56,7 @@ pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationDa
|
||||
.collect::<Vec<(i64, i64)>>();
|
||||
|
||||
for (_, collection) in sets {
|
||||
let fields_property = collection.get("fields");
|
||||
let fields_property = collection.get("flds");
|
||||
if let Some(fields_property) = fields_property {
|
||||
let fields = into_result(fields_property.as_array(), IncorrectAnkiFile)?
|
||||
.iter()
|
||||
@@ -82,7 +93,9 @@ pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationDa
|
||||
}
|
||||
Err(IncorrectAnkiFile)
|
||||
}
|
||||
|
||||
fn load_new_schema(_: &Connection) -> Result<ImportData, NotificationData> {
|
||||
Err(IncorrectAnkiFile)
|
||||
}
|
||||
pub fn get_words_of_group(
|
||||
connection: &Connection,
|
||||
group_id: u64,
|
||||
|
||||
+46
-14
@@ -1,8 +1,8 @@
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::{EntityData};
|
||||
use crate::data::entities::EntityData;
|
||||
use crate::data::repositories::{BatchedDbLayer, DbLayer};
|
||||
use crate::notification::MaybeError;
|
||||
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||
use crate::notification::NotificationData::DbSaveError;
|
||||
use log::{debug, error};
|
||||
use rusqlite::{Connection, Error, Params, Row};
|
||||
use std::marker::PhantomData;
|
||||
@@ -19,12 +19,16 @@ pub(crate) mod voice;
|
||||
pub(crate) mod web_api;
|
||||
pub mod word_groups;
|
||||
pub(crate) mod words;
|
||||
pub(crate) mod exam;
|
||||
|
||||
pub trait TableAccessQuerySet<T> {
|
||||
fn load() -> &'static str;
|
||||
fn save() -> &'static str;
|
||||
fn add() -> &'static str;
|
||||
fn name() -> &'static str;
|
||||
fn id_field() -> &'static str {
|
||||
"id"
|
||||
}
|
||||
fn from_sql(row: &Row) -> Result<T, Error>;
|
||||
fn insert_params(entity: &T) -> impl Params;
|
||||
fn update_params(entity: &T) -> impl Params;
|
||||
@@ -38,9 +42,9 @@ where
|
||||
_phantom: PhantomData<(T, Q)>,
|
||||
}
|
||||
|
||||
impl<T, Q: TableAccessQuerySet<T>> Default for SqliteDbLayer<T, Q>{
|
||||
impl<T, Q: TableAccessQuerySet<T>> Default for SqliteDbLayer<T, Q> {
|
||||
fn default() -> Self {
|
||||
Self{
|
||||
Self {
|
||||
_phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -52,7 +56,10 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> DbLayer<T> for SqliteDbLayer<T, Q
|
||||
|
||||
connection
|
||||
.execute(Q::save(), Q::update_params(entity))
|
||||
.map_err(|e| {error!("{}", e); DbSaveError})?;
|
||||
.map_err(|e| {
|
||||
error!("{}", e);
|
||||
DbSaveError
|
||||
})?;
|
||||
debug!("Updated in {} for {:?}", Q::name(), time.elapsed());
|
||||
Ok(())
|
||||
}
|
||||
@@ -61,8 +68,15 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> DbLayer<T> for SqliteDbLayer<T, Q
|
||||
let time = Instant::now();
|
||||
|
||||
let index: u32 = connection
|
||||
.query_row(Q::add(), Q::insert_params(entity), |row| row.get(0))
|
||||
.map_err(|e| {error!("{}", e); DbSaveError})?;
|
||||
.query_row(
|
||||
format!("{} RETURNING {}", Q::add(), Q::id_field()).as_str(),
|
||||
Q::insert_params(entity),
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|e| {
|
||||
error!("{}", e);
|
||||
DbSaveError
|
||||
})?;
|
||||
|
||||
entity.set_id(index.into());
|
||||
debug!("Added into {} for {:?}", Q::name(), time.elapsed());
|
||||
@@ -80,7 +94,10 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> DbLayer<T> for SqliteDbLayer<T, Q
|
||||
format!("DELETE FROM {} WHERE id = ?1", Q::name()).as_str(),
|
||||
(&id,),
|
||||
)
|
||||
.map_err(|e| {error!("{}", e); DbSaveError})?;
|
||||
.map_err(|e| {
|
||||
error!("{}", e);
|
||||
DbSaveError
|
||||
})?;
|
||||
debug!("Deleted from {} for {:?}", Q::name(), time.elapsed());
|
||||
Ok(())
|
||||
}
|
||||
@@ -91,9 +108,10 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> DbLayer<T> for SqliteDbLayer<T, Q
|
||||
let mut stmt = connection
|
||||
.prepare(Q::load())
|
||||
.expect("Failed to prepare state query");
|
||||
let iter = stmt
|
||||
.query_map([], |row| Ok(Q::from_sql(row)?))
|
||||
.map_err(|e| {error!("{}", e); DbSaveError})?;
|
||||
let iter = stmt.query_map([], |row| Q::from_sql(row)).map_err(|e| {
|
||||
error!("{}", e);
|
||||
DbSaveError
|
||||
})?;
|
||||
|
||||
iter.filter_map(|res| res.ok())
|
||||
.for_each(|i| storage.push(i));
|
||||
@@ -123,7 +141,10 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> BatchedDbLayer<T> for SqliteDbLay
|
||||
format!("DELETE FROM {} WHERE id in ({})", Q::name(), stringed).as_str(),
|
||||
(),
|
||||
)
|
||||
.map_err(|_| DbSaveError)?;
|
||||
.map_err(|e| {
|
||||
error!("{}", e);
|
||||
DbSaveError
|
||||
})?;
|
||||
}
|
||||
debug!(
|
||||
"Deleted {} from {} for {:?}",
|
||||
@@ -145,8 +166,10 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> BatchedDbLayer<T> for SqliteDbLay
|
||||
{
|
||||
let mut stmt = tx.prepare(Q::add()).expect("Failed to prepare state query");
|
||||
for entity in entities.iter() {
|
||||
stmt.execute(Q::insert_params(entity))
|
||||
.map_err(|_| DbSaveError)?;
|
||||
stmt.execute(Q::insert_params(entity)).map_err(|e| {
|
||||
error!("{}", e);
|
||||
DbSaveError
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,3 +191,12 @@ impl<T: EntityData, Q: TableAccessQuerySet<T>> BatchedDbLayer<T> for SqliteDbLay
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! data_access_methods {
|
||||
($layer:ident, $repo:ident, $repoinner:ident, $data:ty, $queryset:ty, $query:ident) => {
|
||||
pub type $repo = DataRepository<$data, $layer>;
|
||||
pub type $repoinner = DataRepositoryInner<$data, $layer>;
|
||||
pub type $layer = SqliteDbLayer<$data, $queryset>;
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::fs::*;
|
||||
use log::error;
|
||||
use rusqlite::Connection;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
@@ -23,6 +24,8 @@ fn create_tables(conn: &Connection) {
|
||||
make_card_stats(conn).expect("Failed to init table");
|
||||
make_history(conn).expect("Failed to init table");
|
||||
make_custom_fields(conn).expect("Failed to init table");
|
||||
make_exams(conn).expect("Failed to init table");
|
||||
make_exam_entry(conn).expect("Failed to init table");
|
||||
}
|
||||
|
||||
fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
@@ -63,6 +66,19 @@ fn make_history(conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
fn make_custom_fields(conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
let query = include_str!("../../sql/custom_fields.sql");
|
||||
conn.execute(query, ())?;
|
||||
conn.execute("insert into custom_fields (name, identifier) values (\"Чтение\", \"reading\"), (\"Описание\", \"description\"), (\"Пример использования\", \"context\")", ())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_exams(conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
let query = include_str!("../../sql/exam.sql");
|
||||
conn.execute(query, ())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_exam_entry(conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
let query = include_str!("../../sql/exam_entry.sql");
|
||||
conn.execute(query, ())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -74,12 +90,9 @@ pub fn default_connection() -> Connection {
|
||||
.expect("Failed to set PRAGMA");
|
||||
connection
|
||||
.query_one("PRAGMA journal_mode = WAL;", [], |row| {
|
||||
println!("{:?}", row);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_or_else(|e| {
|
||||
println!("{}", e);
|
||||
});
|
||||
.expect("Failed to init database");
|
||||
connection
|
||||
.execute("PRAGMA synchronous = NORMAL;", [])
|
||||
.expect("Failed to set PRAGMA");
|
||||
@@ -108,9 +121,28 @@ impl Default for SqliteConnection {
|
||||
|
||||
impl SqliteConnection {
|
||||
pub fn finish(&mut self) {
|
||||
let connection = self.0.take().unwrap();
|
||||
connection
|
||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
|
||||
.unwrap_or_else(|e| {
|
||||
error!("Ошибка при checkpoint WAL: {e}");
|
||||
});
|
||||
connection
|
||||
.execute("PRAGMA optimize", [])
|
||||
.unwrap_or_else(|e| {
|
||||
error!("Ошибка при оптимизации БД: {e}");
|
||||
0
|
||||
});
|
||||
|
||||
self.0 = None;
|
||||
}
|
||||
pub fn restart(&mut self) {
|
||||
self.0 = Some(default_connection());
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteConnection {
|
||||
fn drop(&mut self) {
|
||||
self.finish();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
use crate::fs::*;
|
||||
use crate::notification::NotificationData::{CompressError, PermissionDenied, WebApiUnavailable};
|
||||
use crate::notification::NotificationData::{
|
||||
CompressError, OpenFileError, PermissionDenied, WebApiUnavailable,
|
||||
};
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use log::info;
|
||||
use log::{debug, info};
|
||||
use std::io;
|
||||
use tokio::fs::{File, OpenOptions};
|
||||
use std::time::Instant;
|
||||
use tokio::fs::{File, OpenOptions, remove_file};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
|
||||
|
||||
@@ -35,10 +38,13 @@ pub async fn send_data(id: String) -> MaybeError {
|
||||
}
|
||||
|
||||
fn compress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> {
|
||||
let time = Instant::now();
|
||||
let mut encoder =
|
||||
Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).map_err(|_| CompressError)?;
|
||||
Encoder::new(Vec::new(), 17).map_err(|_| CompressError)?;
|
||||
io::copy(&mut &data[..], &mut encoder).map_err(|_| PermissionDenied)?;
|
||||
encoder.finish().map_err(|_| CompressError)
|
||||
let result = encoder.finish().map_err(|_| CompressError);
|
||||
debug!("Compress time: {:?}", time.elapsed());
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn load_data(id: String, temp: bool) -> MaybeError {
|
||||
@@ -49,7 +55,7 @@ pub async fn load_data(id: String, temp: bool) -> MaybeError {
|
||||
.get(&id_url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| WebApiUnavailable)?
|
||||
.map_err(|e| WebApiUnavailable)?
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|_| WebApiUnavailable)?
|
||||
@@ -74,6 +80,12 @@ pub async fn load_data(id: String, temp: bool) -> MaybeError {
|
||||
.await
|
||||
.map_err(|_| WebApiUnavailable)?;
|
||||
set_local_version(version.parse::<u32>().unwrap_or_default()).await?;
|
||||
if db_wal().exists() {
|
||||
remove_file(db_wal()).await.map_err(|_| OpenFileError)?;
|
||||
}
|
||||
if db_shm().exists() {
|
||||
remove_file(db_shm()).await.map_err(|_| OpenFileError)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,9 @@ use crate::data::entities::WordGroup;
|
||||
use crate::data::repositories::{DataRepository, DataRepositoryInner};
|
||||
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
|
||||
use rusqlite::{Error, Params, Row};
|
||||
use crate::data_access_methods;
|
||||
|
||||
pub type WordGroupRepository = DataRepository<WordGroup, WordGroupDataLayer>;
|
||||
pub type WordGroupRepositoryInner = DataRepositoryInner<WordGroup, WordGroupDataLayer>;
|
||||
pub type WordGroupDataLayer = SqliteDbLayer<WordGroup, WordGroupQuerySet>;
|
||||
data_access_methods!(WordGroupDataLayer, WordGroupRepository, WordGroupRepositoryInner, WordGroup, WordGroupQuerySet, WordGroupQuery);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WordGroupQuerySet;
|
||||
@@ -19,7 +18,7 @@ impl TableAccessQuerySet<WordGroup> for WordGroupQuerySet {
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"INSERT INTO word_groups (name) VALUES (?1) RETURNING id"
|
||||
"INSERT INTO word_groups (name) VALUES (?1)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
|
||||
+29
-172
@@ -1,13 +1,13 @@
|
||||
use crate::data::entities::{WordData, WordGroup};
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::WordData;
|
||||
use crate::data::repositories::{DataRepository, DataRepositoryInner};
|
||||
use crate::data_provider::{SqliteDbLayer, TableAccessQuerySet};
|
||||
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use rusqlite::{Connection, Error, Params, Row, params};
|
||||
use litemap::LiteMap;
|
||||
use rusqlite::{Error, Params, Row};
|
||||
use crate::data_access_methods;
|
||||
|
||||
data_access_methods!(WordDataLayer, WordRepository, WordRepositoryInner, WordData, WordQuerySet, WordQuery);
|
||||
|
||||
pub type WordRepository = DataRepository<WordData, WordDataLayer>;
|
||||
pub type WordRepositoryInner = DataRepositoryInner<WordData, WordDataLayer>;
|
||||
pub type WordDataLayer = SqliteDbLayer<WordData, WordQuerySet>;
|
||||
#[derive(Clone)]
|
||||
pub struct WordQuerySet;
|
||||
impl TableAccessQuerySet<WordData> for WordQuerySet {
|
||||
@@ -20,7 +20,7 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
|
||||
}
|
||||
|
||||
fn add() -> &'static str {
|
||||
"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)"
|
||||
}
|
||||
|
||||
fn name() -> &'static str {
|
||||
@@ -34,7 +34,7 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
|
||||
key: row.get(1)?,
|
||||
value: row.get(2)?,
|
||||
tags: row.get(3)?,
|
||||
additional: serde_json::from_str(&additional).unwrap_or_default(),
|
||||
additional: additional_from_string(additional),
|
||||
group_id: row.get(5)?,
|
||||
})
|
||||
}
|
||||
@@ -44,7 +44,7 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
|
||||
&entity.key,
|
||||
&entity.value,
|
||||
&entity.tags,
|
||||
serde_json::to_string(&entity.additional).unwrap_or_default(),
|
||||
additional_to_string(&entity.additional),
|
||||
entity.group_id,
|
||||
)
|
||||
}
|
||||
@@ -54,175 +54,32 @@ impl TableAccessQuerySet<WordData> for WordQuerySet {
|
||||
&entity.key,
|
||||
&entity.value,
|
||||
&entity.tags,
|
||||
serde_json::to_string(&entity.additional).unwrap_or_default(),
|
||||
additional_to_string(&entity.additional),
|
||||
entity.id,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_word(word: &mut WordData, connection: &Connection) -> MaybeError {
|
||||
let index : u32 = connection
|
||||
.query_row(
|
||||
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
|
||||
(
|
||||
&word.key,
|
||||
&word.value,
|
||||
&word.tags,
|
||||
serde_json::to_string(&word.additional).unwrap_or_default(),
|
||||
&word.group_id,
|
||||
),
|
||||
|row| row.get(0),
|
||||
).map_err(|_| DbSaveError)?;
|
||||
|
||||
word.id = index.into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_words(words: &mut [WordData], connection: &mut Connection) -> MaybeError {
|
||||
let tx = connection.transaction().map_err(|_| DbLoadError)?;
|
||||
let count = words.len();
|
||||
|
||||
{
|
||||
let mut stmt = tx
|
||||
.prepare(
|
||||
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
)
|
||||
.expect("Failed to prepare statement");
|
||||
|
||||
for word in words.iter() {
|
||||
stmt.execute(params![
|
||||
word.key,
|
||||
word.value,
|
||||
word.tags,
|
||||
serde_json::to_string(&word.additional).unwrap_or_default(),
|
||||
word.group_id
|
||||
])
|
||||
.map_err(|_| DbSaveError)?;
|
||||
}
|
||||
fn additional_to_string(map: &LiteMap<Id, String>) -> String {
|
||||
let mut parts = Vec::with_capacity(map.len() * 2);
|
||||
for (id, value) in map {
|
||||
parts.push(id.to_string());
|
||||
parts.push(value.clone());
|
||||
}
|
||||
parts.join("")
|
||||
}
|
||||
|
||||
let last_index: u32 = tx.last_insert_rowid() as u32;
|
||||
tx.commit().map_err(|_| DbSaveError)?;
|
||||
|
||||
let start_index = last_index - (count as u32) + 1;
|
||||
|
||||
for (index, id) in (start_index..=last_index).enumerate() {
|
||||
words[index].id = id.into();
|
||||
fn additional_from_string(data: String) -> LiteMap<Id, String> {
|
||||
if data.is_empty() {
|
||||
return LiteMap::new();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_word(word: &mut WordData, connection: &Connection) -> MaybeError {
|
||||
if !word.id.is_valid() {
|
||||
Ok(add_word(word, connection)?)
|
||||
} else {
|
||||
connection
|
||||
.execute(
|
||||
"UPDATE words SET key = ?1, value = ?2, tags = ?3, more = ?4 WHERE id = ?5",
|
||||
(
|
||||
&word.key,
|
||||
&word.value,
|
||||
&word.tags,
|
||||
serde_json::to_string(&word.additional).map_err(|_| DbSaveError)?,
|
||||
&word.id,
|
||||
),
|
||||
)
|
||||
.map_err(|_| DbSaveError)?;
|
||||
Ok(())
|
||||
let parts = data.split('').collect::<Vec<&str>>();
|
||||
let chunks = parts.chunks(2).collect::<Vec<&[&str]>>();
|
||||
let mut map = LiteMap::with_capacity(parts.len());
|
||||
for part in &chunks {
|
||||
let id: Id = part[0].parse().unwrap();
|
||||
let value: String = part[1].to_string();
|
||||
map.insert(id, value);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_word(word: &WordData, connection: &Connection) -> MaybeError {
|
||||
if !word.id.is_valid() {
|
||||
return Err(DbSaveError);
|
||||
}
|
||||
connection
|
||||
.execute("DELETE FROM words WHERE id = ?1", (&word.id,))
|
||||
.map_err(|_| DbSaveError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_words(connection: &Connection) -> Result<Vec<WordData>, NotificationData> {
|
||||
let mut stmt = connection
|
||||
.prepare("SELECT id, key, value, tags, more, group_id FROM words")
|
||||
.expect("Failed to prepare statement");
|
||||
let word_iter = stmt
|
||||
.query_map([], |row| {
|
||||
let additional: String = row.get(4)?;
|
||||
Ok(WordData {
|
||||
id: row.get(0)?,
|
||||
key: row.get(1)?,
|
||||
value: row.get(2)?,
|
||||
tags: row.get(3)?,
|
||||
additional: serde_json::from_str(&additional).unwrap_or_default(),
|
||||
group_id: row.get(5)?,
|
||||
})
|
||||
})
|
||||
.map_err(|_| DbLoadError)?;
|
||||
|
||||
let mut buffer = Vec::with_capacity(1024);
|
||||
word_iter
|
||||
.filter_map(|res| res.ok())
|
||||
.for_each(|i| buffer.push(i));
|
||||
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
pub fn load_word_groups(connection: &Connection) -> Result<Vec<WordGroup>, NotificationData> {
|
||||
let mut stmt = connection
|
||||
.prepare("SELECT id, name FROM word_groups")
|
||||
.expect("Failed to prepare statement");
|
||||
let group_iter = stmt
|
||||
.query_map([], |row| {
|
||||
Ok(WordGroup {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
})
|
||||
})
|
||||
.map_err(|_| DbLoadError)?;
|
||||
|
||||
let mut buffer = Vec::with_capacity(8);
|
||||
group_iter
|
||||
.filter_map(|res| res.ok())
|
||||
.for_each(|i| buffer.push(i));
|
||||
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
pub fn add_group(group: &mut WordGroup, connection: &Connection) -> MaybeError {
|
||||
let index: u32 = connection
|
||||
.query_row(
|
||||
"INSERT INTO word_groups (name) VALUES (?1) RETURNING id",
|
||||
(&group.name,),
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|_| DbSaveError)?;
|
||||
|
||||
group.id = index.into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_group(group: &mut WordGroup, connection: &Connection) -> MaybeError {
|
||||
if !group.id.is_valid() {
|
||||
Ok(add_group(group, connection)?)
|
||||
} else {
|
||||
connection
|
||||
.execute(
|
||||
"UPDATE word_groups SET name = ?1 WHERE id = ?2",
|
||||
(&group.name, &group.id),
|
||||
)
|
||||
.map_err(|_| DbSaveError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_group(group: &WordGroup, connection: &Connection) -> MaybeError {
|
||||
if !group.id.is_valid() {
|
||||
return Err(DbSaveError);
|
||||
}
|
||||
connection
|
||||
.execute("DELETE FROM word_groups WHERE id = ?1", (&group.id,))
|
||||
.map_err(|_| DbSaveError)?;
|
||||
Ok(())
|
||||
map
|
||||
}
|
||||
@@ -16,6 +16,14 @@ pub fn app_data_dir() -> PathBuf {
|
||||
pub fn db_path() -> PathBuf {
|
||||
app_data_dir().join("data.db")
|
||||
}
|
||||
|
||||
pub fn db_wal() -> PathBuf {
|
||||
app_data_dir().join("data.db-wal")
|
||||
}
|
||||
pub fn db_shm() -> PathBuf {
|
||||
app_data_dir().join("data.db-shm")
|
||||
}
|
||||
|
||||
pub fn temp_db_path() -> PathBuf {
|
||||
app_data_dir().join("data.db.tmp")
|
||||
}
|
||||
@@ -28,14 +36,6 @@ pub fn db_meta_path() -> PathBuf {
|
||||
app_data_dir().join("data.meta")
|
||||
}
|
||||
|
||||
pub fn history_dir() -> Result<PathBuf, NotificationData> {
|
||||
let directory = app_data_dir().join("history");
|
||||
if !directory.exists() {
|
||||
fs::create_dir_all(directory.clone()).map_err(|_| PermissionDenied)?;
|
||||
}
|
||||
Ok(directory)
|
||||
}
|
||||
|
||||
pub fn voice_dir() -> Result<PathBuf, NotificationData> {
|
||||
let directory = app_data_dir().join("voice");
|
||||
if !directory.exists() {
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod notification;
|
||||
mod pages;
|
||||
mod styling;
|
||||
pub mod tests;
|
||||
pub mod widgets;
|
||||
|
||||
use crate::app::start;
|
||||
use mimalloc::MiMalloc;
|
||||
|
||||
+18
-10
@@ -1,5 +1,5 @@
|
||||
use crate::app::{fill_state, AppState};
|
||||
use crate::data_provider::sqlite::{create_db};
|
||||
use crate::data_provider::sqlite::create_db;
|
||||
use crate::data_provider::web_api::{
|
||||
get_local_version, get_web_version, load_data, set_local_version,
|
||||
};
|
||||
@@ -12,6 +12,7 @@ use crate::notification::{
|
||||
};
|
||||
use crate::pages::dictionary::{DictionaryMessage, DictionaryState};
|
||||
use crate::pages::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState};
|
||||
use crate::pages::exams::{ExamsMessage, ExamsState};
|
||||
use crate::pages::history::{HistoryMessage, HistoryState};
|
||||
use crate::pages::import::{ImportMessage, ImportState};
|
||||
use crate::pages::quiz::{QuizMessage, QuizState};
|
||||
@@ -21,7 +22,6 @@ use crate::pages::repetition_settings::{RepetitionSettingsMessage, RepetitionSet
|
||||
use crate::pages::repetitions::{RepetitionsMessage, RepetitionsState};
|
||||
use crate::pages::selector::{SelectorMessage, SelectorState};
|
||||
use crate::pages::sync::{SyncMessage, SyncState};
|
||||
use crate::pages::word::{WordMessage, WordState};
|
||||
use crate::pages::writing::{WritingMessage, WritingState};
|
||||
use crate::state_navigate_handle;
|
||||
use crate::state_update;
|
||||
@@ -33,6 +33,7 @@ use iced::{Element, Task};
|
||||
use iced_core::Length::Fill;
|
||||
use log::{debug, info};
|
||||
use std::time::Instant;
|
||||
use crate::pages::exam::{ExamMessage, ExamState};
|
||||
|
||||
impl Default for ScreenState {
|
||||
fn default() -> Self {
|
||||
@@ -56,11 +57,12 @@ pub enum RootMessage {
|
||||
Randomizer(RandomizerMessage),
|
||||
Repetitions(RepetitionsMessage),
|
||||
Repetition(RepetitionMessage),
|
||||
Word(WordMessage),
|
||||
Sync(SyncMessage),
|
||||
History(HistoryMessage),
|
||||
RepetitionSettings(RepetitionSettingsMessage),
|
||||
Import(ImportMessage),
|
||||
Exams(ExamsMessage),
|
||||
Exam(ExamMessage),
|
||||
Keyboard(Event),
|
||||
PushNotification(NotificationRequest),
|
||||
Notification(NotificationMessage),
|
||||
@@ -78,11 +80,12 @@ pub enum Page {
|
||||
Randomizer(RandomizerState),
|
||||
Repetitions(RepetitionsState),
|
||||
Repetition(RepetitionState),
|
||||
Word(WordState),
|
||||
Sync(SyncState),
|
||||
History(HistoryState),
|
||||
RepetitionSettings(RepetitionSettingsState),
|
||||
Import(ImportState),
|
||||
Exams(ExamsState),
|
||||
Exam(ExamState),
|
||||
PreviousPage,
|
||||
}
|
||||
|
||||
@@ -182,11 +185,12 @@ impl ScreenState {
|
||||
Randomizer,
|
||||
Repetitions,
|
||||
Repetition,
|
||||
Word,
|
||||
Sync,
|
||||
History,
|
||||
RepetitionSettings,
|
||||
Import
|
||||
Import,
|
||||
Exams,
|
||||
Exam
|
||||
);
|
||||
}
|
||||
debug!("Update took {:?}", time.elapsed());
|
||||
@@ -206,11 +210,12 @@ impl ScreenState {
|
||||
Randomizer,
|
||||
Repetitions,
|
||||
Repetition,
|
||||
Word,
|
||||
Sync,
|
||||
History,
|
||||
RepetitionSettings,
|
||||
Import
|
||||
Import,
|
||||
Exams,
|
||||
Exam
|
||||
)
|
||||
}
|
||||
|
||||
@@ -227,11 +232,12 @@ impl ScreenState {
|
||||
Randomizer,
|
||||
Repetitions,
|
||||
Repetition,
|
||||
Word,
|
||||
Sync,
|
||||
History,
|
||||
RepetitionSettings,
|
||||
Import
|
||||
Import,
|
||||
Exams,
|
||||
Exam
|
||||
);
|
||||
|
||||
let notifications = self.notification_manager.draw().map(Notification);
|
||||
@@ -244,6 +250,8 @@ impl ScreenState {
|
||||
if let Some(page) = self.stack.last_mut() {
|
||||
return match page {
|
||||
Repetition(page) => page.press(&message),
|
||||
Dictionary(page) => page.press(&message),
|
||||
Exam(page) => page.press(&message),
|
||||
_ => Task::none(),
|
||||
};
|
||||
}
|
||||
|
||||
+8
-4
@@ -138,8 +138,8 @@ impl NotificationManager {
|
||||
|
||||
fn draw_data<'a>(data: &NotificationData) -> Element<'a, NotificationMessage> {
|
||||
match data {
|
||||
NotificationData::DataLoaded => {
|
||||
text!("Данные успешно загружены на сервер")
|
||||
NotificationData::DataSynced => {
|
||||
text!("Данные успешно синхронизированы")
|
||||
}
|
||||
NotificationData::ImportError => {
|
||||
text!("Ошибка при импорте данных из Anki")
|
||||
@@ -148,7 +148,7 @@ impl NotificationManager {
|
||||
text!("Неподдерживаемый формат файла .apkg")
|
||||
}
|
||||
NotificationData::OpenFileError => {
|
||||
text!("Ошибка открытия файла пакета")
|
||||
text!("Ошибка открытия файла")
|
||||
}
|
||||
NotificationData::VoiceVoxUnavailable => {
|
||||
text!("Не получается подключиться к VoiceVox")
|
||||
@@ -168,6 +168,9 @@ impl NotificationManager {
|
||||
NotificationData::CompressError => {
|
||||
text!("Ошибка сжатия или распаковки данных")
|
||||
}
|
||||
NotificationData::LocalVersionChanged => {
|
||||
text!("Локальная версия будет заменена")
|
||||
}
|
||||
}
|
||||
.width(Fill)
|
||||
.into()
|
||||
@@ -184,7 +187,7 @@ pub enum NotificationRequest {
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum NotificationData {
|
||||
PermissionDenied,
|
||||
DataLoaded,
|
||||
DataSynced,
|
||||
ImportError,
|
||||
IncorrectAnkiFile,
|
||||
OpenFileError,
|
||||
@@ -193,6 +196,7 @@ pub enum NotificationData {
|
||||
DbSaveError,
|
||||
DbLoadError,
|
||||
CompressError,
|
||||
LocalVersionChanged,
|
||||
}
|
||||
|
||||
pub type MaybeError = Result<(), NotificationData>;
|
||||
@@ -11,3 +11,5 @@ pub mod selector;
|
||||
pub mod sync;
|
||||
pub mod word;
|
||||
pub mod writing;
|
||||
pub mod exams;
|
||||
pub mod exam;
|
||||
+481
-194
@@ -2,33 +2,43 @@ use crate::app::AppState;
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::{EntityHandle, WordData, WordGroup};
|
||||
use crate::data::repositories::{Query, Repository};
|
||||
use crate::data_provider::word_groups::{WordGroupDataLayer, WordGroupRepositoryInner};
|
||||
use crate::data_provider::words::WordDataLayer;
|
||||
use crate::data_provider::words::WordRepositoryInner;
|
||||
use crate::navigation::Page::{Import, Word};
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::navigation::Page::Import;
|
||||
use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
|
||||
use crate::pages::dictionary::BasicWordFields::*;
|
||||
use crate::pages::dictionary::DictionaryMessage::*;
|
||||
use crate::pages::dictionary::SelectionChangeDirection::*;
|
||||
use crate::pages::dictionary_quiz::DictionaryQuizState;
|
||||
use crate::pages::import::ImportState;
|
||||
use crate::pages::word::WordState;
|
||||
use crate::push_error;
|
||||
use crate::push_error_task;
|
||||
use crate::pages::word::{WordEditor, WordMessage};
|
||||
use crate::styling::*;
|
||||
use crate::widgets::hard_mouse_area::hard_mouse_area;
|
||||
use crate::{jl_button, push_error};
|
||||
use crate::{jl_text_input, push_error_task};
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use iced::alignment::Vertical::Center;
|
||||
use iced::widget::button::Style;
|
||||
use iced::widget::button::{danger, text};
|
||||
use iced::widget::button::{danger};
|
||||
use iced::widget::operation::focus;
|
||||
use iced::widget::space::horizontal;
|
||||
use iced::widget::text_input::Status::Active;
|
||||
use iced::widget::text_input::default;
|
||||
use iced::widget::*;
|
||||
use iced::{Border, Color, Shadow, Task};
|
||||
use iced_core::Length::Fill;
|
||||
use iced::widget::{row, container, column, text_input, space, button, scrollable, text, Row, checkbox, Column, toggler, lazy};
|
||||
use iced::{Border, Color, Element, Shadow, Task};
|
||||
use iced_core::Length::{Fill, FillPortion};
|
||||
use iced_core::border::Radius;
|
||||
use iced_core::keyboard::Key::Named;
|
||||
use iced_core::keyboard::key::Physical::Code;
|
||||
use iced_core::keyboard::{Event, Modifiers};
|
||||
use iced_core::{keyboard, Padding, Theme};
|
||||
use log::info;
|
||||
use rand::random_range;
|
||||
use std::ops::Add;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use crate::data_provider::word_groups::{WordGroupDataLayer, WordGroupRepositoryInner};
|
||||
|
||||
pub struct DictionaryState {
|
||||
state: AppState,
|
||||
@@ -43,15 +53,15 @@ pub struct DictionaryState {
|
||||
auto_save_queue: HashMap<EntityHandle<WordData>, DateTime<Utc>>,
|
||||
displayed_words_query: Query<WordData, WordRepositoryInner, WordDataLayer>,
|
||||
groups_query: Query<WordGroup, WordGroupRepositoryInner, WordGroupDataLayer>,
|
||||
selected_cell: Option<(EntityHandle<WordData>, BasicWordFields, usize)>,
|
||||
word_editor: Option<WordEditor<DictionaryMessage>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum DictionaryMessage {
|
||||
Back,
|
||||
SetTags(EntityHandle<WordData>, String),
|
||||
SetKey(EntityHandle<WordData>, String),
|
||||
SetValue(EntityHandle<WordData>, String),
|
||||
WordAction(EntityHandle<WordData>),
|
||||
ExtendedEdit(EntityHandle<WordData>),
|
||||
DeleteWord(EntityHandle<WordData>),
|
||||
NewWord,
|
||||
Include(EntityHandle<WordData>, bool),
|
||||
IncludeTag(String, bool),
|
||||
@@ -68,8 +78,31 @@ pub enum DictionaryMessage {
|
||||
ChangeDirection,
|
||||
TrySave(EntityHandle<WordData>),
|
||||
GotoImport,
|
||||
SelectField(EntityHandle<WordData>, BasicWordFields, usize),
|
||||
EditField(String),
|
||||
ChangeSelectedField(SelectionChangeDirection),
|
||||
EditorAction(WordMessage),
|
||||
ExtendedWordEdited,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Copy)]
|
||||
pub enum SelectionChangeDirection {
|
||||
Next,
|
||||
Previous,
|
||||
Forward,
|
||||
Backward,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Copy)]
|
||||
pub enum BasicWordFields {
|
||||
Key,
|
||||
Value,
|
||||
Tags,
|
||||
TotalLine,
|
||||
}
|
||||
|
||||
const FIELDS: &[BasicWordFields] = &[Key, Value, Tags];
|
||||
|
||||
impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
fn navigate(&mut self, message: &DictionaryMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
@@ -81,7 +114,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
let mut words = vec![];
|
||||
let dict = &self.state.dictionary.read();
|
||||
|
||||
let mut query = dict.query(Arc::new(|_| true));
|
||||
let query = dict.query(Arc::new(|_| true));
|
||||
let handles = query.handles();
|
||||
words = handles.filter(|h| self.included.contains(h)).collect();
|
||||
|
||||
@@ -89,14 +122,10 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
words,
|
||||
self.reverse,
|
||||
self.no_typing,
|
||||
self.state.clone()
|
||||
self.state.clone(),
|
||||
)));
|
||||
}
|
||||
if let WordAction(handle) = message
|
||||
&& handle.real()
|
||||
{
|
||||
return Some(Word(WordState::new(*handle, self.state.clone())));
|
||||
}
|
||||
|
||||
if let GotoImport = message {
|
||||
return Some(Import(ImportState::new(self.state.clone())));
|
||||
}
|
||||
@@ -106,6 +135,9 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
fn navigated(&mut self) {
|
||||
self.included = Default::default();
|
||||
self.tag_map = Default::default();
|
||||
let groups = self.state.word_groups.read();
|
||||
self.groups_query.load(&groups);
|
||||
drop(groups);
|
||||
self.update_tags();
|
||||
}
|
||||
|
||||
@@ -116,47 +148,12 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
let mut word = WordData::new();
|
||||
word.group_id = self.selected_group.id;
|
||||
dictionary.create(word);
|
||||
self.displayed_words_query.load(&dictionary);
|
||||
}
|
||||
|
||||
SetKey(handle, v) => {
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
dictionary.get_mut_static(handle).unwrap().key = v;
|
||||
drop(dictionary);
|
||||
return self.launch_auto_save_offset(handle);
|
||||
}
|
||||
SetValue(handle, v) => {
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
dictionary.get_mut_static(handle).unwrap().value = v;
|
||||
drop(dictionary);
|
||||
return self.launch_auto_save_offset(handle);
|
||||
}
|
||||
SetTags(i, mut v) => {
|
||||
{
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
|
||||
let word = dictionary.get_mut_static(i).unwrap();
|
||||
let current_tags_value = word.tags.clone();
|
||||
|
||||
if v.ends_with(", ") && v.len() < current_tags_value.len() {
|
||||
v = v[..v.len() - 2].to_string()
|
||||
}
|
||||
|
||||
while let Some(index) = v.find(",,") {
|
||||
v.remove(index);
|
||||
}
|
||||
|
||||
word.tags = v;
|
||||
}
|
||||
|
||||
self.update_tags();
|
||||
return self.launch_auto_save_offset(i);
|
||||
}
|
||||
|
||||
WordAction(i) => {
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
|
||||
if let Err(err) = dictionary.delete(i) {
|
||||
return push_error_task!(err);
|
||||
ExtendedEdit(i) => {
|
||||
self.word_editor = Some(self.editor_for_word(i));
|
||||
if let Some((_, _, index)) = self.selected_cell {
|
||||
self.selected_cell = Some((i, TotalLine, index))
|
||||
}
|
||||
}
|
||||
Include(i, b) => {
|
||||
@@ -188,6 +185,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
id: 0.into(),
|
||||
name: format!("Группа слов {}", random_range(100..1000)),
|
||||
});
|
||||
self.groups_query.load(&groups);
|
||||
}
|
||||
EditGroup(new) => {
|
||||
let mut groups = self.state.word_groups.write();
|
||||
@@ -198,14 +196,21 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
}
|
||||
}
|
||||
SaveGroup => {
|
||||
let mut groups = self.state.word_groups.write();
|
||||
{
|
||||
let mut groups = self.state.word_groups.write();
|
||||
|
||||
if let Err(err) = groups.save(&mut self.selected_group) {
|
||||
return push_error_task!(err);
|
||||
if let Err(err) = groups.save(&mut self.selected_group) {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
|
||||
self.groups_query.load(&groups);
|
||||
}
|
||||
|
||||
self.setup_words_query();
|
||||
}
|
||||
SelectGroup(i) => {
|
||||
self.selected_group = i;
|
||||
self.setup_words_query();
|
||||
self.update_words_include(i.id)
|
||||
}
|
||||
DeleteGroup => {
|
||||
@@ -213,9 +218,10 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
return Task::none();
|
||||
}
|
||||
{
|
||||
let mut groups = self.state.word_groups.write();
|
||||
let delete_group = self.selected_group;
|
||||
self.selected_group = groups.handle_by_id(Id(1));
|
||||
self.selected_group = EntityHandle::from_id(1.into());
|
||||
self.setup_words_query();
|
||||
let mut groups = self.state.word_groups.write();
|
||||
|
||||
if let Err(err) = groups.delete(delete_group) {
|
||||
return push_error_task!(err);
|
||||
@@ -224,47 +230,175 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
if let Err(err) = self.state.dictionary.write().reload() {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
self.groups_query.load(&groups);
|
||||
}
|
||||
|
||||
self.selected_cell = None;
|
||||
self.word_editor = None;
|
||||
self.update_tags()
|
||||
}
|
||||
ChangeDirection => {
|
||||
self.reverse_list = !self.reverse_list;
|
||||
}
|
||||
TrySave(mut handle) => {
|
||||
let original = handle;
|
||||
let now = Utc::now();
|
||||
if !self.auto_save_queue.contains_key(&handle) {
|
||||
return Task::none();
|
||||
}
|
||||
if self.auto_save_queue[&handle] <= now {
|
||||
self.update_tags();
|
||||
self.auto_save_queue.remove(&handle);
|
||||
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
|
||||
let _ = dictionary.save(&mut handle);
|
||||
let reload_query = !handle.real();
|
||||
let _ = dictionary.save(&mut handle);
|
||||
if reload_query {
|
||||
self.displayed_words_query.load(&dictionary);
|
||||
if let Some(selected) = self.selected_cell
|
||||
&& selected.0 == original
|
||||
{
|
||||
self.selected_cell = Some((handle, selected.1, selected.2));
|
||||
if self.word_editor.is_some() {
|
||||
self.word_editor = Some(self.editor_for_word(handle));
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("Saved word");
|
||||
return Task::none();
|
||||
}
|
||||
}
|
||||
GotoImport => {}
|
||||
SelectField(e, f, index) => {
|
||||
info!("Editing word {}", e.id);
|
||||
if self.word_editor.is_some()
|
||||
&& let Some(selected) = &self.selected_cell
|
||||
&& selected.0 != e
|
||||
{
|
||||
self.word_editor = Some(self.editor_for_word(e));
|
||||
}
|
||||
self.selected_cell = Some((e, f, index));
|
||||
|
||||
return focus(iced::widget::Id::new("editor"));
|
||||
}
|
||||
EditField(value) => {
|
||||
if let Some(selected) = self.selected_cell.as_ref() {
|
||||
{
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
let word = dictionary.get_mut_static(selected.0).unwrap();
|
||||
match selected.1 {
|
||||
Key => {
|
||||
word.key = value;
|
||||
}
|
||||
Value => {
|
||||
word.value = value;
|
||||
}
|
||||
Tags => {
|
||||
word.tags = value;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
return self.launch_auto_save_offset(selected.0);
|
||||
}
|
||||
}
|
||||
ChangeSelectedField(change) => {
|
||||
return if let Some(selected) = self.selected_cell {
|
||||
let update_vertical = move |mut dir: bool| {
|
||||
if self.reverse_list {
|
||||
dir = !dir;
|
||||
}
|
||||
let new_index = if dir {
|
||||
selected.2.saturating_add(1)
|
||||
} else {
|
||||
selected.2.saturating_sub(1)
|
||||
};
|
||||
if new_index < self.displayed_words_query.len() {
|
||||
return SelectField(
|
||||
self.displayed_words_query.get(new_index).unwrap(),
|
||||
selected.1,
|
||||
new_index,
|
||||
);
|
||||
}
|
||||
|
||||
SelectField(selected.0, selected.1, selected.2)
|
||||
};
|
||||
|
||||
let update_horizontal = move |dir: bool| {
|
||||
let current = selected.1;
|
||||
let delta = if dir { 1 } else { -1 };
|
||||
let mut index =
|
||||
FIELDS.iter().position(|&f| f == current).unwrap() as i8 + delta;
|
||||
if index < 0 {
|
||||
index = (FIELDS.len() - 1) as i8;
|
||||
}
|
||||
if index >= FIELDS.len() as i8 {
|
||||
index = 0;
|
||||
}
|
||||
SelectField(selected.0, FIELDS[index as usize], selected.2)
|
||||
};
|
||||
|
||||
Task::done(RootMessage::Dictionary(match change {
|
||||
Next => update_vertical(true),
|
||||
Previous => update_vertical(false),
|
||||
Forward => update_horizontal(true),
|
||||
Backward => update_horizontal(false),
|
||||
}))
|
||||
} else {
|
||||
Task::none()
|
||||
};
|
||||
}
|
||||
DeleteWord(i) => {
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
|
||||
if let Err(err) = dictionary.delete(i) {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
|
||||
self.displayed_words_query.load(&dictionary);
|
||||
self.selected_cell = None;
|
||||
self.word_editor = None;
|
||||
}
|
||||
EditorAction(action) => {
|
||||
let result = self.word_editor.as_mut().unwrap().update(action);
|
||||
if let Some(result) = result {
|
||||
match result {
|
||||
DeleteWord(_) | ExtendedWordEdited => {
|
||||
return Task::done(RootMessage::Dictionary(result));
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
ExtendedWordEdited => {
|
||||
let handle = self.word_editor.as_ref().unwrap().word_handle;
|
||||
return self.launch_auto_save_offset(handle);
|
||||
}
|
||||
}
|
||||
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn view(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
fn view(&self) -> Element<'_, DictionaryMessage> {
|
||||
back_overlay(
|
||||
row![
|
||||
iced::widget::column![
|
||||
column![
|
||||
self.groups_panel(),
|
||||
row![horizontal().width(8), self.words_list(),],
|
||||
column![
|
||||
row![horizontal().width(8), self.words_list(),],
|
||||
self.selection_editor(),
|
||||
],
|
||||
row![
|
||||
self.add_word_button(),
|
||||
horizontal().width(Fill),
|
||||
button("Импорт").style(text).on_press(GotoImport),
|
||||
button("Импорт").style(button::text).on_press(GotoImport),
|
||||
]
|
||||
]
|
||||
.spacing(5),
|
||||
self.filters(),
|
||||
.spacing(5)
|
||||
.width(FillPortion(4)),
|
||||
self.right_panel(),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.into(),
|
||||
@@ -284,12 +418,14 @@ impl DictionaryState {
|
||||
tag_map: HashMap::new(),
|
||||
words_tags: vec![],
|
||||
reverse: false,
|
||||
search: "".to_string(),
|
||||
search: String::new(),
|
||||
no_typing: true,
|
||||
reverse_list: true,
|
||||
auto_save_queue: HashMap::new(),
|
||||
displayed_words_query: words_query,
|
||||
groups_query,
|
||||
selected_cell: None,
|
||||
word_editor: None,
|
||||
};
|
||||
|
||||
result.init();
|
||||
@@ -298,117 +434,145 @@ impl DictionaryState {
|
||||
result
|
||||
}
|
||||
|
||||
fn init(&mut self) {
|
||||
self.displayed_words_query = self.state.dictionary.read().query_par(Arc::new(|word| word.group_id == Id(1)));
|
||||
fn editor_for_word(&self, handle: EntityHandle<WordData>) -> WordEditor<DictionaryMessage> {
|
||||
WordEditor::new(handle, self.state.clone())
|
||||
.on_delete(DeleteWord(handle))
|
||||
.on_edit(ExtendedWordEdited)
|
||||
}
|
||||
|
||||
fn setup_words_query(&mut self, id: Id) {
|
||||
// self.displayed_words_query = self.state.dictionary.read().query_par(Arc::new(|word| word.group_id == Self::get_id(self)));
|
||||
fn init(&mut self) {
|
||||
self.displayed_words_query = self
|
||||
.state
|
||||
.dictionary
|
||||
.read()
|
||||
.query(Arc::new(|word| word.group_id == Id(1)));
|
||||
}
|
||||
|
||||
fn setup_words_query(&mut self) {
|
||||
let id = self.selected_group.id;
|
||||
self.displayed_words_query = self
|
||||
.state
|
||||
.dictionary
|
||||
.read()
|
||||
.query(Arc::new(move |word| word.group_id == id));
|
||||
}
|
||||
|
||||
fn launch_auto_save_offset(&mut self, handle: EntityHandle<WordData>) -> Task<RootMessage> {
|
||||
let save_time = Utc::now().add(TimeDelta::milliseconds(900));
|
||||
let save_time = Utc::now().add(TimeDelta::milliseconds(500));
|
||||
self.auto_save_queue.insert(handle, save_time);
|
||||
let message = RootMessage::Dictionary(TrySave(handle));
|
||||
Task::perform(
|
||||
async { tokio::time::sleep(Duration::from_secs(1)).await },
|
||||
async { tokio::time::sleep(Duration::from_millis(520)).await },
|
||||
|_| message,
|
||||
)
|
||||
}
|
||||
|
||||
fn words_list(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
todo!("Make new display system")
|
||||
// let time = Instant::now();
|
||||
// let mut col = Column::new().width(Fill);
|
||||
//
|
||||
// let query = &self.displayed_words_query;
|
||||
// let dictionary = self.state.dictionary.read();
|
||||
//
|
||||
//
|
||||
// for access_index in 0..query.len() {
|
||||
// let mut i = access_index;
|
||||
// if self.reverse_list {
|
||||
// i = query.len() - access_index - 1;
|
||||
// }
|
||||
// let word_handle = &query[i];
|
||||
// let word = dictionary.get_ref_static(*word_handle).unwrap();
|
||||
//
|
||||
// if !self.search.is_empty()
|
||||
// && !word.key.contains(&self.search)
|
||||
// && !word.value.contains(&self.search)
|
||||
// && !word.tags.contains(&self.search)
|
||||
// {
|
||||
// continue;
|
||||
// }
|
||||
//
|
||||
// let word_line_data = WordLineState {
|
||||
// is_included: self.included.contains(word_handle),
|
||||
// key: word.key.clone().into(),
|
||||
// value: word.value.clone().into(),
|
||||
// tags: word.tags.clone().into(),
|
||||
// handle: word_handle.clone(),
|
||||
// };
|
||||
//
|
||||
//
|
||||
// let lazy_line = lazy(word_line_data, |data: &WordLineState| Self::word_line(data));
|
||||
//
|
||||
// col = col.push(lazy_line);
|
||||
// }
|
||||
//
|
||||
// info!("Words rendering time: {:?}", time.elapsed());
|
||||
// scrollable(col).height(Fill).into()
|
||||
fn words_list(&self) -> Element<'_, DictionaryMessage> {
|
||||
let time = Instant::now();
|
||||
let mut col = Column::new().width(Fill);
|
||||
|
||||
let query = &self.displayed_words_query;
|
||||
let dictionary = self.state.dictionary.read();
|
||||
|
||||
for access_index in 0..query.len() {
|
||||
let mut i = access_index;
|
||||
if self.reverse_list {
|
||||
i = query.len() - access_index - 1;
|
||||
}
|
||||
let word_handle = &query[i];
|
||||
let word = dictionary.get_ref_static(*word_handle).unwrap();
|
||||
|
||||
if !self.search.is_empty()
|
||||
&& !word.key.contains(&self.search)
|
||||
&& !word.value.contains(&self.search)
|
||||
&& !word.tags.contains(&self.search)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut selection = None;
|
||||
|
||||
if let Some(cell) = self.selected_cell.as_ref()
|
||||
&& cell.0 == *word_handle
|
||||
{
|
||||
selection = Some(cell.1);
|
||||
}
|
||||
|
||||
let word_line_data = WordLineState {
|
||||
is_included: self.included.contains(word_handle),
|
||||
key: word.key.clone(),
|
||||
value: word.value.clone(),
|
||||
tags: word.tags.clone(),
|
||||
handle: *word_handle,
|
||||
selection,
|
||||
number: i,
|
||||
};
|
||||
|
||||
let lazy_line = lazy(word_line_data, Self::word_line);
|
||||
|
||||
col = col.push(lazy_line);
|
||||
}
|
||||
|
||||
info!("Words rendering time: {:?}", time.elapsed());
|
||||
scrollable(col).height(Fill).into()
|
||||
}
|
||||
|
||||
pub fn word_line(data: &WordLineState) -> Row<'_, DictionaryMessage>
|
||||
{
|
||||
fn word_line<'a>(data: &WordLineState) -> Element<'a, DictionaryMessage> {
|
||||
let mut line = Row::new().width(Fill).align_y(Center);
|
||||
let handle = data.handle;
|
||||
line = line.push(
|
||||
checkbox(data.is_included)
|
||||
.label("")
|
||||
.spacing(15)
|
||||
.on_toggle(move |b| Include(data.handle, b)),
|
||||
.on_toggle(move |b| Include(handle, b)),
|
||||
);
|
||||
|
||||
let field = |placeholder: &str, data: &str, selected: bool| {
|
||||
text_input(placeholder, data)
|
||||
.size(ACCENT_FONT_SIZE)
|
||||
.width(Fill)
|
||||
.style(move |x, _| {
|
||||
let mut default_style = default(x, Active);
|
||||
default_style.border.radius = 0.0.into();
|
||||
if selected {
|
||||
default_style.border.color = x.extended_palette().secondary.base.color;
|
||||
default_style.border.width = 3.0_f32;
|
||||
}
|
||||
default_style
|
||||
})
|
||||
};
|
||||
|
||||
line = line.push(
|
||||
hard_mouse_area(field(
|
||||
"Слово",
|
||||
&data.key,
|
||||
data.selection.is_some() && data.selection.unwrap() == Key,
|
||||
))
|
||||
.on_press(SelectField(data.handle, Key, data.number)),
|
||||
);
|
||||
line = line.push(
|
||||
hard_mouse_area(field(
|
||||
"Перевод",
|
||||
&data.value,
|
||||
data.selection.is_some() && data.selection.unwrap() == Value,
|
||||
))
|
||||
.on_press(SelectField(data.handle, Value, data.number)),
|
||||
);
|
||||
|
||||
line = line.push(
|
||||
text_input("Слово", &data.key)
|
||||
.size(ACCENT_FONT_SIZE)
|
||||
.width(Fill)
|
||||
.on_input(move |string| SetKey(data.handle, string))
|
||||
.style(|x, status| {
|
||||
let mut default_style = default(x, status);
|
||||
default_style.border.radius = 0.0.into();
|
||||
default_style
|
||||
}),
|
||||
);
|
||||
line = line.push(
|
||||
text_input("Перевод", &data.value)
|
||||
.size(ACCENT_FONT_SIZE)
|
||||
.width(Fill)
|
||||
.on_input(move |string| SetValue(data.handle, string))
|
||||
.style(|x, status| {
|
||||
let mut default_style = default(x, status);
|
||||
default_style.border.radius = 0.0.into();
|
||||
default_style
|
||||
}),
|
||||
);
|
||||
|
||||
line = line.push(
|
||||
text_input("Теги", data.tags.as_ref())
|
||||
.size(ACCENT_FONT_SIZE)
|
||||
.width(Fill)
|
||||
.on_input(move |string| SetTags(data.handle, string))
|
||||
.style(|x, status| {
|
||||
let mut default_style = default(x, status);
|
||||
default_style.border.radius = 0.0.into();
|
||||
default_style
|
||||
}),
|
||||
hard_mouse_area(field(
|
||||
"Теги",
|
||||
&data.tags,
|
||||
data.selection.is_some() && data.selection.unwrap() == Tags,
|
||||
))
|
||||
.on_press(SelectField(data.handle, Tags, data.number)),
|
||||
);
|
||||
|
||||
let line_button = || {
|
||||
if !data.handle.real() {
|
||||
return button("-")
|
||||
.on_press(WordAction(data.handle))
|
||||
.style(|_x: &iced::Theme, _status: iced::widget::button::Status| Style {
|
||||
.on_press(DeleteWord(data.handle))
|
||||
.style(|_x: &Theme, _status: button::Status| Style {
|
||||
background: None,
|
||||
text_color: Color::BLACK,
|
||||
border: Border::default(),
|
||||
@@ -419,25 +583,52 @@ impl DictionaryState {
|
||||
}
|
||||
|
||||
button("")
|
||||
.on_press(WordAction(data.handle))
|
||||
.on_press(ExtendedEdit(data.handle))
|
||||
.style(button::primary)
|
||||
.width(15)
|
||||
};
|
||||
line.push(line_button()).push(space().width(10))
|
||||
|
||||
let assembled = line.push(line_button()).push(space().width(10));
|
||||
|
||||
if let Some(selection) = data.selection
|
||||
&& selection == TotalLine
|
||||
{
|
||||
return container(assembled.padding(Padding {
|
||||
top: 2.0,
|
||||
right: 0.0,
|
||||
bottom: 2.0,
|
||||
left: 0.0,
|
||||
}))
|
||||
.style(|theme: &Theme| {
|
||||
let mut style = container::Style::default();
|
||||
style.border.color = theme.extended_palette().secondary.base.color;
|
||||
style.border.width = 3.0_f32;
|
||||
style
|
||||
})
|
||||
.into();
|
||||
}
|
||||
assembled.into()
|
||||
}
|
||||
|
||||
fn filters(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
fn right_panel(&self) -> Element<'_, DictionaryMessage> {
|
||||
if let Some(editor) = &self.word_editor {
|
||||
container(editor.view().map(EditorAction))
|
||||
.width(FillPortion(3))
|
||||
.into()
|
||||
} else {
|
||||
self.filters()
|
||||
}
|
||||
}
|
||||
|
||||
fn filters(&self) -> Element<'_, DictionaryMessage> {
|
||||
let dict = &self.state.dictionary.read();
|
||||
|
||||
iced::widget::column![
|
||||
text_input("Поиск", &self.search)
|
||||
column![
|
||||
jl_text_input!("Поиск", &self.search)
|
||||
.on_input(Search)
|
||||
.width(Fill),
|
||||
text!("Всего слов: {}", dict.len()),
|
||||
text!(
|
||||
"Выбрано слов: {}",
|
||||
self.included.iter().count()
|
||||
),
|
||||
text!("Выбрано слов: {}", self.included.iter().count()),
|
||||
self.tags_selector(),
|
||||
toggler(self.no_typing)
|
||||
.label("Без набора")
|
||||
@@ -450,12 +641,12 @@ impl DictionaryState {
|
||||
.on_press(GotoTest)
|
||||
.width(Fill),
|
||||
]
|
||||
.width(250)
|
||||
.width(FillPortion(1))
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn tags_selector(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
fn tags_selector(&self) -> Element<'_, DictionaryMessage> {
|
||||
let mut col = Column::new().width(Fill);
|
||||
col = col.push(
|
||||
button("Сбросить")
|
||||
@@ -482,16 +673,21 @@ impl DictionaryState {
|
||||
}
|
||||
|
||||
fn update_tags(&mut self) {
|
||||
self.words_tags.clear();
|
||||
let mut tags_list: HashSet<String> = HashSet::new();
|
||||
let dict = &self.state.dictionary.write();
|
||||
|
||||
dict.iter().for_each(|element| {
|
||||
split_with_coma(element.tags.as_str())
|
||||
.iter()
|
||||
.for_each(|tag| {
|
||||
let mut words_query = dict.full_query();
|
||||
let handles = words_query.handles().collect::<Vec<_>>();
|
||||
words_query
|
||||
.iter(dict)
|
||||
.zip(handles)
|
||||
.for_each(|(element, handle)| {
|
||||
let tags = split_with_coma(element.tags.as_str());
|
||||
tags.iter().for_each(|tag| {
|
||||
tags_list.insert(tag.clone());
|
||||
});
|
||||
});
|
||||
self.words_tags.push((handle, tags))
|
||||
});
|
||||
|
||||
let current_tags = self
|
||||
.tag_map
|
||||
@@ -529,17 +725,15 @@ impl DictionaryState {
|
||||
|
||||
self.included.clear();
|
||||
for (handle, tags) in &mut self.words_tags {
|
||||
if let Some(word) = dict.get_ref(handle) {
|
||||
if let Some(word) = dict.get_ref(handle) {
|
||||
if word.group_id != group_id {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !tags.is_empty()
|
||||
&& tags.iter().all(|t| include_tags.contains(t)) {
|
||||
if !tags.is_empty() && tags.iter().all(|t| include_tags.contains(t)) {
|
||||
self.included.insert(*handle);
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -547,9 +741,47 @@ impl DictionaryState {
|
||||
info!("Time {}", time.elapsed().as_micros());
|
||||
}
|
||||
|
||||
fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
fn selection_editor(&self) -> Element<'_, DictionaryMessage> {
|
||||
let mut display = String::new();
|
||||
let mut editable = false;
|
||||
if let Some(selected) = self.selected_cell.as_ref()
|
||||
&& selected.1 != TotalLine
|
||||
{
|
||||
let mut dictionary = self.state.dictionary.write();
|
||||
let word = dictionary.get_mut_static(selected.0).unwrap();
|
||||
|
||||
match selected.1 {
|
||||
Key => {
|
||||
display = word.key.clone();
|
||||
}
|
||||
Value => {
|
||||
display = word.value.clone();
|
||||
}
|
||||
Tags => {
|
||||
display = word.tags.clone();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
editable = true;
|
||||
}
|
||||
let mut field = jl_text_input!("", display.as_str())
|
||||
.width(Fill)
|
||||
.id(iced::widget::Id::new("editor"))
|
||||
.style(|theme, status| {
|
||||
let mut default = default(theme, status);
|
||||
default.border.radius = Radius::new(0);
|
||||
default
|
||||
});
|
||||
if editable {
|
||||
field = field.on_input(EditField)
|
||||
}
|
||||
|
||||
field.into()
|
||||
}
|
||||
|
||||
fn groups_panel(&self) -> Element<'_, DictionaryMessage> {
|
||||
let mut row = Row::new();
|
||||
row = row.push(button("+").style(text).on_press(CreateGroup));
|
||||
row = row.push(button("+").style(button::text).on_press(CreateGroup));
|
||||
|
||||
let groups = &self.state.word_groups.read();
|
||||
|
||||
@@ -557,19 +789,19 @@ impl DictionaryState {
|
||||
let group_name = groups.get(&mut group).unwrap().name.clone();
|
||||
row = row.push(
|
||||
button(text!("{}", group_name))
|
||||
.style(text)
|
||||
.style(button::text)
|
||||
.on_press(SelectGroup(group)),
|
||||
);
|
||||
}
|
||||
|
||||
let groups = self.state.word_groups.read();
|
||||
let group = groups.get_static(self.selected_group.clone()).unwrap();
|
||||
let group = groups.get_static(self.selected_group).unwrap();
|
||||
|
||||
iced::widget::column![
|
||||
column![
|
||||
scrollable(row).width(Fill).horizontal(),
|
||||
row![
|
||||
button("⇳").on_press(ChangeDirection).style(jl_button),
|
||||
text_input("Название группы слов", &group.name)
|
||||
jl_button!("⇳").on_press(ChangeDirection),
|
||||
jl_text_input!("Название группы слов", &group.name)
|
||||
.on_input(EditGroup)
|
||||
.width(250)
|
||||
.on_submit(SaveGroup),
|
||||
@@ -581,7 +813,7 @@ impl DictionaryState {
|
||||
.into()
|
||||
}
|
||||
|
||||
fn group_delete_button(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
fn group_delete_button(&self) -> Element<'_, DictionaryMessage> {
|
||||
if self.selected_group.real() && self.selected_group.id != 1.into() {
|
||||
button("Удалить").style(danger).on_press(DeleteGroup).into()
|
||||
} else {
|
||||
@@ -589,8 +821,8 @@ impl DictionaryState {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_word_button(&self) -> iced::Element<'_, DictionaryMessage> {
|
||||
let button = button("Добавить слово").style(jl_button);
|
||||
fn add_word_button(&self) -> Element<'_, DictionaryMessage> {
|
||||
let button = jl_button!("Добавить слово");
|
||||
|
||||
if self.selected_group.real() {
|
||||
return button.on_press(NewWord).into();
|
||||
@@ -600,6 +832,59 @@ impl DictionaryState {
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyPressedPage for DictionaryState {
|
||||
fn press(&mut self, message: &Event) -> Task<RootMessage> {
|
||||
if let Event::KeyPressed {
|
||||
key: _,
|
||||
modified_key: modifier,
|
||||
physical_key: pk,
|
||||
location: _,
|
||||
modifiers: mods,
|
||||
text: _,
|
||||
repeat: _,
|
||||
} = message
|
||||
&& let Code(code) = pk
|
||||
{
|
||||
return match code {
|
||||
keyboard::key::Code::ArrowDown => {
|
||||
Task::done(RootMessage::Dictionary(ChangeSelectedField(Next)))
|
||||
}
|
||||
keyboard::key::Code::ArrowUp => {
|
||||
Task::done(RootMessage::Dictionary(ChangeSelectedField(Previous)))
|
||||
}
|
||||
keyboard::key::Code::Tab => {
|
||||
return if *mods == Modifiers::CTRL
|
||||
&& let Some(selected) = self.selected_cell
|
||||
{
|
||||
Task::done(RootMessage::Dictionary(ExtendedEdit(selected.0)))
|
||||
} else if let Named(keyboard::key::Named::Alt) = modifier {
|
||||
Task::done(RootMessage::Dictionary(ChangeSelectedField(Backward)))
|
||||
} else {
|
||||
Task::done(RootMessage::Dictionary(ChangeSelectedField(Forward)))
|
||||
};
|
||||
}
|
||||
keyboard::key::Code::Escape => {
|
||||
if self.word_editor.is_some() {
|
||||
self.word_editor = None;
|
||||
if let Some(selected) = self.selected_cell
|
||||
&& selected.1 == TotalLine
|
||||
{
|
||||
self.selected_cell = None;
|
||||
}
|
||||
} else if self.selected_cell.is_some() {
|
||||
self.selected_cell = None;
|
||||
}
|
||||
|
||||
Task::none()
|
||||
}
|
||||
_ => Task::none(),
|
||||
};
|
||||
}
|
||||
|
||||
Task::none()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn split_with_coma(ts: &str) -> Vec<String> {
|
||||
ts.split(',')
|
||||
.map(|ts| ts.to_lowercase().trim().to_string())
|
||||
@@ -610,8 +895,10 @@ pub fn split_with_coma(ts: &str) -> Vec<String> {
|
||||
#[derive(Clone, Hash, PartialEq, Eq)]
|
||||
struct WordLineState {
|
||||
is_included: bool,
|
||||
key: Box<str>,
|
||||
value: Box<str>,
|
||||
tags: Box<str>,
|
||||
key: String,
|
||||
value: String,
|
||||
tags: String,
|
||||
handle: EntityHandle<WordData>,
|
||||
selection: Option<BasicWordFields>,
|
||||
number: usize,
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::app::AppState;
|
||||
use crate::data::entities::{EntityHandle, WordData};
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::RootMessage;
|
||||
use crate::navigation::*;
|
||||
@@ -6,14 +8,13 @@ use crate::pages::dictionary::split_with_coma;
|
||||
use crate::pages::dictionary_quiz::DictionaryQuizMessage::*;
|
||||
use crate::pages::quiz::Score;
|
||||
use crate::styling::*;
|
||||
use iced::Background::Color;
|
||||
use crate::{jl_button, jl_text_input};
|
||||
use iced::border::Radius;
|
||||
use iced::widget::container::Style;
|
||||
use iced::widget::{Row, button, container, row, space, text, text_input};
|
||||
use iced::{Border, Element, Fill, Task, Theme, alignment};
|
||||
use iced::widget::{container, row, space, text, Row};
|
||||
use iced::Background::Color;
|
||||
use iced::{alignment, Border, Element, Fill, Task, Theme};
|
||||
use rand::prelude::SliceRandom;
|
||||
use crate::app::AppState;
|
||||
use crate::data::repositories::Repository;
|
||||
|
||||
pub struct DictionaryQuizState {
|
||||
state: AppState,
|
||||
@@ -75,7 +76,7 @@ impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
|
||||
]
|
||||
.align_x(alignment::Horizontal::Center)
|
||||
.spacing(5),
|
||||
text_input("Перевод", &self.answer)
|
||||
jl_text_input!("Перевод", &self.answer)
|
||||
.size(28)
|
||||
.width(250)
|
||||
.on_input(AnswerChanged)
|
||||
@@ -90,11 +91,8 @@ impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
|
||||
.size(25),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING),
|
||||
row![
|
||||
button("Закончить").style(jl_button).on_press(Back),
|
||||
self.appeal_button()
|
||||
]
|
||||
.spacing(DEFAULT_SPACING),
|
||||
row![jl_button!("Закончить").on_press(Back), self.appeal_button()]
|
||||
.spacing(DEFAULT_SPACING),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.align_x(alignment::Horizontal::Center),
|
||||
@@ -106,22 +104,25 @@ impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
|
||||
}
|
||||
|
||||
impl DictionaryQuizState {
|
||||
pub fn new(words: Vec<EntityHandle<WordData>>, reverse: bool, no_typing: bool, state: AppState) -> DictionaryQuizState {
|
||||
let state = DictionaryQuizState {
|
||||
pub fn new(
|
||||
words: Vec<EntityHandle<WordData>>,
|
||||
reverse: bool,
|
||||
no_typing: bool,
|
||||
state: AppState,
|
||||
) -> DictionaryQuizState {
|
||||
Self {
|
||||
state,
|
||||
words,
|
||||
current_set: Vec::new(),
|
||||
answer: "".to_string(),
|
||||
answer: String::new(),
|
||||
view: "---".to_string(),
|
||||
correct: "".to_string(),
|
||||
correct: String::new(),
|
||||
score: Default::default(),
|
||||
is_help: false,
|
||||
reverse,
|
||||
laps: 0,
|
||||
no_typing,
|
||||
};
|
||||
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(&mut self) {
|
||||
@@ -218,7 +219,7 @@ impl DictionaryQuizState {
|
||||
|
||||
fn appeal_button(&self) -> Element<'_, DictionaryQuizMessage> {
|
||||
if self.is_help && !self.no_typing {
|
||||
return button("Апелляция").style(jl_button).on_press(Appeal).into();
|
||||
return jl_button!("Апелляция").on_press(Appeal).into();
|
||||
}
|
||||
space().into()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
use crate::app::AppState;
|
||||
use crate::data::entities::{CustomField, DeckSettings, EntityHandle, ExamEntry, WordData};
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::data::Id;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
|
||||
use crate::pages::exam::ExamMessage::*;
|
||||
use crate::pages::repetition::play_sound;
|
||||
use crate::styling::*;
|
||||
use crate::{push_error, push_error_task};
|
||||
use iced::widget::space::horizontal;
|
||||
use iced::widget::{button, column, container, progress_bar, row, text, tooltip};
|
||||
use iced::{Element, Task};
|
||||
use iced_core::keyboard::key::Physical::Code;
|
||||
use iced_core::keyboard::Event;
|
||||
use iced_core::widget::text::Style;
|
||||
use iced_core::Alignment::Center;
|
||||
use iced_core::Length::Fill;
|
||||
use iced_core::{keyboard, Theme};
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::rng;
|
||||
use rodio::MixerDeviceSink;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct ExamState {
|
||||
id: Id,
|
||||
state: AppState,
|
||||
entries: Vec<ExamEntry>,
|
||||
total_count: u32,
|
||||
open: bool,
|
||||
custom_fields_cache: Vec<CustomField>,
|
||||
current_word: WordData,
|
||||
current_exam_entry_handle: EntityHandle<ExamEntry>,
|
||||
deck: DeckSettings,
|
||||
can_play: bool,
|
||||
sink: Arc<Option<MixerDeviceSink>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum ExamMessage {
|
||||
Back,
|
||||
Open,
|
||||
Answer(bool),
|
||||
Play,
|
||||
PlayFinished,
|
||||
}
|
||||
|
||||
impl NavigatedPage<ExamMessage> for ExamState {
|
||||
fn navigate(&mut self, message: &ExamMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
return Some(PreviousPage);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn navigated(&mut self) {}
|
||||
|
||||
fn update(&mut self, message: ExamMessage) -> Task<RootMessage> {
|
||||
match message {
|
||||
Back => {}
|
||||
Open => {
|
||||
if self.open {
|
||||
return Task::none();
|
||||
}
|
||||
|
||||
self.open = true;
|
||||
}
|
||||
Answer(answer) => {
|
||||
if !self.open {
|
||||
return Task::none();
|
||||
}
|
||||
let id = self.current_exam_entry_handle.id;
|
||||
let mut repo = self.state.exam_entries.write();
|
||||
repo.set(
|
||||
&mut self.current_exam_entry_handle,
|
||||
ExamEntry {
|
||||
id,
|
||||
exam_id: self.id,
|
||||
word_id: self.current_word.id,
|
||||
status: Some(answer),
|
||||
},
|
||||
);
|
||||
if let Err(err) = repo.save(&mut self.current_exam_entry_handle) {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
drop(repo);
|
||||
self.open = false;
|
||||
return self.next();
|
||||
}
|
||||
Play => {
|
||||
if !self.can_play {
|
||||
return Task::none();
|
||||
}
|
||||
|
||||
self.can_play = false;
|
||||
let value = self.current_word.key.clone();
|
||||
if self.deck.require_speech() {
|
||||
return Task::perform(play_sound(self.sink.clone(), value), |r| match r {
|
||||
Ok(_) => RootMessage::Exam(PlayFinished),
|
||||
Err(err) => push_error!(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
PlayFinished => {
|
||||
self.can_play = true;
|
||||
}
|
||||
}
|
||||
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn view(&self) -> Element<'_, ExamMessage> {
|
||||
back_overlay(
|
||||
column![
|
||||
column![
|
||||
progress_bar(
|
||||
0.0..=(self.total_count as f32),
|
||||
(self.total_count - self.entries.len() as u32) as f32
|
||||
),
|
||||
row![
|
||||
text!("Решено: {}", self.total_count - self.entries.len() as u32),
|
||||
horizontal().width(Fill),
|
||||
text!("Осталось: {}", self.entries.len())
|
||||
],
|
||||
],
|
||||
crate::widgets::card_display::word_display(
|
||||
&self.deck,
|
||||
&self.current_word,
|
||||
self.open,
|
||||
Play,
|
||||
self.custom_fields_cache.as_slice()
|
||||
),
|
||||
container(self.answer_bar())
|
||||
.width(Fill)
|
||||
.align_x(Center)
|
||||
.height(80),
|
||||
]
|
||||
.into(),
|
||||
Back,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExamState {
|
||||
fn answer_bar(&self) -> Element<'_, ExamMessage> {
|
||||
if !self.open {
|
||||
return text!("Нажмите Пробел для открытия карточки")
|
||||
.style(|theme: &Theme| Style {
|
||||
color: Some(theme.palette().text.scale_alpha(0.3)),
|
||||
})
|
||||
.into();
|
||||
}
|
||||
|
||||
row![
|
||||
tooltip(
|
||||
button("Не знаю").on_press(Answer(false)),
|
||||
"Клавиша 1",
|
||||
tooltip::Position::Top
|
||||
),
|
||||
tooltip(
|
||||
button("Знаю").on_press(Answer(true)),
|
||||
"Клавиша 2",
|
||||
tooltip::Position::Top
|
||||
),
|
||||
]
|
||||
.spacing(QUARTER_SPACING)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExamState {
|
||||
pub fn new(exam_id: Id, deck: DeckSettings, state: &AppState) -> Self {
|
||||
let custom_fields_cache = state.custom_fields.read().iter().cloned().collect();
|
||||
let sink_handle = if deck.require_speech() {
|
||||
rodio::DeviceSinkBuilder::open_default_sink().ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut entries: Vec<_> = state
|
||||
.exam_entries
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|e| e.exam_id == exam_id)
|
||||
.cloned()
|
||||
.collect();
|
||||
let total_count = entries.len() as u32;
|
||||
entries.retain(|e| e.status.is_none());
|
||||
entries.shuffle(&mut rng());
|
||||
let word = state
|
||||
.dictionary
|
||||
.read()
|
||||
.get_static(EntityHandle::from_id(entries.last().unwrap().word_id))
|
||||
.unwrap();
|
||||
Self {
|
||||
id: exam_id,
|
||||
state: state.clone(),
|
||||
current_word: word,
|
||||
current_exam_entry_handle: EntityHandle::from_id(entries.last().unwrap().id),
|
||||
entries,
|
||||
total_count,
|
||||
open: false,
|
||||
custom_fields_cache,
|
||||
deck,
|
||||
can_play: true,
|
||||
sink: Arc::new(sink_handle),
|
||||
}
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Task<RootMessage> {
|
||||
self.entries.pop().unwrap();
|
||||
if self.entries.is_empty() {
|
||||
return Task::done(RootMessage::Exam(Back));
|
||||
}
|
||||
|
||||
let entry = self.entries.last().unwrap();
|
||||
let handle: EntityHandle<ExamEntry> = EntityHandle::from_id(entry.id);
|
||||
let word = self
|
||||
.state
|
||||
.dictionary
|
||||
.read()
|
||||
.get_static(EntityHandle::from_id(entry.word_id))
|
||||
.unwrap();
|
||||
self.current_word = word;
|
||||
self.current_exam_entry_handle = handle;
|
||||
Task::none()
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyPressedPage for ExamState {
|
||||
fn press(&mut self, message: &Event) -> Task<RootMessage> {
|
||||
if let Event::KeyPressed {
|
||||
key: _,
|
||||
modified_key: _,
|
||||
physical_key: pk,
|
||||
location: _,
|
||||
modifiers: _,
|
||||
text: _,
|
||||
repeat: _,
|
||||
} = message
|
||||
&& let Code(code) = pk
|
||||
{
|
||||
return match code {
|
||||
keyboard::key::Code::Space => Task::done(RootMessage::Exam(Open)),
|
||||
keyboard::key::Code::Digit1 => Task::done(RootMessage::Exam(Answer(false))),
|
||||
keyboard::key::Code::Digit2 => Task::done(RootMessage::Exam(Answer(true))),
|
||||
_ => Task::none(),
|
||||
};
|
||||
}
|
||||
|
||||
Task::none()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
use crate::app::AppState;
|
||||
use crate::data::entities::{DeckSettings, EntityHandle, Exam, ExamEntry, WordData};
|
||||
use crate::data::repositories::{BatchedRepository, Repository};
|
||||
use crate::data::Id;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::notification::MaybeError;
|
||||
use crate::pages::exam::ExamState;
|
||||
use crate::pages::exams::ExamsMessage::*;
|
||||
use crate::pages::repetitions::Style;
|
||||
use crate::push_error;
|
||||
use crate::styling::{
|
||||
back_overlay, cta_button, BUTTON_RADIUS, DEFAULT_SPACING, HALF_SPACING, QUARTER_SPACING,
|
||||
};
|
||||
use crate::{jl_button, push_error_task};
|
||||
use chrono::{Local, Utc};
|
||||
use iced::widget::button::Status;
|
||||
use iced::widget::container::bordered_box;
|
||||
use iced::widget::space::horizontal;
|
||||
use iced::widget::{
|
||||
button, center_x, column, container, row, rule, scrollable, space, text, tooltip,
|
||||
Column,
|
||||
};
|
||||
use iced::{Element, Task};
|
||||
use iced_core::Alignment::*;
|
||||
use iced_core::Length::{Fill, FillPortion};
|
||||
use iced_core::{Background, Border, Color, Shadow, Theme};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct ExamsState {
|
||||
state: AppState,
|
||||
deck_id: EntityHandle<DeckSettings>,
|
||||
deck: DeckSettings,
|
||||
selected_exam_id: Option<EntityHandle<Exam>>,
|
||||
exams: BTreeMap<EntityHandle<Exam>, ExamExtended>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
pub enum ExamsMessage {
|
||||
Back,
|
||||
SelectExam(EntityHandle<Exam>),
|
||||
CreateExam,
|
||||
GotoExam,
|
||||
}
|
||||
|
||||
impl NavigatedPage<ExamsMessage> for ExamsState {
|
||||
fn navigate(&mut self, message: &ExamsMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
return Some(PreviousPage);
|
||||
}
|
||||
if let Some(selected_exam_id) = self.selected_exam_id
|
||||
&& GotoExam == *message
|
||||
{
|
||||
return Some(Page::Exam(ExamState::new(
|
||||
selected_exam_id.id,
|
||||
self.deck.clone(),
|
||||
&self.state,
|
||||
)));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn navigated(&mut self) {
|
||||
self.exams = Self::get_exams_list(&self.state, self.deck_id.id);
|
||||
}
|
||||
|
||||
fn update(&mut self, message: ExamsMessage) -> Task<RootMessage> {
|
||||
match message {
|
||||
Back => {}
|
||||
GotoExam => {}
|
||||
SelectExam(id) => {
|
||||
self.selected_exam_id = Some(id);
|
||||
}
|
||||
CreateExam => {
|
||||
let exam = Exam {
|
||||
id: Default::default(),
|
||||
timestamp: Utc::now(),
|
||||
deck_id: self.deck_id.id,
|
||||
};
|
||||
let mut exam_repo = self.state.exam.write();
|
||||
let handle = exam_repo.create_now(exam);
|
||||
if let Ok(handle) = handle {
|
||||
drop(exam_repo);
|
||||
if let Err(err) = self.append_exam_entries(handle) {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
self.exams = Self::get_exams_list(&self.state, self.deck_id.id);
|
||||
self.selected_exam_id = Some(handle);
|
||||
} else {
|
||||
return push_error_task!(handle.err().unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn view(&self) -> Element<'_, ExamsMessage> {
|
||||
back_overlay(
|
||||
column![
|
||||
text(format!("Экзамены для колоды {}", self.deck.name)),
|
||||
row![
|
||||
column![
|
||||
scrollable(self.exams_list()).height(Fill),
|
||||
jl_button!("Добавить").width(Fill).on_press(CreateExam),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.width(FillPortion(1)),
|
||||
self.selected_exam_view(),
|
||||
].spacing(DEFAULT_SPACING)
|
||||
]
|
||||
.into(),
|
||||
Back,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExamsState {
|
||||
pub fn new(deck_id: EntityHandle<DeckSettings>, state: AppState) -> Self {
|
||||
let deck = state.decks.read().get_static(deck_id).unwrap();
|
||||
|
||||
Self {
|
||||
exams: Self::get_exams_list(&state, deck_id.id),
|
||||
state,
|
||||
deck_id,
|
||||
deck,
|
||||
selected_exam_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_exam(&self) -> Option<&ExamExtended> {
|
||||
self.exams.get(&self.selected_exam_id?)
|
||||
}
|
||||
|
||||
fn append_exam_entries(&mut self, handle: EntityHandle<Exam>) -> MaybeError {
|
||||
let deck_id = self.deck_id.id;
|
||||
let words: Vec<_> = self
|
||||
.state
|
||||
.card_states
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|state| state.deck_id == deck_id)
|
||||
.map(|state| state.word_id)
|
||||
.collect();
|
||||
let mut entries = words
|
||||
.iter()
|
||||
.map(|word_id| ExamEntry {
|
||||
id: Default::default(),
|
||||
exam_id: handle.id,
|
||||
word_id: *word_id,
|
||||
status: None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
self.state
|
||||
.exam_entries
|
||||
.write()
|
||||
.create_now_many(entries.as_mut_slice())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_exams_list(state: &AppState, deck_id: Id) -> BTreeMap<EntityHandle<Exam>, ExamExtended> {
|
||||
let mut query = state
|
||||
.exam
|
||||
.read()
|
||||
.query(Arc::new(move |exam| exam.deck_id == deck_id));
|
||||
let handles: Vec<_> = query.handles().collect();
|
||||
query
|
||||
.iter(&state.exam.read())
|
||||
.cloned()
|
||||
.zip(handles)
|
||||
.map(|(e, h)| (h, ExamExtended::from(e, state)))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExamsState {
|
||||
pub fn exams_list(&self) -> Column<'_, ExamsMessage> {
|
||||
let mut column = Column::new();
|
||||
|
||||
for (handle, deck) in self.exams.iter() {
|
||||
column = column.push(
|
||||
jl_button!(text!(
|
||||
"{}",
|
||||
&deck
|
||||
.timestamp
|
||||
.with_timezone(&Local)
|
||||
.format("%d/%m/%Y %H:%M")
|
||||
))
|
||||
.on_press_with(move || SelectExam(*handle))
|
||||
.style(move |_x: &Theme, status: Status| Style {
|
||||
background: if status == Status::Hovered {
|
||||
Some(Background::Color(Color::WHITE.scale_alpha(0.2)))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
text_color: if deck.finished() {
|
||||
_x.palette().success
|
||||
} else {
|
||||
_x.palette().primary
|
||||
},
|
||||
border: Border {
|
||||
color: Default::default(),
|
||||
width: 0.0,
|
||||
radius: BUTTON_RADIUS.into(),
|
||||
},
|
||||
shadow: Shadow::default(),
|
||||
snap: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
column
|
||||
}
|
||||
pub fn selected_exam_view(&self) -> Element<'_, ExamsMessage> {
|
||||
if let Some(exam) = self.selected_exam() {
|
||||
return column![
|
||||
center_x(text!(
|
||||
"Экзамен от {}",
|
||||
exam.timestamp
|
||||
.with_timezone(&Local)
|
||||
.format("%d/%m/%Y %H:%M")
|
||||
)),
|
||||
row![text!("{} карточек", exam.total), Self::exam_bar(exam)]
|
||||
.height(30)
|
||||
.align_y(Center)
|
||||
.width(Fill)
|
||||
.spacing(HALF_SPACING),
|
||||
rule::horizontal(2),
|
||||
self.exam_variable_view(exam),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.width(FillPortion(2))
|
||||
.into();
|
||||
}
|
||||
|
||||
space().width(FillPortion(3)).into()
|
||||
}
|
||||
|
||||
fn exam_bar(exam: &ExamExtended) -> Element<'_, ExamsMessage> {
|
||||
let total = 1000.0;
|
||||
let answered = (exam.answered as f64 / exam.total as f64 * total).round();
|
||||
let unknown = (exam.unknown as f64 / exam.total as f64 * total).round();
|
||||
let remaining = (exam.remaining() as f64 / exam.total as f64 * total).round();
|
||||
let mut row = row![];
|
||||
if answered > 0.0 {
|
||||
row = row.push(tooltip(
|
||||
container(space())
|
||||
.height(Fill)
|
||||
.width(FillPortion(answered as u16))
|
||||
.style(|theme: &Theme| container::Style {
|
||||
background: Some(Background::Color(theme.palette().success)),
|
||||
text_color: Default::default(),
|
||||
border: Default::default(),
|
||||
shadow: Default::default(),
|
||||
snap: false,
|
||||
}),
|
||||
text!("Правильно: {}% ({})", answered / 10.0, exam.answered),
|
||||
tooltip::Position::Bottom,
|
||||
));
|
||||
}
|
||||
if unknown > 0.0 {
|
||||
row = row.push(tooltip(
|
||||
container(space())
|
||||
.height(Fill)
|
||||
.width(FillPortion(unknown as u16))
|
||||
.style(|theme: &Theme| container::Style {
|
||||
background: Some(Background::Color(theme.palette().danger)),
|
||||
text_color: Default::default(),
|
||||
border: Default::default(),
|
||||
shadow: Default::default(),
|
||||
snap: false,
|
||||
}),
|
||||
text!("Не получилось: {}% ({})", unknown / 10.0, exam.unknown),
|
||||
tooltip::Position::Bottom,
|
||||
));
|
||||
}
|
||||
if remaining > 0.0 {
|
||||
row = row.push(tooltip(
|
||||
container(space())
|
||||
.height(Fill)
|
||||
.width(FillPortion(remaining as u16))
|
||||
.style(|theme: &Theme| container::Style {
|
||||
background: Some(Background::Color(theme.palette().primary)),
|
||||
text_color: Default::default(),
|
||||
border: Default::default(),
|
||||
shadow: Default::default(),
|
||||
snap: false,
|
||||
}),
|
||||
text!("Осталось {}% ({})", remaining / 10.0, exam.remaining()),
|
||||
tooltip::Position::Bottom,
|
||||
));
|
||||
}
|
||||
|
||||
row.width(Fill).height(Fill).into()
|
||||
}
|
||||
|
||||
fn exam_variable_view(&self, exam: &ExamExtended) -> Element<'_, ExamsMessage> {
|
||||
if exam.finished() {
|
||||
self.exam_finished_view(exam)
|
||||
} else {
|
||||
self.exam_ongoing_view(exam)
|
||||
}
|
||||
}
|
||||
|
||||
fn exam_finished_view(&self, exam: &ExamExtended) -> Element<'_, ExamsMessage> {
|
||||
let result = (exam.answered as f64 / exam.total as f64 * 1000.0).round() / 10.0;
|
||||
let words_repo = self.state.dictionary.read();
|
||||
column![
|
||||
center_x(text!("Итоговый результат: {}%", result).size(28)),
|
||||
row![
|
||||
Self::words_list(
|
||||
"Правильно",
|
||||
exam.answered_list
|
||||
.iter()
|
||||
.map(|handle| words_repo.get_ref_static(*handle).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
.as_slice()
|
||||
)
|
||||
.width(Fill),
|
||||
Self::words_list(
|
||||
"Не получилось",
|
||||
exam.unknows_list
|
||||
.iter()
|
||||
.map(|handle| words_repo.get_ref_static(*handle).unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
.as_slice()
|
||||
)
|
||||
.width(Fill)
|
||||
]
|
||||
.width(Fill)
|
||||
.spacing(QUARTER_SPACING)
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn exam_ongoing_view(&self, _: &ExamExtended) -> Element<'_, ExamsMessage> {
|
||||
center_x(
|
||||
button("Продолжить экзамен")
|
||||
.style(cta_button)
|
||||
.on_press(GotoExam),
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn words_list<'a>(name: &str, words: &[&WordData]) -> Column<'a, ExamsMessage> {
|
||||
let mut column = column![];
|
||||
for word in words {
|
||||
let container = container(
|
||||
column![text!("{}", word.key), text!("{}", word.value)].padding(QUARTER_SPACING),
|
||||
)
|
||||
.width(Fill)
|
||||
.style(bordered_box);
|
||||
column = column.push(container);
|
||||
}
|
||||
column![
|
||||
text!("{}", name),
|
||||
scrollable(row![
|
||||
column.spacing(QUARTER_SPACING),
|
||||
horizontal().width(DEFAULT_SPACING)
|
||||
])
|
||||
]
|
||||
.align_x(Center)
|
||||
}
|
||||
}
|
||||
|
||||
struct ExamExtended {
|
||||
exam: Exam,
|
||||
total: u32,
|
||||
answered: u32,
|
||||
unknown: u32,
|
||||
answered_list: Vec<EntityHandle<WordData>>,
|
||||
unknows_list: Vec<EntityHandle<WordData>>,
|
||||
}
|
||||
|
||||
impl ExamExtended {
|
||||
fn from(exam: Exam, state: &AppState) -> Self {
|
||||
let entries = state.exam_entries.read();
|
||||
let mut total = 0;
|
||||
let mut answered = 0;
|
||||
let mut unknown = 0;
|
||||
let mut answered_list = Vec::with_capacity(128);
|
||||
let mut unknows_list = Vec::with_capacity(128);
|
||||
entries
|
||||
.iter()
|
||||
.filter(|e| e.exam_id == exam.id)
|
||||
.for_each(|e| {
|
||||
total += 1;
|
||||
match e.status {
|
||||
None => {}
|
||||
Some(s) => {
|
||||
if s {
|
||||
answered += 1;
|
||||
answered_list.push(EntityHandle::from_id(e.word_id));
|
||||
} else {
|
||||
unknown += 1;
|
||||
unknows_list.push(EntityHandle::from_id(e.word_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
exam,
|
||||
total,
|
||||
answered,
|
||||
unknown,
|
||||
answered_list,
|
||||
unknows_list,
|
||||
}
|
||||
}
|
||||
fn solved(&self) -> u32 {
|
||||
self.answered + self.unknown
|
||||
}
|
||||
|
||||
fn finished(&self) -> bool {
|
||||
self.solved() == self.total
|
||||
}
|
||||
|
||||
fn remaining(&self) -> u32 {
|
||||
self.total - self.solved()
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for ExamExtended {
|
||||
type Target = Exam;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.exam
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for ExamExtended {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.exam
|
||||
}
|
||||
}
|
||||
+26
-34
@@ -3,18 +3,16 @@ use crate::data::entities::{HistoryNote, WordData};
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::navigation::*;
|
||||
use crate::styling::*;
|
||||
use HistoryMessage::Back;
|
||||
use chrono::Local;
|
||||
use iced::alignment::Horizontal::Center;
|
||||
use iced::widget::space::horizontal;
|
||||
use iced::widget::*;
|
||||
use iced::{Element, Fill, FillPortion, Task};
|
||||
use std::sync::Arc;
|
||||
use HistoryMessage::Back;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HistoryState {
|
||||
list: Vec<(WordData, HistoryNote)>,
|
||||
pub state: AppState,
|
||||
}
|
||||
|
||||
impl NavigatedPage<HistoryMessage> for HistoryState {
|
||||
@@ -37,9 +35,9 @@ impl NavigatedPage<HistoryMessage> for HistoryState {
|
||||
.width(FillPortion(5)),
|
||||
horizontal().width(FillPortion(1))
|
||||
]
|
||||
.height(Fill)
|
||||
.width(Fill)
|
||||
.into(),
|
||||
.height(Fill)
|
||||
.width(Fill)
|
||||
.into(),
|
||||
Back,
|
||||
)
|
||||
}
|
||||
@@ -50,57 +48,51 @@ impl HistoryState {
|
||||
let dict = &state.dictionary.read();
|
||||
let history_repo = &mut state.history.write();
|
||||
history_repo.init().expect("TODO: panic message");
|
||||
let id = id.clone();
|
||||
let mut history = history_repo.query(Arc::new(move |h| h.deck_id == id));
|
||||
let words = history
|
||||
let mut words: Vec<_> = history
|
||||
.iter(history_repo)
|
||||
.map(
|
||||
|item| {let handle = dict.handle_by_id(item.word_id);
|
||||
let word = dict.get_static(handle).unwrap_or(WordData {
|
||||
id: Default::default(),
|
||||
group_id: Default::default(),
|
||||
key: "Удаленное слово".to_string(),
|
||||
value: "".to_string(),
|
||||
tags: "".to_string(),
|
||||
additional: Default::default(),
|
||||
});
|
||||
(word, item.clone())
|
||||
}
|
||||
)
|
||||
.map(|item| {
|
||||
let handle = dict.handle_by_id(item.word_id);
|
||||
let word = dict.get_static(handle).unwrap_or(WordData {
|
||||
id: Default::default(),
|
||||
group_id: Default::default(),
|
||||
key: "Удаленное слово".to_string(),
|
||||
value: String::new(),
|
||||
tags: String::new(),
|
||||
additional: Default::default(),
|
||||
});
|
||||
(word, item.clone())
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
list: words,
|
||||
state: state.clone(),
|
||||
}
|
||||
words.reverse();
|
||||
Self { list: words }
|
||||
}
|
||||
|
||||
fn history_lines(&self) -> Column<'_, HistoryMessage> {
|
||||
let mut column = Column::new();
|
||||
for (index, item) in &self.list {
|
||||
|
||||
let activity = item;
|
||||
column = column.push(
|
||||
row![
|
||||
iced::widget::column![
|
||||
text!("{}", index.key)
|
||||
.width(Fill)
|
||||
.align_x(Center),
|
||||
text!("{}", index.value)
|
||||
.width(Fill)
|
||||
.align_x(Center),
|
||||
text!("{}", index.key).width(Fill).align_x(Center),
|
||||
text!("{}", index.value).width(Fill).align_x(Center),
|
||||
]
|
||||
.align_x(Center),
|
||||
iced::widget::column![
|
||||
text!("{} ➞ {}", activity.before, activity.after),
|
||||
text!(
|
||||
"{}",
|
||||
activity.timestamp.with_timezone(&Local).format("%d.%m %H:%M")
|
||||
activity
|
||||
.timestamp
|
||||
.with_timezone(&Local)
|
||||
.format("%d.%m %H:%M")
|
||||
)
|
||||
]
|
||||
.spacing(5)
|
||||
.align_x(Center)
|
||||
]
|
||||
.spacing(5),
|
||||
.spacing(5),
|
||||
);
|
||||
column = column.push(rule::horizontal(1));
|
||||
}
|
||||
|
||||
+74
-22
@@ -1,19 +1,21 @@
|
||||
use crate::app::AppState;
|
||||
use crate::data::entities::EntityData;
|
||||
use crate::data::entities::WordData;
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::WordGroup;
|
||||
use crate::data::entities::{CustomField, WordData};
|
||||
use crate::data::repositories::{BatchedRepository, Repository};
|
||||
use crate::data_provider::import::{ImportData, ImportGroup, get_words_of_group, load_groups};
|
||||
use crate::fs::*;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::notification::NotificationData::OpenFileError;
|
||||
use crate::notification::NotificationData::{CompressError, OpenFileError};
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use crate::pages::import::ImportMessage::*;
|
||||
use crate::push_error;
|
||||
use crate::styling::*;
|
||||
use crate::{jl_button, push_error_task};
|
||||
use crate::{jl_text_input, push_error};
|
||||
use iced::widget::button::danger;
|
||||
use iced::widget::container::success;
|
||||
use iced::widget::{
|
||||
Row, button, checkbox, column, container, progress_bar, row, rule, text, text_input,
|
||||
Row, button, checkbox, column, container, progress_bar, row, rule, text,
|
||||
};
|
||||
use iced::widget::{scrollable, space};
|
||||
use iced::{Element, Task};
|
||||
@@ -24,17 +26,17 @@ use log::info;
|
||||
use parking_lot::Mutex;
|
||||
use rfd::AsyncFileDialog;
|
||||
use rusqlite::Connection;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::BufReader;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::task::spawn_blocking;
|
||||
use zip::ZipArchive;
|
||||
use crate::data::repositories::{BatchedRepository, Repository};
|
||||
use zstd::Decoder;
|
||||
|
||||
const DEFAULT_FIELDS: [&str; 6] = ["key", "value", "tags", "reading", "context", "description"];
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ImportState {
|
||||
state: AppState,
|
||||
path: Option<PathBuf>,
|
||||
@@ -155,7 +157,7 @@ impl NavigatedPage<ImportMessage> for ImportState {
|
||||
scrollable(
|
||||
column![
|
||||
row![
|
||||
button("Выбрать файл").style(jl_button).on_press(SelectFile),
|
||||
jl_button!("Выбрать файл").on_press(SelectFile),
|
||||
text!("{}", {
|
||||
if let Some(path) = &self.path {
|
||||
path.to_string_lossy().to_string()
|
||||
@@ -267,7 +269,7 @@ impl ImportState {
|
||||
self.available_properties(),
|
||||
button("Добавить напрямую").on_press(SetupDirect),
|
||||
row![
|
||||
text_input("Пользовательское поле", &self.custom_property_name)
|
||||
jl_text_input!("Пользовательское поле", &self.custom_property_name)
|
||||
.on_input(EditCustomProperty),
|
||||
button("Установить привязку").on_press(SetupCustomProperty)
|
||||
]
|
||||
@@ -295,7 +297,7 @@ impl ImportState {
|
||||
.on_toggle(SwitchSkipEmpty),
|
||||
column![
|
||||
text!("Разделитель при множественном объединении"),
|
||||
text_input("", &self.separator).on_input(EditSeparator)
|
||||
jl_text_input!("", &self.separator).on_input(EditSeparator)
|
||||
]
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
@@ -327,7 +329,7 @@ impl ImportState {
|
||||
import_data: None,
|
||||
selected_index: 0,
|
||||
selected_property: None,
|
||||
custom_property_name: "".to_string(),
|
||||
custom_property_name: String::new(),
|
||||
skip_empty: true,
|
||||
separator: ", ".to_string(),
|
||||
progress: None,
|
||||
@@ -361,8 +363,8 @@ impl ImportState {
|
||||
Task::perform(
|
||||
async {
|
||||
spawn_blocking(move || {
|
||||
Self::extract_import_file(path)?;
|
||||
let data = Self::read_import_file()?;
|
||||
let schema = Self::extract_import_file(path)?;
|
||||
let data = Self::read_import_file(schema)?;
|
||||
Ok(data)
|
||||
})
|
||||
.await
|
||||
@@ -375,7 +377,7 @@ impl ImportState {
|
||||
)
|
||||
}
|
||||
|
||||
fn extract_import_file(path: PathBuf) -> MaybeError {
|
||||
fn extract_import_file(path: PathBuf) -> Result<AnkiSchema, NotificationData> {
|
||||
let file = File::open(path).map_err(|_| OpenFileError)?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut archive = ZipArchive::new(reader).map_err(|_| OpenFileError)?;
|
||||
@@ -386,20 +388,24 @@ impl ImportState {
|
||||
.truncate(true)
|
||||
.open(&temp_file_path)
|
||||
.map_err(|_| OpenFileError)?;
|
||||
if let Ok(mut file) = archive.by_name("collection.anki21") {
|
||||
if let Ok(mut file) = archive.by_name("collection.anki21b") {
|
||||
let mut decoder = Decoder::new(&mut file).map_err(|_| CompressError)?;
|
||||
std::io::copy(&mut decoder, &mut temp_file).map_err(|_| OpenFileError)?;
|
||||
Ok(AnkiSchema::Beta)
|
||||
} else if let Ok(mut file) = archive.by_name("collection.anki21") {
|
||||
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
|
||||
Ok(())
|
||||
Ok(AnkiSchema::Old)
|
||||
} else if let Ok(mut file) = archive.by_name("collection.anki2") {
|
||||
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
|
||||
Ok(())
|
||||
Ok(AnkiSchema::Old)
|
||||
} else {
|
||||
Err(OpenFileError)
|
||||
}
|
||||
}
|
||||
fn read_import_file() -> Result<ImportData, NotificationData> {
|
||||
fn read_import_file(schema: AnkiSchema) -> Result<ImportData, NotificationData> {
|
||||
let temp_file_path = temp_import_path();
|
||||
let connection = Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
|
||||
let data = load_groups(&connection)?;
|
||||
let data = load_groups(&connection, schema)?;
|
||||
Ok(data)
|
||||
}
|
||||
fn setup_mapping(&mut self, property_name: String) {
|
||||
@@ -429,17 +435,29 @@ impl ImportState {
|
||||
let separator = self.separator.clone();
|
||||
let skip_empty = self.skip_empty;
|
||||
let group = self.import_data.as_ref().unwrap().0[self.selected_index].clone();
|
||||
let map_indices = Self::get_mapping_indices(&group);
|
||||
let progress = self.progress.clone().unwrap();
|
||||
if let Err(err) = Self::ensure_fields(&state, &map_indices) {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
let fields: HashMap<String, Id> = HashMap::from_iter(
|
||||
state
|
||||
.custom_fields
|
||||
.read()
|
||||
.iter()
|
||||
.map(|f| (f.identifier.clone(), f.id)),
|
||||
);
|
||||
|
||||
info!("{}", group.name);
|
||||
Task::perform(
|
||||
async move {
|
||||
spawn_blocking(move || {
|
||||
let temp_file_path = temp_import_path();
|
||||
let connection = Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
|
||||
let connection =
|
||||
Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
|
||||
let import_list = get_words_of_group(&connection, group.id)?;
|
||||
let mut words_list = Vec::with_capacity(import_list.len());
|
||||
|
||||
let map_indices = Self::get_mapping_indices(&group);
|
||||
let group_handle;
|
||||
{
|
||||
let group_entity = WordGroup {
|
||||
@@ -474,7 +492,7 @@ impl ImportState {
|
||||
word.tags = collected_string;
|
||||
}
|
||||
&_ => {
|
||||
word.additional.insert((*dest).clone(), collected_string);
|
||||
word.additional.insert(fields[dest], collected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -554,4 +572,38 @@ impl ImportState {
|
||||
|_| RootMessage::Import(NextProgress),
|
||||
)
|
||||
}
|
||||
|
||||
fn ensure_fields(
|
||||
state: &AppState,
|
||||
import_group: &Vec<(String, Vec<usize>)>,
|
||||
) -> Result<(), NotificationData> {
|
||||
let mut fields_repo = state.custom_fields.write();
|
||||
let mut current_fields: Vec<String> = fields_repo
|
||||
.iter()
|
||||
.map(|field| field.identifier.clone())
|
||||
.collect();
|
||||
current_fields.append(&mut vec![
|
||||
"key".to_string(),
|
||||
"value".to_string(),
|
||||
"tags".to_string(),
|
||||
]);
|
||||
for (field, _) in import_group {
|
||||
if current_fields.contains(field) {
|
||||
continue;
|
||||
}
|
||||
|
||||
fields_repo.create_now(CustomField {
|
||||
id: Default::default(),
|
||||
name: field.clone(),
|
||||
identifier: field.clone(),
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub enum AnkiSchema {
|
||||
Old,
|
||||
Beta,
|
||||
}
|
||||
+4
-4
@@ -4,11 +4,11 @@ use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::pages::quiz::QuizMessage::*;
|
||||
use crate::styling::*;
|
||||
use crate::{jl_button, jl_text_input};
|
||||
use iced::widget::*;
|
||||
use iced::{Element, Fill, Task, alignment};
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct QuizState {
|
||||
kana: String,
|
||||
current_roman: String,
|
||||
@@ -77,12 +77,12 @@ impl NavigatedPage<QuizMessage> for QuizState {
|
||||
]
|
||||
.align_y(alignment::Vertical::Center)
|
||||
.spacing(20),
|
||||
text_input("Романдзи", &self.current_roman)
|
||||
jl_text_input!("Романдзи", &self.current_roman)
|
||||
.size(28)
|
||||
.width(150)
|
||||
.on_input(ContentChanged),
|
||||
score_display(&self.score),
|
||||
button("Закончить").style(jl_button).on_press(Back),
|
||||
jl_button!("Закончить").on_press(Back),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.align_x(alignment::Horizontal::Center),
|
||||
@@ -113,7 +113,7 @@ impl QuizState {
|
||||
kana: "ぁ".to_string(),
|
||||
correct_roman: "a".to_string(),
|
||||
is_help: false,
|
||||
current_roman: "".to_string(),
|
||||
current_roman: String::new(),
|
||||
set: KanaSet::hiragana(),
|
||||
queue: Vec::new(),
|
||||
score: Score {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
use crate::jl_button;
|
||||
use crate::navigation::RootMessage;
|
||||
use crate::navigation::{NavigatedPage, Page};
|
||||
use crate::pages::randomizer::RandomizerMessage::{Back, Edit, Start};
|
||||
use crate::styling::{HALF_SPACING, back_overlay, jl_button};
|
||||
use crate::styling::{HALF_SPACING, back_overlay};
|
||||
use iced::Task;
|
||||
use iced::widget::{button, text_editor};
|
||||
use iced::widget::text_editor;
|
||||
use rand::prelude::SliceRandom;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RandomizerState {
|
||||
text: text_editor::Content,
|
||||
list: Vec<String>,
|
||||
@@ -56,7 +56,7 @@ impl NavigatedPage<RandomizerMessage> for RandomizerState {
|
||||
.width(400)
|
||||
.height(400)
|
||||
.placeholder("Каждый элемент с новой строки"),
|
||||
button("Перемешать").style(jl_button).on_press(Start),
|
||||
jl_button!("Перемешать").on_press(Start),
|
||||
]
|
||||
.spacing(HALF_SPACING)
|
||||
.into(),
|
||||
|
||||
+17
-91
@@ -1,28 +1,30 @@
|
||||
use crate::app::AppState;
|
||||
use crate::core::deck::DeckData;
|
||||
use crate::core::srs::WordOpenMode;
|
||||
use crate::data::entities::{CardState, CustomField, WordData};
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::{CardState, DeckSettings, WordData};
|
||||
use crate::data_provider::voice::get_voice;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
|
||||
use crate::notification::{MaybeError, NotificationData};
|
||||
use crate::pages::repetition::RepetitionMessage::Play;
|
||||
use crate::pages::repetitions::DeckRunData;
|
||||
use crate::styling::*;
|
||||
use crate::{push_error, push_error_task};
|
||||
use iced::alignment::Horizontal::Center;
|
||||
use iced::keyboard::key::Physical::Code;
|
||||
use iced::widget::text::Style;
|
||||
use iced::widget::{Column, button, column, container, row, rule, space, text, tooltip};
|
||||
use iced::{Element, Fill, Task, Theme, alignment, keyboard};
|
||||
use iced::widget::{button, column, container, row, text, tooltip};
|
||||
use iced::{keyboard, Element, Fill, Task, Theme};
|
||||
use rodio::MixerDeviceSink;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use tokio::task::spawn_blocking;
|
||||
use crate::data::repositories::Repository;
|
||||
|
||||
pub struct RepetitionState {
|
||||
state: AppState,
|
||||
pub settings: DeckSettings,
|
||||
pub settings: DeckRunData,
|
||||
pub set: DeckData,
|
||||
current_word: WordData,
|
||||
current_statistic: CardState,
|
||||
@@ -30,6 +32,7 @@ pub struct RepetitionState {
|
||||
can_play: bool,
|
||||
sink: Arc<Option<MixerDeviceSink>>,
|
||||
opened: HashSet<Id>,
|
||||
custom_fields_cache: Vec<CustomField>,
|
||||
}
|
||||
|
||||
impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
||||
@@ -47,7 +50,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
||||
RepetitionMessage::Back => {}
|
||||
RepetitionMessage::Next => return self.next(),
|
||||
RepetitionMessage::Answer(m) => return self.answer(m),
|
||||
RepetitionMessage::Play => {
|
||||
Play => {
|
||||
if !self.can_play {
|
||||
return Task::none();
|
||||
}
|
||||
@@ -71,17 +74,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
||||
fn view(&self) -> Element<'_, RepetitionMessage> {
|
||||
back_overlay(
|
||||
column![
|
||||
container(self.draw_forward())
|
||||
.width(Fill)
|
||||
.height(Fill)
|
||||
.align_x(Center)
|
||||
.align_y(alignment::Vertical::Center),
|
||||
rule::horizontal(2),
|
||||
container(self.draw_backward())
|
||||
.width(Fill)
|
||||
.height(Fill)
|
||||
.align_x(Center)
|
||||
.align_y(alignment::Vertical::Center),
|
||||
crate::widgets::card_display::word_display(&self.settings.general_settings, &self.current_word, self.open, Play, self.custom_fields_cache.as_slice()),
|
||||
container(self.answer_bar())
|
||||
.width(Fill)
|
||||
.align_x(Center)
|
||||
@@ -90,7 +83,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
||||
"Затронуто слов {}, {}%",
|
||||
self.opened.len(),
|
||||
(self.opened.len() as f32 / self.set.len() as f32 * 10000.0).round() / 100.0
|
||||
)
|
||||
),
|
||||
]
|
||||
.height(Fill)
|
||||
.width(Fill)
|
||||
@@ -102,10 +95,10 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
||||
|
||||
impl RepetitionState {
|
||||
pub(crate) fn new(
|
||||
set: DeckSettings,
|
||||
set: DeckRunData,
|
||||
state: AppState,
|
||||
) -> Result<RepetitionState, NotificationData> {
|
||||
let mut card_set = DeckData::new(&set, state.clone())?;
|
||||
let mut card_set = DeckData::new(&set, set.open_mode, state.clone());
|
||||
let (word, stat) = card_set.next();
|
||||
let word = state.dictionary.read().get_static(word).unwrap();
|
||||
let stat = state.card_states.read().get_static(stat).unwrap();
|
||||
@@ -115,6 +108,8 @@ impl RepetitionState {
|
||||
None
|
||||
};
|
||||
|
||||
let custom_fields_cache = state.custom_fields.read().iter().cloned().collect();
|
||||
|
||||
Ok(RepetitionState {
|
||||
state,
|
||||
settings: set,
|
||||
@@ -125,6 +120,7 @@ impl RepetitionState {
|
||||
can_play: true,
|
||||
sink: Arc::new(sink_handle),
|
||||
opened: HashSet::new(),
|
||||
custom_fields_cache,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -167,43 +163,6 @@ impl RepetitionState {
|
||||
Task::none()
|
||||
}
|
||||
|
||||
fn draw_forward(&self) -> Element<'_, RepetitionMessage> {
|
||||
self.draw_card_view(self.settings.forward.as_str())
|
||||
}
|
||||
|
||||
fn draw_backward(&self) -> Element<'_, RepetitionMessage> {
|
||||
if !self.open {
|
||||
return container(text!("?").size(72))
|
||||
.width(Fill)
|
||||
.height(Fill)
|
||||
.align_y(alignment::Vertical::Center)
|
||||
.align_x(Center)
|
||||
.into();
|
||||
}
|
||||
|
||||
self.draw_card_view(self.settings.backward.as_str())
|
||||
}
|
||||
|
||||
fn draw_card_view(&self, properties: &str) -> Element<'_, RepetitionMessage> {
|
||||
let word = &self.current_word;
|
||||
|
||||
let mut col = Column::new();
|
||||
|
||||
for view_type in properties.split(" ") {
|
||||
col = col.push(match view_type {
|
||||
"key" => self.draw_key(word),
|
||||
"value" => self.draw_value(word),
|
||||
"speech" => self.draw_voice(),
|
||||
"reading" => self.draw_reading(word),
|
||||
"context" => self.draw_context(word),
|
||||
"description" => self.draw_description(word),
|
||||
_ => space().into(),
|
||||
})
|
||||
}
|
||||
|
||||
col.spacing(DEFAULT_SPACING).align_x(Center).into()
|
||||
}
|
||||
|
||||
fn answer_bar(&self) -> Element<'_, RepetitionMessage> {
|
||||
if !self.open {
|
||||
return text!("Нажмите Пробел для открытия карточки")
|
||||
@@ -245,39 +204,6 @@ impl RepetitionState {
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn draw_key(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
|
||||
text!("{}", word.key).size(36).into()
|
||||
}
|
||||
fn draw_value(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
|
||||
text!("{}", word.value).size(24).into()
|
||||
}
|
||||
|
||||
fn draw_voice(&self) -> Element<'_, RepetitionMessage> {
|
||||
button("Воспроизвести")
|
||||
.style(jl_button)
|
||||
.on_press(RepetitionMessage::Play)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn draw_reading(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
|
||||
match word.additional.get("reading") {
|
||||
None => space().into(),
|
||||
Some(reading) => text!("{}", reading).size(24).into(),
|
||||
}
|
||||
}
|
||||
fn draw_context(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
|
||||
match word.additional.get("context") {
|
||||
None => space().into(),
|
||||
Some(context) => text!("{}", context).size(24).into(),
|
||||
}
|
||||
}
|
||||
fn draw_description(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
|
||||
match word.additional.get("description") {
|
||||
None => space().into(),
|
||||
Some(context) => text!("{}", context).size(24).into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyPressedPage for RepetitionState {
|
||||
@@ -316,7 +242,7 @@ pub enum RepetitionMessage {
|
||||
PlayFinished,
|
||||
}
|
||||
|
||||
async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) -> MaybeError {
|
||||
pub async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) -> MaybeError {
|
||||
let data = get_voice(text.as_str()).await?;
|
||||
spawn_blocking(move || {
|
||||
if let Some(sink) = sink.as_ref()
|
||||
|
||||
@@ -7,13 +7,15 @@ use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::notification::MaybeError;
|
||||
use crate::pages::repetition_settings::RepetitionSettingsMessage::*;
|
||||
use crate::styling::*;
|
||||
use crate::{jl_button, jl_text_input};
|
||||
use crate::{push_error, push_error_task};
|
||||
use iced::widget::button::danger;
|
||||
use iced::widget::space::horizontal;
|
||||
use iced::widget::text_input::Catalog;
|
||||
use iced::widget::{button, column, row, scrollable, space, text, text_input};
|
||||
use iced::widget::{button, column, row, scrollable, space, text};
|
||||
use iced::{Element, Task};
|
||||
use iced_core::Length::Fill;
|
||||
use iced_core::{Padding, Theme, color};
|
||||
use iced_core::{color, Padding, Theme};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -22,6 +24,7 @@ pub struct RepetitionSettingsState {
|
||||
settings_data: DeckSettings,
|
||||
state: AppState,
|
||||
real_delete: bool,
|
||||
real_delete_states: bool,
|
||||
correct_filter: bool,
|
||||
filter_changed: bool,
|
||||
filtered_words: Option<u32>,
|
||||
@@ -38,6 +41,7 @@ impl RepetitionSettingsState {
|
||||
settings_handle: settings,
|
||||
state,
|
||||
real_delete: false,
|
||||
real_delete_states: false,
|
||||
correct_filter: true,
|
||||
filter_changed: false,
|
||||
filtered_words: None,
|
||||
@@ -105,7 +109,29 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
|
||||
return Task::done(RootMessage::RepetitionSettings(Back));
|
||||
}
|
||||
RevertDeleteSet => self.real_delete = false,
|
||||
RevertDeleteSet => {
|
||||
self.real_delete = false;
|
||||
self.real_delete_states = true;
|
||||
}
|
||||
DeleteStates => {
|
||||
if !self.real_delete_states {
|
||||
self.real_delete_states = true;
|
||||
return Task::future(async {
|
||||
tokio::time::sleep(Duration::from_millis(3000)).await;
|
||||
RootMessage::RepetitionSettings(RevertDeleteSet)
|
||||
});
|
||||
}
|
||||
let mut states = self.state.card_states.write();
|
||||
let deck_id = self.settings_handle.id;
|
||||
let mut query = states
|
||||
.query(Arc::new(move |state| state.deck_id == deck_id))
|
||||
.handles()
|
||||
.collect::<Vec<_>>();
|
||||
if let Err(e) = states.delete_many(query.as_mut_slice()) {
|
||||
return push_error_task!(e);
|
||||
}
|
||||
self.real_delete_states = false;
|
||||
}
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
@@ -117,22 +143,22 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
column![
|
||||
column![
|
||||
text!("Название набора"),
|
||||
text_input("", &self.settings_data.name).on_input(SetName),
|
||||
jl_text_input!("", &self.settings_data.name).on_input(SetName),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Передняя сторона"),
|
||||
text_input("", &self.settings_data.forward).on_input(SetForward),
|
||||
jl_text_input!("", &self.settings_data.forward).on_input(SetForward),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Задняя сторона"),
|
||||
text_input("", &self.settings_data.backward).on_input(SetBackward),
|
||||
jl_text_input!("", &self.settings_data.backward).on_input(SetBackward),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Фильтр"),
|
||||
text_input("", &self.settings_data.filter)
|
||||
jl_text_input!("", &self.settings_data.filter)
|
||||
.style(|x, status| {
|
||||
let mut primary = Theme::default()(x, status);
|
||||
if !self.correct_filter {
|
||||
@@ -141,9 +167,7 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
primary
|
||||
})
|
||||
.on_input(SetFilter),
|
||||
button("Проверить фильтр")
|
||||
.style(jl_button)
|
||||
.on_press(TryFilter),
|
||||
jl_button!("Проверить фильтр").on_press(TryFilter),
|
||||
self.count_view(),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
@@ -158,7 +182,15 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
)
|
||||
.height(Fill),
|
||||
row![
|
||||
button("Сохранить").style(jl_button).on_press(Save),
|
||||
jl_button!("Сохранить").on_press(Save),
|
||||
horizontal(),
|
||||
button(if self.real_delete_states {
|
||||
"Вы уверены?"
|
||||
} else {
|
||||
"Удалить прогресс?"
|
||||
})
|
||||
.style(danger)
|
||||
.on_press(DeleteStates),
|
||||
button(if self.real_delete {
|
||||
"Вы уверены?"
|
||||
} else {
|
||||
@@ -166,7 +198,6 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
})
|
||||
.style(danger)
|
||||
.on_press(DeleteSet),
|
||||
space().width(Fill),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING),
|
||||
]
|
||||
@@ -182,14 +213,14 @@ fn update_deck_stats(deck: &DeckSettings, state: &AppState) -> MaybeError {
|
||||
let deck_id = deck.id;
|
||||
let mut db_stats = states_repo
|
||||
.query_par(Arc::new(move |s| s.deck_id == deck_id))
|
||||
.iter(&states_repo)
|
||||
.iter(states_repo)
|
||||
.collect::<Vec<_>>();
|
||||
let filtered_words = DeckData::list(deck, state)
|
||||
.iter()
|
||||
.map(|w| w.id)
|
||||
.collect::<Vec<_>>();
|
||||
filtered_words.iter().for_each(|word_id| {
|
||||
if let Some(index) = db_stats.iter().position(|stat_id| stat_id.id == *word_id) {
|
||||
if let Some(index) = db_stats.iter().position(|stat_id| stat_id.word_id == *word_id) {
|
||||
db_stats.remove(index);
|
||||
}
|
||||
});
|
||||
@@ -222,5 +253,6 @@ pub enum RepetitionSettingsMessage {
|
||||
SetFilter(String),
|
||||
TryFilter,
|
||||
DeleteSet,
|
||||
DeleteStates,
|
||||
RevertDeleteSet,
|
||||
}
|
||||
+47
-48
@@ -3,9 +3,10 @@ use crate::core::deck::DeckData;
|
||||
use crate::core::srs::{AppendMode, OrderMode};
|
||||
use crate::data::entities::{CardState, DeckSettings, EntityHandle, WordData};
|
||||
use crate::data::repositories::{BatchedRepository, Repository};
|
||||
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
|
||||
use crate::navigation::Page::{Exams, History, PreviousPage, Repetition, RepetitionSettings};
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::notification::MaybeError;
|
||||
use crate::pages::exams::ExamsState;
|
||||
use crate::pages::history::HistoryState;
|
||||
use crate::pages::repetition::RepetitionState;
|
||||
use crate::pages::repetition_settings::RepetitionSettingsState;
|
||||
@@ -13,27 +14,26 @@ use crate::pages::repetitions::RepetitionsMessage::*;
|
||||
use crate::push_error;
|
||||
use crate::push_error_task;
|
||||
use crate::styling::*;
|
||||
use crate::{jl_button, jl_text_input};
|
||||
use chrono::{Days, Local, Utc};
|
||||
use hashbrown::HashSet;
|
||||
use iced::widget::button::{danger, Status};
|
||||
pub use iced::widget::button::{Catalog, Style};
|
||||
use iced::widget::button::{Status, danger};
|
||||
use iced::widget::tooltip::Position::Top;
|
||||
use iced::widget::{
|
||||
Column, Row, button, column, container, lazy, radio, row, scrollable, space, svg, text,
|
||||
text_input, tooltip,
|
||||
button, column, container, lazy, radio, row, scrollable, space, svg, text, tooltip, Column, Row,
|
||||
};
|
||||
use iced::{Background, Border, Center, Color, Element, Fill, Length, Shadow, Task, Theme};
|
||||
use iced_core::Padding;
|
||||
use iced_core::border::Radius;
|
||||
use iced_core::svg::Handle;
|
||||
use iced_core::Padding;
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RepetitionsState {
|
||||
selected_deck_handle: Option<EntityHandle<DeckSettings>>,
|
||||
decks: BTreeMap<EntityHandle<DeckSettings>, DeckViewData>,
|
||||
decks: BTreeMap<EntityHandle<DeckSettings>, DeckRunData>,
|
||||
state: AppState,
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
}
|
||||
|
||||
if let Ok(repetition_state) =
|
||||
RepetitionState::new(selected_set.general_settings.clone(), self.state.clone())
|
||||
RepetitionState::new(selected_set.clone(), self.state.clone())
|
||||
{
|
||||
return Some(Repetition(repetition_state));
|
||||
}
|
||||
@@ -74,9 +74,9 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
self.selected_deck_handle.unwrap(),
|
||||
self.state.clone(),
|
||||
)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else if let GoToExams = message {
|
||||
Some(Exams(ExamsState::new(self.selected_deck_handle.unwrap(), self.state.clone())))
|
||||
} else { None }
|
||||
}
|
||||
fn navigated(&mut self) {
|
||||
if let Some(index) = self.selected_deck_handle {
|
||||
@@ -94,8 +94,9 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
self.clear_selection();
|
||||
}
|
||||
} else {
|
||||
let _ = self.fill_deck_word_indices();
|
||||
self.fill_deck_word_indices();
|
||||
}
|
||||
_ = self.state.history.write().reload()
|
||||
}
|
||||
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
|
||||
match message {
|
||||
@@ -111,7 +112,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
let handle = self.state.decks.write().create(general.clone());
|
||||
self.decks.insert(
|
||||
handle,
|
||||
DeckViewData {
|
||||
DeckRunData {
|
||||
settings_handle: handle,
|
||||
general_settings: general,
|
||||
existing_words_indices: Default::default(),
|
||||
@@ -126,7 +127,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
DeleteSet => {
|
||||
let index = self.selected_deck_handle.unwrap();
|
||||
self.clear_selection();
|
||||
let deck = self.decks.remove(&index);
|
||||
self.decks.remove(&index);
|
||||
|
||||
if index.real() {
|
||||
let mut repo = self.state.decks.write();
|
||||
@@ -152,7 +153,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
let mut repo = self.state.decks.write();
|
||||
|
||||
repo.set(handle, deck.general_settings.clone());
|
||||
let old = handle.clone();
|
||||
let old = *handle;
|
||||
if let Err(err) = repo.save(handle) {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
@@ -175,7 +176,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
}
|
||||
TryFilter => {
|
||||
let deck = self.selected_deck().unwrap();
|
||||
let count = DeckData::list(&deck, &self.state).len();
|
||||
let count = DeckData::list(deck, &self.state).len();
|
||||
let deck = self.selected_deck_mut().unwrap();
|
||||
deck.count = Some(count);
|
||||
}
|
||||
@@ -218,6 +219,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
}
|
||||
GoToExams => {}
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
@@ -227,10 +229,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
row![
|
||||
column![
|
||||
scrollable(self.decks_list()).height(Fill),
|
||||
button("Добавить")
|
||||
.style(jl_button)
|
||||
.width(Fill)
|
||||
.on_press(CreateSet),
|
||||
jl_button!("Добавить").width(Fill).on_press(CreateSet),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.width(Length::FillPortion(1)),
|
||||
@@ -256,9 +255,7 @@ impl RepetitionsState {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_decks_from_state(
|
||||
state: &AppState,
|
||||
) -> BTreeMap<EntityHandle<DeckSettings>, DeckViewData> {
|
||||
fn get_decks_from_state(state: &AppState) -> BTreeMap<EntityHandle<DeckSettings>, DeckRunData> {
|
||||
state
|
||||
.decks
|
||||
.read()
|
||||
@@ -267,7 +264,7 @@ impl RepetitionsState {
|
||||
.map(|(index, deck)| {
|
||||
(
|
||||
EntityHandle::new(deck.id, index, true),
|
||||
DeckViewData {
|
||||
DeckRunData {
|
||||
settings_handle: EntityHandle::new(deck.id, index, true),
|
||||
general_settings: deck.clone(),
|
||||
existing_words_indices: Default::default(),
|
||||
@@ -284,7 +281,7 @@ impl RepetitionsState {
|
||||
}
|
||||
|
||||
impl RepetitionsState {
|
||||
fn launch_delete_button(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||
fn launch_delete_button(&self, deck: &DeckRunData) -> Element<'_, RepetitionsMessage> {
|
||||
if deck.id.is_valid() {
|
||||
if deck.append_mode == AppendMode::Manual && deck.existing_words_indices.is_empty() {
|
||||
return text!("Добавьте карточки или измените фильтр").into();
|
||||
@@ -307,7 +304,7 @@ impl RepetitionsState {
|
||||
column![
|
||||
text!("Название набора"),
|
||||
row![
|
||||
text_input("", &deck.name).on_input(SetName),
|
||||
jl_text_input!("", &deck.name).on_input(SetName),
|
||||
button(svg(Handle::from_memory(SETTINGS_ICON)))
|
||||
.width(43)
|
||||
.on_press(GoToSettings),
|
||||
@@ -320,20 +317,18 @@ impl RepetitionsState {
|
||||
column![
|
||||
column![
|
||||
text!("Передняя сторона"),
|
||||
text_input("", &deck.forward).on_input(SetForward),
|
||||
jl_text_input!("", &deck.forward).on_input(SetForward),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Задняя сторона"),
|
||||
text_input("", &deck.backward).on_input(SetBackward),
|
||||
jl_text_input!("", &deck.backward).on_input(SetBackward),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Фильтр"),
|
||||
text_input("", &deck.filter).on_input(SetFilter),
|
||||
button("Проверить фильтр")
|
||||
.style(jl_button)
|
||||
.on_press(TryFilter),
|
||||
jl_text_input!("", &deck.filter).on_input(SetFilter),
|
||||
jl_button!("Проверить фильтр").on_press(TryFilter),
|
||||
self.count_view(deck),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
@@ -361,7 +356,10 @@ impl RepetitionsState {
|
||||
Some(deck.open_mode),
|
||||
SetOpenMode
|
||||
),
|
||||
button("История").style(jl_button).on_press(GoToHistory),
|
||||
row![
|
||||
jl_button!("История").on_press(GoToHistory),
|
||||
jl_button!("Экзамены").on_press(GoToExams),
|
||||
].spacing(DEFAULT_SPACING),
|
||||
]
|
||||
.spacing(HALF_SPACING)
|
||||
}
|
||||
@@ -378,7 +376,7 @@ impl RepetitionsState {
|
||||
)
|
||||
.height(Fill),
|
||||
row![
|
||||
button("Сохранить").style(jl_button).on_press(Save),
|
||||
jl_button!("Сохранить").on_press(Save),
|
||||
self.launch_delete_button(deck)
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
@@ -468,7 +466,7 @@ impl RepetitionsState {
|
||||
})
|
||||
.into()
|
||||
}
|
||||
fn word_append_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||
fn word_append_panel(&self, deck: &DeckRunData) -> Element<'_, RepetitionsMessage> {
|
||||
column![
|
||||
text!("Режим добавления карточек"),
|
||||
row![
|
||||
@@ -491,7 +489,7 @@ impl RepetitionsState {
|
||||
.spacing(HALF_SPACING)
|
||||
.into()
|
||||
}
|
||||
fn adder_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||
fn adder_panel(&self, deck: &DeckRunData) -> Element<'_, RepetitionsMessage> {
|
||||
match deck.append_mode {
|
||||
AppendMode::Full => space().into(),
|
||||
AppendMode::Manual => row![
|
||||
@@ -511,7 +509,7 @@ impl RepetitionsState {
|
||||
let available = selected_deck.available_words_indices.len();
|
||||
text!("{} слова добавлено из {}", now, available).into()
|
||||
}
|
||||
fn count_view(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||
fn count_view(&self, deck: &DeckRunData) -> Element<'_, RepetitionsMessage> {
|
||||
if let Some(count) = deck.count {
|
||||
return text!("Количество слов: {}", count).into();
|
||||
}
|
||||
@@ -520,7 +518,7 @@ impl RepetitionsState {
|
||||
fn decks_list(&self) -> Column<'_, RepetitionsMessage> {
|
||||
let mut column = Column::new();
|
||||
|
||||
for (i, (handle, deck)) in self.decks.iter().enumerate() {
|
||||
for (handle, deck) in self.decks.iter() {
|
||||
column = column.push(
|
||||
button(text!("{}", &deck.name))
|
||||
.on_press_with(move || SelectSet(*handle))
|
||||
@@ -547,7 +545,7 @@ impl RepetitionsState {
|
||||
}
|
||||
|
||||
impl RepetitionsState {
|
||||
fn append_all_words(state: &mut AppState, deck: &DeckViewData) -> MaybeError {
|
||||
fn append_all_words(state: &mut AppState, deck: &DeckRunData) -> MaybeError {
|
||||
let existing = &deck.existing_words_indices;
|
||||
let mut created_set = HashSet::with_capacity(existing.len());
|
||||
existing.iter().for_each(|c| {
|
||||
@@ -566,7 +564,6 @@ impl RepetitionsState {
|
||||
deck: &DeckSettings,
|
||||
indices: impl Iterator<Item = EntityHandle<WordData>>,
|
||||
) -> MaybeError {
|
||||
let words = &state.dictionary;
|
||||
let stats = &mut indices
|
||||
.map(|i| CardState {
|
||||
id: 0.into(),
|
||||
@@ -593,10 +590,10 @@ impl RepetitionsState {
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_deck(&self) -> Option<&DeckViewData> {
|
||||
fn selected_deck(&self) -> Option<&DeckRunData> {
|
||||
self.decks.get(&self.selected_deck_handle?)
|
||||
}
|
||||
fn selected_deck_mut(&mut self) -> Option<&mut DeckViewData> {
|
||||
fn selected_deck_mut(&mut self) -> Option<&mut DeckRunData> {
|
||||
self.decks.get_mut(&self.selected_deck_handle?)
|
||||
}
|
||||
|
||||
@@ -616,6 +613,7 @@ impl RepetitionsState {
|
||||
let total = DeckData::list(&deck, &self.state);
|
||||
deck.existing_words_indices = added;
|
||||
deck.available_words_indices = total;
|
||||
deck.indices_ready = true;
|
||||
self.decks.insert(self.selected_deck_handle.unwrap(), deck);
|
||||
}
|
||||
}
|
||||
@@ -636,23 +634,24 @@ pub enum RepetitionsMessage {
|
||||
SetOpenMode(OrderMode),
|
||||
SetAppendMode(AppendMode),
|
||||
GoToHistory,
|
||||
GoToExams,
|
||||
GoToSettings,
|
||||
AppendWords(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DeckViewData {
|
||||
settings_handle: EntityHandle<DeckSettings>,
|
||||
general_settings: DeckSettings,
|
||||
pub struct DeckRunData {
|
||||
pub settings_handle: EntityHandle<DeckSettings>,
|
||||
pub general_settings: DeckSettings,
|
||||
existing_words_indices: Vec<EntityHandle<WordData>>,
|
||||
available_words_indices: Vec<EntityHandle<WordData>>,
|
||||
indices_ready: bool,
|
||||
append_mode: AppendMode,
|
||||
pub append_mode: AppendMode,
|
||||
count: Option<usize>,
|
||||
open_mode: OrderMode,
|
||||
pub open_mode: OrderMode,
|
||||
}
|
||||
|
||||
impl Deref for DeckViewData {
|
||||
impl Deref for DeckRunData {
|
||||
type Target = DeckSettings;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::app::AppState;
|
||||
use crate::core::kana_set::{KanaSet, KanaType};
|
||||
use crate::jl_button;
|
||||
use crate::navigation::Page::*;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::pages::dictionary::DictionaryState;
|
||||
@@ -16,8 +17,6 @@ use iced::{Element, Task, alignment};
|
||||
use iced_core::Alignment::Center;
|
||||
use iced_core::Background;
|
||||
use iced_core::Color;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct SelectorState {
|
||||
pub set: KanaSet,
|
||||
@@ -81,9 +80,7 @@ impl NavigatedPage<SelectorMessage> for SelectorState {
|
||||
container(
|
||||
iced::widget::column![
|
||||
row![
|
||||
button("あ ↔ ア")
|
||||
.on_press(SelectorMessage::Change)
|
||||
.style(jl_button),
|
||||
jl_button!("あ ↔ ア").on_press(SelectorMessage::Change),
|
||||
button("Словарь")
|
||||
.on_press(SelectorMessage::ToDictionary)
|
||||
.style(Self::nav_style),
|
||||
|
||||
+43
-14
@@ -2,6 +2,7 @@ use crate::app::AppState;
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::data_provider::settings::{delete_settings, set_setting};
|
||||
use crate::data_provider::web_api::*;
|
||||
use crate::jl_button;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::notification::{NotificationData, NotificationRequest};
|
||||
@@ -14,6 +15,7 @@ use iced::widget::{button, column, container, progress_bar, row, space, text, to
|
||||
use iced::{Center, Element, Fill, Font, Length, Task};
|
||||
use log::error;
|
||||
use std::time::Duration;
|
||||
use crate::notification::NotificationData::LocalVersionChanged;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum SyncMessage {
|
||||
@@ -30,12 +32,13 @@ pub enum SyncMessage {
|
||||
Disable,
|
||||
DisableSync,
|
||||
SwitchAutoSync,
|
||||
ResetRealLoad,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct SyncState {
|
||||
state: AppState,
|
||||
auto_fetch: bool,
|
||||
frozen: bool,
|
||||
real_load: bool,
|
||||
progress: f32,
|
||||
}
|
||||
|
||||
@@ -99,13 +102,29 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
||||
return tasks;
|
||||
}
|
||||
GetLast => {
|
||||
if !self.real_load {
|
||||
self.real_load = true;
|
||||
return Task::batch([
|
||||
Task::future(async {
|
||||
tokio::time::sleep(Duration::from_millis(3000)).await;
|
||||
RootMessage::Sync(ResetRealLoad)
|
||||
}),
|
||||
Task::done(RootMessage::PushNotification(NotificationRequest::Warning(LocalVersionChanged)))
|
||||
]);
|
||||
}
|
||||
|
||||
self.real_load = false;
|
||||
let id = self.state.sync_data.read().key.clone().unwrap();
|
||||
self.state.connection.lock().finish();
|
||||
let tasks = Task::batch([
|
||||
Task::perform(
|
||||
async { tokio::time::sleep(Duration::from_millis(200)).await },
|
||||
|_| RootMessage::Sync(NextAnimation),
|
||||
),
|
||||
Task::perform(load_data(id, false), |_| RootMessage::Sync(NetworkFinished)),
|
||||
Task::perform(load_data(id, false), |load_result| match load_result {
|
||||
Ok(_) => RootMessage::Sync(NetworkFinished),
|
||||
Err(error) => push_error!(error)
|
||||
}),
|
||||
]);
|
||||
|
||||
return tasks;
|
||||
@@ -134,7 +153,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
||||
}
|
||||
|
||||
return Task::done(RootMessage::PushNotification(NotificationRequest::Info(
|
||||
NotificationData::DataLoaded,
|
||||
NotificationData::DataSynced,
|
||||
)));
|
||||
}
|
||||
Disable => {}
|
||||
@@ -166,6 +185,9 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
||||
return push_error_task!(err);
|
||||
}
|
||||
}
|
||||
ResetRealLoad => {
|
||||
self.real_load = false;
|
||||
}
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
@@ -189,6 +211,7 @@ impl SyncState {
|
||||
auto_fetch,
|
||||
state,
|
||||
frozen: false,
|
||||
real_load: false,
|
||||
progress: 0.0,
|
||||
}
|
||||
}
|
||||
@@ -199,6 +222,8 @@ impl SyncState {
|
||||
self.state.decks.write().reload()?;
|
||||
self.state.dictionary.write().reload()?;
|
||||
self.state.history.write().reload()?;
|
||||
self.state.exam.write().reload()?;
|
||||
self.state.exam_entries.write().reload()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -221,14 +246,13 @@ impl SyncState {
|
||||
.padding(3)
|
||||
)
|
||||
.style(rounded_box),
|
||||
button("Скопировать в буфер обмена")
|
||||
.style(jl_button)
|
||||
jl_button!("Скопировать в буфер обмена")
|
||||
.on_press(CopyKey)
|
||||
.width(Fill),
|
||||
row![
|
||||
button("↑ Отправить").style(jl_button).on_press(Send),
|
||||
jl_button!("↑ Отправить").on_press(Send),
|
||||
space().width(Fill),
|
||||
button("↓ Скачать").style(jl_button).on_press(GetLast)
|
||||
jl_button!("↓ Скачать").on_press(GetLast)
|
||||
]
|
||||
.spacing(DEFAULT_SPACING),
|
||||
toggler(self.auto_fetch)
|
||||
@@ -241,12 +265,8 @@ impl SyncState {
|
||||
]
|
||||
} else {
|
||||
column![
|
||||
button("Создать сохранение")
|
||||
.style(jl_button)
|
||||
.on_press(InitSync),
|
||||
button("Вставить ключ из буфера")
|
||||
.style(jl_button)
|
||||
.on_press(GetKey),
|
||||
jl_button!("Создать сохранение").on_press(InitSync),
|
||||
jl_button!("Вставить ключ из буфера").on_press(GetKey),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -273,7 +293,16 @@ impl SyncState {
|
||||
.unwrap_or_else(|e| {
|
||||
error!("Ошибка при checkpoint WAL: {e}");
|
||||
});
|
||||
|
||||
connection.execute("VACUUM;", []).unwrap_or_else(|e| {
|
||||
error!("Ошибка при checkpoint WAL: {e}");
|
||||
0
|
||||
});
|
||||
connection
|
||||
.execute("PRAGMA optimize;", [])
|
||||
.unwrap_or_else(|e| {
|
||||
error!("Ошибка при checkpoint WAL: {e}");
|
||||
0
|
||||
});
|
||||
connection.finish();
|
||||
}
|
||||
}
|
||||
|
||||
+127
-158
@@ -1,183 +1,154 @@
|
||||
use crate::app::AppState;
|
||||
use crate::data::entities::{EntityHandle, WordData};
|
||||
use crate::data_provider::words::{delete_word, update_word};
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::data::Id;
|
||||
use crate::data::entities::{CustomField, EntityHandle, WordData};
|
||||
use crate::data::repositories::Repository;
|
||||
use crate::jl_text_input;
|
||||
use crate::pages::word::WordMessage::*;
|
||||
use crate::push_error;
|
||||
use crate::push_error_task;
|
||||
use crate::styling::*;
|
||||
use iced::widget::button::danger;
|
||||
use iced::widget::{button, column, row, rule, scrollable, space, text, text_input};
|
||||
use iced::{Element, Fill, Task};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use iced::widget::space::horizontal;
|
||||
use iced::widget::{button, column, row, rule, scrollable, text};
|
||||
use iced::{Element, Fill};
|
||||
use iced_core::Padding;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WordState {
|
||||
pub struct WordEditor<Message : Clone> {
|
||||
state: AppState,
|
||||
handle: EntityHandle<WordData>,
|
||||
pub word_handle: EntityHandle<WordData>,
|
||||
on_delete: Option<Message>,
|
||||
on_edit: Option<Message>,
|
||||
fields: Vec<CustomField>,
|
||||
}
|
||||
|
||||
impl NavigatedPage<WordMessage> for WordState {
|
||||
fn navigate(&mut self, message: &WordMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
Some(PreviousPage)
|
||||
} else {
|
||||
None
|
||||
impl<Message: std::clone::Clone> WordEditor<Message> {
|
||||
pub(crate) fn update(&mut self, message: WordMessage) -> Option<Message> {
|
||||
let dictionary = &mut self.state.dictionary.write();
|
||||
let word = dictionary.get_mut(&mut self.word_handle).unwrap();
|
||||
match message {
|
||||
Delete => {
|
||||
return self.on_delete.clone();
|
||||
}
|
||||
SetTags(n) => word.tags = n,
|
||||
SetKey(n) => {
|
||||
word.key = n;
|
||||
}
|
||||
SetValue(n) => {
|
||||
word.value = n;
|
||||
}
|
||||
SetAdditional(key, value) => {
|
||||
word.additional.insert(key, value.replace("", ""));
|
||||
}
|
||||
AddAdditional(key) => {
|
||||
word.additional.insert(key, String::new());
|
||||
}
|
||||
RemoveAdditional(key) => {
|
||||
word.additional.remove(&key);
|
||||
}
|
||||
}
|
||||
self.on_edit.clone()
|
||||
}
|
||||
|
||||
fn navigated(&mut self) {}
|
||||
fn update(&mut self, message: WordMessage) -> Task<RootMessage> {
|
||||
// match message {
|
||||
// Back => {}
|
||||
// Save => {
|
||||
// let mut state = self.state.lock();
|
||||
// state.dictionary[self.index] = self.word.clone();
|
||||
//
|
||||
// if let Err(err) = update_word(&mut self.word, &state.connection) {
|
||||
// return push_error_task!(err);
|
||||
// }
|
||||
// return Task::done(RootMessage::Word(Back));
|
||||
// }
|
||||
// Delete => {
|
||||
// let mut state = self.state.lock();
|
||||
// state.dictionary.remove(self.index);
|
||||
// if let Err(err) = delete_word(&self.word, &state.connection) {
|
||||
// return push_error_task!(err);
|
||||
// }
|
||||
// return Task::done(RootMessage::Word(Back));
|
||||
// }
|
||||
// SetTags(n) => self.word.tags = n,
|
||||
// SetKey(n) => {
|
||||
// self.word.key = n;
|
||||
// }
|
||||
// SetValue(n) => {
|
||||
// self.word.value = n;
|
||||
// }
|
||||
// SetAdditional(key, value) => {
|
||||
// self.word.additional.insert(key, value.clone());
|
||||
// }
|
||||
// AddAdditional(key) => {
|
||||
// self.word.additional.insert(key, "".to_string());
|
||||
// }
|
||||
// RemoveAdditional(key) => {
|
||||
// self.word.additional.remove(key.as_str());
|
||||
// }
|
||||
// }
|
||||
Task::none()
|
||||
}
|
||||
pub(crate) fn view(&self) -> Element<'_, WordMessage> {
|
||||
let mut fast_add = row![];
|
||||
let word = self
|
||||
.state
|
||||
.dictionary
|
||||
.read()
|
||||
.get_static(self.word_handle)
|
||||
.unwrap();
|
||||
for field in &self.fields {
|
||||
if !word.additional.contains_key(&field.id) {
|
||||
fast_add = fast_add.push(
|
||||
button(field.name.as_str())
|
||||
.style(button::text)
|
||||
.on_press(AddAdditional(field.id)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn view(&self) -> Element<'_, WordMessage> {
|
||||
// let mut fast_add = row![];
|
||||
// if !self.word.additional.contains_key("reading") {
|
||||
// fast_add = fast_add.push(
|
||||
// button("Чтение")
|
||||
// .style(button::text)
|
||||
// .on_press(AddAdditional("reading".to_string())),
|
||||
// );
|
||||
// }
|
||||
// if !self.word.additional.contains_key("description") {
|
||||
// fast_add = fast_add.push(
|
||||
// button("Описание")
|
||||
// .style(button::text)
|
||||
// .on_press(AddAdditional("description".to_string())),
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// if !self.word.additional.contains_key("context") {
|
||||
// fast_add = fast_add.push(
|
||||
// button("В контексте")
|
||||
// .style(button::text)
|
||||
// .on_press(AddAdditional("context".to_string())),
|
||||
// );
|
||||
// }
|
||||
//
|
||||
// let mut col = iced::widget::column![
|
||||
// column![
|
||||
// text!("Ключ"),
|
||||
// text_input("key", &self.word.key).on_input(SetKey),
|
||||
// ]
|
||||
// .spacing(QUARTER_SPACING),
|
||||
// column![
|
||||
// text!("Значение"),
|
||||
// text_input("value", &self.word.value).on_input(SetValue),
|
||||
// ]
|
||||
// .spacing(QUARTER_SPACING),
|
||||
// column![
|
||||
// text!("Теги"),
|
||||
// text_input("tags", &self.word.tags).on_input(SetTags),
|
||||
// ]
|
||||
// .spacing(QUARTER_SPACING),
|
||||
// rule::horizontal(2),
|
||||
// scrollable(fast_add),
|
||||
// ];
|
||||
//
|
||||
// for more in &self.word.additional {
|
||||
// col = col.push(self.get_view_for_more(more));
|
||||
// }
|
||||
//
|
||||
// back_overlay(
|
||||
// column![
|
||||
// col.spacing(DEFAULT_SPACING / 2.0).width(Fill).height(Fill),
|
||||
// row![
|
||||
// button("Сохранить").style(jl_button).on_press(Save),
|
||||
// button("Удалить").style(danger).on_press(Delete),
|
||||
// ]
|
||||
// .spacing(DEFAULT_SPACING)
|
||||
// ]
|
||||
// .spacing(DEFAULT_SPACING)
|
||||
// .into(),
|
||||
// Back,
|
||||
// )
|
||||
space().into()
|
||||
let mut col = iced::widget::column![
|
||||
column![
|
||||
text!("Ключ"),
|
||||
jl_text_input!("key", &word.key).on_input(SetKey),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Значение"),
|
||||
jl_text_input!("value", &word.value).on_input(SetValue),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Теги"),
|
||||
jl_text_input!("tags", &word.tags).on_input(SetTags),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
rule::horizontal(2),
|
||||
scrollable(fast_add.padding(Padding {
|
||||
top: 0.0,
|
||||
right: 0.0,
|
||||
bottom: 4.0,
|
||||
left: 0.0,
|
||||
}))
|
||||
.horizontal(),
|
||||
];
|
||||
|
||||
for more in &word.additional {
|
||||
col = col.push(self.get_view_for_more(more));
|
||||
}
|
||||
|
||||
column![
|
||||
col.spacing(DEFAULT_SPACING / 2.0).width(Fill).height(Fill),
|
||||
row![
|
||||
horizontal().width(Fill),
|
||||
button("Удалить").style(danger).on_press(Delete),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl WordState {
|
||||
impl<Message: std::clone::Clone> WordEditor<Message> {
|
||||
pub fn new(handle: EntityHandle<WordData>, state: AppState) -> Self {
|
||||
Self{
|
||||
let fields = state
|
||||
.custom_fields
|
||||
.read()
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
Self {
|
||||
state,
|
||||
handle,
|
||||
word_handle: handle,
|
||||
on_delete: None,
|
||||
on_edit: None,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_delete(mut self, message: Message) -> Self {
|
||||
self.on_delete = Some(message);
|
||||
self
|
||||
}
|
||||
pub fn on_edit(mut self, message: Message) -> Self {
|
||||
self.on_edit = Some(message);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl WordState {
|
||||
fn get_view_for_more(&self, value: (&String, &String)) -> Element<'_, WordMessage> {
|
||||
match value.0.as_str() {
|
||||
"reading" => self.reading_field(value.1),
|
||||
"description" => self.description_field(value.1),
|
||||
"context" => self.context_field(value.1),
|
||||
_ => self.additional_field(value.1, value.0.clone(), value.0.clone()),
|
||||
}
|
||||
impl<Message: std::clone::Clone> WordEditor<Message> {
|
||||
fn get_view_for_more(&self, value: (&Id, &String)) -> Element<'_, WordMessage> {
|
||||
let field = self.fields.iter().find(|f| f.id == *value.0).unwrap();
|
||||
self.additional_field(value.1, field.name.as_str(), *value.0)
|
||||
}
|
||||
|
||||
fn reading_field(&self, value: &str) -> Element<'_, WordMessage> {
|
||||
self.additional_field(value, "Чтение слова".to_string(), "reading".to_string())
|
||||
}
|
||||
|
||||
fn description_field(&self, value: &str) -> Element<'_, WordMessage> {
|
||||
self.additional_field(value, "Описание".to_string(), "description".to_string())
|
||||
}
|
||||
|
||||
fn context_field(&self, value: &str) -> Element<'_, WordMessage> {
|
||||
self.additional_field(value, "В контексте".to_string(), "context".to_string())
|
||||
}
|
||||
fn additional_field(&self, value: &str, name: String, id: String) -> Element<'_, WordMessage> {
|
||||
fn additional_field(&self, value: &str, name: &str, id: Id) -> Element<'_, WordMessage> {
|
||||
column![
|
||||
text!("{}", name),
|
||||
row![
|
||||
text_input(id.clone().as_str(), value)
|
||||
.on_input({
|
||||
let value = id.clone();
|
||||
move |string| SetAdditional(value.clone(), string)
|
||||
})
|
||||
jl_text_input!(name, value)
|
||||
.on_input(move |string| SetAdditional(id, string))
|
||||
.width(Fill),
|
||||
button("-")
|
||||
.on_press(RemoveAdditional(id.clone()))
|
||||
.style(danger),
|
||||
button("-").on_press(RemoveAdditional(id)).style(danger),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
]
|
||||
@@ -188,13 +159,11 @@ impl WordState {
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum WordMessage {
|
||||
Save,
|
||||
Back,
|
||||
Delete,
|
||||
SetTags(String),
|
||||
SetKey(String),
|
||||
SetValue(String),
|
||||
AddAdditional(String),
|
||||
RemoveAdditional(String),
|
||||
SetAdditional(String, String),
|
||||
AddAdditional(Id),
|
||||
RemoveAdditional(Id),
|
||||
SetAdditional(Id, String),
|
||||
}
|
||||
+9
-13
@@ -1,4 +1,5 @@
|
||||
use crate::core::kana_set::KanaSet;
|
||||
use crate::jl_button;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::styling::*;
|
||||
@@ -6,7 +7,6 @@ use iced::widget::*;
|
||||
use iced::{Element, Fill, Task, alignment};
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WritingState {
|
||||
kana: String,
|
||||
set: Vec<(String, String)>,
|
||||
@@ -45,12 +45,8 @@ impl NavigatedPage<WritingMessage> for WritingState {
|
||||
text!("{}", self.kana).size(48),
|
||||
self.answers(),
|
||||
row![
|
||||
button(text!("{}", self.next_text))
|
||||
.style(jl_button)
|
||||
.on_press(WritingMessage::Next),
|
||||
button("Закончить")
|
||||
.style(jl_button)
|
||||
.on_press(WritingMessage::Back),
|
||||
jl_button!(text!("{}", self.next_text)).on_press(WritingMessage::Next),
|
||||
jl_button!("Закончить").on_press(WritingMessage::Back),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
]
|
||||
@@ -69,11 +65,11 @@ impl WritingState {
|
||||
let mut list = set.list();
|
||||
list.shuffle(&mut rand::rng());
|
||||
WritingState {
|
||||
kana: "".to_string(),
|
||||
kana: String::new(),
|
||||
set: list.clone(),
|
||||
original_set: list,
|
||||
kana_total: "".to_string(),
|
||||
roman_total: "".to_string(),
|
||||
kana_total: String::new(),
|
||||
roman_total: String::new(),
|
||||
next_text: "Дальше".to_string(),
|
||||
show_all: false,
|
||||
}
|
||||
@@ -83,9 +79,9 @@ impl WritingState {
|
||||
impl WritingState {
|
||||
fn next(&mut self) {
|
||||
if self.set.is_empty() {
|
||||
self.kana = "".to_string();
|
||||
self.roman_total = "".to_string();
|
||||
self.kana_total = "".to_string();
|
||||
self.kana = String::new();
|
||||
self.roman_total = String::new();
|
||||
self.kana_total = String::new();
|
||||
|
||||
self.set = self.original_set.clone();
|
||||
self.set.shuffle(&mut rand::rng());
|
||||
|
||||
+29
-9
@@ -1,7 +1,7 @@
|
||||
use iced::Element;
|
||||
use iced::border::Radius;
|
||||
use iced::widget::button::*;
|
||||
use iced::widget::{button, container};
|
||||
use iced::widget::container;
|
||||
use iced_core::Length::Fill;
|
||||
use iced_core::alignment::Horizontal::Left;
|
||||
use iced_core::{Border, Theme};
|
||||
@@ -14,7 +14,7 @@ pub const BUTTON_RADIUS: f32 = 8.0;
|
||||
|
||||
pub const SETTINGS_ICON: &[u8] = include_bytes!("../settings_icon.svg");
|
||||
|
||||
pub fn jl_button(theme: &Theme, status: Status) -> Style {
|
||||
pub fn jl_button_style(theme: &Theme, status: Status) -> Style {
|
||||
let mut style = primary(theme, status);
|
||||
style.border = Border {
|
||||
color: Default::default(),
|
||||
@@ -23,6 +23,15 @@ pub fn jl_button(theme: &Theme, status: Status) -> Style {
|
||||
};
|
||||
style
|
||||
}
|
||||
|
||||
pub fn jl_text_input_style(
|
||||
theme: &Theme,
|
||||
status: iced::widget::text_input::Status,
|
||||
) -> iced::widget::text_input::Style {
|
||||
let mut style = iced::widget::text_input::default(theme, status);
|
||||
style.border.radius = Radius::new(BUTTON_RADIUS);
|
||||
style
|
||||
}
|
||||
pub fn cta_button(theme: &Theme, status: Status) -> Style {
|
||||
let mut style = secondary(theme, status);
|
||||
style.border.width = 1.0;
|
||||
@@ -30,15 +39,26 @@ pub fn cta_button(theme: &Theme, status: Status) -> Style {
|
||||
style
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! jl_button {
|
||||
($content:expr) => {
|
||||
iced::widget::button($content).style($crate::styling::jl_button_style)
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! jl_text_input {
|
||||
($placeholder:expr, $content:expr) => {
|
||||
iced::widget::text_input($placeholder, $content).style($crate::styling::jl_text_input_style)
|
||||
};
|
||||
}
|
||||
|
||||
pub fn back_overlay<'a, T: Clone + 'a>(content: Element<'a, T>, back_message: T) -> Element<'a, T> {
|
||||
container(
|
||||
iced::widget::column![
|
||||
button("Назад").style(jl_button).on_press(back_message),
|
||||
content
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.align_x(Left)
|
||||
.width(Fill),
|
||||
iced::widget::column![jl_button!("Назад").on_press(back_message), content]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.align_x(Left)
|
||||
.width(Fill),
|
||||
)
|
||||
.center_x(Fill)
|
||||
.padding(10)
|
||||
|
||||
+4
-4
@@ -73,13 +73,13 @@ mod mod_tests {
|
||||
#[test]
|
||||
fn id_0() {
|
||||
let entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, true);
|
||||
assert_eq!(entity.real(), true)
|
||||
assert!(entity.real())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_1() {
|
||||
let entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, false);
|
||||
assert_eq!(entity.real(), false)
|
||||
assert!(!entity.real())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -97,14 +97,14 @@ mod mod_tests {
|
||||
fn id_5() {
|
||||
let mut entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, true);
|
||||
entity.set_real(true);
|
||||
assert_eq!(entity.real(), true)
|
||||
assert!(entity.real())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_6() {
|
||||
let mut entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, false);
|
||||
entity.set_real(true);
|
||||
assert_eq!(entity.real(), true)
|
||||
assert!(entity.real())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
use crate::data::entities::{CustomField, DeckSettings, WordData};
|
||||
use crate::data::Id;
|
||||
use crate::styling::HALF_SPACING;
|
||||
use iced::widget::{button, center, column, rule, text};
|
||||
use iced_core::Alignment::Center;
|
||||
use iced_core::Length::Fill;
|
||||
|
||||
pub fn word_display<'a, T: 'a + Clone>(
|
||||
deck: &DeckSettings,
|
||||
word: &WordData,
|
||||
open: bool,
|
||||
speech_action: T,
|
||||
fields_set: &[CustomField],
|
||||
) -> iced::Element<'a, T> {
|
||||
column![
|
||||
forward_side(deck, word, speech_action.clone(), fields_set),
|
||||
rule::horizontal(2),
|
||||
backward_side(deck, word, speech_action, fields_set, open)
|
||||
]
|
||||
.into()
|
||||
}
|
||||
|
||||
fn forward_side<'a, T: 'a + Clone>(
|
||||
deck: &DeckSettings,
|
||||
word: &WordData,
|
||||
speech_action: T,
|
||||
fields_set: &[CustomField],
|
||||
) -> iced::Element<'a, T> {
|
||||
center(property_draw(
|
||||
deck.forward.as_str(),
|
||||
word,
|
||||
speech_action,
|
||||
fields_set,
|
||||
))
|
||||
.into()
|
||||
}
|
||||
|
||||
fn backward_side<'a, T: 'a + Clone>(
|
||||
deck: &DeckSettings,
|
||||
word: &WordData,
|
||||
speech_action: T,
|
||||
fields_set: &[CustomField],
|
||||
open: bool,
|
||||
) -> iced::Element<'a, T> {
|
||||
if open {
|
||||
return center(property_draw(
|
||||
deck.backward.as_str(),
|
||||
word,
|
||||
speech_action,
|
||||
fields_set,
|
||||
))
|
||||
.into();
|
||||
}
|
||||
center(text!("?").size(72)).width(Fill).height(Fill).into()
|
||||
}
|
||||
|
||||
fn property_draw<'a, T: 'a + Clone>(
|
||||
formula: &str,
|
||||
word: &WordData,
|
||||
speech_action: T,
|
||||
fields_set: &[CustomField],
|
||||
) -> iced::Element<'a, T> {
|
||||
let mut column = column![];
|
||||
let parts = formula.split(" ");
|
||||
println!("{:?}", formula);
|
||||
for part in parts {
|
||||
println!("displaying {}", part);
|
||||
match part {
|
||||
"key" => column = column.push(text!("{}", word.key).align_x(Center).size(48)),
|
||||
"value" => column = column.push(text!("{}", word.value).align_x(Center).size(28)),
|
||||
"tags" => column = column.push(text!("{}", word.tags).align_x(Center).size(28)),
|
||||
"speech" => {
|
||||
column = column.push(button("Воспроизвести").on_press(speech_action.clone()))
|
||||
}
|
||||
_ => {
|
||||
if part == "reading"
|
||||
&& let Some(reading) = word.additional.get(&Id(1))
|
||||
{
|
||||
column = column.push(text!("{}", reading).align_x(Center).size(24));
|
||||
continue
|
||||
}
|
||||
|
||||
if part == "description"
|
||||
&& let Some(description) = word.additional.get(&Id(2))
|
||||
{
|
||||
column = column.push(text!("{}", description).align_x(Center).size(20));
|
||||
continue
|
||||
}
|
||||
|
||||
if part == "context"
|
||||
&& let Some(context) = word.additional.get(&Id(3))
|
||||
{
|
||||
column = column.push(text!("{}", context).align_x(Center).size(24));
|
||||
continue
|
||||
}
|
||||
|
||||
let field_id = fields_set.iter().find(|f| f.identifier == part);
|
||||
if let Some(id) = field_id
|
||||
&& let Some(custom) = word.additional.get(&id.id)
|
||||
{
|
||||
column = column.push(text!("{}", custom).align_x(Center).size(24))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
column.align_x(Center).spacing(HALF_SPACING).into()
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
use iced_core::widget::{tree, Operation, Tree};
|
||||
use iced_core::{
|
||||
layout, mouse, overlay, renderer, touch, Clipboard, Element, Event, Layout, Length, Point,
|
||||
Rectangle, Shell, Size, Vector, Widget,
|
||||
};
|
||||
|
||||
pub fn hard_mouse_area<'a, Message, Theme, Renderer>(
|
||||
widget: impl Into<Element<'a, Message, Theme, Renderer>>,
|
||||
) -> HardMouseArea<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: iced_core::Renderer,
|
||||
{
|
||||
HardMouseArea::new(widget)
|
||||
}
|
||||
|
||||
pub struct HardMouseArea<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> {
|
||||
content: Element<'a, Message, Theme, Renderer>,
|
||||
on_press: Option<Message>,
|
||||
on_release: Option<Message>,
|
||||
on_double_click: Option<Message>,
|
||||
on_right_press: Option<Message>,
|
||||
on_right_release: Option<Message>,
|
||||
on_middle_press: Option<Message>,
|
||||
on_middle_release: Option<Message>,
|
||||
on_scroll: Option<Box<dyn Fn(mouse::ScrollDelta) -> Message + 'a>>,
|
||||
on_enter: Option<Message>,
|
||||
on_move: Option<Box<dyn Fn(Point) -> Message + 'a>>,
|
||||
on_exit: Option<Message>,
|
||||
interaction: Option<mouse::Interaction>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> HardMouseArea<'a, Message, Theme, Renderer> {
|
||||
/// The message to emit on a left button press.
|
||||
#[must_use]
|
||||
pub fn on_press(mut self, message: Message) -> Self {
|
||||
self.on_press = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit on a left button release.
|
||||
#[must_use]
|
||||
pub fn on_release(mut self, message: Message) -> Self {
|
||||
self.on_release = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit on a double click.
|
||||
///
|
||||
/// If you use this with [`on_press`]/[`on_release`], those
|
||||
/// event will be emit as normal.
|
||||
///
|
||||
/// The events stream will be: on_press -> on_release -> on_press
|
||||
/// -> on_double_click -> on_release -> on_press ...
|
||||
///
|
||||
/// [`on_press`]: Self::on_press
|
||||
/// [`on_release`]: Self::on_release
|
||||
#[must_use]
|
||||
pub fn on_double_click(mut self, message: Message) -> Self {
|
||||
self.on_double_click = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit on a right button press.
|
||||
#[must_use]
|
||||
pub fn on_right_press(mut self, message: Message) -> Self {
|
||||
self.on_right_press = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit on a right button release.
|
||||
#[must_use]
|
||||
pub fn on_right_release(mut self, message: Message) -> Self {
|
||||
self.on_right_release = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit on a middle button press.
|
||||
#[must_use]
|
||||
pub fn on_middle_press(mut self, message: Message) -> Self {
|
||||
self.on_middle_press = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit on a middle button release.
|
||||
#[must_use]
|
||||
pub fn on_middle_release(mut self, message: Message) -> Self {
|
||||
self.on_middle_release = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit when scroll wheel is used
|
||||
#[must_use]
|
||||
pub fn on_scroll(mut self, on_scroll: impl Fn(mouse::ScrollDelta) -> Message + 'a) -> Self {
|
||||
self.on_scroll = Some(Box::new(on_scroll));
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit when the mouse enters the area.
|
||||
#[must_use]
|
||||
pub fn on_enter(mut self, message: Message) -> Self {
|
||||
self.on_enter = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit when the mouse moves in the area.
|
||||
#[must_use]
|
||||
pub fn on_move(mut self, on_move: impl Fn(Point) -> Message + 'a) -> Self {
|
||||
self.on_move = Some(Box::new(on_move));
|
||||
self
|
||||
}
|
||||
|
||||
/// The message to emit when the mouse exits the area.
|
||||
#[must_use]
|
||||
pub fn on_exit(mut self, message: Message) -> Self {
|
||||
self.on_exit = Some(message);
|
||||
self
|
||||
}
|
||||
|
||||
/// The [`mouse::Interaction`] to use when hovering the area.
|
||||
#[must_use]
|
||||
pub fn interaction(mut self, interaction: mouse::Interaction) -> Self {
|
||||
self.interaction = Some(interaction);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Local state of the [`HardMouseArea`].
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
is_hovered: bool,
|
||||
bounds: Rectangle,
|
||||
cursor_position: Option<Point>,
|
||||
previous_click: Option<mouse::Click>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> HardMouseArea<'a, Message, Theme, Renderer> {
|
||||
/// Creates a [`HardMouseArea`] with the given content.
|
||||
pub fn new(content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
|
||||
HardMouseArea {
|
||||
content: content.into(),
|
||||
on_press: None,
|
||||
on_release: None,
|
||||
on_double_click: None,
|
||||
on_right_press: None,
|
||||
on_right_release: None,
|
||||
on_middle_press: None,
|
||||
on_middle_release: None,
|
||||
on_scroll: None,
|
||||
on_enter: None,
|
||||
on_move: None,
|
||||
on_exit: None,
|
||||
interaction: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for HardMouseArea<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Renderer: renderer::Renderer,
|
||||
Message: Clone,
|
||||
{
|
||||
fn size(&self) -> Size<Length> {
|
||||
self.content.as_widget().size()
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.layout(&mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
renderer_style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
self.content.as_widget().draw(
|
||||
&tree.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
renderer_style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<State>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(State::default())
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.content)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
tree.diff_children(std::slice::from_ref(&self.content));
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn Operation,
|
||||
) {
|
||||
self.content
|
||||
.as_widget_mut()
|
||||
.operate(&mut tree.children[0], layout, renderer, operation);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
if self.on_move.is_none()
|
||||
&& let Event::Mouse(mouse::Event::CursorMoved { .. }) = event
|
||||
{
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
if self.on_enter.is_none()
|
||||
&& let Event::Mouse(mouse::Event::CursorEntered) = event
|
||||
{
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
if self.on_exit.is_none()
|
||||
&& let Event::Mouse(mouse::Event::CursorLeft) = event
|
||||
{
|
||||
self.content.as_widget_mut().update(
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
if shell.is_event_captured() {
|
||||
return;
|
||||
}
|
||||
|
||||
update(self, tree, event, layout, cursor, shell);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let content_interaction = self.content.as_widget().mouse_interaction(
|
||||
&tree.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
);
|
||||
|
||||
match (self.interaction, content_interaction) {
|
||||
(Some(interaction), mouse::Interaction::None) if cursor.is_over(layout.bounds()) => {
|
||||
interaction
|
||||
}
|
||||
_ => content_interaction,
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay<'b>(
|
||||
&'b mut self,
|
||||
tree: &'b mut Tree,
|
||||
layout: Layout<'b>,
|
||||
renderer: &Renderer,
|
||||
viewport: &Rectangle,
|
||||
translation: Vector,
|
||||
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
|
||||
self.content.as_widget_mut().overlay(
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
viewport,
|
||||
translation,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer> From<HardMouseArea<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a + Clone,
|
||||
Theme: 'a,
|
||||
Renderer: 'a + renderer::Renderer,
|
||||
{
|
||||
fn from(
|
||||
area: HardMouseArea<'a, Message, Theme, Renderer>,
|
||||
) -> Element<'a, Message, Theme, Renderer> {
|
||||
Element::new(area)
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes the given [`Event`] and updates the [`State`] of an [`HardMouseArea`]
|
||||
/// accordingly.
|
||||
fn update<Message: Clone, Theme, Renderer>(
|
||||
widget: &mut HardMouseArea<'_, Message, Theme, Renderer>,
|
||||
tree: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
let state: &mut State = tree.state.downcast_mut();
|
||||
|
||||
let cursor_position = cursor.position();
|
||||
let bounds = layout.bounds();
|
||||
|
||||
if state.cursor_position != cursor_position || state.bounds != bounds {
|
||||
let was_hovered = state.is_hovered;
|
||||
|
||||
state.is_hovered = cursor.is_over(layout.bounds());
|
||||
state.cursor_position = cursor_position;
|
||||
state.bounds = bounds;
|
||||
|
||||
match (
|
||||
widget.on_enter.as_ref(),
|
||||
widget.on_move.as_ref(),
|
||||
widget.on_exit.as_ref(),
|
||||
) {
|
||||
(Some(on_enter), _, _) if state.is_hovered && !was_hovered => {
|
||||
shell.publish(on_enter.clone());
|
||||
}
|
||||
(_, Some(on_move), _) if state.is_hovered => {
|
||||
if let Some(position) = cursor.position_in(layout.bounds()) {
|
||||
shell.publish(on_move(position));
|
||||
}
|
||||
}
|
||||
(_, _, Some(on_exit)) if !state.is_hovered && was_hovered => {
|
||||
shell.publish(on_exit.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !cursor.is_over(layout.bounds()) {
|
||||
return;
|
||||
}
|
||||
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
|
||||
| Event::Touch(touch::Event::FingerPressed { .. }) => {
|
||||
if let Some(message) = widget.on_press.as_ref() {
|
||||
shell.publish(message.clone());
|
||||
shell.capture_event();
|
||||
}
|
||||
|
||||
if let Some(position) = cursor_position
|
||||
&& let Some(message) = widget.on_double_click.as_ref()
|
||||
{
|
||||
let new_click =
|
||||
mouse::Click::new(position, mouse::Button::Left, state.previous_click);
|
||||
|
||||
if new_click.kind() == mouse::click::Kind::Double {
|
||||
shell.publish(message.clone());
|
||||
}
|
||||
|
||||
state.previous_click = Some(new_click);
|
||||
|
||||
// Even if this is not a double click, but the press is nevertheless
|
||||
// processed by us and should not be popup to parent widgets.
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
|
||||
| Event::Touch(touch::Event::FingerLifted { .. }) => {
|
||||
if let Some(message) = widget.on_release.as_ref() {
|
||||
shell.publish(message.clone());
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)) => {
|
||||
if let Some(message) = widget.on_right_press.as_ref() {
|
||||
shell.publish(message.clone());
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Right)) => {
|
||||
if let Some(message) = widget.on_right_release.as_ref() {
|
||||
shell.publish(message.clone());
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Middle)) => {
|
||||
if let Some(message) = widget.on_middle_press.as_ref() {
|
||||
shell.publish(message.clone());
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Middle)) => {
|
||||
if let Some(message) = widget.on_middle_release.as_ref() {
|
||||
shell.publish(message.clone());
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
|
||||
if let Some(on_scroll) = widget.on_scroll.as_ref() {
|
||||
shell.publish(on_scroll(*delta));
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod hard_mouse_area;
|
||||
pub mod card_display;
|
||||
Reference in new issue
Block a user