Author SHA1 Message Date
micialware 3ac7cd068b Rename methods 2026-08-30 19:22:28 +03:00
micialware b006ece0c1 Clear code and add shifts into Query 2026-08-29 23:15:22 +03:00
micialware ea214d8ac0 Change connection type from Mutex to RwLock 2026-08-29 23:10:57 +03:00
micialware 4b17a5a4a7 Fix incorrect handle_by_id 2026-08-29 22:50:18 +03:00
micialware 2c1163fc3b Compress EntityHandle 2026-08-29 22:41:11 +03:00
micialware d8e3a5b6db Load code fixed 2026-08-28 17:15:16 +03:00
micialware a01a29c492 Query manager code 2026-08-28 16:52:48 +03:00
micialware 70aff6ed18 Better query code 2026-08-27 14:51:35 +03:00
micialware 89aa1abc13 Query partial code 2026-08-27 14:05:05 +03:00
micialware 0f2090af77 Test update, repo update 2026-08-27 09:21:16 +03:00
micialware 0326b56ded Update save_many 2026-08-26 23:55:24 +03:00
micialware 3eba0c93d4 save_many code 2026-08-26 19:48:22 +03:00
micialware d99fd337da More repo code 2026-08-26 17:53:09 +03:00
micialware 807f398d81 First repo code 2026-08-25 15:46:39 +03:00
micialware 1f3ad22e05 Merge pull request 'Data provider refactor' (#11) from data-provider-refactor into master
Reviewed-on: https://gitea.micialware.ru/micialware/jap_learn/pulls/11
2026-08-25 12:21:54 +03:00
micialware 10cf7f0d2e Formatting 2026-08-25 12:04:07 +03:00
micialware dddac01bdf Fix compression bug 2026-08-25 01:05:15 +03:00
micialware 1d24fe2631 Finishing deunprap 2026-08-24 23:48:00 +03:00
micialware a60ed37cd4 Introduce MaybeError type 2026-08-24 23:42:58 +03:00
micialware d836b57d2a Remove more unwrap 2026-08-24 23:27:24 +03:00
micialware b5b1eb768c remove more unwrap 2026-08-24 23:10:23 +03:00
micialware 5a6747030b Rewrite words and groups into result 2026-08-24 18:46:54 +03:00
micialware c56d135ce8 More web-api notifications 2026-08-24 18:27:32 +03:00
micialware 6f8adde06b Rewrite settings to result 2026-08-24 18:23:29 +03:00
micialware 8841a51897 Rewrite fully second db table into result 2026-08-24 18:16:41 +03:00
micialware 06bf9138c0 First database deunwrap 2026-08-24 17:33:21 +03:00
micialware 3cbdf0803b Remove Option for vecs in repetitions 2026-08-24 13:15:49 +03:00
micialware d261a08932 Remove unused import 2026-08-24 11:41:20 +03:00
micialware 92ca42869c Extract all entities to entities.rs 2026-08-24 11:40:31 +03:00
micialware c67663141f Full split of lang.rs 2026-08-24 11:35:37 +03:00
micialware 22b455a640 Splitting to deck and srs 2026-08-24 01:37:00 +03:00
micialware c74a0eb311 Splitting kana set 2026-08-24 01:22:00 +03:00
micialware 36e5693564 Simple srs refactoring 2026-08-24 00:29:41 +03:00
micialware 42c9a5095a Remove unused import 2026-08-23 22:48:46 +03:00
micialware 0baf6cadf7 Migrate to structured logging 2026-08-23 22:48:00 +03:00
micialware 0367d5001b Remove ensure db 2026-08-23 22:22:26 +03:00
micialware 3fcfe95720 More notifications 2026-08-23 22:16:02 +03:00
micialware f113d2b3d7 Change notification layout 2026-08-23 22:05:08 +03:00
micialware 5a926b1419 More notifications and move start code to another file 2026-08-23 21:49:01 +03:00
micialware e1bfd9494d Notification base 2026-08-23 21:00:48 +03:00
micialware dfaff30efa Return par_iter 2026-08-23 00:32:43 +03:00
micialware 163ebc44a5 Fix id eval filter bug 2026-08-23 00:01:57 +03:00
micialware d42d618066 Merge pull request 'Repetitions remake' (#1) from repetitions-remake into master
Reviewed-on: https://gitea.micialware.ru/micialware/jap_learn/pulls/1
2026-08-20 19:48:19 +03:00
micialware 1406fc8f21 Change TEXT to INTEGER in card_stats 2026-08-20 18:53:13 +03:00
micialware e8c9e37ca1 Fix semirandom srs bug 2026-08-20 18:27:05 +03:00
micialware c5c1f34e1c Fix history bug 2026-08-20 18:18:14 +03:00
micialware 9456eec2af Rename DictionaryTest to DictionaryQuiz 2026-08-20 17:48:03 +03:00
micialware c9508922f4 Gitignore update for macOS 2026-08-20 16:25:41 +03:00
micialware 878ff3f1e4 Formatting 2026-08-20 16:23:22 +03:00
micialware 3f43676580 Fix deck data collecting 2026-08-20 16:22:38 +03:00
micialware c5e91b844c found bug in random srs 2026-08-20 11:17:51 +03:00
micialware 01ba0567f5 Change version 2026-08-20 00:55:20 +03:00
micialware 44644500b5 Fix repetition display bug and history find bug 2026-08-20 00:49:49 +03:00
micialware 3661173bb0 Final code cleanup 2026-08-20 00:42:06 +03:00
micialware ac1b516a88 Fixing Into<u32> clippy 2026-08-20 00:18:16 +03:00
micialware 66f8a83dec Migrate to parking_lot 2026-08-20 00:07:09 +03:00
micialware bf805b79e5 Formating with fmt 2026-08-19 23:51:41 +03:00
micialware de2dbaf6c1 Remove silent unwrap in data providers 2026-08-19 23:37:59 +03:00
micialware 01f0999772 Remove many unwrap 2026-08-19 19:21:21 +03:00
micialware 39f8845119 Rewrite for dictionary rw indexer 2026-08-19 18:49:32 +03:00
micialware e7023752f1 Rewrite for dictionary indexer 2026-08-19 18:00:03 +03:00
micialware 746071125a Remove unnecessary into() 2026-08-19 17:39:52 +03:00
micialware bb673ed7c7 Remove debug from repetitions.rs 2026-08-19 17:34:48 +03:00
micialware 98c8093961 Fixing some code problems 2026-08-19 17:33:22 +03:00
micialware a4d77196d0 Small code edit 2026-08-18 17:47:37 +03:00
micialware 4187344a29 Filter check on edit page 2026-08-18 17:45:50 +03:00
micialware d3c28179b6 Use is_valid for Id 2026-08-18 17:31:19 +03:00
micialware 3cd7c12baa Fixing bugs 2026-08-18 17:15:03 +03:00
micialware 306febc514 Rename set to deck in repetitions.rs 2026-08-18 15:16:51 +03:00
micialware 80785ff9e6 Rewrite repetitions page 2026-08-18 15:13:10 +03:00
micialware 9e28b05167 More migration code 2026-08-18 12:58:02 +03:00
micialware 97c76350e1 Migrate to Id type 2026-08-18 12:47:06 +03:00
micialware 99b3818181 Rename and clear bad code 2026-08-18 12:14:35 +03:00
micialware 3fcbd235cf Migrate to hashbrown structures 2026-08-16 23:50:14 +03:00
micialware dcf7352553 Fix windows autofetch 2026-08-16 23:42:56 +03:00
micialware 11b38479c1 Fixing partial adding bug 2026-08-16 14:23:00 +03:00
micialware 51c8d7be74 Adding words by parts 2026-08-15 21:32:24 +03:00
micialware 8f789facd7 Add anki21 format and fix multi import bug 2026-08-15 20:16:48 +03:00
micialware e676898135 Clippy code cleanup 2026-08-15 13:22:59 +03:00
47 changed files with 4242 additions and 2161 deletions

No files matched your search

Generated
+203 -16
View File
@@ -73,6 +73,12 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]] [[package]]
name = "alsa" name = "alsa"
version = "0.11.0" version = "0.11.0"
@@ -146,12 +152,56 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]] [[package]]
name = "anstyle" name = "anstyle"
version = "1.0.14" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.101" version = "1.0.101"
@@ -722,6 +772,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]] [[package]]
name = "combine" name = "combine"
version = "4.6.7" version = "4.6.7"
@@ -1010,7 +1066,7 @@ dependencies = [
"cosmic-text", "cosmic-text",
"etagere", "etagere",
"lru", "lru",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"wgpu", "wgpu",
] ]
@@ -1062,6 +1118,37 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2" checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
[[package]]
name = "defmt"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"
dependencies = [
"bitflags 1.3.2",
"defmt-macros",
]
[[package]]
name = "defmt-macros"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"
dependencies = [
"defmt-parser",
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]]
name = "defmt-parser"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
dependencies = [
"thiserror 2.0.18",
]
[[package]] [[package]]
name = "deranged" name = "deranged"
version = "0.5.8" version = "0.5.8"
@@ -1209,6 +1296,29 @@ dependencies = [
"syn 2.0.114", "syn 2.0.114",
] ]
[[package]]
name = "env_filter"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"jiff",
"log",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@@ -1750,6 +1860,8 @@ version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
dependencies = [ dependencies = [
"allocator-api2",
"equivalent",
"foldhash 0.2.0", "foldhash 0.2.0",
] ]
@@ -1962,7 +2074,7 @@ dependencies = [
"lilt", "lilt",
"log", "log",
"num-traits", "num-traits",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"smol_str", "smol_str",
"thiserror 2.0.18", "thiserror 2.0.18",
"web-time", "web-time",
@@ -1988,7 +2100,7 @@ dependencies = [
"futures", "futures",
"iced_core", "iced_core",
"log", "log",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"tokio", "tokio",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"wasmtimer", "wasmtimer",
@@ -2008,7 +2120,7 @@ dependencies = [
"iced_futures", "iced_futures",
"log", "log",
"raw-window-handle", "raw-window-handle",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"thiserror 2.0.18", "thiserror 2.0.18",
"unicode-segmentation", "unicode-segmentation",
] ]
@@ -2062,7 +2174,7 @@ dependencies = [
"kurbo 0.10.4", "kurbo 0.10.4",
"log", "log",
"resvg", "resvg",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"softbuffer", "softbuffer",
"tiny-skia", "tiny-skia",
] ]
@@ -2083,7 +2195,7 @@ dependencies = [
"iced_graphics", "iced_graphics",
"log", "log",
"resvg", "resvg",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"thiserror 2.0.18", "thiserror 2.0.18",
"wgpu", "wgpu",
] ]
@@ -2098,7 +2210,7 @@ dependencies = [
"log", "log",
"num-traits", "num-traits",
"ouroboros", "ouroboros",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"thiserror 2.0.18", "thiserror 2.0.18",
"unicode-segmentation", "unicode-segmentation",
] ]
@@ -2113,7 +2225,7 @@ dependencies = [
"iced_program", "iced_program",
"log", "log",
"mundy", "mundy",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"thiserror 2.0.18", "thiserror 2.0.18",
"tracing", "tracing",
"wasm-bindgen-futures", "wasm-bindgen-futures",
@@ -2284,6 +2396,12 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]] [[package]]
name = "itertools" name = "itertools"
version = "0.13.0" version = "0.13.0"
@@ -2301,22 +2419,27 @@ checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]] [[package]]
name = "jap_learn" name = "jap_learn"
version = "0.1.2" version = "0.1.3"
dependencies = [ dependencies = [
"chrono", "chrono",
"criterion", "criterion",
"dirs", "dirs",
"env_logger",
"hashbrown 0.17.1",
"hex", "hex",
"iced", "iced",
"iced_core", "iced_core",
"log",
"mimalloc", "mimalloc",
"parking_lot",
"rand", "rand",
"rayon",
"reqwest", "reqwest",
"rfd", "rfd",
"rhai", "rhai",
"rodio", "rodio",
"rusqlite", "rusqlite",
"serde", "rustc-hash 2.1.3",
"serde_json", "serde_json",
"sha2", "sha2",
"tokio", "tokio",
@@ -2324,6 +2447,42 @@ dependencies = [
"zstd", "zstd",
] ]
[[package]]
name = "jiff"
version = "0.2.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc"
dependencies = [
"defmt",
"jiff-core",
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
]
[[package]]
name = "jiff-core"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09"
dependencies = [
"defmt",
]
[[package]]
name = "jiff-static"
version = "0.2.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 2.0.114",
]
[[package]] [[package]]
name = "jni" name = "jni"
version = "0.21.1" version = "0.21.1"
@@ -2574,9 +2733,9 @@ dependencies = [
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.29" version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]] [[package]]
name = "lru" name = "lru"
@@ -2783,6 +2942,15 @@ dependencies = [
"jni-sys 0.3.0", "jni-sys 0.3.0",
] ]
[[package]]
name = "no-std-compat"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b93853da6d84c2e3c7d730d6473e8817692dd89be387eb01b94d7f108ecb5b8c"
dependencies = [
"spin",
]
[[package]] [[package]]
name = "num-bigint" name = "num-bigint"
version = "0.4.6" version = "0.4.6"
@@ -3290,6 +3458,12 @@ dependencies = [
"portable-atomic", "portable-atomic",
] ]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]] [[package]]
name = "oorandom" name = "oorandom"
version = "11.1.5" version = "11.1.5"
@@ -3662,7 +3836,7 @@ dependencies = [
"pin-project-lite", "pin-project-lite",
"quinn-proto", "quinn-proto",
"quinn-udp", "quinn-udp",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"rustls", "rustls",
"socket2", "socket2",
"thiserror 2.0.18", "thiserror 2.0.18",
@@ -3684,7 +3858,7 @@ dependencies = [
"rand", "rand",
"rand_pcg", "rand_pcg",
"ring", "ring",
"rustc-hash 2.1.1", "rustc-hash 2.1.3",
"rustls", "rustls",
"rustls-pki-types", "rustls-pki-types",
"slab", "slab",
@@ -3986,6 +4160,7 @@ checksum = "dd4dd0f8c36625202a4ba553c416c19b719947cd2a31d1bda06126e4a5727daf"
dependencies = [ dependencies = [
"ahash", "ahash",
"bitflags 2.10.0", "bitflags 2.10.0",
"no-std-compat",
"num-traits", "num-traits",
"once_cell", "once_cell",
"rhai_codegen", "rhai_codegen",
@@ -4082,9 +4257,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"
version = "2.1.1" version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
@@ -4582,6 +4757,12 @@ dependencies = [
"x11rb", "x11rb",
] ]
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]] [[package]]
name = "spirv" name = "spirv"
version = "0.3.0+sdk-1.3.268.0" version = "0.3.0+sdk-1.3.268.0"
@@ -5364,6 +5545,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.20.0" version = "1.20.0"
+14 -7
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "jap_learn" name = "jap_learn"
version = "0.1.2" version = "0.1.3"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
@@ -8,9 +8,8 @@ iced = { version = "0.14.0", features = ["tokio", "svg", "lazy"]}
iced_core = "0.14.0" iced_core = "0.14.0"
rand = "0.10.2" rand = "0.10.2"
dirs = "6.0.0" dirs = "6.0.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151" serde_json = "1.0.151"
rhai = "1.25.1" rhai = { version = "1.25.1", features = ["sync"] }
chrono = "0.4.45" chrono = "0.4.45"
rusqlite = { version = "0.40.2", features = ["chrono", "bundled"] } rusqlite = { version = "0.40.2", features = ["chrono", "bundled"] }
reqwest = { version = "0.13.4", features = ["json", "stream", "multipart"] } reqwest = { version = "0.13.4", features = ["json", "stream", "multipart"] }
@@ -22,6 +21,11 @@ zstd = "0.13.3"
zip = "8.6.0" zip = "8.6.0"
rfd = "0.17.2" rfd = "0.17.2"
mimalloc = "0.1.52" mimalloc = "0.1.52"
hashbrown = "0.17.1"
rayon = "1.12.0"
parking_lot = "0.12.5"
env_logger = "0.11.11"
log = "0.4.34"
[profile.super-release] [profile.super-release]
inherits = "release" inherits = "release"
@@ -32,10 +36,13 @@ strip = true
panic = "abort" panic = "abort"
[dev-dependencies] [dev-dependencies]
criterion = "0.8.2" criterion = { version = "0.8.2", features = ["html_reports"] }
rustc-hash = "2.1.3"
[[bench]] [[bench]]
name = "split_bench" # Имя файла в benches/ без расширения name = "map_bench"
harness = false # Отключаем стандартный тестовый раннер harness = false
[[bench]]
name = "repo_cache_bench"
harness = false
+126
View File
@@ -0,0 +1,126 @@
use criterion::{Criterion, criterion_group, criterion_main};
use std::collections::HashMap as StdHashMap;
use std::hint::black_box;
use hashbrown::HashMap as BrownHashMap;
const SIZES: [usize; 3] = [5, 10, 50];
const QUERY_COUNT: usize = 4096;
/// Детерминированный ключ ~17 символов, например "key_9e3779b9_0042".
fn make_key(i: u64) -> String {
let h = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
format!("key_{:08x}_{:04}", h & 0xFFFF_FFFF, i)
}
// Для длинных ключей (пути/URL) замени на:
// fn make_key(i: u64) -> String {
// format!(
// "/api/v2/users/{i}/settings/visibility_{:08x}",
// i.wrapping_mul(0x9E37_79B9)
// )
// }
fn make_vec(n: usize) -> Vec<(String, u64)> {
(0..n as u64).map(|i| (make_key(i), i)).collect()
}
fn make_std_map(data: &[(String, u64)]) -> StdHashMap<String, u64> {
data.iter().map(|(k, v)| (k.clone(), *v)).collect()
}
fn make_brown_map(data: &[(String, u64)]) -> BrownHashMap<String, u64> {
data.iter().map(|(k, v)| (k.clone(), *v)).collect()
}
fn make_queries(n: usize, with_misses: bool) -> Vec<String> {
let keys: Vec<String> = (0..n as u64).map(make_key).collect();
let missing = "__missing_key__".to_string();
(0..QUERY_COUNT)
.map(|i| {
if with_misses && i % 16 == 15 {
missing.clone()
} else {
let idx = i.wrapping_mul(2_654_435_761) % n;
keys[idx].clone()
}
})
.collect()
}
fn lookup_std(map: &StdHashMap<String, u64>, queries: &[String]) -> u64 {
let mut sum = 0u64;
for q in queries {
match map.get(black_box(q.as_str())) {
Some(v) => sum = sum.wrapping_add(*v),
None => sum = sum.wrapping_add(1),
}
}
black_box(sum)
}
fn lookup_brown(map: &BrownHashMap<String, u64>, queries: &[String]) -> u64 {
let mut sum = 0u64;
for q in queries {
match map.get(black_box(q.as_str())) {
Some(v) => sum = sum.wrapping_add(*v),
None => sum = sum.wrapping_add(1),
}
}
black_box(sum)
}
fn lookup_vec(data: &[(String, u64)], queries: &[String]) -> u64 {
let mut sum = 0u64;
for q in queries {
let q = black_box(q);
match data.iter().find(|(k, _)| k == q) {
Some((_, v)) => sum = sum.wrapping_add(*v),
None => sum = sum.wrapping_add(1),
}
}
black_box(sum)
}
fn bench(c: &mut Criterion) {
let mut group = c.benchmark_group("map_vs_vec_str");
for n in SIZES {
let vec_data = make_vec(n);
let std_map = make_std_map(&vec_data);
let brown_map = make_brown_map(&vec_data);
let queries_hit = make_queries(n, false);
let queries_mixed = make_queries(n, true);
// std::collections::HashMap (SipHash)
group.bench_function(format!("std_hashmap_hit/{n}"), |b| {
b.iter(|| lookup_std(black_box(&std_map), black_box(&queries_hit)))
});
group.bench_function(format!("std_hashmap_mixed/{n}"), |b| {
b.iter(|| lookup_std(black_box(&std_map), black_box(&queries_mixed)))
});
// hashbrown (SwissTable + foldhash)
group.bench_function(format!("hashbrown_hit/{n}"), |b| {
b.iter(|| lookup_brown(black_box(&brown_map), black_box(&queries_hit)))
});
group.bench_function(format!("hashbrown_mixed/{n}"), |b| {
b.iter(|| lookup_brown(black_box(&brown_map), black_box(&queries_mixed)))
});
// Vec<(String, u64)>, линейный поиск
group.bench_function(format!("vec_linear_hit/{n}"), |b| {
b.iter(|| lookup_vec(black_box(&vec_data), black_box(&queries_hit)))
});
group.bench_function(format!("vec_linear_mixed/{n}"), |b| {
b.iter(|| lookup_vec(black_box(&vec_data), black_box(&queries_mixed)))
});
}
group.finish();
}
criterion_group!(benches, bench);
criterion_main!(benches);
+325
View File
@@ -0,0 +1,325 @@
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);
-43
View File
@@ -1,43 +0,0 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
fn bench_split(c: &mut Criterion) {
let input = "data_1";
c.bench_function("split_with_comma", |b| {
b.iter(|| {
// black_box запрещает компилятору оптимизировать результат
black_box(split_with_coma(black_box(input)))
})
});
}
fn bench_split_new(c: &mut Criterion) {
let input = "data_1";
c.bench_function("split_with_comma gpt", |b| {
b.iter(|| {
// black_box запрещает компилятору оптимизировать результат
black_box(split_with_coma(black_box(input)))
})
});
}
pub fn split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|ts| ts.to_lowercase().trim().to_string())
.filter(|t| !t.is_empty())
.collect::<Vec<String>>()
}
pub fn new_split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|s| s.trim()) // 0 аллокаций, просто срез
.filter(|s| !s.is_empty()) // отбрасываем пустые до аллокации
.map(|s| s.to_lowercase()) // 1 аллокация на валидный токен
.collect()
}
// Можно добавить несколько бенчмарков в группу
criterion_group!(benches, bench_split, bench_split_new);
criterion_main!(benches);
+2 -2
View File
@@ -5,9 +5,9 @@ create table card_stats
word_id INTEGER not null word_id INTEGER not null
references words references words
on delete cascade, on delete cascade,
set_id TEXT not null set_id INTEGER not null
references card_set references card_set
on delete cascade, on delete cascade,
score INTEGER default 1 not null, score INTEGER default 1 not null,
last_opened integer not null last_opened INTEGER not null
); );
+113
View File
@@ -0,0 +1,113 @@
use crate::data::Id;
use crate::data::entities::DeckSettings;
use crate::data::entities::{WordData, WordGroup};
use crate::data_provider::card_sets::load_sets;
use crate::data_provider::settings::get_setting;
use crate::data_provider::sqlite::default_connection;
use crate::data_provider::words::{load_word_groups, load_words};
use crate::navigation::RootMessage::Keyboard;
use crate::navigation::{AppSettings, RootMessage, ScreenState};
use chrono::NaiveDate;
use hashbrown::HashMap;
use iced::{Subscription, keyboard, window};
use iced_core::window::Position;
#[cfg(target_os = "linux")]
use iced_core::window::settings::PlatformSpecific;
use iced_core::{Font, Size, Theme};
use log::info;
use rusqlite::Connection;
pub const USER_FONT: Font = Font::with_name("Noto Sans JP");
pub fn start() -> iced::Result {
info!("Welcome to JapLearn");
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view)
.window(window_settings())
.subscription(subscription)
.title("JapLearn")
.settings(iced::Settings {
default_text_size: iced::Pixels(18.0),
..iced::Settings::default()
})
.font(include_bytes!("../noto.ttf"))
.default_font(USER_FONT)
.theme(Theme::GruvboxDark)
.run()
}
#[allow(unused_mut)]
fn window_settings() -> window::Settings {
let mut settings = window::Settings {
position: Position::Centered,
min_size: Some(Size::new(700.0_f32, 700.0_f32)),
..Default::default()
};
#[cfg(target_os = "linux")]
{
settings.platform_specific = PlatformSpecific {
application_id: "JapLearn".to_string(),
override_redirect: false,
};
}
settings
}
fn subscription(_state: &ScreenState) -> Subscription<RootMessage> {
keyboard::listen().map(Keyboard)
}
pub struct AppState {
pub dictionary: Vec<WordData>,
pub decks: Vec<DeckSettings>,
pub word_groups: Vec<WordGroup>,
pub connection: Connection,
pub sync_data: AppSettings,
pub activity: HashMap<Id, Vec<(NaiveDate, u32)>>,
}
impl Default for AppState {
fn default() -> Self {
Self::new()
}
}
impl AppState {
pub fn new() -> Self {
Self {
dictionary: vec![],
decks: vec![],
word_groups: vec![],
connection: default_connection(),
sync_data: AppSettings {
key: None,
auto_web_fetch: false,
},
activity: Default::default(),
}
}
}
pub fn fill_state(state: &mut AppState) {
let list = load_words(&state.connection);
let sets = load_sets(&state.connection);
let groups = load_word_groups(&state.connection);
let setting = load_settings(&state.connection);
state.dictionary = list.unwrap_or_default();
state.decks = sets.unwrap_or_default();
state.word_groups = groups.unwrap_or_default();
state.sync_data = setting
}
fn load_settings(connection: &Connection) -> AppSettings {
let key = get_setting("SYNC_KEY".to_string(), connection);
let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection)
.unwrap_or("false".to_string())
.parse::<bool>()
.unwrap();
AppSettings {
key,
auto_web_fetch: fetch,
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod deck;
pub mod kana_set;
pub mod srs;
+121
View File
@@ -0,0 +1,121 @@
use crate::app::AppState;
use crate::core::srs::{
OrderMode, OrderModule, RandomSRSModule, SRSModule, SemiRandomSRSModule, WordOpenMode,
WorstWordsSRSModule,
};
use crate::data::entities::*;
use crate::data_provider::card_stats::{load_stats_of_deck, update_stat_score};
use crate::data_provider::history::push_note;
use crate::notification::{MaybeError, NotificationData};
use chrono::Utc;
use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Clone)]
pub struct DeckData {
pub(crate) words: Vec<WordData>,
pub(crate) set: Vec<CardStatistics>,
current_word_index: Option<usize>,
state: Arc<Mutex<AppState>>,
order_module: OrderModule,
settings: DeckSettings,
}
impl DeckData {
pub fn new(
settings: &DeckSettings,
state: Arc<Mutex<AppState>>,
) -> Result<Self, NotificationData> {
let state_for = state.clone();
let state_locked = state.lock();
let stats = load_stats_of_deck(settings, &state_locked.connection)?;
let words = stats
.iter()
.map(|stat| {
state_locked
.dictionary
.binary_search_by_key(&stat.word_id, |w| w.id)
.expect("No word found in dictionary")
})
.map(|index| &state_locked.dictionary[index])
.cloned()
.collect();
Ok(Self {
set: stats,
words,
current_word_index: None,
state: state_for,
order_module: match settings.open_mode {
OrderMode::Default => OrderModule::SemiRandomSRS(SemiRandomSRSModule::new()),
OrderMode::TrainWorstFirst => {
OrderModule::WorstWordsSRS(WorstWordsSRSModule::new())
}
OrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()),
},
settings: settings.clone(),
})
}
pub fn next(&mut self) -> (WordData, CardStatistics) {
let index = match self.order_module {
OrderModule::SemiRandomSRS(ref mut module) => {
if !module.initialized {
module.init(self.set.as_slice())
}
module.next(self.set.as_slice())
}
OrderModule::RandomSRS(ref mut module) => {
if !module.initialized {
module.init(self.set.as_slice())
}
module.next(self.set.as_slice())
}
OrderModule::WorstWordsSRS(ref mut module) => {
if !module.initialized {
module.init(self.set.as_slice())
}
module.next(self.set.as_slice())
}
};
self.current_word_index = Some(index);
(self.words[index].clone(), self.set[index].clone())
}
pub fn open(&mut self, status: WordOpenMode) -> MaybeError {
if let Some(index) = self.current_word_index {
let word: &mut CardStatistics = &mut self.set[index];
let old_score = word.score;
word.update(status);
let new_score = word.score;
match self.order_module {
OrderModule::SemiRandomSRS(ref mut module) => {
module.open(status, index, word);
}
OrderModule::RandomSRS(ref mut module) => {
module.open(status, index, word);
}
OrderModule::WorstWordsSRS(ref mut module) => {
module.open(status, index, word);
}
}
update_stat_score(word, &self.state.lock().connection)?;
let _ = push_note(
self.settings.id,
HistoryItem {
timestamp: Utc::now(),
word_id: word.word_id,
mode: status,
before: old_score,
after: new_score,
},
);
}
Ok(())
}
pub fn len(&self) -> usize {
self.set.len()
}
}
+201
View File
@@ -0,0 +1,201 @@
#[derive(Clone, Debug)]
pub struct KanaSet {
name: String,
pub(crate) chars_type: KanaType,
pub(crate) dictionary: Vec<Vec<(String, String)>>,
pub(crate) include_map: [bool; 10],
}
#[derive(Clone, Debug)]
pub enum KanaType {
Hiragana,
Katakana,
}
impl KanaSet {
pub fn hiragana() -> Self {
Self {
name: "Хирагана".to_string(),
chars_type: KanaType::Hiragana,
dictionary: vec![
vec![
(String::from("ぁ"), String::from("a")),
(String::from("ぃ"), String::from("i")),
(String::from("ぅ"), String::from("u")),
(String::from("ぇ"), String::from("e")),
(String::from("ぉ"), String::from("o")),
],
vec![
(String::from("さ"), String::from("sa")),
(String::from("し"), String::from("shi")),
(String::from("す"), String::from("su")),
(String::from("せ"), String::from("se")),
(String::from("そ"), String::from("so")),
],
vec![
(String::from("か"), String::from("ka")),
(String::from("き"), String::from("ki")),
(String::from("く"), String::from("ku")),
(String::from("け"), String::from("ke")),
(String::from("こ"), String::from("ko")),
],
// Ряд «та» (たちつてと)
vec![
(String::from("た"), String::from("ta")),
(String::from("ち"), String::from("chi")),
(String::from("つ"), String::from("tsu")),
(String::from("て"), String::from("te")),
(String::from("と"), String::from("to")),
],
// Ряд «на» (なにぬねの)
vec![
(String::from("な"), String::from("na")),
(String::from("に"), String::from("ni")),
(String::from("ぬ"), String::from("nu")),
(String::from("ね"), String::from("ne")),
(String::from("の"), String::from("no")),
],
// Ряд «ха» (はひふへほ)
vec![
(String::from("は"), String::from("ha")),
(String::from("ひ"), String::from("hi")),
(String::from("ふ"), String::from("fu")),
(String::from("へ"), String::from("he")),
(String::from("ほ"), String::from("ho")),
],
// Ряд «ма» (まみむめも)
vec![
(String::from("ま"), String::from("ma")),
(String::from("み"), String::from("mi")),
(String::from("む"), String::from("mu")),
(String::from("め"), String::from("me")),
(String::from("も"), String::from("mo")),
],
// Ряд «я» (やゆよ) — только 3 символа
vec![
(String::from("や"), String::from("ya")),
(String::from("ゆ"), String::from("yu")),
(String::from("よ"), String::from("yo")),
],
// Ряд «ра» (らりるれろ)
vec![
(String::from("ら"), String::from("ra")),
(String::from("り"), String::from("ri")),
(String::from("る"), String::from("ru")),
(String::from("れ"), String::from("re")),
(String::from("ろ"), String::from("ro")),
],
vec![
(String::from("わ"), String::from("wa")),
(String::from("を"), String::from("wo")),
(String::from("ん"), String::from("n")),
],
],
include_map: [true; 10],
}
}
pub fn katakana() -> Self {
Self {
name: "Катакана".to_string(),
chars_type: KanaType::Katakana,
dictionary: vec![
vec![
(String::from("ァ"), String::from("a")),
(String::from("ィ"), String::from("i")),
(String::from("ゥ"), String::from("u")),
(String::from("ェ"), String::from("e")),
(String::from("ォ"), String::from("o")),
],
vec![
(String::from("サ"), String::from("sa")),
(String::from("シ"), String::from("shi")),
(String::from("ス"), String::from("su")),
(String::from("セ"), String::from("se")),
(String::from("ソ"), String::from("so")),
],
vec![
(String::from("カ"), String::from("ka")),
(String::from("キ"), String::from("ki")),
(String::from("ク"), String::from("ku")),
(String::from("ケ"), String::from("ke")),
(String::from("コ"), String::from("ko")),
],
// Ряд «та» (タチツテト)
vec![
(String::from("タ"), String::from("ta")),
(String::from("チ"), String::from("chi")),
(String::from("ツ"), String::from("tsu")),
(String::from("テ"), String::from("te")),
(String::from("ト"), String::from("to")),
],
// Ряд «на» (ナニヌネノ)
vec![
(String::from("ナ"), String::from("na")),
(String::from("ニ"), String::from("ni")),
(String::from("ヌ"), String::from("nu")),
(String::from("ネ"), String::from("ne")),
(String::from("ノ"), String::from("no")),
],
// Ряд «ха» (ハヒフヘホ)
vec![
(String::from("ハ"), String::from("ha")),
(String::from("ヒ"), String::from("hi")),
(String::from("フ"), String::from("fu")),
(String::from("ヘ"), String::from("he")),
(String::from("ホ"), String::from("ho")),
],
// Ряд «ма» (マミムメモ)
vec![
(String::from("マ"), String::from("ma")),
(String::from("ミ"), String::from("mi")),
(String::from("ム"), String::from("mu")),
(String::from("メ"), String::from("me")),
(String::from("モ"), String::from("mo")),
],
// Ряд «я» (ヤユヨ) — только 3 символа
vec![
(String::from("ヤ"), String::from("ya")),
(String::from("ユ"), String::from("yu")),
(String::from("ヨ"), String::from("yo")),
],
// Ряд «ра» (ラリルレロ)
vec![
(String::from("ラ"), String::from("ra")),
(String::from("リ"), String::from("ri")),
(String::from("ル"), String::from("ru")),
(String::from("レ"), String::from("re")),
(String::from("ロ"), String::from("ro")),
],
vec![
(String::from("ワ"), String::from("wa")),
(String::from("ヲ"), String::from("wo")),
(String::from("ン"), String::from("n")),
],
],
include_map: [true; 10],
}
}
pub fn list(&self) -> Vec<(String, String)> {
let mut current_set: Vec<(String, String)> = Vec::new();
for i in 0..10 {
if self.include_map[i] {
self.dictionary[i].iter().for_each(|v| {
current_set.push(v.clone());
});
}
}
current_set
}
}
impl Default for KanaSet {
fn default() -> Self {
KanaSet::hiragana()
}
}
impl PartialEq<Self> for KanaSet {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
+181
View File
@@ -0,0 +1,181 @@
use crate::data::entities::CardStatistics;
use rand::distr::weighted::WeightedIndex;
use rand::prelude::ThreadRng;
use rand::prelude::{Distribution, SliceRandom};
use rand::rng;
const MAX_HISTORY_LEN: usize = 20;
const MAX_HISTORY_LEN_PART: f32 = 0.33;
pub const MAX_SCORE: u8 = 25;
pub const FADE_PER_DAY: f32 = 0.95;
#[derive(Clone, PartialEq, Copy, Eq)]
pub enum OrderMode {
Default,
TrainWorstFirst,
FullRandom,
}
#[derive(Clone, Copy, Eq, PartialEq, Default)]
pub enum AppendMode {
Full,
#[default]
Manual,
}
#[derive(Clone)]
pub enum OrderModule {
SemiRandomSRS(SemiRandomSRSModule),
RandomSRS(RandomSRSModule),
WorstWordsSRS(WorstWordsSRSModule),
}
pub trait SRSModule {
fn next(&mut self, set: &[CardStatistics]) -> usize;
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: &CardStatistics);
fn init(&mut self, set: &[CardStatistics]);
}
#[derive(Clone)]
pub struct RandomSRSModule {
basket: Vec<usize>,
pub(crate) initialized: bool,
}
impl RandomSRSModule {
pub(crate) fn new() -> RandomSRSModule {
Self {
basket: vec![],
initialized: false,
}
}
}
impl SRSModule for RandomSRSModule {
fn next(&mut self, set: &[CardStatistics]) -> usize {
match self.basket.pop() {
Some(index) => index,
None => {
self.basket = (0..set.len()).collect::<Vec<usize>>();
self.basket.shuffle(&mut rand::rng());
self.basket.pop().expect("empty basket")
}
}
}
fn open(&mut self, _: WordOpenMode, _: usize, _: &CardStatistics) {}
fn init(&mut self, set: &[CardStatistics]) {
self.initialized = true;
self.basket = (0..set.len()).collect::<Vec<usize>>();
self.basket.shuffle(&mut rand::rng())
}
}
#[derive(Clone)]
pub struct SemiRandomSRSModule {
history: Vec<usize>,
last_weights: WeightedIndex<f32>,
generator: ThreadRng,
pub(crate) initialized: bool,
}
impl SemiRandomSRSModule {
pub(crate) fn new() -> SemiRandomSRSModule {
SemiRandomSRSModule {
history: vec![],
last_weights: WeightedIndex::new([1.0]).unwrap(),
generator: rng(),
initialized: false,
}
}
}
impl SRSModule for SemiRandomSRSModule {
fn next(&mut self, set: &[CardStatistics]) -> usize {
let index = self.last_weights.sample(&mut self.generator);
if self.history.contains(&index) && self.history.len() != 1 {
return self.next(set);
}
if self.history.len() == self.history_len(set) {
self.history.remove(0);
}
self.history.push(index);
index
}
fn open(&mut self, _: WordOpenMode, index: usize, word: &CardStatistics) {
let new_weight = (100.0 / word.calculated_score()).powf(2.0);
self.last_weights
.update_weights(&[(index, &new_weight)])
.expect("update weights error");
}
fn init(&mut self, set: &[CardStatistics]) {
self.initialized = true;
let weights = set
.iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>();
self.last_weights = WeightedIndex::new(weights).expect("Incorrect weights update");
}
}
impl SemiRandomSRSModule {
fn history_len(&self, set: &[CardStatistics]) -> usize {
((set.len() as f32 * MAX_HISTORY_LEN_PART) as usize).clamp(1, MAX_HISTORY_LEN)
}
}
#[derive(Clone)]
pub struct WorstWordsSRSModule {
pub(crate) initialized: bool,
pool_size: usize,
rounds_remaining: u8,
pool: Vec<usize>,
queue: Vec<usize>,
rounds_count: u8,
}
impl SRSModule for WorstWordsSRSModule {
fn next(&mut self, set: &[CardStatistics]) -> usize {
if self.rounds_remaining == 0 {
self.fill_pool(set);
self.rounds_remaining = self.rounds_count;
}
match self.queue.pop() {
Some(index) => index,
None => {
self.queue.append(&mut self.pool.clone());
self.rounds_remaining -= 1;
self.queue.pop().expect("empty queue")
}
}
}
fn open(&mut self, _: WordOpenMode, _: usize, _: &CardStatistics) {}
fn init(&mut self, _: &[CardStatistics]) {
self.initialized = true;
}
}
impl WorstWordsSRSModule {
pub(crate) fn new() -> WorstWordsSRSModule {
WorstWordsSRSModule {
initialized: false,
pool_size: 15,
rounds_count: 2,
rounds_remaining: 0,
pool: vec![],
queue: vec![],
}
}
fn fill_pool(&mut self, set: &[CardStatistics]) {
let mut sorted = set.iter().enumerate().collect::<Vec<_>>();
sorted.sort_by_key(|c| c.1.score);
let mut worst = sorted[0..self.pool_size]
.iter()
.map(|(index, _)| *index)
.collect::<Vec<usize>>();
worst.shuffle(&mut rand::rng());
self.pool = worst;
}
}
#[derive(Clone, Copy)]
pub enum WordOpenMode {
Easy,
Ok,
Hard,
None,
}
+63
View File
@@ -0,0 +1,63 @@
pub mod entities;
pub mod repositories;
use rusqlite::ToSql;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
use std::fmt::{Display, Formatter};
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Clone, PartialEq, Eq, Debug, Hash, Copy, Ord, PartialOrd, Default)]
pub struct Id(pub(crate) u32);
pub const INVALID_ID: Id = Id(0);
impl FromStr for Id {
type Err = ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Id(s.parse::<u32>()?))
}
}
impl From<u32> for Id {
fn from(value: u32) -> Self {
Id(value)
}
}
impl From<Id> for u32 {
fn from(value: Id) -> Self {
value.0
}
}
impl Display for Id {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromSql for Id {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Integer(i) => Ok(Id(i as u32)),
_ => Err(FromSqlError::InvalidType),
}
}
}
impl ToSql for Id {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0 as i64))
}
}
impl From<Id> for String {
fn from(value: Id) -> Self {
value.0.to_string()
}
}
impl Id {
pub(crate) fn is_valid(self) -> bool {
self.0 != 0
}
}
+252
View File
@@ -0,0 +1,252 @@
use crate::app::AppState;
use crate::core::srs::{FADE_PER_DAY, MAX_SCORE, OrderMode, WordOpenMode};
use crate::data::{INVALID_ID, Id};
use crate::notification::MaybeError;
use chrono::{DateTime, Utc};
use log::info;
use rayon::prelude::*;
use rhai::{Engine, Scope};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::time::Instant;
#[derive(Clone, Debug)]
pub struct WordData {
pub id: Id,
pub key: String,
pub value: String,
pub tags: String,
pub additional: HashMap<String, String>,
pub group_id: Id,
}
impl EntityData for WordData {
fn id(&self) -> Id {
self.id
}
fn set_id(&mut self, id: Id) {
self.id = id;
}
}
#[derive(Clone)]
pub struct WordGroup {
pub id: Id,
pub name: String,
}
impl WordData {
pub fn new() -> Self {
Self {
id: INVALID_ID,
key: String::new(),
value: String::new(),
tags: String::new(),
additional: Default::default(),
group_id: 1.into(),
}
}
}
#[derive(Clone)]
pub struct HistoryItem {
pub timestamp: DateTime<Utc>,
pub word_id: Id,
pub mode: WordOpenMode,
pub before: u8,
pub after: u8,
}
#[derive(Clone)]
pub struct DeckSettings {
pub id: Id,
pub name: String,
pub forward: String,
pub backward: String,
pub filter: String,
pub count: Option<usize>,
pub open_mode: OrderMode,
}
impl DeckSettings {
pub(crate) fn with_name(name: String) -> DeckSettings {
DeckSettings {
id: 0.into(),
name,
forward: "".to_string(),
backward: "".to_string(),
filter: "true".to_string(),
count: None,
open_mode: OrderMode::Default,
}
}
pub fn check_filter(&self) -> bool {
let time = Instant::now();
let engine = Engine::new();
let ast = engine.compile(&self.filter);
info!("Compile time is {:?}", time.elapsed());
ast.is_ok()
}
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
let time = Instant::now();
let mut list = vec![];
let engine = Engine::new();
let ast = engine.compile(&self.filter);
if let Ok(ast) = ast {
let groups = &state.word_groups;
list = state
.dictionary
.par_iter()
.enumerate()
.filter(|(_, word)| {
let mut more = rhai::Map::new();
for iced in &word.additional {
more.insert(iced.0.clone().into(), iced.1.clone().into());
}
let mut scope = Scope::new();
scope
.push_constant("id", word.id.0 as i64)
.push_constant("key", word.key.clone())
.push_constant("value", word.value.clone())
.push_constant("tags", word.tags.clone())
.push_constant("more", more)
.push_constant(
"group",
groups
.iter()
.find(|g| g.id == word.group_id)
.cloned()
.expect("No group id")
.name,
);
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
if let Ok(result) = result {
return result;
}
false
})
.map(|(index, _)| index)
.collect();
info!("Collecting available words is {:?}", time.elapsed());
list
} else {
list
}
}
pub fn require_speech(&self) -> bool {
self.forward == "speech" || self.backward == "speech"
}
}
#[derive(Clone, PartialEq)]
pub struct CardStatistics {
pub id: Id,
pub word_id: Id,
pub set_id: Id,
pub last_open: DateTime<Utc>,
pub score: u8,
}
impl CardStatistics {
pub fn update(&mut self, status: WordOpenMode) {
match status {
WordOpenMode::Easy => {
self.score = (self.calculated_score() + 5.0).round() as u8;
}
WordOpenMode::Ok => self.score = (self.calculated_score() + 2.0).round() as u8,
WordOpenMode::Hard => {
self.score = (self.calculated_score() * 0.75).round() as u8;
}
WordOpenMode::None => {
self.score = (self.calculated_score() * 0.4) as u8;
}
}
self.score = self.score.clamp(1, MAX_SCORE);
self.last_open = Utc::now();
}
pub fn calculated_score(&self) -> f32 {
let time = Utc::now() - self.last_open;
let days = time.num_days();
let multiplier = FADE_PER_DAY.powi(days as i32);
(self.score as f32 * multiplier).max(1.0)
}
}
#[derive(Copy)]
pub struct EntityHandle<E> {
pub(crate) id: Id,
index: i32,
pub(crate) _phantom: PhantomData<E>,
}
impl<T> Clone for EntityHandle<T> {
fn clone(&self) -> Self {
EntityHandle {
id: self.id,
index: self.index,
_phantom: Default::default(),
}
}
}
impl<T> EntityHandle<T> {
pub fn new(id: Id, index: usize, real: bool) -> Self {
Self {
id,
index: index as i32 | (!real as i32) << 31,
_phantom: Default::default(),
}
}
pub fn index(&self) -> usize {
(self.index << 1 >> 1) as usize
}
pub fn set_index(&mut self, index: usize) {
self.index = self.index >> 31 << 31 | index as i32;
}
pub fn real(&self) -> bool {
(self.index >> 31) == 0
}
pub fn set_real(&mut self, value: bool) {
self.index = self.index << 1 >> 1 | (!value as i32) << 31;
}
}
impl<T> Eq for EntityHandle<T> {}
impl<T> PartialEq<Self> for EntityHandle<T> {
fn eq(&self, other: &Self) -> bool {
self.real() == other.real() && self.id == other.id
}
}
impl<T> PartialOrd<Self> for EntityHandle<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for EntityHandle<T> {
fn cmp(&self, other: &Self) -> Ordering {
if self.real() && !other.real() {
return Ordering::Less;
}
if !self.real() && other.real() {
return Ordering::Greater;
}
self.id.cmp(&other.id)
}
}
pub trait EntityData {
fn id(&self) -> Id;
fn set_id(&mut self, id: Id);
}
+531
View File
@@ -0,0 +1,531 @@
use crate::data::Id;
use crate::data::entities::{EntityData, EntityHandle};
use crate::helpers::into_result;
use crate::notification::{MaybeError, NotificationData};
use parking_lot::{Mutex, RwLock};
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use rusqlite::Connection;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::Arc;
pub trait Repository<T, D>
where
D: DbLayer<T>,
{
fn get(&self, handle: &mut EntityHandle<T>) -> Option<T>;
fn get_ref(&self, handle: &mut EntityHandle<T>) -> Option<&T>;
fn get_mut(&mut self, handle: &mut EntityHandle<T>) -> Option<&mut T>;
fn handle_by_id(&self, id: Id) -> EntityHandle<T>;
fn create(&mut self, new: T) -> EntityHandle<T>;
fn save(&mut self, entity: &mut EntityHandle<T>) -> MaybeError;
fn delete(&mut self, handle: EntityHandle<T>) -> MaybeError;
fn init(&mut self) -> MaybeError;
fn reload(&mut self) -> MaybeError;
}
struct QueryManger<T, R, D>
where
R: Repository<T, D>,
D: DbLayer<T>,
{
queries: Vec<Arc<Mutex<Query<T, R, D>>>>,
}
impl<T, R, D> QueryManger<T, R, D>
where
R: Repository<T, D>,
D: DbLayer<T>,
T: EntityData,
{
pub(crate) fn handle_save(&self, old: EntityHandle<T>, new: &mut EntityHandle<T>, data: &T) {
return;
if old.real() && new.real() {
return;
}
let affected = self.get_affected_queries(data);
for q in affected {
let mut query = self.queries[q].lock();
let index = query.cache.binary_search(&old).unwrap();
query.cache.remove(index);
let real_end = query.cache.iter().rposition(|r| r.real()).unwrap() + 1;
query.cache.insert(real_end, new.clone());
}
}
pub(crate) fn handle_delete(&self, handle: &EntityHandle<T>, data: &T) {
return;
let affected = self.get_affected_queries(data);
for q in affected {
let mut query = self.queries[q].lock();
let slice = query.cache.as_slice();
if let Ok(index) = slice.binary_search(&handle) {
query.cache.remove(index);
}
}
}
fn get_affected_queries(&self, data: &T) -> Vec<usize> {
self.queries
.iter()
.enumerate()
.filter(|(_, q)| {
let query = q.lock();
let rule = &query.rule;
return rule(data);
false
})
.map(|(i, _)| i)
.collect()
}
fn reload_queries(&mut self, data_repository: impl Repository<T, D>) {
for q in &self.queries {
let mut query = q.lock();
query.cache.clear();
}
}
}
pub struct Query<T, R, D>
where
R: Repository<T, D>,
D: DbLayer<T>,
{
cache: Vec<EntityHandle<T>>,
rule: Box<dyn Fn(&T) -> bool + Send + Sync>,
parallel: bool,
_marker: PhantomData<(R, D)>,
shift_stamp: u16,
}
impl<T: EntityData + Clone, R: Repository<T, D>, D: DbLayer<T>> Query<T, R, D> {
pub fn iter<'a>(&mut self, data_repository_inner: &'a R) -> impl Iterator<Item = &'a T>
where
T: 'a,
{
self.cache
.iter_mut()
.filter_map(move |e| data_repository_inner.get_ref(e))
}
pub fn for_each_mut<F>(&mut self, repo: &mut R, mut f: F)
where
F: FnMut(&mut T),
{
for handle in &mut self.cache {
if let Some(entity) = repo.get_mut(handle) {
f(entity);
}
}
}
pub fn load(&mut self, data_repository: &DataRepositoryInner<T, D>)
where
T: Send + Sync,
{
self.cache.clear();
if self.parallel {
self.cache = data_repository
.cache
.par_iter()
.enumerate()
.filter(|(_, entity)| (self.rule)(entity))
.map(|(i, entity)| EntityHandle::new(entity.id(), i, true))
.collect();
} else {
self.cache = data_repository
.cache
.iter()
.enumerate()
.filter(|(_, entity)| (self.rule)(entity))
.map(|(i, entity)| EntityHandle::new(entity.id(), i, true))
.collect();
}
self.cache.extend(
data_repository
.temporal
.iter()
.enumerate()
.filter(|(_, entity)| (self.rule)(entity))
.map(|(i, entity)| EntityHandle::new(entity.id(), i, false))
.collect::<Vec<_>>(),
);
}
}
pub trait BatchedRepository<T, D>
where
D: BatchedDbLayer<T>,
T: EntityData,
{
fn save_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError;
fn delete_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError;
}
pub trait DbLayer<T> {
fn write_entity(&self, entity: &T, connection: &Connection) -> MaybeError;
fn add_entity(&mut self, entity: &mut T, connection: &Connection) -> MaybeError;
fn delete_entity(&mut self, id: Id, connection: &Connection) -> MaybeError;
fn load_all(&self, storage: &mut Vec<T>, connection: &Connection) -> MaybeError;
}
pub trait BatchedDbLayer<T>
where
T: EntityData,
{
fn delete_many_entities(&mut self, ids: &[Id], connection: &Connection) -> MaybeError;
fn add_many_entities(&mut self, entity: &mut [T], connection: &Connection) -> MaybeError;
}
#[derive(Clone)]
pub struct DataRepository<T: std::clone::Clone + EntityData, D: DbLayer<T>> {
inner: Arc<RwLock<DataRepositoryInner<T, D>>>,
}
pub struct DataRepositoryInner<T: std::clone::Clone + EntityData, D: DbLayer<T>> {
cache: Vec<T>,
temporal: Vec<T>,
next_temporal: u32,
connection: Arc<RwLock<Connection>>,
data_layer: D,
query_manger: QueryManger<T, Self, D>,
version: u16,
shifts: u16,
}
impl<T: std::clone::Clone + EntityData, D: DbLayer<T>> Deref for DataRepository<T, D> {
type Target = Arc<RwLock<DataRepositoryInner<T, D>>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: EntityData + Clone, D: DbLayer<T>> DataRepositoryInner<T, D> {
pub fn query_par(
&self,
rule: Box<dyn Fn(&T) -> bool + Send + Sync>,
) -> Query<T, DataRepositoryInner<T, D>, 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,
rule,
parallel: true,
_marker: PhantomData,
shift_stamp: self.shifts,
}
}
pub fn query(
&self,
rule: Box<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,
rule,
parallel: false,
_marker: PhantomData,
shift_stamp: self.shifts,
}
}
}
impl<T: EntityData + Clone, D: DbLayer<T>> Repository<T, D> for DataRepositoryInner<T, D> {
fn get(&self, handle: &mut EntityHandle<T>) -> Option<T> {
let slice = if handle.real() {
self.cache.as_slice()
} else {
self.temporal.as_slice()
};
let index = fast_position_of(slice, handle)?;
Some(slice[index].clone())
}
fn get_ref(&self, handle: &mut EntityHandle<T>) -> Option<&T> {
let slice = if handle.real() {
self.cache.as_slice()
} else {
self.temporal.as_slice()
};
let index = fast_position_of(slice, handle)?;
Some(&slice[index])
}
fn get_mut(&mut self, handle: &mut EntityHandle<T>) -> Option<&mut T> {
let slice = if handle.real() {
self.cache.as_mut_slice()
} else {
self.temporal.as_mut_slice()
};
let index = fast_position_of(slice, handle)?;
Some(&mut slice[index])
}
fn handle_by_id(&self, id: Id) -> EntityHandle<T> {
EntityHandle::new(id, id.0 as usize, true)
}
fn create(&mut self, mut new: T) -> EntityHandle<T> {
let next_temporal = self.next_temporal;
self.next_temporal += 1;
let entity = EntityHandle::new(next_temporal.into(), self.temporal.len(), false);
new.set_id(entity.id);
self.temporal.push(new);
entity
}
fn save(&mut self, entity: &mut EntityHandle<T>) -> MaybeError {
let original_state = entity.clone();
if entity.real() {
let data = self.get_ref(entity).unwrap();
self.data_layer
.write_entity(data, &self.connection.read())?;
} else {
let index = fast_position_of(self.temporal.as_slice(), entity).unwrap();
let mut data = self.temporal.remove(index);
self.data_layer
.add_entity(&mut data, &self.connection.read())?;
entity.set_real(true);
entity.id = data.id();
entity.set_index(self.cache.len());
self.query_manger.handle_save(original_state, entity, &data);
self.cache.push(data);
self.shifts += 1;
}
Ok(())
}
fn delete(&mut self, mut handle: EntityHandle<T>) -> MaybeError {
let vec = if handle.real() {
self.data_layer
.delete_entity(handle.id, &self.connection.read())?;
&mut self.cache
} else {
&mut self.temporal
};
let index = into_result(
fast_position_of(vec.as_slice(), &mut handle),
NotificationData::DbSaveError,
)?;
let value = vec.remove(index);
self.query_manger.handle_delete(&handle, &value);
self.shifts += 1;
Ok(())
}
fn init(&mut self) -> MaybeError {
self.data_layer
.load_all(&mut self.cache, &self.connection.read())?;
self.version += 1;
Ok(())
}
fn reload(&mut self) -> MaybeError {
self.cache.clear();
self.temporal.clear();
self.init()?;
Ok(())
}
}
impl<T: EntityData + Clone, D: BatchedDbLayer<T> + DbLayer<T>> BatchedRepository<T, D>
for DataRepositoryInner<T, D>
{
fn save_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError {
let mut temp = Vec::with_capacity(handles.len() / 2);
let mut cached = Vec::with_capacity(handles.len() / 2);
handles.sort_by_key(|a| a.id);
handles.iter_mut().for_each(|handle| {
if handle.real() {
cached.push(handle)
} else {
temp.push(handle)
}
});
let mut temp_values = Vec::with_capacity(temp.len());
let mut cell = 0;
let len = temp.len();
self.temporal.retain(|x| {
if cell == len {
return true;
}
let find = temp[cell].id;
let remove = x.id() == find;
if remove {
cell += 1;
temp_values.push(x.clone());
}
!remove
});
self.data_layer
.add_many_entities(&mut temp_values, &self.connection.read())?;
let start = self.cache.len();
for (i, (handle, data)) in temp.into_iter().zip(&mut temp_values).enumerate() {
let old = handle.clone();
handle.id = data.id();
handle.set_index(start + i);
handle.set_real(true);
self.query_manger.handle_save(old, handle, data);
}
self.cache.extend(temp_values);
for handle in cached.into_iter() {
let h = handle;
let idx = fast_position_of(self.cache.as_slice(), h).unwrap();
self.data_layer
.write_entity(&self.cache[idx], &self.connection.read())?;
}
self.shifts += 1;
Ok(())
}
fn delete_many(&mut self, handles: &mut [EntityHandle<T>]) -> MaybeError {
let (cached, temp) = split_temp_real(handles, |e| e.id);
let mut cell = 0;
let len = temp.len();
self.temporal.retain(|x| {
if cell == len {
return true;
}
let find = temp[cell];
let remove = x.id() == find;
if remove {
cell += 1;
}
!remove
});
self.data_layer
.delete_many_entities(cached.as_slice(), &self.connection.read())?;
let len = cached.len();
cell = 0;
self.cache.retain(|x| {
if cell == len {
return true;
}
let find = cached[cell];
let remove = x.id() == find;
if remove {
cell += 1;
}
!remove
});
self.shifts += 1;
Ok(())
}
}
fn split_temp_real<T, F, V>(handles: &mut [EntityHandle<T>], getter: F) -> (Vec<V>, Vec<V>)
where
F: Fn(&EntityHandle<T>) -> V,
{
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.iter().for_each(|handle| {
if handle.real() {
cached.push(getter(handle))
} else {
temp.push(getter(handle))
}
});
(cached, temp)
}
pub fn fast_position_of<E: EntityData>(
storage: &[E],
handle: &mut EntityHandle<E>,
) -> Option<usize> {
if storage.is_empty() {
return None;
}
let max_idx = storage.len() - 1;
let upper = (handle.index()).min(max_idx);
let peek = storage[upper].id();
if peek == handle.id {
handle.set_index(upper);
return Some(upper);
}
if peek.0 < handle.id.0 {
return None;
}
let target_id_val = handle.id.0 as i64;
let peek_val = peek.0 as i64;
let delta = peek_val - target_id_val;
let new_index = (upper as i64 - delta).max(0) as usize;
if storage[new_index].id() == handle.id {
handle.set_index(new_index);
return Some(new_index);
}
if new_index == upper {
return None;
}
let index = storage[new_index..upper]
.binary_search_by(|e| e.id().cmp(&handle.id))
.ok()?
+ new_index;
handle.set_index(index);
Some(index)
}
+28 -29
View File
@@ -1,36 +1,35 @@
use crate::lang::SetOrderMode; use crate::core::srs::OrderMode;
use crate::repetitions::CardSetSettings;
use crate::data::entities::DeckSettings;
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
use crate::notification::{MaybeError, NotificationData};
use rusqlite::Connection; use rusqlite::Connection;
pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> { pub fn load_sets(connection: &Connection) -> Result<Vec<DeckSettings>, NotificationData> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT id, name, forward, backward, filter FROM card_set") .prepare("SELECT id, name, forward, backward, filter FROM card_set")
.unwrap(); .expect("Failed to prepare state query");
let iter = stmt let iter = stmt
.query_map([], |row| { .query_map([], |row| {
Ok(CardSetSettings { Ok(DeckSettings {
id: row.get(0)?, id: row.get(0)?,
name: row.get(1)?, name: row.get(1)?,
forward: row.get(2)?, forward: row.get(2)?,
backward: row.get(3)?, backward: row.get(3)?,
filter: row.get(4)?, filter: row.get(4)?,
count: None, count: None,
worst_words_list: None, open_mode: OrderMode::Default,
open_mode: SetOrderMode::Default,
}) })
}) })
.unwrap(); .map_err(|_| DbLoadError)?;
let mut buffer = vec![]; let mut buffer = Vec::with_capacity(16);
for word in iter { iter.filter_map(|res| res.ok()).for_each(|i| buffer.push(i));
buffer.push(word.unwrap()); Ok(buffer)
}
buffer
} }
pub fn add_set(set: &mut CardSetSettings, connection: &Connection) { pub fn add_set(set: &mut DeckSettings, connection: &Connection) -> MaybeError {
let index = connection let index : u32 = connection
.query_row( .query_row(
"INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id", "INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id",
( (
@@ -41,14 +40,15 @@ pub fn add_set(set: &mut CardSetSettings, connection: &Connection) {
), ),
|row| row.get(0) |row| row.get(0)
) )
.unwrap_or_else(|e| {println!("{}", e); 0}); .map_err(|_| DbSaveError)?;
set.id = index; set.id = index.into();
Ok(())
} }
pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) { pub fn update_deck(set: &mut DeckSettings, connection: &Connection) -> MaybeError {
if set.id == 0 { if !set.id.is_valid() {
add_set(set, &connection); add_set(set, connection)?;
} else { } else {
connection connection
.execute( .execute(
@@ -61,18 +61,17 @@ pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) {
&set.id &set.id
), ),
) )
.unwrap_or_else(|e| {println!("{}", e); 0}); .map_err(|_| DbSaveError)?;
} }
Ok(())
} }
pub fn delete_set(set: &CardSetSettings, connection: &Connection) { pub fn delete_set(set: &DeckSettings, connection: &Connection) -> MaybeError {
if set.id == 0 { if !set.id.is_valid() {
return; return Err(DbSaveError);
} }
connection connection
.execute("DELETE FROM card_set WHERE id = ?1", (&set.id,)) .execute("DELETE FROM card_set WHERE id = ?1", (&set.id,))
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
+62 -78
View File
@@ -1,12 +1,17 @@
use crate::lang::CardStatistics; use crate::data::entities::{CardStatistics, DeckSettings};
use crate::repetitions::CardSetSettings; use crate::notification::NotificationData::{DbLoadError, DbSaveError};
use rusqlite::Connection; use crate::notification::{MaybeError, NotificationData};
use log::info;
use rusqlite::{Connection, params};
use std::time::Instant; use std::time::Instant;
pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec<CardStatistics> { pub fn load_stats_of_deck(
set: &DeckSettings,
connection: &Connection,
) -> Result<Vec<CardStatistics>, NotificationData> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT id, word_id, score, last_opened FROM card_stats WHERE set_id = ?1") .prepare("SELECT id, word_id, score, last_opened FROM card_stats WHERE set_id = ?1")
.unwrap(); .expect("Failed to prepare state query");
let iter = stmt let iter = stmt
.query_map((set.id,), |row| { .query_map((set.id,), |row| {
Ok(CardStatistics { Ok(CardStatistics {
@@ -17,78 +22,53 @@ pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec<
last_open: row.get(3)?, last_open: row.get(3)?,
}) })
}) })
.unwrap(); .map_err(|_| DbLoadError)?;
let mut buffer = vec![]; let mut buffer = Vec::with_capacity(512);
for word in iter { iter.filter_map(|res| res.ok()).for_each(|i| buffer.push(i));
buffer.push(word.unwrap());
}
buffer Ok(buffer)
} }
pub fn add_stat_list(stat: &mut Vec<CardStatistics>, connection: &Connection) { pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) -> MaybeError {
let inserting = stat let time = Instant::now();
.iter() let tx = connection
.map(|stat| { .transaction()
format!( .expect("Failed to create transaction");
"({}, {}, {}, {})", let count = stats.len();
stat.word_id.to_string(),
stat.set_id.to_string(),
stat.score.to_string(),
stat.last_open.timestamp().to_string()
)
})
.collect::<Vec<_>>()
.join(", ");
let query = format!(
"INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES {}",
inserting
);
let count = connection.execute(query.as_str(), ());
if count.is_err() { {
println!("{}", count.unwrap_err()); let mut stmt = tx
return; .prepare(
"INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4)",
)
.expect("Failed to prepare state query");
for stat in stats.iter() {
stmt.execute(params![
stat.word_id,
stat.set_id,
stat.score,
stat.last_open.timestamp()
])
.map_err(|_| DbSaveError)?;
}
} }
let last_index: u32 = connection let last_index: u32 = tx.last_insert_rowid() as u32;
.query_one( tx.commit().expect("Failed to commit");
"SELECT seq from sqlite_sequence WHERE name == ?1",
("card_stats".to_string(),),
|row| row.get(0),
)
.unwrap();
let start_index = last_index - (count.unwrap() as u32) + 1; let start_index = last_index - (count as u32) + 1;
let mut index = 0; for (index, id) in (start_index..=last_index).enumerate() {
for id in start_index..=last_index { stats[index].id = id.into();
stat[index].id = id;
index += 1;
} }
info!("Added {} cards for {:?}", stats.len(), time.elapsed());
Ok(())
} }
// pub fn add_stat(stat: &mut CardStatistics, connection: &Connection) { pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) -> MaybeError {
// let time = Instant::now();
// let index = connection
// .query_row(
// "INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4) RETURNING id",
// (
// &stat.word_id,
// &stat.set_id,
// &stat.score,
// &stat.last_open.timestamp(),
// ),
// |row| row.get(0)
// )
// .unwrap_or_else(|e| {println!("{}", e); 0});
//
// stat.id = index;
// println!("Added stat: {}", time.elapsed().as_millis());
// }
pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
let time = Instant::now(); let time = Instant::now();
connection connection
@@ -96,21 +76,25 @@ pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
"UPDATE card_stats SET score = ?1, last_opened = ?2 WHERE id = ?3", "UPDATE card_stats SET score = ?1, last_opened = ?2 WHERE id = ?3",
(&stat.score, &stat.last_open.timestamp(), &stat.id), (&stat.score, &stat.last_open.timestamp(), &stat.id),
) )
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); info!("Updated stat: {}", time.elapsed().as_millis());
0 Ok(())
});
println!("Updated stat: {}", time.elapsed().as_millis());
} }
pub fn delete_stat(stat: &CardStatistics, connection: &Connection) { pub fn delete_stats(stat: &[CardStatistics], connection: &Connection) -> MaybeError {
if stat.id == 0 { if stat.is_empty() {
return; return Ok(());
} }
let ids = stat
.iter()
.map(|s| s.id.into())
.collect::<Vec<String>>()
.join(", ");
connection connection
.execute("DELETE FROM card_stats WHERE id = ?1", (&stat.id,)) .execute(
.unwrap_or_else(|e| { format!("DELETE FROM card_stats WHERE id in ({ids})").as_str(),
println!("{}", e); (),
0 )
}); .map_err(|_| DbSaveError)?;
Ok(())
} }
+37 -39
View File
@@ -1,46 +1,60 @@
use std::fs; use crate::core::srs::WordOpenMode;
use crate::dictionary::app_data_dir; use crate::data::Id;
use crate::lang::WordOpenMode; use crate::data::entities::HistoryItem;
use chrono::{DateTime, Utc}; use crate::fs::*;
use crate::notification::NotificationData::PermissionDenied;
use crate::notification::{MaybeError, NotificationData};
use chrono::DateTime;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::Write; use std::io::Write;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::path::PathBuf; use std::path::PathBuf;
pub fn get_history_of_set(id: u32) -> Vec<HistoryItem> { pub fn get_history_of_set(id: Id) -> Result<Vec<HistoryItem>, NotificationData> {
let app_dir = history_dir(); let app_dir = history_dir()?;
let head = app_dir.clone().join(format!("set_{}_history.csv", id)); let head = app_dir.clone().join(format!("set_{}_history.csv", id));
let mut lines = Vec::new(); let mut lines = Vec::new();
append_lines_if_exists(head, &mut lines); append_lines_if_exists(head, &mut lines)?;
lines.reverse(); lines.reverse();
parse_history_items(lines) Ok(parse_history_items(lines))
} }
fn append_lines_if_exists(path: PathBuf, lines: &mut Vec<String>) { fn append_lines_if_exists(path: PathBuf, lines: &mut Vec<String>) -> MaybeError {
if path.exists() { if path.exists() {
let reader = BufReader::new(File::open(path).unwrap()); let reader = BufReader::new(File::open(path).map_err(|_| PermissionDenied)?);
for line in reader.lines() { reader
lines.push(line.unwrap()); .lines()
} .map_while(Result::ok)
.for_each(|i| lines.push(i));
} }
Ok(())
} }
fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> { fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
let mut items = Vec::with_capacity(strings.len()); let mut items = Vec::with_capacity(strings.len());
for string in strings { for string in strings {
if let [time, word, mode, before, after] = string.split(';').collect::<Vec<&str>>()[..] { if let [time, word, mode, before, after] = string.split(';').collect::<Vec<&str>>()[..] {
let id = word.parse::<Id>();
if id.is_err() {
continue;
}
let id = id.unwrap_or_default();
if !id.is_valid() {
continue;
}
items.push(HistoryItem { items.push(HistoryItem {
timestamp: DateTime::from_timestamp(time.parse().unwrap(), 0).unwrap(), timestamp: DateTime::from_timestamp(time.parse().unwrap_or_default(), 0)
word_id: word.parse::<u32>().unwrap(), .unwrap_or_default(),
mode: match mode.parse::<u8>().unwrap() { word_id: id,
mode: match mode.parse::<u8>().unwrap_or_default() {
2 => WordOpenMode::Hard, 2 => WordOpenMode::Hard,
3 => WordOpenMode::Ok, 3 => WordOpenMode::Ok,
4 => WordOpenMode::Easy, 4 => WordOpenMode::Easy,
_ => WordOpenMode::None, _ => WordOpenMode::None,
}, },
before: before.parse().unwrap(), before: before.parse().unwrap_or_default(),
after: after.parse().unwrap(), after: after.parse().unwrap_or_default(),
}); });
} }
} }
@@ -48,15 +62,15 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
items items
} }
pub fn push_note(set_id: u32, item: HistoryItem) { pub fn push_note(set_id: Id, item: HistoryItem) -> MaybeError {
let app_dir = history_dir(); let app_dir = history_dir()?;
let path = app_dir.clone().join(format!("set_{}_history.csv", set_id)); let path = app_dir.clone().join(format!("set_{}_history.csv", set_id));
let mut file = OpenOptions::new() let mut file = OpenOptions::new()
.create(true) .create(true)
.append(true) .append(true)
.open(path) .open(path)
.unwrap(); .map_err(|_| PermissionDenied)?;
let line_str = format!( let line_str = format!(
"{};{};{};{};{}", "{};{};{};{};{}",
item.timestamp.timestamp(), item.timestamp.timestamp(),
@@ -70,22 +84,6 @@ pub fn push_note(set_id: u32, item: HistoryItem) {
item.before, item.before,
item.after item.after
); );
writeln!(&mut file, "{}", line_str.to_string()).unwrap(); writeln!(&mut file, "{}", line_str).map_err(|_| PermissionDenied)?;
} Ok(())
pub fn history_dir() -> PathBuf {
let directory = app_data_dir().join("history");
if !directory.exists() {
fs::create_dir(directory.clone()).unwrap();
}
directory
}
#[derive(Clone)]
pub struct HistoryItem {
pub timestamp: DateTime<Utc>,
pub word_id: u32,
pub mode: WordOpenMode,
pub before: u8,
pub after: u8,
} }
+51 -23
View File
@@ -1,6 +1,10 @@
use crate::helpers::into_result;
use crate::notification::NotificationData;
use crate::notification::NotificationData::IncorrectAnkiFile;
use hashbrown::HashMap;
use log::info;
use rusqlite::Connection; use rusqlite::Connection;
use serde_json::Value; use serde_json::Value;
use std::collections::HashMap;
#[derive(Clone)] #[derive(Clone)]
pub struct ImportData(pub(crate) Vec<ImportGroup>); pub struct ImportData(pub(crate) Vec<ImportGroup>);
@@ -12,7 +16,7 @@ pub struct ImportGroup {
pub fields: Vec<String>, pub fields: Vec<String>,
pub length: u64, pub length: u64,
pub mapping: HashMap<String, String>, pub mapping: HashMap<String, String>,
pub imported: bool pub imported: bool,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -21,34 +25,47 @@ pub struct ImportNote {
pub fields: Vec<String>, pub fields: Vec<String>,
} }
pub fn load_groups(connection: &Connection) -> ImportData { pub fn load_groups(connection: &Connection) -> Result<ImportData, NotificationData> {
let json_models: String = connection let json_models: String = connection
.query_one("select models from col", (), |row| row.get(0)) .query_one("select models from col", (), |row| row.get(0))
.unwrap(); .map_err(|_| IncorrectAnkiFile)?;
let raw: Value = serde_json::from_str(json_models.as_str()).unwrap(); let raw: Value = serde_json::from_str(json_models.as_str()).map_err(|_| IncorrectAnkiFile)?;
let sets = raw.as_object().unwrap(); let sets = raw.as_object();
if let Some(sets) = sets {
let mut total_data = ImportData(vec![]); let mut total_data = ImportData(vec![]);
let mut count_stmt = connection let mut count_stmt = connection
.prepare("select mid, count(id) from notes group by mid") .prepare("select mid, count(id) from notes group by mid")
.unwrap(); .map_err(|_| IncorrectAnkiFile)?;
let counts = count_stmt let counts = count_stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?))) .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap() .map_err(|_| IncorrectAnkiFile)?
.map(|x| x.unwrap()) .filter_map(|x| x.ok())
.collect::<Vec<(i64, i64)>>(); .collect::<Vec<(i64, i64)>>();
for (_, collection) in sets { for (_, collection) in sets {
let fields = collection["flds"] let fields_property = collection.get("fields");
.as_array() if let Some(fields_property) = fields_property {
.unwrap() let fields = into_result(fields_property.as_array(), IncorrectAnkiFile)?
.iter() .iter()
.map(|x| x["name"].as_str().unwrap().to_string()) .filter_map(|x| x.get("name"))
.map(|x| x.as_str().unwrap().to_string())
.collect(); .collect();
let id = collection.get("id");
if id.is_none() || id.unwrap().as_u64().is_none() {
return Err(IncorrectAnkiFile);
}
let id = id.unwrap().as_u64().unwrap();
let name = collection.get("name");
if name.is_none() || name.unwrap().as_str().is_none() {
return Err(IncorrectAnkiFile);
}
let name = name.unwrap().as_str().unwrap().to_string();
let mut group = ImportGroup { let mut group = ImportGroup {
id: collection["id"].as_u64().unwrap(), id,
name: collection["name"].as_str().unwrap().to_string(), name,
fields, fields,
mapping: Default::default(), mapping: Default::default(),
length: 0, length: 0,
@@ -57,24 +74,35 @@ pub fn load_groups(connection: &Connection) -> ImportData {
if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) { if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) {
group.length = *count as u64 group.length = *count as u64
} }
println!("{:?}", group); info!("{:?}", group);
total_data.0.push(group); total_data.0.push(group);
} }
total_data }
return Ok(total_data);
}
Err(IncorrectAnkiFile)
} }
pub fn get_words_of_group(connection: &Connection, group_id: u64) -> Vec<ImportNote> { pub fn get_words_of_group(
connection: &Connection,
group_id: u64,
) -> Result<Vec<ImportNote>, NotificationData> {
let mut count_stmt = connection let mut count_stmt = connection
.prepare("select tags, flds from notes where mid == ?1;") .prepare("select tags, flds from notes where mid == ?1;")
.unwrap(); .map_err(|_| IncorrectAnkiFile)?;
count_stmt.query_map((group_id as i64, ), |row| { Ok(count_stmt
.query_map((group_id as i64,), |row| {
Ok(ImportNote { Ok(ImportNote {
tags: row.get(0)?, tags: row.get(0)?,
fields: row.get::<usize, String>(1)? fields: row
.get::<usize, String>(1)?
.split('') .split('')
.map(|x| x.to_string()) .map(|x| x.to_string())
.collect() .collect(),
}) })
}).unwrap().map(|x| x.unwrap()).collect::<Vec<ImportNote>>() })
.map_err(|_| IncorrectAnkiFile)?
.filter_map(|x| x.ok())
.collect::<Vec<ImportNote>>())
} }
+2 -2
View File
@@ -1,9 +1,9 @@
pub(crate) mod card_sets; pub(crate) mod card_sets;
pub(crate) mod card_stats; pub(crate) mod card_stats;
pub(crate) mod history; pub(crate) mod history;
pub(crate) mod import;
pub(crate) mod settings; pub(crate) mod settings;
pub(crate) mod sqlite; pub(crate) mod sqlite;
pub(crate) mod voice; pub(crate) mod voice;
pub(crate) mod words;
pub(crate) mod web_api; pub(crate) mod web_api;
pub(crate) mod import; pub(crate) mod words;
+31 -29
View File
@@ -1,51 +1,51 @@
use crate::notification::NotificationData::{DbLoadError, DbSaveError};
use crate::notification::{MaybeError, NotificationData};
use rusqlite::Connection; use rusqlite::Connection;
pub fn get_setting(key: String, connection: &Connection) -> Option<String> { pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT value FROM settings WHERE id = ?1") .prepare("SELECT value FROM settings WHERE id = ?1")
.unwrap(); .expect("Failed to prepare statement.");
let iter = stmt.query_map((key,), |row| row.get(0)).unwrap(); let mut iter = stmt.query_map((key,), |row| row.get(0)).ok()?;
for row in iter { if let Some(row) = iter.next()
if let Ok(value) = row { && let Ok(value) = row
{
return Some(value); return Some(value);
} }
return None;
}
None None
} }
pub fn set_setting(key: String, value: String, connection: &Connection) { pub fn set_setting(key: String, value: String, connection: &Connection) -> MaybeError {
let current = get_settings_list(connection); let current = get_settings_list(connection)?;
if current.contains(&key) { if current.contains(&key) {
update_settings(key, value, connection); update_settings(key, value, connection)?;
} else { } else {
create_settings(key, value, connection); create_settings(key, value, connection)?;
} }
Ok(())
} }
pub fn delete_settings(key: String, connection: &Connection) { pub fn delete_settings(key: String, connection: &Connection) -> MaybeError {
connection connection
.execute("DELETE FROM settings WHERE id = ?1", (&key,)) .execute("DELETE FROM settings WHERE id = ?1", (&key,))
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
fn create_settings(key: String, value: String, connection: &Connection) { fn create_settings(key: String, value: String, connection: &Connection) -> MaybeError {
connection connection
.execute( .execute(
"INSERT into settings (id, value) VALUES (?1, ?2)", "INSERT into settings (id, value) VALUES (?1, ?2)",
(key, value), (key, value),
) )
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
fn update_settings(key: String, value: String, connection: &Connection) { fn update_settings(key: String, value: String, connection: &Connection) -> MaybeError {
connection connection
.execute( .execute(
"update settings "update settings
@@ -53,14 +53,16 @@ set value = ?2
where id = ?1", where id = ?1",
(key, value), (key, value),
) )
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
fn get_settings_list(connection: &Connection) -> Vec<String> { fn get_settings_list(connection: &Connection) -> Result<Vec<String>, NotificationData> {
let mut stmt = connection.prepare("SELECT id FROM settings").unwrap(); let mut stmt = connection
let iter = stmt.query_map((), |row| row.get(0)).unwrap(); .prepare("SELECT id FROM settings")
iter.map(|row| row.unwrap()).collect() .expect("prepare stmt failed");
let iter = stmt
.query_map((), |row| row.get(0))
.map_err(|_| DbLoadError)?;
Ok(iter.filter_map(|i| i.ok()).collect())
} }
+17 -21
View File
@@ -1,30 +1,25 @@
use crate::dictionary::app_data_dir; use crate::fs::*;
use rusqlite::Connection; use rusqlite::Connection;
pub fn create_db() { pub fn create_db() {
let path = app_data_dir(); let db_file = db_path();
let db_file = path.join("data.db");
if !db_file.exists() { if !db_file.exists() {
std::fs::File::create(&db_file).unwrap(); std::fs::File::create(&db_file).expect("Database file creation failed");
let connection = Connection::open(&db_file).unwrap(); let connection = Connection::open(&db_file).expect("Connection open failed");
connection.execute("PRAGMA foreign_keys = ON;", []).unwrap(); connection
.execute("PRAGMA foreign_keys = ON;", [])
.expect("Failed to set PRAGMA");
create_tables(&connection); create_tables(&connection);
} else {
let connection = Connection::open(&db_file).unwrap();
ensure_db_schema(&connection);
} }
} }
fn ensure_db_schema(_: &Connection) {}
fn create_tables(conn: &Connection) { fn create_tables(conn: &Connection) {
make_card_set(conn).unwrap(); make_card_set(conn).expect("Failed to init table");
make_settings(conn).unwrap(); make_settings(conn).expect("Failed to init table");
make_word_group(conn).unwrap(); make_word_group(conn).expect("Failed to init table");
make_words(conn).unwrap(); make_words(conn).expect("Failed to init table");
make_card_stats(conn).unwrap(); make_card_stats(conn).expect("Failed to init table");
} }
fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> { fn make_settings(conn: &Connection) -> Result<(), rusqlite::Error> {
@@ -57,9 +52,10 @@ fn make_card_stats(conn: &Connection) -> Result<(), rusqlite::Error> {
} }
pub fn default_connection() -> Connection { pub fn default_connection() -> Connection {
let path = app_data_dir(); let db_file = db_path();
let db_file = path.join("data.db"); let connection = Connection::open(db_file).expect("Failed to open database");
let connection = Connection::open(db_file).unwrap(); connection
connection.execute("PRAGMA foreign_keys = ON;", []).unwrap(); .execute("PRAGMA foreign_keys = ON;", [])
.expect("Failed to set PRAGMA");
connection connection
} }
+19 -12
View File
@@ -1,15 +1,14 @@
use crate::dictionary::app_data_dir; use crate::fs::*;
use crate::notification::NotificationData;
use crate::notification::NotificationData::*;
use reqwest::Client; use reqwest::Client;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::fs::File; use std::fs::File;
use std::io::BufReader; use std::io::BufReader;
pub async fn get_voice(text: &str) -> BufReader<File> { pub async fn get_voice(text: &str) -> Result<BufReader<File>, NotificationData> {
let mut path = app_data_dir(); let mut path = voice_dir()?;
path.push("voice");
if !path.exists() {
std::fs::create_dir(path.clone()).unwrap();
}
let hash = format!("{}.wav", hex::encode(Sha256::digest(text.as_bytes()))); let hash = format!("{}.wav", hex::encode(Sha256::digest(text.as_bytes())));
path.push(hash); path.push(hash);
if !path.exists() { if !path.exists() {
@@ -20,7 +19,11 @@ pub async fn get_voice(text: &str) -> BufReader<File> {
.send() .send()
.await; .await;
let query = query.unwrap().text().await.unwrap(); let query = query
.map_err(|_| VoiceVoxUnavailable)?
.text()
.await
.map_err(|_| VoiceVoxUnavailable)?;
// Synthesis // Synthesis
let audio = client let audio = client
.post(format!("{engine_url}/synthesis?speaker=11")) .post(format!("{engine_url}/synthesis?speaker=11"))
@@ -28,13 +31,17 @@ pub async fn get_voice(text: &str) -> BufReader<File> {
.body(query) .body(query)
.send() .send()
.await .await
.unwrap() .map_err(|_| VoiceVoxUnavailable)?
.bytes() .bytes()
.await .await
.unwrap(); .map_err(|_| VoiceVoxUnavailable)?;
tokio::fs::write(&path, &audio).await.unwrap(); tokio::fs::write(&path, &audio)
.await
.map_err(|_| PermissionDenied)?;
} }
BufReader::new(File::open(path).unwrap()) Ok(BufReader::new(
File::open(path).map_err(|_| PermissionDenied)?,
))
} }
+97 -48
View File
@@ -1,34 +1,47 @@
use crate::dictionary::app_data_dir; use crate::fs::*;
use crate::notification::NotificationData::{CompressError, PermissionDenied, WebApiUnavailable};
use crate::notification::{MaybeError, NotificationData};
use log::info;
use std::io; use std::io;
use tokio::fs::{File, OpenOptions}; use tokio::fs::{File, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use zstd::{Decoder, Encoder, DEFAULT_COMPRESSION_LEVEL}; use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
// const API_URL: &str = "http://127.0.0.1:8089/"; // const API_URL: &str = "http://127.0.0.1:8089/";
const API_URL: &str = "https://learning.micialware.ru/"; const API_URL: &str = "https://learning.micialware.ru/";
pub async fn send_data(id: String) { pub async fn send_data(id: String) -> MaybeError {
let path = app_data_dir(); let db_file = db_path();
let db_file = path.join("data.db"); let data = tokio::fs::read(db_file)
let data = tokio::fs::read(db_file).await.unwrap(); .await
let data = compress(data); .map_err(|_| WebApiUnavailable)?;
let data = compress(data)?;
let api_url = API_URL.to_string(); let api_url = API_URL.to_string();
let id_url = format!("{api_url}upload/stream/{id}"); let id_url = format!("{api_url}upload/stream/{id}");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let new_version = client.post(&id_url).body(data).send().await.unwrap().text().await.unwrap(); let new_version = client
set_local_version(new_version.parse::<u32>().unwrap()).await; .post(&id_url)
.body(data)
.send()
.await
.map_err(|_| WebApiUnavailable)?
.text()
.await
.map_err(|_| WebApiUnavailable)?;
set_local_version(new_version.parse::<u32>().unwrap_or_default()).await?;
Ok(())
} }
fn compress(data: Vec<u8>) -> Vec<u8> { fn compress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> {
let mut encoder = Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).unwrap(); let mut encoder =
io::copy(&mut &data[..], &mut encoder).unwrap(); Encoder::new(Vec::new(), DEFAULT_COMPRESSION_LEVEL).map_err(|_| CompressError)?;
let compressed = encoder.finish().unwrap(); io::copy(&mut &data[..], &mut encoder).map_err(|_| PermissionDenied)?;
compressed encoder.finish().map_err(|_| CompressError)
} }
pub async fn load_data(id: String, temp: bool) { pub async fn load_data(id: String, temp: bool) -> MaybeError {
let api_url = API_URL.to_string(); let api_url = API_URL.to_string();
let id_url = format!("{api_url}download/{id}"); let id_url = format!("{api_url}download/{id}");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
@@ -36,35 +49,42 @@ pub async fn load_data(id: String, temp: bool) {
.get(&id_url) .get(&id_url)
.send() .send()
.await .await
.unwrap() .map_err(|_| WebApiUnavailable)?
.bytes() .bytes()
.await .await
.unwrap() .map_err(|_| WebApiUnavailable)?
.to_vec(); .to_vec();
let data = decompress(data); let data = decompress(data)?;
let path = app_data_dir(); let path = app_data_dir();
let file_name = if temp { "data.db.tmp" } else { "data.db" }; let file_name = if temp { "data.db.tmp" } else { "data.db" };
let db_file = path.join(file_name); let db_file = path.join(file_name);
tokio::fs::write(db_file, data).await.unwrap(); tokio::fs::write(db_file, data)
.await
.map_err(|_| PermissionDenied)?;
let version_url = format!("{API_URL}{id}/version"); let version_url = format!("{API_URL}{id}/version");
let version = client.get(&version_url).send().await.unwrap().text().await.unwrap(); let version = client
set_local_version(version.parse::<u32>().unwrap()).await; .get(&version_url)
.send()
.await
.map_err(|_| WebApiUnavailable)?
.text()
.await
.map_err(|_| WebApiUnavailable)?;
set_local_version(version.parse::<u32>().unwrap_or_default()).await?;
Ok(())
} }
pub fn decompress(data: Vec<u8>) -> Vec<u8> { pub fn decompress(data: Vec<u8>) -> Result<Vec<u8>, NotificationData> {
let mut decoder = Decoder::new(&data[..]).unwrap(); let mut decoder = Decoder::new(&data[..]).map_err(|_| CompressError)?;
let mut decompressed = Vec::new(); let mut decompressed = Vec::new();
let res = io::copy(&mut decoder, &mut decompressed); io::copy(&mut decoder, &mut decompressed).map_err(|_| PermissionDenied)?;
if let Err(e) = res { Ok(decompressed)
println!("{}", e);
}
decompressed
} }
pub async fn first_sync() -> String { pub async fn first_sync() -> Result<String, NotificationData> {
let id_url = API_URL.to_string() + "generate"; let id_url = API_URL.to_string() + "generate";
let client = reqwest::Client::new(); let client = reqwest::Client::new();
@@ -72,37 +92,66 @@ pub async fn first_sync() -> String {
.get(&id_url) .get(&id_url)
.send() .send()
.await .await
.unwrap() .map_err(|_| WebApiUnavailable)?
.text() .text()
.await .await
.unwrap(); .map_err(|_| WebApiUnavailable)?;
println!("id: {}", id); info!("id: {}", id);
id Ok(id)
} }
pub async fn get_web_version(key: &str) -> Result<u32, reqwest::Error> { pub async fn get_web_version(key: &str) -> Result<u32, NotificationData> {
let id_url = format!("{API_URL}{key}/version"); let id_url = format!("{API_URL}{key}/version");
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let version = client.get(&id_url).send().await?.text().await?; let version = client
return Ok(version.parse::<u32>().unwrap()); .get(&id_url)
.send()
.await
.map_err(|_| WebApiUnavailable)?
.text()
.await
.map_err(|_| WebApiUnavailable)?;
info!("version: {}", version);
Ok(version.parse::<u32>().unwrap_or_default())
} }
pub async fn get_local_version() -> u32 { pub async fn get_local_version() -> Result<u32, NotificationData> {
let file = app_data_dir().join("data.meta"); let file = db_meta_path();
if file.exists() { if file.exists() {
let mut data = String::new(); let mut data = String::new();
File::open(file.clone()).await.unwrap().read_to_string(&mut data).await.unwrap(); File::open(file.clone())
return data.parse::<u32>().unwrap(); .await
.map_err(|_| PermissionDenied)?
.read_to_string(&mut data)
.await
.map_err(|_| PermissionDenied)?;
return Ok(data.parse::<u32>().unwrap_or_default());
} }
let mut file = OpenOptions::new().write(true).create(true).open(file).await.unwrap(); let mut file = OpenOptions::new()
file.write_all("0".as_bytes()).await.unwrap(); .write(true)
0 .create(true)
.truncate(true)
.open(file)
.await
.map_err(|_| PermissionDenied)?;
file.write_all("0".as_bytes())
.await
.map_err(|_| PermissionDenied)?;
Ok(0)
} }
pub async fn set_local_version(version: u32) { pub async fn set_local_version(version: u32) -> Result<(), NotificationData> {
let file_path = app_data_dir().join("data.meta"); let file_path = db_meta_path();
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(file_path).await.unwrap(); let mut file = OpenOptions::new()
file.write_all(version.to_string().as_bytes()).await.unwrap(); .write(true)
.create(true)
.truncate(true)
.open(file_path)
.await
.map_err(|_| PermissionDenied)?;
file.write_all(version.to_string().as_bytes())
.await
.map_err(|_| PermissionDenied)?;
Ok(())
} }
+74 -83
View File
@@ -1,65 +1,65 @@
use crate::lang::{WordData, WordGroup}; use crate::data::entities::{WordData, WordGroup};
use rusqlite::{params, Connection}; use crate::notification::NotificationData::{DbLoadError, DbSaveError};
use crate::notification::{MaybeError, NotificationData};
use rusqlite::{Connection, params};
use std::collections::HashMap; use std::collections::HashMap;
pub fn add_word(word: &mut WordData, connection: &Connection) { pub fn add_word(word: &mut WordData, connection: &Connection) -> MaybeError {
let index = connection let index : u32 = connection
.query_row( .query_row(
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id", "INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5) RETURNING id",
( (
&word.key, &word.key,
&word.value, &word.value,
&word.tags, &word.tags,
serde_json::to_string(&word.additional).unwrap(), serde_json::to_string(&word.additional).unwrap_or_default(),
&word.group_id, &word.group_id,
), ),
|row| row.get(0), |row| row.get(0),
) ).map_err(|_| DbSaveError)?;
.unwrap_or_else(|e| {
println!("{}", e);
0
});
word.id = index; word.id = index.into();
Ok(())
} }
pub fn add_words(words: &mut[WordData], connection: &mut Connection) { pub fn add_words(words: &mut [WordData], connection: &mut Connection) -> MaybeError {
let tx = connection.transaction().unwrap(); let tx = connection.transaction().map_err(|_| DbLoadError)?;
let count = words.len(); let count = words.len();
{ {
let mut stmt = tx.prepare( let mut stmt = tx
.prepare(
"INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)", "INSERT INTO words (key, value, tags, more, group_id) VALUES (?1, ?2, ?3, ?4, ?5)",
).unwrap(); )
.expect("Failed to prepare statement");
for word in words.iter() { for word in words.iter() {
stmt.execute(params![word.key, word.value, word.tags, serde_json::to_string(&word.additional).unwrap(), word.group_id]).unwrap(); stmt.execute(params![
word.key,
word.value,
word.tags,
serde_json::to_string(&word.additional).unwrap_or_default(),
word.group_id
])
.map_err(|_| DbSaveError)?;
} }
} }
tx.commit().unwrap(); let last_index: u32 = tx.last_insert_rowid() as u32;
tx.commit().map_err(|_| DbSaveError)?;
let last_index: u32 = connection
.query_one(
"SELECT seq from sqlite_sequence WHERE name == ?1",
("words".to_string(),),
|row| row.get(0),
)
.unwrap();
let start_index = last_index - (count as u32) + 1; let start_index = last_index - (count as u32) + 1;
let mut index = 0; for (index, id) in (start_index..=last_index).enumerate() {
for id in start_index..=last_index { words[index].id = id.into();
words[index].id = id;
index += 1;
} }
Ok(())
} }
pub fn update_word(word: &mut WordData, connection: &Connection) { pub fn update_word(word: &mut WordData, connection: &Connection) -> MaybeError {
if word.id == 0 { if !word.id.is_valid() {
add_word(word, &connection); Ok(add_word(word, connection)?)
} else { } else {
connection connection
.execute( .execute(
@@ -68,33 +68,29 @@ pub fn update_word(word: &mut WordData, connection: &Connection) {
&word.key, &word.key,
&word.value, &word.value,
&word.tags, &word.tags,
serde_json::to_string(&word.additional).unwrap(), serde_json::to_string(&word.additional).map_err(|_| DbSaveError)?,
&word.id, &word.id,
), ),
) )
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
} }
pub fn delete_word(word: &WordData, connection: &Connection) { pub fn delete_word(word: &WordData, connection: &Connection) -> MaybeError {
if word.id == 0 { if !word.id.is_valid() {
return; return Err(DbSaveError);
} }
connection connection
.execute("DELETE FROM words WHERE id = ?1", (&word.id,)) .execute("DELETE FROM words WHERE id = ?1", (&word.id,))
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
pub fn load_words(connection: &Connection) -> Vec<WordData> { pub fn load_words(connection: &Connection) -> Result<Vec<WordData>, NotificationData> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT id, key, value, tags, more, group_id FROM words") .prepare("SELECT id, key, value, tags, more, group_id FROM words")
.unwrap(); .expect("Failed to prepare statement");
let word_iter = stmt let word_iter = stmt
.query_map([], |row| { .query_map([], |row| {
let additional: String = row.get(4)?; let additional: String = row.get(4)?;
@@ -103,24 +99,25 @@ pub fn load_words(connection: &Connection) -> Vec<WordData> {
key: row.get(1)?, key: row.get(1)?,
value: row.get(2)?, value: row.get(2)?,
tags: row.get(3)?, tags: row.get(3)?,
additional: serde_json::from_str::<HashMap<String, String>>(&additional).unwrap(), additional: serde_json::from_str::<HashMap<String, String>>(&additional)
.unwrap_or_default(),
group_id: row.get(5)?, group_id: row.get(5)?,
}) })
}) })
.unwrap(); .map_err(|_| DbLoadError)?;
let mut buffer = vec![]; let mut buffer = Vec::with_capacity(1024);
for word in word_iter { word_iter
buffer.push(word.unwrap()); .filter_map(|res| res.ok())
} .for_each(|i| buffer.push(i));
buffer Ok(buffer)
} }
pub fn load_word_groups(connection: &Connection) -> Vec<WordGroup> { pub fn load_word_groups(connection: &Connection) -> Result<Vec<WordGroup>, NotificationData> {
let mut stmt = connection let mut stmt = connection
.prepare("SELECT id, name FROM word_group") .prepare("SELECT id, name FROM word_group")
.unwrap(); .expect("Failed to prepare statement");
let group_iter = stmt let group_iter = stmt
.query_map([], |row| { .query_map([], |row| {
Ok(WordGroup { Ok(WordGroup {
@@ -128,55 +125,49 @@ pub fn load_word_groups(connection: &Connection) -> Vec<WordGroup> {
name: row.get(1)?, name: row.get(1)?,
}) })
}) })
.unwrap(); .map_err(|_| DbLoadError)?;
let mut buffer = vec![]; let mut buffer = Vec::with_capacity(8);
for group in group_iter { group_iter
buffer.push(group.unwrap()); .filter_map(|res| res.ok())
} .for_each(|i| buffer.push(i));
buffer Ok(buffer)
} }
pub fn add_group(group: &mut WordGroup, connection: &Connection) { pub fn add_group(group: &mut WordGroup, connection: &Connection) -> MaybeError {
let index = connection let index: u32 = connection
.query_row( .query_row(
"INSERT INTO word_group (name) VALUES (?1) RETURNING id", "INSERT INTO word_group (name) VALUES (?1) RETURNING id",
(&group.name,), (&group.name,),
|row| row.get(0), |row| row.get(0),
) )
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e);
0
});
group.id = index; group.id = index.into();
Ok(())
} }
pub fn update_group(group: &mut WordGroup, connection: &Connection) { pub fn update_group(group: &mut WordGroup, connection: &Connection) -> MaybeError {
if group.id == 0 { if !group.id.is_valid() {
add_group(group, &connection); Ok(add_group(group, connection)?)
} else { } else {
connection connection
.execute( .execute(
"UPDATE word_group SET name = ?1 WHERE id = ?2", "UPDATE word_group SET name = ?1 WHERE id = ?2",
(&group.name, &group.id), (&group.name, &group.id),
) )
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
} }
pub fn delete_group(group: &WordGroup, connection: &Connection) { pub fn delete_group(group: &WordGroup, connection: &Connection) -> MaybeError {
if group.id == 0 { if !group.id.is_valid() {
return; return Err(DbSaveError);
} }
connection connection
.execute("DELETE FROM word_group WHERE id = ?1", (&group.id,)) .execute("DELETE FROM word_group WHERE id = ?1", (&group.id,))
.unwrap_or_else(|e| { .map_err(|_| DbSaveError)?;
println!("{}", e); Ok(())
0
});
} }
+45
View File
@@ -0,0 +1,45 @@
use crate::notification::NotificationData;
use crate::notification::NotificationData::PermissionDenied;
use std::fs;
use std::path::PathBuf;
pub fn app_data_dir() -> PathBuf {
let mut dir = dirs::data_dir().expect("Unsupported OS");
dir.push("jap_learn");
if !dir.exists() {
fs::create_dir_all(dir.clone()).expect("Unable to create directory");
}
dir
}
pub fn db_path() -> PathBuf {
app_data_dir().join("data.db")
}
pub fn temp_db_path() -> PathBuf {
app_data_dir().join("data.db.tmp")
}
pub fn temp_import_path() -> PathBuf {
app_data_dir().join("import")
}
pub fn db_meta_path() -> PathBuf {
app_data_dir().join("data.meta")
}
pub fn history_dir() -> Result<PathBuf, NotificationData> {
let directory = app_data_dir().join("history");
if !directory.exists() {
fs::create_dir_all(directory.clone()).map_err(|_| PermissionDenied)?;
}
Ok(directory)
}
pub fn voice_dir() -> Result<PathBuf, NotificationData> {
let directory = app_data_dir().join("voice");
if !directory.exists() {
fs::create_dir_all(directory.clone()).map_err(|_| PermissionDenied)?;
}
Ok(directory)
}
+24
View File
@@ -0,0 +1,24 @@
#[macro_export]
macro_rules! push_error_task {
($e:expr) => {
iced::Task::done(push_error!($e))
};
}
#[macro_export]
macro_rules! push_error {
($e:expr) => {
$crate::navigation::RootMessage::PushNotification(
$crate::notification::NotificationRequest::Error($e),
)
};
}
#[inline(always)]
pub fn into_result<R, E>(option: Option<R>, error: E) -> Result<R, E> {
if let Some(r) = option {
Ok(r)
} else {
Err(error)
}
}
-633
View File
@@ -1,633 +0,0 @@
use crate::data_provider::card_stats::{
add_stat_list, delete_stat, load_stats_of_set, update_stat_score,
};
use crate::data_provider::history::{push_note, HistoryItem};
use crate::repetitions::CardSetSettings;
use crate::AppState;
use chrono::{DateTime, Utc};
use rand::distr::weighted::WeightedIndex;
use rand::distr::Distribution;
use rand::prelude::SliceRandom;
use rand::rng;
use rand::rngs::ThreadRng;
use serde::{Deserialize, Serialize};
use std::cmp::min;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
const MAX_HISTORY_LEN: usize = 20;
const MAX_HISTORY_LEN_PART: f32 = 0.33;
const MAX_SCORE: u8 = 25;
const FADE_PER_DAY: f32 = 0.95;
#[derive(Clone, Debug)]
pub struct KanaSet {
name: String,
pub(crate) chars_type: KanaType,
pub(crate) dictionary: Vec<Vec<(String, String)>>,
pub(crate) include_map: [bool; 10],
}
#[derive(Clone, Debug)]
pub enum KanaType {
Hiragana,
Katakana,
}
impl KanaSet {
pub fn hiragana() -> Self {
Self {
name: "Хирагана".to_string(),
chars_type: KanaType::Hiragana,
dictionary: vec![
vec![
(String::from("ぁ"), String::from("a")),
(String::from("ぃ"), String::from("i")),
(String::from("ぅ"), String::from("u")),
(String::from("ぇ"), String::from("e")),
(String::from("ぉ"), String::from("o")),
],
vec![
(String::from("さ"), String::from("sa")),
(String::from("し"), String::from("shi")),
(String::from("す"), String::from("su")),
(String::from("せ"), String::from("se")),
(String::from("そ"), String::from("so")),
],
vec![
(String::from("か"), String::from("ka")),
(String::from("き"), String::from("ki")),
(String::from("く"), String::from("ku")),
(String::from("け"), String::from("ke")),
(String::from("こ"), String::from("ko")),
],
// Ряд «та» (たちつてと)
vec![
(String::from("た"), String::from("ta")),
(String::from("ち"), String::from("chi")),
(String::from("つ"), String::from("tsu")),
(String::from("て"), String::from("te")),
(String::from("と"), String::from("to")),
],
// Ряд «на» (なにぬねの)
vec![
(String::from("な"), String::from("na")),
(String::from("に"), String::from("ni")),
(String::from("ぬ"), String::from("nu")),
(String::from("ね"), String::from("ne")),
(String::from("の"), String::from("no")),
],
// Ряд «ха» (はひふへほ)
vec![
(String::from("は"), String::from("ha")),
(String::from("ひ"), String::from("hi")),
(String::from("ふ"), String::from("fu")),
(String::from("へ"), String::from("he")),
(String::from("ほ"), String::from("ho")),
],
// Ряд «ма» (まみむめも)
vec![
(String::from("ま"), String::from("ma")),
(String::from("み"), String::from("mi")),
(String::from("む"), String::from("mu")),
(String::from("め"), String::from("me")),
(String::from("も"), String::from("mo")),
],
// Ряд «я» (やゆよ) — только 3 символа
vec![
(String::from("や"), String::from("ya")),
(String::from("ゆ"), String::from("yu")),
(String::from("よ"), String::from("yo")),
],
// Ряд «ра» (らりるれろ)
vec![
(String::from("ら"), String::from("ra")),
(String::from("り"), String::from("ri")),
(String::from("る"), String::from("ru")),
(String::from("れ"), String::from("re")),
(String::from("ろ"), String::from("ro")),
],
vec![
(String::from("わ"), String::from("wa")),
(String::from("を"), String::from("wo")),
(String::from("ん"), String::from("n")),
],
],
include_map: [true; 10],
}
}
pub fn katakana() -> Self {
Self {
name: "Катакана".to_string(),
chars_type: KanaType::Katakana,
dictionary: vec![
vec![
(String::from("ァ"), String::from("a")),
(String::from("ィ"), String::from("i")),
(String::from("ゥ"), String::from("u")),
(String::from("ェ"), String::from("e")),
(String::from("ォ"), String::from("o")),
],
vec![
(String::from("サ"), String::from("sa")),
(String::from("シ"), String::from("shi")),
(String::from("ス"), String::from("su")),
(String::from("セ"), String::from("se")),
(String::from("ソ"), String::from("so")),
],
vec![
(String::from("カ"), String::from("ka")),
(String::from("キ"), String::from("ki")),
(String::from("ク"), String::from("ku")),
(String::from("ケ"), String::from("ke")),
(String::from("コ"), String::from("ko")),
],
// Ряд «та» (タチツテト)
vec![
(String::from("タ"), String::from("ta")),
(String::from("チ"), String::from("chi")),
(String::from("ツ"), String::from("tsu")),
(String::from("テ"), String::from("te")),
(String::from("ト"), String::from("to")),
],
// Ряд «на» (ナニヌネノ)
vec![
(String::from("ナ"), String::from("na")),
(String::from("ニ"), String::from("ni")),
(String::from("ヌ"), String::from("nu")),
(String::from("ネ"), String::from("ne")),
(String::from("ノ"), String::from("no")),
],
// Ряд «ха» (ハヒフヘホ)
vec![
(String::from("ハ"), String::from("ha")),
(String::from("ヒ"), String::from("hi")),
(String::from("フ"), String::from("fu")),
(String::from("ヘ"), String::from("he")),
(String::from("ホ"), String::from("ho")),
],
// Ряд «ма» (マミムメモ)
vec![
(String::from("マ"), String::from("ma")),
(String::from("ミ"), String::from("mi")),
(String::from("ム"), String::from("mu")),
(String::from("メ"), String::from("me")),
(String::from("モ"), String::from("mo")),
],
// Ряд «я» (ヤユヨ) — только 3 символа
vec![
(String::from("ヤ"), String::from("ya")),
(String::from("ユ"), String::from("yu")),
(String::from("ヨ"), String::from("yo")),
],
// Ряд «ра» (ラリルレロ)
vec![
(String::from("ラ"), String::from("ra")),
(String::from("リ"), String::from("ri")),
(String::from("ル"), String::from("ru")),
(String::from("レ"), String::from("re")),
(String::from("ロ"), String::from("ro")),
],
vec![
(String::from("ワ"), String::from("wa")),
(String::from("ヲ"), String::from("wo")),
(String::from("ン"), String::from("n")),
],
],
include_map: [true; 10],
}
}
/* pub fn next(&mut self) -> (String, String) {
let current_set = self.list();
let mut rand = rand::rng();
let index: u32 = rand.random();
current_set[index as usize % current_set.len()].clone()
}*/
pub fn list(&self) -> Vec<(String, String)> {
let mut current_set: Vec<(String, String)> = Vec::new();
for i in 0..10 {
if self.include_map[i] {
self.dictionary[i].iter().for_each(|v| {
current_set.push(v.clone());
});
}
}
current_set
}
}
impl Default for KanaSet {
fn default() -> Self {
KanaSet::hiragana()
}
}
impl PartialEq<Self> for KanaSet {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct WordData {
pub id: u32,
pub key: String,
pub value: String,
pub tags: String,
pub additional: HashMap<String, String>,
pub group_id: u32,
}
impl WordData {
pub fn new() -> Self {
Self {
id: 0,
key: String::new(),
value: String::new(),
tags: String::new(),
additional: Default::default(),
group_id: 1,
}
}
}
#[derive(Clone)]
pub struct WordGroup {
pub id: u32,
pub name: String,
}
#[derive(Clone, PartialEq)]
pub struct CardStatistics {
pub id: u32,
pub word_id: u32,
pub set_id: u32,
pub last_open: DateTime<Utc>,
pub score: u8,
}
impl CardStatistics {
pub fn update(&mut self, status: WordOpenMode) {
match status {
WordOpenMode::Easy => {
self.score = (self.calculated_score() + 5.0).round() as u8;
}
WordOpenMode::Ok => self.score = (self.calculated_score() + 2.0).round() as u8,
WordOpenMode::Hard => {
self.score = (self.calculated_score() * 0.75).round() as u8;
}
WordOpenMode::None => {
self.score = (self.calculated_score() * 0.4) as u8;
}
}
if self.score < 1 {
self.score = 1
} else if self.score > MAX_SCORE {
self.score = MAX_SCORE
}
self.last_open = Utc::now();
}
pub fn calculated_score(&self) -> f32 {
let time = Utc::now() - self.last_open;
let days = time.num_days();
let multiplier = FADE_PER_DAY.powi(days as i32);
(self.score as f32 * multiplier).max(1.0)
}
}
#[derive(Clone, Copy)]
pub enum WordOpenMode {
Easy,
Ok,
Hard,
None,
}
#[derive(Clone)]
pub struct CardSet {
words: Vec<WordData>,
set: Vec<CardStatistics>,
current_word_index: Option<usize>,
state: Arc<Mutex<AppState>>,
order_module: OrderModule,
settings: CardSetSettings,
}
impl CardSet {
pub fn new(settings: &CardSetSettings, state: Arc<Mutex<AppState>>) -> Self {
let state_for = state.clone();
let state_locked = state.lock().unwrap();
let mut current_set = load_stats_of_set(&settings, &state_locked.connection);
let last_list = settings.get_word_list(&state_locked);
let saved_ids = current_set.iter().map(|l| l.word_id).collect::<Vec<u32>>();
let word_ids = last_list.iter().map(|l| l.id).collect::<Vec<u32>>();
let new_stats: &mut Vec<CardStatistics> = &mut last_list
.iter()
.filter(|word| !saved_ids.contains(&word.id))
.map(|word| CardStatistics {
id: 0,
word_id: word.id.clone(),
last_open: Utc::now(),
score: 1,
set_id: settings.id.clone(),
})
.collect();
let time = Instant::now();
if !new_stats.is_empty() {
add_stat_list(new_stats, &state_locked.connection);
current_set.append(new_stats);
}
println!(
"Added {} stats: {}",
new_stats.len(),
time.elapsed().as_millis()
);
let mut index = 0;
for stat in current_set.clone() {
if !word_ids.contains(&stat.word_id) {
delete_stat(&stat, &state_locked.connection);
current_set.remove(index);
} else {
index += 1;
}
}
Self {
set: current_set,
words: last_list,
current_word_index: None,
state: state_for,
order_module: match settings.open_mode {
SetOrderMode::Default => OrderModule::SemiRandomSRS(SemiRandomSRSModule::new()),
SetOrderMode::TrainWorstFirst => {
OrderModule::WorstWordsSRS(WorstWordsSRSModule::new())
}
SetOrderMode::FullRandom => OrderModule::RandomSRS(RandomSRSModule::new()),
},
settings: settings.clone(),
}
}
pub fn next(&mut self) -> (WordData, CardStatistics) {
let index = match self.order_module.clone() {
OrderModule::SemiRandomSRS(mut module) => {
if module.initialized == false {
module.init(self)
}
let index = module.next(self);
self.order_module = OrderModule::SemiRandomSRS(module);
index
}
OrderModule::RandomSRS(mut module) => {
if module.initialized == false {
module.init(self)
}
let index = module.next(self);
self.order_module = OrderModule::RandomSRS(module);
index
}
OrderModule::WorstWordsSRS(mut module) => {
if module.initialized == false {
module.init(self)
}
let index = module.next(self);
self.order_module = OrderModule::WorstWordsSRS(module);
index
}
};
self.current_word_index = Some(index);
(self.words[index].clone(), self.set[index].clone())
}
pub fn open(&mut self, status: WordOpenMode) {
if let None = self.current_word_index {
return;
}
let index = self.current_word_index.unwrap();
let word = &mut self.set[index];
let old_score = word.score;
word.update(status);
let new_score = word.score;
match self.order_module.clone() {
OrderModule::SemiRandomSRS(mut module) => {
module.open(status, index, word.clone());
self.order_module = OrderModule::SemiRandomSRS(module);
}
OrderModule::RandomSRS(mut module) => {
module.open(status, index, word.clone());
self.order_module = OrderModule::RandomSRS(module);
}
OrderModule::WorstWordsSRS(mut module) => {
module.open(status, index, word.clone());
self.order_module = OrderModule::WorstWordsSRS(module);
}
}
update_stat_score(word, &self.state.lock().unwrap().connection);
push_note(
self.settings.id,
HistoryItem {
timestamp: Utc::now(),
word_id: word.word_id,
mode: WordOpenMode::Easy,
before: old_score,
after: new_score,
},
)
}
pub fn len(&self) -> usize {
self.set.len()
}
}
#[derive(Clone, PartialEq, Copy, Eq)]
pub enum SetOrderMode {
Default,
TrainWorstFirst,
FullRandom,
}
#[derive(Clone)]
enum OrderModule {
SemiRandomSRS(SemiRandomSRSModule),
RandomSRS(RandomSRSModule),
WorstWordsSRS(WorstWordsSRSModule),
}
trait SRSModule {
fn next(&mut self, set: &mut CardSet) -> usize;
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: CardStatistics);
fn init(&mut self, set: &mut CardSet);
}
#[derive(Clone)]
struct RandomSRSModule {
basket: Vec<usize>,
initialized: bool,
}
impl RandomSRSModule {
fn new() -> RandomSRSModule {
Self {
basket: vec![],
initialized: false,
}
}
}
impl SRSModule for RandomSRSModule {
fn next(&mut self, set: &mut CardSet) -> usize {
if self.basket.is_empty() {
self.basket = (0..set.words.len()).collect::<Vec<usize>>();
self.basket.shuffle(&mut rand::rng())
}
self.basket.pop().unwrap()
}
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
fn init(&mut self, set: &mut CardSet) {
self.initialized = true;
self.basket = (0..set.words.len()).collect::<Vec<usize>>();
self.basket.shuffle(&mut rand::rng())
}
}
#[derive(Clone)]
struct SemiRandomSRSModule {
history: Vec<usize>,
last_weights: WeightedIndex<f32>,
generator: ThreadRng,
initialized: bool,
}
impl SemiRandomSRSModule {
fn new() -> SemiRandomSRSModule {
SemiRandomSRSModule {
history: vec![],
last_weights: WeightedIndex::new([1.0]).unwrap(),
generator: rng(),
initialized: false,
}
}
}
impl SRSModule for SemiRandomSRSModule {
fn next(&mut self, set: &mut CardSet) -> usize {
let index = self.last_weights.sample(&mut self.generator);
if self.history.contains(&index) {
return self.next(set);
}
if self.history.len() == self.history_len(set) {
self.history.remove(0);
}
self.history.push(index);
index
}
fn open(&mut self, _: WordOpenMode, index: usize, word: CardStatistics) {
let new_weight = (100.0 / word.calculated_score()).powf(2.0);
self.last_weights
.update_weights(&[(index, &new_weight)])
.unwrap();
}
fn init(&mut self, set: &mut CardSet) {
self.initialized = true;
let weights = set
.set
.iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>();
self.last_weights = WeightedIndex::new(weights).unwrap();
}
}
impl SemiRandomSRSModule {
fn history_len(&self, set: &CardSet) -> usize {
min(
MAX_HISTORY_LEN,
(set.len() as f32 * MAX_HISTORY_LEN_PART) as usize,
)
}
}
#[derive(Clone)]
struct WorstWordsSRSModule {
initialized: bool,
pool_size: usize,
rounds_remaining: u8,
pool: Vec<usize>,
queue: Vec<usize>,
rounds_count: u8,
}
impl SRSModule for WorstWordsSRSModule {
fn next(&mut self, set: &mut CardSet) -> usize {
if self.rounds_remaining == 0 {
self.fill_pool(set);
self.rounds_remaining = self.rounds_count;
}
if self.queue.is_empty() {
self.queue.append(&mut self.pool.clone());
self.rounds_remaining -= 1;
}
self.queue.pop().unwrap()
}
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
fn init(&mut self, _: &mut CardSet) {
self.initialized = true;
}
}
impl WorstWordsSRSModule {
fn new() -> WorstWordsSRSModule {
WorstWordsSRSModule {
initialized: false,
pool_size: 15,
rounds_count: 2,
rounds_remaining: 0,
pool: vec![],
queue: vec![],
}
}
fn fill_pool(&mut self, set: &CardSet) {
let mut sorted = set
.set
.clone()
.into_iter()
.zip(0..set.set.len())
.collect::<Vec<_>>();
sorted.sort_by_key(|c| c.0.score);
let mut worst = sorted[0..self.pool_size]
.iter()
.map(|(_, index)| *index)
.collect::<Vec<usize>>();
worst.shuffle(&mut rand::rng());
self.pool = worst;
}
}
+13 -111
View File
@@ -1,121 +1,23 @@
#![windows_subsystem = "windows"] #![windows_subsystem = "windows"]
pub mod app;
mod core;
mod data;
mod data_provider; mod data_provider;
mod dictionary; mod fs;
mod dictionary_test; pub mod helpers;
mod history; mod navigation;
mod lang; pub mod notification;
pub mod navigation; mod pages;
mod quiz; mod styling;
mod randomizer; pub mod tests;
mod repetition;
mod repetitions;
mod selector;
pub mod styling;
mod sync;
mod word;
mod writing;
mod repetition_settings;
pub mod import;
use crate::data_provider::card_sets::load_sets; use crate::app::start;
use crate::data_provider::settings::get_setting;
use crate::data_provider::sqlite::default_connection;
use crate::data_provider::words::{load_word_groups, load_words};
use crate::lang::{WordData, WordGroup};
use crate::navigation::{AppSettings, RootMessage, ScreenState};
use crate::quiz::*;
use crate::repetitions::CardSetSettings;
use crate::RootMessage::Keyboard;
use chrono::NaiveDate;
use iced::{keyboard, Subscription, Theme};
use iced::{window, Font};
use iced_core::window::Position;
use iced_core::Size;
use rusqlite::Connection;
use std::collections::HashMap;
use iced_core::window::settings::PlatformSpecific;
use mimalloc::MiMalloc; use mimalloc::MiMalloc;
#[global_allocator] #[global_allocator]
static GLOBAL: MiMalloc = MiMalloc; static GLOBAL: MiMalloc = MiMalloc;
const USER_FONT: Font = Font::with_name("Noto Sans JP");
fn main() -> iced::Result { fn main() -> iced::Result {
println!("Welcome to JapLearn"); env_logger::init();
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view).window(window_settings()) start()
.subscription(subscription)
.title("JapLearn")
.settings(iced::Settings {
default_text_size: iced::Pixels(18.0),
..iced::Settings::default()
})
.font(include_bytes!("../noto.ttf"))
.default_font(USER_FONT)
.theme(Theme::GruvboxDark).run()
}
fn window_settings() -> window::Settings {
let mut settings = window::Settings{
position: Position::Centered,
min_size: Some(Size::new(700.0_f32.into(), 700.0_f32.into())),
.. Default::default()
};
#[cfg(target_os = "linux")]
{
settings.platform_specific =
PlatformSpecific {
application_id: "JapLearn".to_string(),
override_redirect: false
};
}
settings
}
fn subscription(_state: &ScreenState) -> Subscription<RootMessage> {
keyboard::listen().map(|e| Keyboard(e))
}
pub struct AppState {
pub dictionary: Vec<WordData>,
pub card_sets: Vec<CardSetSettings>,
pub word_groups: Vec<WordGroup>,
pub connection: Connection,
pub sync_data: AppSettings,
pub activity: HashMap<u32, Vec<(NaiveDate, u32)>>
}
impl AppState {
pub fn new() -> Self {
Self {
dictionary: vec![],
card_sets: vec![],
word_groups: vec![],
connection: default_connection(),
sync_data: AppSettings { key: None, auto_web_fetch: false },
activity: Default::default(),
}
}
}
fn fill_state(state: &mut AppState) {
let list = load_words(&state.connection);
let sets = load_sets(&state.connection);
let groups = load_word_groups(&state.connection);
let setting = load_settings(&state.connection);
state.dictionary = list;
state.card_sets = sets;
state.word_groups = groups;
state.sync_data = setting
}
fn load_settings(connection: &Connection) -> AppSettings {
let key = get_setting("SYNC_KEY".to_string(), connection);
let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection).unwrap_or("false".to_string()).parse::<bool>().unwrap();
AppSettings { key, auto_web_fetch: fetch }
} }
+125 -78
View File
@@ -1,33 +1,47 @@
use crate::data_provider::history::{get_history_of_set, history_dir}; use crate::app::{AppState, fill_state};
use crate::data::Id;
use crate::data_provider::history::get_history_of_set;
use crate::data_provider::sqlite::{create_db, default_connection}; use crate::data_provider::sqlite::{create_db, default_connection};
use crate::data_provider::web_api::{get_local_version, get_web_version, load_data, set_local_version}; use crate::data_provider::web_api::{
use crate::dictionary::{app_data_dir, DictionaryMessage, DictionaryState}; get_local_version, get_web_version, load_data, set_local_version,
use crate::dictionary_test::{DictionaryQuizMessage, DictionaryQuizState}; };
use crate::history::{HistoryMessage, HistoryState}; use crate::fs::*;
use crate::message_navigation;
use crate::navigation::Page::*; use crate::navigation::Page::*;
use crate::navigation::RootMessage::{DataLoaded, Keyboard, UpdateData}; use crate::navigation::RootMessage::{
use crate::quiz::{QuizMessage, QuizState}; DataLoaded, Keyboard, Notification, PushNotification, UpdateData,
use crate::randomizer::{RandomizerMessage, RandomizerState}; };
use crate::repetition::{RepetitionMessage, RepetitionState}; use crate::notification::NotificationData::PermissionDenied;
use crate::repetition_settings::{RepetitionSettingsMessage, RepetitionSettingsState}; use crate::notification::{
use crate::repetitions::{RepetitionsMessage, RepetitionsState}; NotificationData, NotificationManager, NotificationMessage, NotificationRequest,
use crate::selector::{SelectorMessage, SelectorState}; };
use crate::pages::dictionary::{DictionaryMessage, DictionaryState};
use crate::pages::dictionary_quiz::{DictionaryQuizMessage, DictionaryQuizState};
use crate::pages::history::{HistoryMessage, HistoryState};
use crate::pages::import::{ImportMessage, ImportState};
use crate::pages::quiz::{QuizMessage, QuizState};
use crate::pages::randomizer::{RandomizerMessage, RandomizerState};
use crate::pages::repetition::{RepetitionMessage, RepetitionState};
use crate::pages::repetition_settings::{RepetitionSettingsMessage, RepetitionSettingsState};
use crate::pages::repetitions::{RepetitionsMessage, RepetitionsState};
use crate::pages::selector::{SelectorMessage, SelectorState};
use crate::pages::sync::{SyncMessage, SyncState};
use crate::pages::word::{WordMessage, WordState};
use crate::pages::writing::{WritingMessage, WritingState};
use crate::state_navigate_handle; use crate::state_navigate_handle;
use crate::state_update; use crate::state_update;
use crate::sync::{SyncMessage, SyncState};
use crate::view_navigation; use crate::view_navigation;
use crate::word::{WordMessage, WordState}; use crate::{message_navigation, push_error, push_error_task};
use crate::writing::{WritingMessage, WritingState};
use crate::{AppState, fill_state};
use chrono::NaiveDate; use chrono::NaiveDate;
use hashbrown::HashMap;
use iced::keyboard::Event; use iced::keyboard::Event;
use iced::widget::stack;
use iced::{Element, Task}; use iced::{Element, Task};
use reqwest::Error; use iced_core::Length::Fill;
use std::collections::HashMap; use log::info;
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use rusqlite::Connection;
use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
use crate::import::{ImportMessage, ImportState};
impl Default for ScreenState { impl Default for ScreenState {
fn default() -> Self { fn default() -> Self {
@@ -37,6 +51,7 @@ impl Default for ScreenState {
ScreenState { ScreenState {
stack: vec![Selector(SelectorState::new(state.clone()))], stack: vec![Selector(SelectorState::new(state.clone()))],
app_state: state.clone(), app_state: state.clone(),
notification_manager: NotificationManager::new(),
} }
} }
} }
@@ -57,11 +72,14 @@ pub enum RootMessage {
RepetitionSettings(RepetitionSettingsMessage), RepetitionSettings(RepetitionSettingsMessage),
Import(ImportMessage), Import(ImportMessage),
Keyboard(Event), Keyboard(Event),
DataLoaded(HashMap<u32, Vec<(NaiveDate, u32)>>), DataLoaded(HashMap<Id, Vec<(NaiveDate, u32)>>),
PushNotification(NotificationRequest),
Notification(NotificationMessage),
None, None,
UpdateData, UpdateData,
} }
#[allow(clippy::enum_variant_names)]
#[allow(clippy::large_enum_variant)]
pub enum Page { pub enum Page {
Selector(SelectorState), Selector(SelectorState),
Quiz(QuizState), Quiz(QuizState),
@@ -82,51 +100,62 @@ pub enum Page {
pub struct ScreenState { pub struct ScreenState {
stack: Vec<Page>, stack: Vec<Page>,
app_state: Arc<Mutex<AppState>>, app_state: Arc<Mutex<AppState>>,
notification_manager: NotificationManager,
} }
impl ScreenState { impl ScreenState {
pub fn boot() -> (ScreenState, Task<RootMessage>) { pub fn boot() -> (ScreenState, Task<RootMessage>) {
println!("Booting"); info!("Booting");
create_db(); create_db();
println!("Db created"); info!("Db created");
let state = ScreenState::default(); let state = ScreenState::default();
let reading_additional_task = Task::perform(Self::load_additional_data(), |data| data); let reading_additional_task = Task::perform(Self::load_additional_data(), |data| {
data.unwrap_or_else(|err| push_error!(err))
});
let final_task; let mut final_task = reading_additional_task;
let state_guard = state.app_state.lock().unwrap(); let state_guard = state.app_state.lock();
if state_guard.sync_data.auto_web_fetch { if state_guard.sync_data.auto_web_fetch
let key = state_guard.sync_data.key.clone().unwrap(); && let Some(key) = state_guard.sync_data.key.clone()
{
final_task = Task::batch([ final_task = Task::batch([
reading_additional_task, final_task,
Task::perform(Self::load_web_backup(key), |result| { Task::perform(Self::load_web_backup(key), |result| match result {
if let Ok(update) = result && update { Ok(update) => {
if update {
UpdateData UpdateData
} else { } else {
RootMessage::None RootMessage::None
} }
}
Err(err) => push_error!(err),
}), }),
]); ]);
} else {
final_task = reading_additional_task;
} }
drop(state_guard); drop(state_guard);
println!("Boot finished"); info!("Boot finished");
(state, final_task) (state, final_task)
} }
async fn load_additional_data() -> RootMessage { async fn load_additional_data() -> Result<RootMessage, NotificationData> {
let directory = history_dir(); let directory = history_dir()?;
let mut map = HashMap::new();
for file in directory.read_dir().unwrap() {
if let Ok(file) = file {
let mut vec = vec![];
let history_file_name = file.file_name().into_string().unwrap();
let id = history_file_name[4..history_file_name.len() - 12]
.parse::<u32>()
.unwrap();
let history = get_history_of_set(id); let mut map = HashMap::new();
for file in directory
.read_dir()
.map_err(|_| PermissionDenied)?
.filter_map(Result::ok)
{
let mut vec = vec![];
let history_file_name = match file.file_name().into_string() {
Err(_) => continue,
Ok(v) => v,
};
if let Ok(id) = history_file_name.split('_').collect::<Vec<_>>()[1].parse::<Id>()
&& let Ok(history) = get_history_of_set(id)
{
let by_date = history.chunk_by(|x, x1| { let by_date = history.chunk_by(|x, x1| {
x.timestamp.naive_local().date() == x1.timestamp.naive_local().date() x.timestamp.naive_local().date() == x1.timestamp.naive_local().date()
}); });
@@ -134,48 +163,64 @@ impl ScreenState {
vec.push((group[0].timestamp.naive_local().date(), group.len() as u32)); vec.push((group[0].timestamp.naive_local().date(), group.len() as u32));
} }
map.insert(id, vec); map.insert(id, vec);
} else {
continue;
} }
} }
DataLoaded(map) Ok(DataLoaded(map))
} }
async fn load_web_backup(string: String) -> Result<bool, Error> { async fn load_web_backup(string: String) -> Result<bool, NotificationData> {
let local = get_local_version().await; let local = get_local_version().await?;
let web = get_web_version(string.as_str()).await?; let web = get_web_version(string.as_str()).await?;
info!("{} {}", local, web);
if web > local { if web > local {
println!("Web version is newer than local version"); info!("Web version is newer than local version");
load_data(string, true).await; load_data(string, true).await?;
set_local_version(web).await; set_local_version(web).await?;
}else { } else {
return Ok(false); return Ok(false);
} }
Ok(true) Ok(true)
} }
pub fn update(&mut self, message: RootMessage) -> Task<RootMessage> { pub fn update(&mut self, message: RootMessage) -> Task<RootMessage> {
println!("Updating"); info!("Updating");
let time = Instant::now(); let time = Instant::now();
if let Keyboard(e) = message { if let Keyboard(e) = message {
return self.handle_keyboard(e); return self.handle_keyboard(e);
} }
if let DataLoaded(data) = message { if let DataLoaded(data) = message {
self.app_state.lock().unwrap().activity = data; self.app_state.lock().activity = data;
return Task::none(); return Task::none();
} }
if let UpdateData = message{ if let UpdateData = message {
println!("Loading data"); info!("Loading data");
let mut state = self.app_state.lock().unwrap(); let mut state = self.app_state.lock();
let path = app_data_dir(); if cfg!(windows) {
let db_file = path.join("data.db"); state.connection = Connection::open_in_memory().unwrap();
let temp_db_file = path.join("data.db.tmp"); }
std::fs::rename(temp_db_file, &db_file).unwrap(); let db_file = db_path();
let temp_db_file = temp_db_path();
if std::fs::rename(temp_db_file, &db_file).is_err() {
return push_error_task!(PermissionDenied);
}
state.connection = default_connection(); state.connection = default_connection();
fill_state(&mut state); fill_state(&mut state);
return Task::none(); return Task::none();
} }
if let Notification(message) = message {
return self.notification_manager.update(message);
}
if let PushNotification(notification) = &message {
return self.notification_manager.push(notification.clone());
}
let task: (Task<RootMessage>, bool) = self.navigate_or_update(message); let task: (Task<RootMessage>, bool) = self.navigate_or_update(message);
if task.1 { if task.1 {
@@ -196,7 +241,7 @@ impl ScreenState {
Import Import
); );
} }
println!("Update took {:?}", time.elapsed()); info!("Update took {:?}", time.elapsed());
task.0 task.0
} }
@@ -222,7 +267,7 @@ impl ScreenState {
} }
pub fn view(&self) -> Element<'_, RootMessage> { pub fn view(&self) -> Element<'_, RootMessage> {
println!("View update"); info!("View update");
let time = Instant::now(); let time = Instant::now();
let view = view_navigation!( let view = view_navigation!(
self.stack, self.stack,
@@ -241,16 +286,20 @@ impl ScreenState {
Import Import
); );
println!("View took {:?}", time.elapsed()); let notifications = self.notification_manager.draw().map(Notification);
view
info!("View took {:?}", time.elapsed());
stack![view, notifications].width(Fill).height(Fill).into()
} }
fn handle_keyboard(&mut self, message: Event) -> Task<RootMessage> { fn handle_keyboard(&mut self, message: Event) -> Task<RootMessage> {
let page = self.stack.last_mut().unwrap(); if let Some(page) = self.stack.last_mut() {
match page { return match page {
Repetition(page) => page.press(&message), Repetition(page) => page.press(&message),
_ => Task::none(), _ => Task::none(),
};
} }
Task::none()
} }
} }
@@ -262,7 +311,7 @@ pub struct AppSettings {
#[macro_export] #[macro_export]
macro_rules! view_navigation { macro_rules! view_navigation {
($stack:expr, $($e:ident), *) => { ($stack:expr, $($e:ident), *) => {
match &$stack.last().unwrap() { match &$stack.last().expect("Unexpected stack state") {
$( $(
$e(s) => s.view().map(RootMessage::$e), $e(s) => s.view().map(RootMessage::$e),
)* )*
@@ -270,14 +319,13 @@ macro_rules! view_navigation {
} }
} }
} }
#[macro_export] #[macro_export]
macro_rules! state_update { macro_rules! state_update {
($message:expr, $stack:expr, $($e:ident), *) => { ($message:expr, $stack:expr, $($e:ident), *) => {
match $message { match $message {
$( $(
RootMessage::$e(msg) => { RootMessage::$e(msg) => {
if let $e(s) = $stack.last_mut().unwrap() { if let $e(s) = $stack.last_mut().expect("Unexpected stack state") {
message_navigation!(msg, $stack, s) message_navigation!(msg, $stack, s)
} }
else { else {
@@ -289,13 +337,15 @@ macro_rules! state_update {
} }
} }
} }
#[macro_export] #[macro_export]
macro_rules! message_navigation { macro_rules! message_navigation {
($msg:expr, $stack:expr, $state:expr) => { ($msg:expr, $stack:expr, $state:expr) => {
if let Some(new_page) = $state.navigate(&$msg) { if let Some(new_page) = $state.navigate(&$msg) {
if let Page::PreviousPage = new_page { if let Page::PreviousPage = new_page {
if $stack.len() > 1 {
$stack.pop(); $stack.pop();
}
return (Task::<RootMessage>::none(), true); return (Task::<RootMessage>::none(), true);
} else { } else {
$stack.push(new_page); $stack.push(new_page);
@@ -307,11 +357,10 @@ macro_rules! message_navigation {
} }
}; };
} }
#[macro_export] #[macro_export]
macro_rules! state_navigate_handle { macro_rules! state_navigate_handle {
($stack:expr, $($e:ident), *) => { ($stack:expr, $($e:ident), *) => {
match $stack.last_mut().unwrap() { match $stack.last_mut().expect("Unexpected stack state") {
$( $(
Page::$e(page) => { Page::$e(page) => {
page.navigated(); page.navigated();
@@ -321,14 +370,12 @@ macro_rules! state_navigate_handle {
} }
} }
} }
pub trait NavigatedPage<T> { pub trait NavigatedPage<T> {
fn navigate(&self, message: &T) -> Option<Page>; fn navigate(&mut self, message: &T) -> Option<Page>;
fn navigated(&mut self); fn navigated(&mut self);
fn update(&mut self, message: T) -> Task<RootMessage>; fn update(&mut self, message: T) -> Task<RootMessage>;
fn view(&self) -> Element<'_, T>; fn view(&self) -> Element<'_, T>;
} }
pub trait KeyPressedPage { pub trait KeyPressedPage {
fn press(&mut self, message: &Event) -> Task<RootMessage>; fn press(&mut self, message: &Event) -> Task<RootMessage>;
} }
+198
View File
@@ -0,0 +1,198 @@
use crate::navigation::RootMessage;
use crate::styling::{BUTTON_RADIUS, HALF_SPACING};
use chrono::Utc;
use iced::widget::container::Style;
use iced::widget::{Column, container, row, scrollable, text};
use iced::{Element, Task};
use iced_core::Alignment::Center;
use iced_core::Background::Color;
use iced_core::Border;
use iced_core::Length::Fill;
use iced_core::alignment::Horizontal::Right;
use iced_core::alignment::Vertical;
pub struct NotificationManager {
list: Vec<(u32, NotificationRequest, u32)>,
notification_lifetime: u32,
next_id: u32,
}
#[derive(Clone)]
pub enum NotificationMessage {
Remove(u32),
}
impl Default for NotificationManager {
fn default() -> Self {
Self::new()
}
}
impl NotificationManager {
pub fn new() -> Self {
Self {
list: Vec::new(),
notification_lifetime: 10,
next_id: 1,
}
}
pub fn draw(&self) -> Element<'_, NotificationMessage> {
let mut column = Column::new().spacing(HALF_SPACING);
for (id, notif, time) in &self.list {
column = column.push(Self::draw_notif(id, notif, time));
}
container(scrollable(column))
.width(Fill)
.height(Fill)
.align_x(Right)
.align_y(Vertical::Top)
.padding(HALF_SPACING)
.into()
}
pub fn push(&mut self, notification: NotificationRequest) -> Task<RootMessage> {
let id = self.next_id;
self.list.push((
id,
notification,
Utc::now().timestamp() as u32 + self.notification_lifetime,
));
self.next_id += 1;
let message = NotificationMessage::Remove(id);
let time = self.notification_lifetime;
Task::perform(
async move {
tokio::time::sleep(core::time::Duration::from_secs(time as u64)).await;
},
|_| RootMessage::Notification(message),
)
}
pub fn update(&mut self, message: NotificationMessage) -> Task<RootMessage> {
match message {
NotificationMessage::Remove(id) => {
if let Some(index) = self.list.iter().position(|item| item.0 == id) {
self.list.remove(index);
}
}
}
Task::none()
}
fn draw_notif<'a>(
id: &u32,
notif: &NotificationRequest,
_time: &u32,
) -> Element<'a, NotificationMessage> {
let color_id;
let content = match notif {
NotificationRequest::Info(data) => {
color_id = 1;
Self::draw_data(data)
}
NotificationRequest::Warning(data) => {
color_id = 2;
Self::draw_data(data)
}
NotificationRequest::Error(data) => {
color_id = 3;
Self::draw_data(data)
}
};
let container = container(
row![
content,
iced::widget::button("✕")
.on_press(NotificationMessage::Remove(*id))
.style(iced::widget::button::text)
]
.align_y(Center)
.width(300)
.padding(HALF_SPACING),
);
container
.style(move |theme| {
let color = match color_id {
1 => theme.palette().success,
2 => theme.palette().warning,
3 => theme.palette().danger,
_ => theme.palette().warning,
};
Style {
text_color: None,
background: Some(Color(color.scale_alpha(0.3))),
border: Border::default()
.width(1)
.color(color)
.rounded(BUTTON_RADIUS),
shadow: Default::default(),
snap: false,
}
})
.into()
}
fn draw_data<'a>(data: &NotificationData) -> Element<'a, NotificationMessage> {
match data {
NotificationData::DataLoaded => {
text!("Данные успешно скачаны")
}
NotificationData::ImportError => {
text!("Ошибка при импорте данных из Anki")
}
NotificationData::IncorrectAnkiFile => {
text!("Неподдерживаемый формат файла .apkg")
}
NotificationData::OpenFileError => {
text!("Ошибка открытия файла пакета")
}
NotificationData::VoiceVoxUnavailable => {
text!("Не получается подключиться к VoiceVox")
}
NotificationData::PermissionDenied => {
text!("У приложение недостаточно прав")
}
NotificationData::WebApiUnavailable => {
text!("Не получается подключиться к Api")
}
NotificationData::DbSaveError => {
text!("Не получается сохранить данные")
}
NotificationData::DbLoadError => {
text!("Не получается загрузить данные")
}
NotificationData::CompressError => {
text!("Ошибка сжатия или распаковки данных")
}
}
.width(Fill)
.into()
}
}
#[derive(Clone)]
pub enum NotificationRequest {
Info(NotificationData),
Warning(NotificationData),
Error(NotificationData),
}
#[derive(Clone, Debug)]
pub enum NotificationData {
PermissionDenied,
DataLoaded,
ImportError,
IncorrectAnkiFile,
OpenFileError,
VoiceVoxUnavailable,
WebApiUnavailable,
DbSaveError,
DbLoadError,
CompressError,
}
pub type MaybeError = Result<(), NotificationData>;
+13
View File
@@ -0,0 +1,13 @@
pub mod dictionary;
pub mod dictionary_quiz;
pub mod history;
pub mod import;
pub mod quiz;
pub mod randomizer;
pub mod repetition;
pub mod repetition_settings;
pub mod repetitions;
pub mod selector;
pub mod sync;
pub mod word;
pub mod writing;
+96 -84
View File
@@ -1,14 +1,18 @@
use crate::app::AppState;
use crate::data::Id;
use crate::data::entities::{WordData, WordGroup};
use crate::data_provider::words::{delete_group, delete_word, update_group, update_word}; use crate::data_provider::words::{delete_group, delete_word, update_group, update_word};
use crate::dictionary::DictionaryMessage::*;
use crate::dictionary_test::DictionaryQuizState;
use crate::import::ImportState;
use crate::lang::{WordData, WordGroup};
use crate::navigation::Page::{Import, Word}; use crate::navigation::Page::{Import, Word};
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::pages::dictionary::DictionaryMessage::*;
use crate::pages::dictionary_quiz::DictionaryQuizState;
use crate::pages::import::ImportState;
use crate::pages::word::WordState;
use crate::push_error;
use crate::push_error_task;
use crate::styling::*; use crate::styling::*;
use crate::word::WordState;
use crate::{AppState, RootMessage};
use chrono::{DateTime, TimeDelta, Utc}; use chrono::{DateTime, TimeDelta, Utc};
use hashbrown::{HashMap, HashSet};
use iced::alignment::Vertical::Center; use iced::alignment::Vertical::Center;
use iced::widget::button::Style; use iced::widget::button::Style;
use iced::widget::button::{danger, text}; use iced::widget::button::{danger, text};
@@ -17,12 +21,11 @@ use iced::widget::text_input::default;
use iced::widget::*; use iced::widget::*;
use iced::{Border, Color, Shadow, Task}; use iced::{Border, Color, Shadow, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use log::info;
use parking_lot::Mutex;
use rand::random_range; use rand::random_range;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::ops::Add; use std::ops::Add;
use std::path::PathBuf; use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
#[derive(Clone)] #[derive(Clone)]
@@ -65,14 +68,15 @@ pub enum DictionaryMessage {
} }
impl NavigatedPage<DictionaryMessage> for DictionaryState { impl NavigatedPage<DictionaryMessage> for DictionaryState {
fn navigate(&self, message: &DictionaryMessage) -> Option<Page> { fn navigate(&mut self, message: &DictionaryMessage) -> Option<Page> {
if let Back = message { if let Back = message {
return Some(Page::PreviousPage); return Some(Page::PreviousPage);
} }
if let Test = message { if let Test = message
if self.include_map.iter().any(|x| *x) { && self.include_map.iter().any(|x| *x)
{
let mut words = vec![]; let mut words = vec![];
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
words = self words = self
.include_map .include_map
@@ -88,15 +92,14 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
self.no_typing, self.no_typing,
))); )));
} }
}
if let WordAction(index) = message { if let WordAction(index) = message {
let word: WordData; let word: WordData;
{ {
let state = self.state.lock().unwrap(); let state = self.state.lock();
let dict = &state.dictionary; let dict = &state.dictionary;
word = dict[*index].clone(); word = dict[*index].clone();
} }
if word.id != 0 { if word.id.is_valid() {
return Some(Word(WordState::new(word, *index, self.state.clone()))); return Some(Word(WordState::new(word, *index, self.state.clone())));
} }
} }
@@ -107,7 +110,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
fn navigated(&mut self) { fn navigated(&mut self) {
let len = self.state.lock().unwrap().dictionary.len(); let len = self.state.lock().dictionary.len();
self.include_map = vec![false; len]; self.include_map = vec![false; len];
self.tag_map = Default::default(); self.tag_map = Default::default();
@@ -117,9 +120,9 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
fn update(&mut self, message: DictionaryMessage) -> Task<RootMessage> { fn update(&mut self, message: DictionaryMessage) -> Task<RootMessage> {
match message { match message {
NewWord => { NewWord => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
let mut word = WordData::new(); let mut word = WordData::new();
word.group_id = state.word_groups[self.selected_group_index].id.clone(); word.group_id = state.word_groups[self.selected_group_index].id;
let dict = &mut state.dictionary; let dict = &mut state.dictionary;
dict.push(word); dict.push(word);
@@ -128,21 +131,21 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
SetKey(i, v) => { SetKey(i, v) => {
{ {
let dict = &mut self.state.lock().unwrap().dictionary; let dict = &mut self.state.lock().dictionary;
dict[i].key = v; dict[i].key = v;
} }
return self.launch_auto_save_offset(i); return self.launch_auto_save_offset(i);
} }
SetValue(i, v) => { SetValue(i, v) => {
{ {
let dict = &mut self.state.lock().unwrap().dictionary; let dict = &mut self.state.lock().dictionary;
dict[i].value = v dict[i].value = v
} }
return self.launch_auto_save_offset(i); return self.launch_auto_save_offset(i);
} }
SetTags(i, mut v) => { SetTags(i, mut v) => {
{ {
let dict = &mut self.state.lock().unwrap().dictionary; let dict = &mut self.state.lock().dictionary;
let current_tags_value = dict[i].tags.clone(); let current_tags_value = dict[i].tags.clone();
@@ -150,12 +153,11 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
v = v[..v.len() - 2].to_string() v = v[..v.len() - 2].to_string()
} }
while v.contains(",,") { while let Some(index) = v.find(",,") {
let index = v.find(",,").unwrap();
v.remove(index); v.remove(index);
} }
dict.get_mut(i).unwrap().tags = v; dict[i].tags = v;
} }
self.update_tags(); self.update_tags();
@@ -163,18 +165,20 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
WordAction(i) => { WordAction(i) => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let dict = &mut state.dictionary; let dict = &mut state.dictionary;
let word = dict.remove(i); let word = dict.remove(i);
self.include_map.remove(i); self.include_map.remove(i);
self.auto_save_queue.remove(&i); self.auto_save_queue.remove(&i);
delete_word(&word, &state.connection) if let Err(err) = delete_word(&word, &state.connection) {
return push_error_task!(err);
}
} }
Include(i, b) => self.include_map[i] = b, Include(i, b) => self.include_map[i] = b,
IncludeTag(t, v) => { IncludeTag(t, v) => {
let index: u32; let index;
{ {
let state = self.state.lock().unwrap(); let state = self.state.lock();
index = state.word_groups[self.selected_group_index].id; index = state.word_groups[self.selected_group_index].id;
} }
self.tag_map.insert(t, v); self.tag_map.insert(t, v);
@@ -190,41 +194,40 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
self.search = s; self.search = s;
} }
SetTyping(b) => self.no_typing = b, SetTyping(b) => self.no_typing = b,
SubmitWord(i) => self.save_word(i), SubmitWord(i) => return self.save_word(i),
Back => {} Back => {}
Test => {} Test => {}
CreateGroup => { CreateGroup => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
state.word_groups.push(WordGroup { state.word_groups.push(WordGroup {
id: 0, id: 0.into(),
name: format!("Группа слов {}", random_range(100..1000)), name: format!("Группа слов {}", random_range(100..1000)),
}); });
} }
EditGroup(new) => { EditGroup(new) => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let group = state.word_groups.get_mut(self.selected_group_index); let group = state.word_groups.get_mut(self.selected_group_index);
if let Some(group) = group { if let Some(group) = group {
group.name = new.clone(); group.name = new.clone();
} }
} }
SaveGroup => { SaveGroup => {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let connection = &state.connection; let connection = &state.connection;
let group = &mut state let mut group = state.word_groups[self.selected_group_index].clone();
.word_groups
.get(self.selected_group_index)
.unwrap()
.clone();
update_group(group, connection); if let Err(err) = update_group(&mut group, connection) {
state.word_groups[self.selected_group_index] = group.clone(); return push_error_task!(err);
}
state.word_groups[self.selected_group_index] = group;
} }
SelectGroup(i) => { SelectGroup(i) => {
self.selected_group_index = i; self.selected_group_index = i;
let index: u32; let index;
{ {
let state = self.state.lock().unwrap(); let state = self.state.lock();
index = state.word_groups[i].id; index = state.word_groups[i].id;
} }
self.update_words_include(index) self.update_words_include(index)
@@ -234,13 +237,16 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
return Task::none(); return Task::none();
} }
{ {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
if let Some(group) = state.word_groups.get(self.selected_group_index) { if let Some(group) = state.word_groups.get(self.selected_group_index) {
let remove_group_id = group.id; let remove_group_id = group.id;
let connection = &state.connection; let connection = &state.connection;
delete_group(group, connection); if let Err(err) = delete_group(group, connection) {
return push_error_task!(err);
}
state.word_groups.remove(self.selected_group_index); state.word_groups.remove(self.selected_group_index);
state state
.dictionary .dictionary
@@ -261,7 +267,8 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
if self.auto_save_queue[&word_index] <= now { if self.auto_save_queue[&word_index] <= now {
self.auto_save_queue.remove(&word_index); self.auto_save_queue.remove(&word_index);
self.save_word(word_index);
return self.save_word(word_index);
} }
} }
ToImport => {} ToImport => {}
@@ -277,7 +284,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
self.groups_panel(), self.groups_panel(),
row![horizontal().width(8), self.words_list(),], row![horizontal().width(8), self.words_list(),],
row![ row![
button("Добавить слово").style(jl_button).on_press(NewWord), self.add_word_button(),
horizontal().width(Fill), horizontal().width(Fill),
button("Импорт").style(text).on_press(ToImport), button("Импорт").style(text).on_press(ToImport),
] ]
@@ -294,7 +301,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
impl DictionaryState { impl DictionaryState {
pub fn new(state: Arc<Mutex<AppState>>) -> Self { pub fn new(state: Arc<Mutex<AppState>>) -> Self {
let len = state.lock().unwrap().dictionary.len(); let len = state.lock().dictionary.len();
let mut result = DictionaryState { let mut result = DictionaryState {
include_map: vec![false; len], include_map: vec![false; len],
@@ -313,13 +320,17 @@ impl DictionaryState {
result result
} }
fn save_word(&mut self, i: usize) { fn save_word(&mut self, i: usize) -> Task<RootMessage> {
let state = &mut self.state.lock().unwrap(); let state = &mut self.state.lock();
let connection = &state.connection; let connection = &state.connection;
let word = &mut state.dictionary.get(i).unwrap().clone(); let word = &mut state.dictionary[i].clone();
if let Err(err) = update_word(word, connection) {
return push_error_task!(err);
}
update_word(word, &connection);
state.dictionary[i] = word.clone(); state.dictionary[i] = word.clone();
Task::none()
} }
fn launch_auto_save_offset(&mut self, index: usize) -> Task<RootMessage> { fn launch_auto_save_offset(&mut self, index: usize) -> Task<RootMessage> {
@@ -336,7 +347,7 @@ impl DictionaryState {
let time = Instant::now(); let time = Instant::now();
let mut col = Column::new().width(Fill); let mut col = Column::new().width(Fill);
let state = self.state.lock().unwrap(); let state = self.state.lock();
let group_id = state.word_groups[self.selected_group_index].id; let group_id = state.word_groups[self.selected_group_index].id;
let dict = &state.dictionary; let dict = &state.dictionary;
@@ -353,14 +364,13 @@ impl DictionaryState {
continue; continue;
} }
if !self.search.is_empty() { if !self.search.is_empty()
if word.key.contains(&self.search) == false && !word.key.contains(&self.search)
&& word.value.contains(&self.search) == false && !word.value.contains(&self.search)
&& word.tags.contains(&self.search) == false && !word.tags.contains(&self.search)
{ {
continue; continue;
} }
}
let word_line_data = WordLineState { let word_line_data = WordLineState {
is_included: self.include_map[i], is_included: self.include_map[i],
@@ -424,7 +434,7 @@ impl DictionaryState {
let line_button = || { let line_button = || {
let action = WordAction(index); let action = WordAction(index);
if data.id == 0 { if !data.id.is_valid() {
return button("-").on_press(action).style(|_x, _status| Style { return button("-").on_press(action).style(|_x, _status| Style {
background: None, background: None,
text_color: Color::BLACK, text_color: Color::BLACK,
@@ -443,13 +453,13 @@ impl DictionaryState {
col = col.push(lazy_line); col = col.push(lazy_line);
} }
println!("Drawing {index} lines"); info!("Drawing {index} lines");
println!("Words rendering time: {:?}", time.elapsed()); info!("Words rendering time: {:?}", time.elapsed());
scrollable(col).height(Fill).into() scrollable(col).height(Fill).into()
} }
fn filters(&self) -> iced::Element<'_, DictionaryMessage> { fn filters(&self) -> iced::Element<'_, DictionaryMessage> {
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
iced::widget::column![ iced::widget::column![
text_input("Поиск", &self.search) text_input("Поиск", &self.search)
@@ -505,7 +515,7 @@ impl DictionaryState {
fn update_tags(&mut self) { fn update_tags(&mut self) {
let mut tags_list: HashSet<String> = HashSet::new(); let mut tags_list: HashSet<String> = HashSet::new();
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
dict.iter().for_each(|element| { dict.iter().for_each(|element| {
split_with_coma(element.tags.as_str()) split_with_coma(element.tags.as_str())
@@ -533,7 +543,7 @@ impl DictionaryState {
}); });
} }
fn update_words_include(&mut self, group_id: u32) { fn update_words_include(&mut self, group_id: Id) {
let include_tags = self let include_tags = self
.tag_map .tag_map
.iter() .iter()
@@ -546,35 +556,35 @@ impl DictionaryState {
return; return;
} }
let dict = &self.state.lock().unwrap().dictionary; let dict = &self.state.lock().dictionary;
let time = Instant::now(); let time = Instant::now();
self.include_map = dict self.include_map = dict
.iter() .iter()
.map(|word| (split_with_coma(word.tags.as_str()), word.group_id)) .map(|word| (split_with_coma(word.tags.as_str()), word.group_id))
.map(|(tags, word_group_id)| { .map(|(tags, word_group_id)| {
tags.iter().all(|t| include_tags.contains(t)) && tags.len() != 0 && word_group_id == group_id !tags.is_empty()
&& tags.iter().all(|t| include_tags.contains(t))
&& word_group_id == group_id
}) })
.collect(); .collect();
println!("Time {}", time.elapsed().as_micros()); info!("Time {}", time.elapsed().as_micros());
} }
fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> { fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> {
let mut row = Row::new(); let mut row = Row::new();
row = row.push(button("+").style(text).on_press(CreateGroup)); row = row.push(button("+").style(text).on_press(CreateGroup));
let state = &self.state.lock().unwrap(); let state = &self.state.lock();
let groups = &state.word_groups; let groups = &state.word_groups;
let mut index = 0; for (index, group) in groups.iter().enumerate() {
for group in groups {
row = row.push( row = row.push(
button(text!("{}", group.name.clone())) button(text!("{}", group.name.clone()))
.style(text) .style(text)
.on_press(SelectGroup(index)), .on_press(SelectGroup(index)),
); );
index = index + 1;
} }
let group = state.word_groups[self.selected_group_index].clone(); let group = state.word_groups[self.selected_group_index].clone();
@@ -602,6 +612,18 @@ impl DictionaryState {
space().into() space().into()
} }
} }
fn add_word_button(&self) -> iced::Element<'_, DictionaryMessage> {
let state = self.state.lock();
let group_id = state.word_groups[self.selected_group_index].id;
let button = button("Добавить слово").style(jl_button);
if group_id.is_valid() {
return button.on_press(NewWord).into();
}
button.into()
}
} }
pub fn split_with_coma(ts: &str) -> Vec<String> { pub fn split_with_coma(ts: &str) -> Vec<String> {
@@ -611,22 +633,12 @@ pub fn split_with_coma(ts: &str) -> Vec<String> {
.collect::<Vec<String>>() .collect::<Vec<String>>()
} }
pub fn app_data_dir() -> PathBuf {
let mut dir = dirs::data_dir().unwrap();
dir.push("jap_learn");
if !dir.exists() {
fs::create_dir(dir.clone()).unwrap();
}
dir
}
#[derive(Hash, PartialEq, Eq)] #[derive(Hash, PartialEq, Eq)]
struct WordLineState { struct WordLineState {
is_included: bool, is_included: bool,
key: String, key: String,
value: String, value: String,
tags: String, tags: String,
id: u32, id: Id,
index: usize, index: usize,
} }
@@ -1,16 +1,16 @@
use crate::dictionary::split_with_coma; use crate::data::entities::WordData;
use crate::dictionary_test::DictionaryQuizMessage::*;
use crate::lang::WordData;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::RootMessage;
use crate::navigation::*; use crate::navigation::*;
use crate::quiz::Score; use crate::pages::dictionary::split_with_coma;
use crate::pages::dictionary_quiz::DictionaryQuizMessage::*;
use crate::pages::quiz::Score;
use crate::styling::*; use crate::styling::*;
use crate::RootMessage; use iced::Background::Color;
use iced::border::Radius; use iced::border::Radius;
use iced::widget::container::Style; use iced::widget::container::Style;
use iced::widget::{button, container, row, space, text, text_input, Row}; use iced::widget::{Row, button, container, row, space, text, text_input};
use iced::Background::Color; use iced::{Border, Element, Fill, Task, Theme, alignment};
use iced::{alignment, Border, Element, Fill, Task, Theme};
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -35,15 +35,14 @@ pub enum DictionaryQuizMessage {
} }
impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState { impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
fn navigate(&self, message: &DictionaryQuizMessage) -> Option<Page> { fn navigate(&mut self, message: &DictionaryQuizMessage) -> Option<Page> {
match message { match message {
Back => Some(PreviousPage), Back => Some(PreviousPage),
_ => None, _ => None,
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: DictionaryQuizMessage) -> Task<RootMessage> { fn update(&mut self, message: DictionaryQuizMessage) -> Task<RootMessage> {
match message { match message {
@@ -120,7 +119,6 @@ impl DictionaryQuizState {
} }
} }
fn submit(&mut self) { fn submit(&mut self) {
if self.view == "---" { if self.view == "---" {
self.show_next(); self.show_next();
@@ -148,10 +146,11 @@ impl DictionaryQuizState {
if !self.is_help { if !self.is_help {
self.score.total += 1; self.score.total += 1;
} }
if self.answer == self.correct if self.answer.to_lowercase() == self.correct.to_lowercase()
|| split_with_coma(self.correct.as_str()).contains(&self.answer) || split_with_coma(self.correct.to_lowercase().as_str())
.contains(&self.answer.to_lowercase())
{ {
if self.is_help == false { if !self.is_help {
self.score.correct += 1; self.score.correct += 1;
} }
self.show_next() self.show_next()
@@ -173,11 +172,14 @@ impl DictionaryQuizState {
self.is_help = false; self.is_help = false;
self.answer = String::new(); self.answer = String::new();
if self.current_set.is_empty() { let next: WordData = match self.current_set.pop() {
Some(word) => word,
None => {
self.update_set(); self.update_set();
self.current_set.pop().expect("Empty set")
} }
};
let next = self.current_set.pop().unwrap();
if self.reverse { if self.reverse {
self.view = next.value.clone(); self.view = next.value.clone();
self.correct = next.key.clone(); self.correct = next.key.clone();
@@ -208,7 +210,7 @@ impl DictionaryQuizState {
} }
fn appeal_button(&self) -> Element<'_, DictionaryQuizMessage> { fn appeal_button(&self) -> Element<'_, DictionaryQuizMessage> {
if self.is_help && self.no_typing == false { if self.is_help && !self.no_typing {
return button("Апелляция").style(jl_button).on_press(Appeal).into(); return button("Апелляция").style(jl_button).on_press(Appeal).into();
} }
space().into() space().into()
+30 -24
View File
@@ -1,15 +1,17 @@
use crate::data_provider::history::{HistoryItem, get_history_of_set}; use crate::app::AppState;
use crate::lang::WordData; use crate::data::INVALID_ID;
use crate::navigation::{NavigatedPage, Page}; use crate::data::entities::{HistoryItem, WordData};
use crate::data_provider::history::get_history_of_set;
use crate::navigation::*;
use crate::styling::*; use crate::styling::*;
use crate::{AppState, RootMessage};
use HistoryMessage::Back; use HistoryMessage::Back;
use chrono::Local; use chrono::Local;
use iced::alignment::Horizontal::Center; use iced::alignment::Horizontal::Center;
use iced::widget::space::horizontal; use iced::widget::space::horizontal;
use iced::widget::*; use iced::widget::*;
use iced::{Element, Fill, FillPortion, Task}; use iced::{Element, Fill, FillPortion, Task};
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Clone)] #[derive(Clone)]
pub struct HistoryState { pub struct HistoryState {
@@ -18,13 +20,12 @@ pub struct HistoryState {
} }
impl NavigatedPage<HistoryMessage> for HistoryState { impl NavigatedPage<HistoryMessage> for HistoryState {
fn navigate(&self, message: &HistoryMessage) -> Option<Page> { fn navigate(&mut self, message: &HistoryMessage) -> Option<Page> {
match message { match message {
Back => Some(Page::PreviousPage), Back => Some(Page::PreviousPage),
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, _: HistoryMessage) -> Task<RootMessage> { fn update(&mut self, _: HistoryMessage) -> Task<RootMessage> {
Task::none() Task::none()
} }
@@ -47,19 +48,24 @@ impl NavigatedPage<HistoryMessage> for HistoryState {
} }
impl HistoryState { impl HistoryState {
pub fn new(id: u32, state: Arc<Mutex<AppState>>) -> Self { pub fn new(id: crate::data::Id, state: Arc<Mutex<AppState>>) -> Self {
let state = state.lock().unwrap(); let state = state.lock();
let history = get_history_of_set(id); let history = get_history_of_set(id).unwrap_or_default();
let words = history let words = history
.iter() .iter()
.map(|item| { .map(
state |item| match state.dictionary.iter().find(|w| w.id == item.word_id) {
.dictionary None => WordData {
.iter() id,
.find(|w| w.id == item.word_id) key: "Удаленное слово".to_string(),
.unwrap() value: "Удаленное слово".to_string(),
.clone() tags: "Удаленное слово".to_string(),
}) additional: Default::default(),
group_id: INVALID_ID,
},
Some(word) => word.clone(),
},
)
.collect(); .collect();
Self { Self {
@@ -68,11 +74,9 @@ impl HistoryState {
} }
} }
fn history_lines(&self) -> Column<'_, HistoryMessage> { fn history_lines(&self) -> Column<'_, HistoryMessage> {
let mut column = Column::new(); let mut column = Column::new();
for (item, index) in self.list.iter().zip(0..self.list.len()) { for (index, item) in self.list.iter().enumerate() {
column = column.push( column = column.push(
row![ row![
iced::widget::column![ iced::widget::column![
@@ -86,11 +90,13 @@ impl HistoryState {
.align_x(Center), .align_x(Center),
iced::widget::column![ iced::widget::column![
text!("{} ➞ {}", item.before, item.after), text!("{} ➞ {}", item.before, item.after),
text!("{}", item.timestamp.with_timezone(&Local).format("%d.%m %H:%M")) text!(
"{}",
item.timestamp.with_timezone(&Local).format("%d.%m %H:%M")
)
] ]
.spacing(5) .spacing(5)
.align_x(Center) .align_x(Center)
] ]
.spacing(5), .spacing(5),
); );
+72 -67
View File
@@ -1,10 +1,13 @@
use crate::AppState; use crate::app::AppState;
use crate::data::entities::{WordData, WordGroup};
use crate::data_provider::import::{ImportData, ImportGroup, get_words_of_group, load_groups}; use crate::data_provider::import::{ImportData, ImportGroup, get_words_of_group, load_groups};
use crate::data_provider::words::{add_group, add_words}; use crate::data_provider::words::{add_group, add_words};
use crate::dictionary::app_data_dir; use crate::fs::*;
use crate::import::ImportMessage::*;
use crate::lang::{WordData, WordGroup};
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::NotificationData::OpenFileError;
use crate::notification::{MaybeError, NotificationData};
use crate::pages::import::ImportMessage::*;
use crate::push_error;
use crate::styling::*; use crate::styling::*;
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::container::success; use iced::widget::container::success;
@@ -16,12 +19,14 @@ use iced::{Element, Task};
use iced_core::Alignment::Center; use iced_core::Alignment::Center;
use iced_core::Length::Fill; use iced_core::Length::Fill;
use iced_core::Padding; use iced_core::Padding;
use log::info;
use parking_lot::Mutex;
use rfd::AsyncFileDialog; use rfd::AsyncFileDialog;
use rusqlite::Connection; use rusqlite::Connection;
use std::fs::{File, OpenOptions}; use std::fs::{File, OpenOptions};
use std::io::BufReader; use std::io::BufReader;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use tokio::task::spawn_blocking; use tokio::task::spawn_blocking;
use zip::ZipArchive; use zip::ZipArchive;
@@ -62,8 +67,8 @@ pub enum ImportMessage {
} }
impl NavigatedPage<ImportMessage> for ImportState { impl NavigatedPage<ImportMessage> for ImportState {
fn navigate(&self, message: &ImportMessage) -> Option<Page> { fn navigate(&mut self, message: &ImportMessage) -> Option<Page> {
if let Some(_) = self.progress { if self.progress.is_some() {
return None; return None;
} }
@@ -80,10 +85,12 @@ impl NavigatedPage<ImportMessage> for ImportState {
Back => {} Back => {}
UpdateFile(path) => { UpdateFile(path) => {
self.path = Some(path); self.path = Some(path);
self.import_data = None;
return self.load_package(); return self.load_package();
} }
SelectFile => return Self::select_import_file(), SelectFile => return Self::select_import_file(),
UpdateImport(import) => { UpdateImport(import) => {
self.selected_index = 0;
self.import_data = Some(import); self.import_data = Some(import);
} }
NextGroup => { NextGroup => {
@@ -128,12 +135,7 @@ impl NavigatedPage<ImportMessage> for ImportState {
} }
ImportFinished => { ImportFinished => {
self.progress = None; self.progress = None;
let group = self let group = &mut self.import_data.as_mut().unwrap().0[self.selected_index];
.import_data.as_mut()
.unwrap()
.0
.get_mut(self.selected_index)
.unwrap();
group.imported = true; group.imported = true;
} }
} }
@@ -144,7 +146,7 @@ impl NavigatedPage<ImportMessage> for ImportState {
back_overlay( back_overlay(
{ {
if let Some(value) = &self.progress { if let Some(value) = &self.progress {
column![progress_bar(0f32..=1f32, *value.lock().unwrap()),] column![progress_bar(0f32..=1f32, *value.lock()),]
.spacing(QUARTER_SPACING) .spacing(QUARTER_SPACING)
.into() .into()
} else { } else {
@@ -200,7 +202,9 @@ impl ImportState {
fn import_button(&self, group: &ImportGroup) -> Element<'_, ImportMessage> { fn import_button(&self, group: &ImportGroup) -> Element<'_, ImportMessage> {
if group.imported { if group.imported {
return container(text!("Группа слов успешно импортирована")).padding(HALF_SPACING).align_x(Center) return container(text!("Группа слов успешно импортирована"))
.padding(HALF_SPACING)
.align_x(Center)
.style(success) .style(success)
.width(Fill) .width(Fill)
.into(); .into();
@@ -254,7 +258,7 @@ impl ImportState {
} }
fn property_selector(&self) -> Element<'_, ImportMessage> { fn property_selector(&self) -> Element<'_, ImportMessage> {
if self.selected_property == None { if self.selected_property.is_none() {
return space().into(); return space().into();
} }
column![ column![
@@ -275,9 +279,6 @@ impl ImportState {
let mut row = Row::new(); let mut row = Row::new();
for default in DEFAULT_FIELDS { for default in DEFAULT_FIELDS {
// if group.mapping.values().any(|name| name == default) {
// continue;
// }
row = row.push( row = row.push(
button(text!("{default}")).on_press(SetupDefaultProperty(default.to_string())), button(text!("{default}")).on_press(SetupDefaultProperty(default.to_string())),
); );
@@ -360,49 +361,48 @@ impl ImportState {
spawn_blocking(move || { spawn_blocking(move || {
Self::extract_import_file(path)?; Self::extract_import_file(path)?;
let data = Self::read_import_file()?; let data = Self::read_import_file()?;
return Ok(data); Ok(data)
}) })
.await .await
.unwrap() .unwrap()
}, },
|result: Result<ImportData, ()>| { |result: Result<ImportData, NotificationData>| match result {
if let Ok(import) = result { Ok(import) => RootMessage::Import(UpdateImport(import)),
RootMessage::Import(UpdateImport(import)) Err(err) => push_error!(err),
} else {
RootMessage::None
}
}, },
) )
} }
fn extract_import_file(path: PathBuf) -> Result<(), ()> { fn extract_import_file(path: PathBuf) -> MaybeError {
let file = File::open(path).map_err(|_| ())?; let file = File::open(path).map_err(|_| OpenFileError)?;
let reader = BufReader::new(file); let reader = BufReader::new(file);
let mut archive = ZipArchive::new(reader).map_err(|_| ())?; let mut archive = ZipArchive::new(reader).map_err(|_| OpenFileError)?;
let db_file = archive.by_name("collection.anki2"); let temp_file_path = temp_import_path();
if let Ok(mut file) = db_file {
let temp_file_path = app_data_dir().join("import");
let mut temp_file = OpenOptions::new() let mut temp_file = OpenOptions::new()
.write(true) .write(true)
.create(true) .create(true)
.truncate(true) .truncate(true)
.open(&temp_file_path) .open(&temp_file_path)
.map_err(|_| ())?; .map_err(|_| OpenFileError)?;
std::io::copy(&mut file, &mut temp_file).map_err(|_| ())?; if let Ok(mut file) = archive.by_name("collection.anki21") {
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
Ok(())
} else if let Ok(mut file) = archive.by_name("collection.anki2") {
std::io::copy(&mut file, &mut temp_file).map_err(|_| OpenFileError)?;
Ok(()) Ok(())
} else { } else {
Err(()) Err(OpenFileError)
} }
} }
fn read_import_file() -> Result<ImportData, ()> { fn read_import_file() -> Result<ImportData, NotificationData> {
let temp_file_path = app_data_dir().join("import"); let temp_file_path = temp_import_path();
let connection = Connection::open(&temp_file_path).map_err(|_| ())?; let connection = Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
let data = load_groups(&connection); let data = load_groups(&connection)?;
Ok(data) Ok(data)
} }
fn setup_mapping(&mut self, property_name: String) { fn setup_mapping(&mut self, property_name: String) {
let group = self.import_data.as_mut().unwrap(); let group = self.import_data.as_mut().unwrap();
let group = group.0.get_mut(self.selected_index).unwrap(); let group = &mut group.0[self.selected_index];
group group
.mapping .mapping
.insert(self.selected_property.clone().unwrap(), property_name); .insert(self.selected_property.clone().unwrap(), property_name);
@@ -411,7 +411,7 @@ impl ImportState {
} }
fn remove_mapping(&mut self, property_name: String) { fn remove_mapping(&mut self, property_name: String) {
let group = self.import_data.as_mut().unwrap(); let group = self.import_data.as_mut().unwrap();
let group = group.0.get_mut(self.selected_index).unwrap(); let group = &mut group.0[self.selected_index];
let remove_key = group let remove_key = group
.mapping .mapping
.keys() .keys()
@@ -428,23 +428,24 @@ impl ImportState {
let skip_empty = self.skip_empty; let skip_empty = self.skip_empty;
let group = self.import_data.as_ref().unwrap().0[self.selected_index].clone(); let group = self.import_data.as_ref().unwrap().0[self.selected_index].clone();
let progress = self.progress.clone().unwrap(); let progress = self.progress.clone().unwrap();
println!("{}", group.name); info!("{}", group.name);
Task::perform( Task::perform(
async move { async move {
spawn_blocking(move || { spawn_blocking(move || {
let temp_file_path = app_data_dir().join("import"); let temp_file_path = temp_import_path();
let connection = Connection::open(&temp_file_path).map_err(|_| ())?; let connection =
let import_list = get_words_of_group(&connection, group.id); Connection::open(&temp_file_path).map_err(|_| OpenFileError)?;
let import_list = get_words_of_group(&connection, group.id)?;
let mut words_list = Vec::with_capacity(import_list.len()); let mut words_list = Vec::with_capacity(import_list.len());
let map_indices = Self::get_mapping_indices(&group); let map_indices = Self::get_mapping_indices(&group);
let mut group_entity = WordGroup { let mut group_entity = WordGroup {
id: 0, id: 0.into(),
name: group.name.clone(), name: group.name.clone(),
}; };
{ {
let state = state.lock().unwrap(); let state = state.lock();
add_group(&mut group_entity, &state.connection); add_group(&mut group_entity, &state.connection)?;
} }
let group_id = group_entity.id; let group_id = group_entity.id;
@@ -452,11 +453,11 @@ impl ImportState {
let mut word = WordData::new(); let mut word = WordData::new();
word.tags = import.tags.trim().replace(" ", ", "); word.tags = import.tags.trim().replace(" ", ", ");
word.group_id = group_id.clone(); word.group_id = group_id;
for (dest, indices) in &map_indices { for (dest, indices) in &map_indices {
let collected_string = Self::collect_strings( let collected_string = Self::collect_strings(
&import.fields, &import.fields,
&indices, indices,
&separator, &separator,
skip_empty, skip_empty,
); );
@@ -476,19 +477,18 @@ impl ImportState {
} }
} }
println!("{word:?}");
words_list.push(word); words_list.push(word);
} }
let mut state = state.lock().unwrap(); let mut state = state.lock();
let connection = &mut state.connection; let connection = &mut state.connection;
let mut index = 0; let mut index = 0;
let total_len = words_list.len() as f32 / 256.0; let total_len = words_list.len() as f32 / 1024.0;
for word in &mut words_list.chunks_mut(256) { for word in &mut words_list.chunks_mut(1024) {
add_words(word, connection); add_words(word, connection)?;
index += 1; index += 1;
let mut progress = progress.lock().unwrap(); let mut progress = progress.lock();
*progress = index as f32 / total_len; *progress = (index as f32 / total_len).min(1.0);
} }
state.dictionary.append(&mut words_list); state.dictionary.append(&mut words_list);
@@ -499,7 +499,10 @@ impl ImportState {
.await .await
.unwrap() .unwrap()
}, },
|_: Result<(), ()>| RootMessage::Import(ImportFinished), |r: Result<(), NotificationData>| match r {
Ok(_) => RootMessage::Import(ImportFinished),
Err(err) => push_error!(err),
},
) )
} }
@@ -511,29 +514,31 @@ impl ImportState {
.iter() .iter()
.map(|name| (name.clone(), Vec::<usize>::with_capacity(1))) .map(|name| (name.clone(), Vec::<usize>::with_capacity(1)))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for key in group.mapping.keys() { for (key, endpoint) in &group.mapping {
let endpoint = group.mapping.get(key).unwrap(); let property_index = group
let property_index = group.fields.iter().position(|f| f == key).unwrap(); .fields
.iter()
.position(|f| f == key)
.expect("Unknown property");
let group_index = result let group_index = result
.iter() .iter()
.position(|(name, _)| name == endpoint) .position(|(name, _)| name == endpoint)
.unwrap(); .unwrap();
result.get_mut(group_index).unwrap().1.push(property_index); result[group_index].1.push(property_index);
} }
result result
} }
fn collect_strings( fn collect_strings(
properties: &Vec<String>, properties: &[String],
indices: &Vec<usize>, indices: &[usize],
separator: &str, separator: &str,
skip_empty: bool, skip_empty: bool,
) -> String { ) -> String {
let mut working_words = Vec::with_capacity(indices.len()); let mut working_words = Vec::with_capacity(indices.len());
for i in 0..indices.len() { for index in indices {
let index = indices[i]; let str = &properties[*index];
let str = properties.get(index).unwrap();
if skip_empty && str.is_empty() { if skip_empty && str.is_empty() {
continue; continue;
} }
+24 -22
View File
@@ -1,11 +1,11 @@
use crate::lang::KanaSet; use crate::app::USER_FONT;
use crate::core::kana_set::KanaSet;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::quiz::QuizMessage::*; use crate::pages::quiz::QuizMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::{RootMessage, USER_FONT};
use iced::widget::*; use iced::widget::*;
use iced::{alignment, Element, Fill, Task}; use iced::{Element, Fill, Task, alignment};
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -20,7 +20,7 @@ pub struct QuizState {
} }
impl NavigatedPage<QuizMessage> for QuizState { impl NavigatedPage<QuizMessage> for QuizState {
fn navigate(&self, message: &QuizMessage) -> Option<Page> { fn navigate(&mut self, message: &QuizMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -28,8 +28,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: QuizMessage) -> Task<RootMessage> { fn update(&mut self, message: QuizMessage) -> Task<RootMessage> {
match message { match message {
@@ -42,7 +41,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
} }
self.current_roman = content; self.current_roman = content;
if self.correct_roman == self.current_roman { if self.correct_roman == self.current_roman {
if self.is_help == false { if !self.is_help {
self.score.correct += 1; self.score.correct += 1;
} }
@@ -55,13 +54,11 @@ impl NavigatedPage<QuizMessage> for QuizState {
self.update_showed() self.update_showed()
} }
} }
Back => todo!(), Back => {}
} }
Task::none() Task::none()
} }
fn view(&self) -> Element<'_, QuizMessage> { fn view(&self) -> Element<'_, QuizMessage> {
container( container(
iced::widget::column![ iced::widget::column![
@@ -84,16 +81,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
.size(28) .size(28)
.width(150) .width(150)
.on_input(ContentChanged), .on_input(ContentChanged),
row![ score_display(&self.score),
text!("{}", self.score.total.to_string()).size(25),
text!("{}", self.score.correct.to_string())
.size(25)
.color(iced::Color::from_rgb8(60, 170, 60)),
text!("{}", self.score.fail.to_string())
.color(iced::Color::from_rgb8(255, 79, 0))
.size(25),
]
.spacing(DEFAULT_SPACING),
button("Закончить").style(jl_button).on_press(Back), button("Закончить").style(jl_button).on_press(Back),
] ]
.spacing(DEFAULT_SPACING) .spacing(DEFAULT_SPACING)
@@ -105,6 +93,20 @@ impl NavigatedPage<QuizMessage> for QuizState {
} }
} }
fn score_display<'a, T: 'a>(score: &Score) -> Element<'a, T> {
row![
text!("{}", score.total.to_string()).size(25),
text!("{}", score.correct.to_string())
.size(25)
.color(iced::Color::from_rgb8(60, 170, 60)),
text!("{}", score.fail.to_string())
.color(iced::Color::from_rgb8(255, 79, 0))
.size(25),
]
.spacing(DEFAULT_SPACING)
.into()
}
impl QuizState { impl QuizState {
pub(crate) fn new() -> QuizState { pub(crate) fn new() -> QuizState {
QuizState { QuizState {
+8 -10
View File
@@ -1,9 +1,9 @@
use crate::navigation::RootMessage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page};
use crate::randomizer::RandomizerMessage::{Back, Edit, Start}; use crate::pages::randomizer::RandomizerMessage::{Back, Edit, Start};
use crate::styling::{back_overlay, jl_button, HALF_SPACING}; use crate::styling::{HALF_SPACING, back_overlay, jl_button};
use crate::RootMessage;
use iced::widget::{button, text_editor};
use iced::Task; use iced::Task;
use iced::widget::{button, text_editor};
use rand::prelude::SliceRandom; use rand::prelude::SliceRandom;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -20,15 +20,14 @@ pub enum RandomizerMessage {
} }
impl NavigatedPage<RandomizerMessage> for RandomizerState { impl NavigatedPage<RandomizerMessage> for RandomizerState {
fn navigate(&self, message: &RandomizerMessage) -> Option<Page> { fn navigate(&mut self, message: &RandomizerMessage) -> Option<Page> {
if let Back = message { if let Back = message {
return Some(Page::PreviousPage); return Some(Page::PreviousPage);
} }
None None
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: RandomizerMessage) -> Task<RootMessage> { fn update(&mut self, message: RandomizerMessage) -> Task<RootMessage> {
match message { match message {
Edit(action) => { Edit(action) => {
@@ -63,7 +62,8 @@ impl NavigatedPage<RandomizerMessage> for RandomizerState {
.into(), .into(),
Back, Back,
) )
}} }
}
impl Default for RandomizerState { impl Default for RandomizerState {
fn default() -> Self { fn default() -> Self {
@@ -78,6 +78,4 @@ impl RandomizerState {
list: vec![], list: vec![],
} }
} }
} }
+56 -36
View File
@@ -1,35 +1,40 @@
use crate::app::AppState;
use crate::core::deck::DeckData;
use crate::core::srs::WordOpenMode;
use crate::data::Id;
use crate::data::entities::{CardStatistics, DeckSettings, WordData};
use crate::data_provider::voice::get_voice; use crate::data_provider::voice::get_voice;
use crate::lang::{CardSet, CardStatistics, WordData, WordOpenMode};
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{KeyPressedPage, NavigatedPage, Page}; use crate::navigation::{KeyPressedPage, NavigatedPage, Page, RootMessage};
use crate::repetitions::CardSetSettings; use crate::notification::{MaybeError, NotificationData};
use crate::styling::*; use crate::styling::*;
use crate::{AppState, RootMessage}; use crate::{push_error, push_error_task};
use chrono::Local; use chrono::Local;
use iced::alignment::Horizontal::Center; use iced::alignment::Horizontal::Center;
use iced::keyboard::key::Physical::Code; use iced::keyboard::key::Physical::Code;
use iced::widget::text::Style; use iced::widget::text::Style;
use iced::widget::{Column, button, column, container, row, rule, space, text, tooltip}; use iced::widget::{Column, button, column, container, row, rule, space, text, tooltip};
use iced::{Element, Fill, Task, Theme, alignment, keyboard}; use iced::{Element, Fill, Task, Theme, alignment, keyboard};
use parking_lot::Mutex;
use rodio::MixerDeviceSink; use rodio::MixerDeviceSink;
use std::collections::HashSet; use std::collections::HashSet;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use tokio::task::spawn_blocking; use tokio::task::spawn_blocking;
pub struct RepetitionState { pub struct RepetitionState {
state: Arc<Mutex<AppState>>, state: Arc<Mutex<AppState>>,
pub settings: CardSetSettings, pub settings: DeckSettings,
pub set: CardSet, pub set: DeckData,
current_word: WordData, current_word: WordData,
current_statistic: CardStatistics, current_statistic: CardStatistics,
open: bool, open: bool,
can_play: bool, can_play: bool,
sink: Arc<MixerDeviceSink>, sink: Arc<Option<MixerDeviceSink>>,
opened: HashSet<u32>, opened: HashSet<Id>,
} }
impl NavigatedPage<RepetitionMessage> for RepetitionState { impl NavigatedPage<RepetitionMessage> for RepetitionState {
fn navigate(&self, message: &RepetitionMessage) -> Option<Page> { fn navigate(&mut self, message: &RepetitionMessage) -> Option<Page> {
if let RepetitionMessage::Back = message { if let RepetitionMessage::Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -37,8 +42,7 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: RepetitionMessage) -> Task<RootMessage> { fn update(&mut self, message: RepetitionMessage) -> Task<RootMessage> {
match message { match message {
RepetitionMessage::Back => {} RepetitionMessage::Back => {}
@@ -52,8 +56,9 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
self.can_play = false; self.can_play = false;
let value = self.current_word.key.clone(); let value = self.current_word.key.clone();
if self.settings.require_speech() { if self.settings.require_speech() {
return Task::perform(play_sound(self.sink.clone(), value), |_| { return Task::perform(play_sound(self.sink.clone(), value), |r| match r {
RootMessage::Repetition(RepetitionMessage::PlayFinished) Ok(_) => RootMessage::Repetition(RepetitionMessage::PlayFinished),
Err(err) => push_error!(err),
}); });
} }
} }
@@ -97,12 +102,20 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
} }
impl RepetitionState { impl RepetitionState {
pub(crate) fn new(set: CardSetSettings, state: Arc<Mutex<AppState>>) -> RepetitionState { pub(crate) fn new(
let mut card_set = CardSet::new(&set, state.clone()); set: DeckSettings,
state: Arc<Mutex<AppState>>,
) -> Result<RepetitionState, NotificationData> {
let mut card_set = DeckData::new(&set, state.clone())?;
let (word, stat) = card_set.next(); let (word, stat) = card_set.next();
let sink_handle = rodio::DeviceSinkBuilder::open_default_sink().unwrap();
RepetitionState { let sink_handle = if set.forward.contains("speech") || set.backward.contains("speech") {
rodio::DeviceSinkBuilder::open_default_sink().ok()
} else {
None
};
Ok(RepetitionState {
state, state,
settings: set, settings: set,
set: card_set, set: card_set,
@@ -112,13 +125,11 @@ impl RepetitionState {
can_play: true, can_play: true,
sink: Arc::new(sink_handle), sink: Arc::new(sink_handle),
opened: HashSet::new(), opened: HashSet::new(),
} })
} }
} }
impl RepetitionState { impl RepetitionState {
fn next(&mut self) -> Task<RootMessage> { fn next(&mut self) -> Task<RootMessage> {
if self.open { if self.open {
self.answer(WordOpenMode::None) self.answer(WordOpenMode::None)
@@ -133,25 +144,30 @@ impl RepetitionState {
return Task::none(); return Task::none();
} }
self.set.open(mode); if let Err(err) = self.set.open(mode) {
return push_error_task!(err);
}
self.open = false; self.open = false;
self.opened.insert(self.current_word.id); self.opened.insert(self.current_word.id);
let next = self.set.next(); let next = self.set.next();
self.current_word = next.0; self.current_word = next.0;
self.current_statistic = next.1; self.current_statistic = next.1;
if self.settings.require_speech() { if self.settings.require_speech() && self.sink.is_some() {
return Task::perform( let sink = self.sink.clone();
play_sound(self.sink.clone(), self.current_word.key.clone()), let task = play_sound(sink, self.current_word.key.clone());
|_| RootMessage::Repetition(RepetitionMessage::PlayFinished), return Task::perform(task, |r| match r {
); Ok(_) => RootMessage::Repetition(RepetitionMessage::PlayFinished),
Err(err) => push_error!(err),
});
} }
self.increment_counter(); self.increment_counter();
Task::none() Task::none()
} }
fn increment_counter(&mut self) { fn increment_counter(&mut self) {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
let id = self.settings.id; let id = self.settings.id;
let activity = state.activity.get_mut(&id); let activity = state.activity.get_mut(&id);
@@ -169,7 +185,6 @@ impl RepetitionState {
} }
} }
fn draw_forward(&self) -> Element<'_, RepetitionMessage> { fn draw_forward(&self) -> Element<'_, RepetitionMessage> {
self.draw_card_view(self.settings.forward.as_str()) self.draw_card_view(self.settings.forward.as_str())
} }
@@ -276,7 +291,7 @@ impl RepetitionState {
} }
} }
fn draw_description(&self, word: &WordData) -> Element<'_, RepetitionMessage> { fn draw_description(&self, word: &WordData) -> Element<'_, RepetitionMessage> {
match word.additional.get("context") { match word.additional.get("description") {
None => space().into(), None => space().into(),
Some(context) => text!("{}", context).size(24).into(), Some(context) => text!("{}", context).size(24).into(),
} }
@@ -294,8 +309,8 @@ impl KeyPressedPage for RepetitionState {
text: _, text: _,
repeat: _, repeat: _,
} = message } = message
&& let Code(code) = pk
{ {
if let Code(code) = pk {
return match code { return match code {
keyboard::key::Code::Space => self.next(), keyboard::key::Code::Space => self.next(),
keyboard::key::Code::Digit1 => self.answer(WordOpenMode::None), keyboard::key::Code::Digit1 => self.answer(WordOpenMode::None),
@@ -305,7 +320,7 @@ impl KeyPressedPage for RepetitionState {
_ => Task::none(), _ => Task::none(),
}; };
} }
}
Task::none() Task::none()
} }
} }
@@ -319,11 +334,16 @@ pub enum RepetitionMessage {
PlayFinished, PlayFinished,
} }
async fn play_sound(sink: Arc<MixerDeviceSink>, text: String) { async fn play_sound(sink: Arc<Option<MixerDeviceSink>>, text: String) -> MaybeError {
let data = get_voice(text.as_str()).await; let data = get_voice(text.as_str()).await?;
spawn_blocking(move || { spawn_blocking(move || {
rodio::play(&sink.mixer(), data).unwrap().sleep_until_end(); if let Some(sink) = sink.as_ref()
&& let Ok(play) = rodio::play(sink.mixer(), data)
{
play.sleep_until_end()
}
}) })
.await .await
.unwrap(); .expect("Playing sound failed");
Ok(())
} }
@@ -1,43 +1,54 @@
use crate::data_provider::card_sets::{delete_set, update_card_set}; use crate::app::AppState;
use crate::data::entities::DeckSettings;
use crate::data_provider::card_sets::{delete_set, update_deck};
use crate::data_provider::card_stats::{delete_stats, load_stats_of_deck};
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page, RootMessage}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::repetition_settings::RepetitionSettingsMessage::*; use crate::notification::MaybeError;
use crate::repetitions::CardSetSettings; use crate::pages::repetition_settings::RepetitionSettingsMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::AppState; use crate::{push_error, push_error_task};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::text_input::Catalog;
use iced::widget::{button, column, row, scrollable, space, text, text_input}; use iced::widget::{button, column, row, scrollable, space, text, text_input};
use iced::{Element, Task}; use iced::{Element, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use iced_core::Padding; use iced_core::{Padding, Theme, color};
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
pub struct RepetitionSettingsState { pub struct RepetitionSettingsState {
set: CardSetSettings, set: DeckSettings,
index: usize, index: usize,
state: Arc<Mutex<AppState>>, state: Arc<Mutex<AppState>>,
real_delete: bool, real_delete: bool,
correct_filter: bool,
filter_changed: bool,
} }
impl RepetitionSettingsState { impl RepetitionSettingsState {
pub(crate) fn new(index: usize, p1: Arc<Mutex<AppState>>) -> RepetitionSettingsState { pub(crate) fn new(index: usize, state: Arc<Mutex<AppState>>) -> RepetitionSettingsState {
let set; let set;
{ {
let local_state = p1.lock().unwrap(); let local_state = state.lock();
set = local_state.card_sets[index].clone(); set = local_state.decks[index].clone();
} }
let filter_state = set.check_filter();
RepetitionSettingsState { RepetitionSettingsState {
index, index,
set, set,
state: p1, state,
real_delete: false, real_delete: false,
correct_filter: filter_state,
filter_changed: false,
} }
} }
} }
impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState { impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
fn navigate(&self, message: &RepetitionSettingsMessage) -> Option<Page> { fn navigate(&mut self, message: &RepetitionSettingsMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -45,15 +56,21 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: RepetitionSettingsMessage) -> Task<RootMessage> { fn update(&mut self, message: RepetitionSettingsMessage) -> Task<RootMessage> {
match message { match message {
Back => {} Back => {}
Save => { Save => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
update_card_set(&mut self.set, &state.connection); if let Err(e) = update_deck(&mut self.set, &state.connection) {
state.card_sets[self.index] = self.set.clone(); return push_error_task!(e);
}
if self.filter_changed
&& let Err(e) = update_deck_stats(&self.set, &state)
{
return push_error_task!(e);
}
state.decks[self.index] = self.set.clone();
} }
SetName(new) => { SetName(new) => {
self.set.name = new; self.set.name = new;
@@ -66,25 +83,30 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
} }
SetFilter(new) => { SetFilter(new) => {
self.set.filter = new; self.set.filter = new;
self.correct_filter = self.set.check_filter();
self.filter_changed = true;
} }
TryFilter => { TryFilter => {
let state = self.state.lock().unwrap(); let state = self.state.lock();
let count = self.set.get_word_list(&state).len(); let count = self.set.get_word_list(&state).len();
self.set.count = Some(count); self.set.count = Some(count);
} }
DeleteSet => { DeleteSet => {
if self.real_delete == false { if !self.real_delete {
self.real_delete = true; self.real_delete = true;
return Task::future(async { return Task::future(async {
tokio::time::sleep(Duration::from_millis(3000)).await; tokio::time::sleep(Duration::from_millis(3000)).await;
return RootMessage::RepetitionSettings(RevertDeleteSet); RootMessage::RepetitionSettings(RevertDeleteSet)
}); });
} }
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
delete_set(&self.set, &state.connection); if let Err(e) = delete_set(&self.set, &state.connection) {
state.card_sets.remove(self.index); return push_error_task!(e);
}
state.decks.remove(self.index);
return Task::done(RootMessage::RepetitionSettings(Back)); return Task::done(RootMessage::RepetitionSettings(Back));
}, }
RevertDeleteSet => self.real_delete = false, RevertDeleteSet => self.real_delete = false,
} }
Task::none() Task::none()
@@ -112,7 +134,15 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
.spacing(QUARTER_SPACING), .spacing(QUARTER_SPACING),
column![ column![
text!("Фильтр"), text!("Фильтр"),
text_input("", &self.set.filter).on_input(SetFilter), text_input("", &self.set.filter)
.style(|x, status| {
let mut primary = Theme::default()(x, status);
if !self.correct_filter {
primary.border.color = color!(255, 255, 0);
}
primary
})
.on_input(SetFilter),
button("Проверить фильтр") button("Проверить фильтр")
.style(jl_button) .style(jl_button)
.on_press(TryFilter), .on_press(TryFilter),
@@ -149,10 +179,22 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
} }
} }
fn update_deck_stats(deck: &DeckSettings, state: &AppState) -> MaybeError {
let mut db_stats = load_stats_of_deck(deck, &state.connection).expect("Wrong db operation");
let filtered_words = deck.get_word_list(state);
filtered_words.iter().for_each(|word| {
let word_id = state.dictionary[*word].id;
if let Some(index) = db_stats.iter().position(|stat| stat.word_id == word_id) {
db_stats.remove(index);
}
});
delete_stats(db_stats.as_slice(), &state.connection)?;
Ok(())
}
impl RepetitionSettingsState { impl RepetitionSettingsState {
fn count_view(&self, set: &DeckSettings) -> Element<'_, RepetitionSettingsMessage> {
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionSettingsMessage> {
if let Some(count) = set.count { if let Some(count) = set.count {
return text!("Количество слов: {}", count).into(); return text!("Количество слов: {}", count).into();
} }
+672
View File
@@ -0,0 +1,672 @@
use crate::app::AppState;
use crate::core::srs::{AppendMode, OrderMode};
use crate::data::Id;
use crate::data::entities::{CardStatistics, DeckSettings};
use crate::data_provider::card_sets::update_deck;
use crate::data_provider::card_stats::{add_stat_list, load_stats_of_deck};
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::{MaybeError, NotificationRequest};
use crate::pages::history::HistoryState;
use crate::pages::repetition::RepetitionState;
use crate::pages::repetition_settings::RepetitionSettingsState;
use crate::pages::repetitions::RepetitionsMessage::*;
use crate::push_error;
use crate::push_error_task;
use crate::styling::*;
use chrono::{Days, Local, Utc};
use hashbrown::{HashMap, HashSet};
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,
};
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 parking_lot::Mutex;
use std::ops::Deref;
use std::sync::Arc;
#[derive(Clone)]
pub struct RepetitionsState {
word_id_index_map: HashMap<Id, usize>,
selected_deck_index: Option<usize>,
decks: Vec<DeckViewData>,
state: Arc<Mutex<AppState>>,
}
impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
fn navigate(&mut self, message: &RepetitionsMessage) -> Option<Page> {
if let Back = message {
Some(PreviousPage)
} else if let GoToHistory = message {
Some(History(HistoryState::new(
self.selected_deck().unwrap().id,
self.state.clone(),
)))
} else if let GoToRepetition = message {
let clone = self.state.clone();
let selected_set = self.selected_deck_mut().unwrap();
if selected_set.append_mode == AppendMode::Full {
if let Err(_err) = Self::append_all_words(&mut clone.lock(), selected_set) {
return None;
}
selected_set.existing_words_indices = selected_set.available_words_indices.clone();
} else {
if selected_set.available_words_indices.is_empty()
|| selected_set.existing_words_indices.is_empty()
{
return None;
}
}
if let Ok(repetition_state) =
RepetitionState::new(selected_set.general_settings.clone(), clone)
{
return Some(Repetition(repetition_state));
}
None
} else if let GoToSettings = message {
Some(RepetitionSettings(RepetitionSettingsState::new(
self.selected_deck().unwrap().index.unwrap(),
self.state.clone(),
)))
} else {
None
}
}
fn navigated(&mut self) {
if let Some(index) = self.selected_deck_index {
let state = self.state.lock();
if let Some(global_deck) = state.decks.get(index) {
if global_deck.id != self.selected_deck().unwrap().id {
drop(state);
self.decks.remove(index);
self.clear_selection();
} else {
self.decks[index].general_settings = state.decks[index].clone();
drop(state);
let _ = self.fill_deck_word_indices();
}
} else {
drop(state);
self.decks.remove(index);
self.clear_selection()
}
}
}
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
match message {
Next => {}
Back => {}
GoToRepetition => {}
GoToHistory => {}
GoToSettings => {}
CreateSet => {
let index = self.decks.len() + 1;
self.decks.push(DeckViewData {
general_settings: DeckSettings::with_name(format!("Колода #{}", index)),
existing_words_indices: Default::default(),
available_words_indices: Default::default(),
indices_ready: false,
append_mode: Default::default(),
index: None,
});
}
DeleteSet => {
let index = self.selected_deck_index.unwrap();
self.clear_selection();
let deck = self.decks.remove(index);
if deck.id.is_valid() {
let mut state = self.state.lock();
state.decks.remove(index);
self.decks = self
.decks
.clone()
.into_iter()
.map(|mut deck| {
deck.index = state.decks.iter().position(|d| d.id == deck.id);
deck
})
.collect();
}
}
SetName(value) => {
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.name = value;
}
SelectSet(index) => {
self.select_deck(index);
let deck = self.selected_deck().unwrap();
if !deck.indices_ready
&& let Err(err) = self.fill_deck_word_indices()
{
return push_error_task!(err);
}
}
Save => {
let mut deck = self.selected_deck().unwrap().clone();
let mut state = self.state.lock();
{
if let Err(e) = update_deck(&mut deck.general_settings, &state.connection) {
return Task::done(RootMessage::PushNotification(
NotificationRequest::Error(e),
));
}
if let Some(index) = deck.index {
state.decks[index] = deck.general_settings.clone();
} else {
state.decks.push(deck.general_settings.clone());
deck.index = Some(state.decks.len() - 1);
self.decks[self.selected_deck_index.unwrap()] = deck.clone();
}
}
}
SetForward(value) => {
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.forward = value;
}
SetBackward(value) => {
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.backward = value;
}
SetFilter(value) => {
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.filter = value;
}
TryFilter => {
let state = self.state.lock();
let deck = self.selected_deck().unwrap();
let count = deck.get_word_list(&state).len();
drop(state);
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.count = Some(count);
}
SetOpenMode(mode) => {
let deck = self.selected_deck_mut().unwrap();
deck.general_settings.open_mode = mode;
}
SetAppendMode(mode) => {
let deck = self.selected_deck_mut().unwrap();
deck.append_mode = mode;
}
AppendWords(count) => {
let adding: Vec<usize>;
{
{
let deck = self.selected_deck().unwrap();
let existing_words_indices = &deck.existing_words_indices;
let mut created_set = HashSet::with_capacity(existing_words_indices.len());
existing_words_indices.iter().for_each(|c| {
created_set.insert(c);
});
adding = deck
.available_words_indices
.iter()
.filter(|c| !created_set.contains(c))
.take(count)
.cloned()
.collect();
}
let deck = self.selected_deck_mut().unwrap();
deck.existing_words_indices.append(&mut adding.clone());
}
let deck = self.selected_deck().unwrap();
let mut state = self.state.lock();
if let Err(err) =
Self::append_words(&mut state, &deck.general_settings, adding.into_iter())
{
return push_error_task!(err);
}
}
}
Task::none()
}
fn view(&self) -> Element<'_, RepetitionsMessage> {
back_overlay(
row![
column![
scrollable(self.decks_list()).height(Fill),
button("Добавить")
.style(jl_button)
.width(Fill)
.on_press(CreateSet),
]
.spacing(DEFAULT_SPACING)
.width(Length::FillPortion(1)),
self.selected_deck_view(),
]
.align_y(Center)
.spacing(DEFAULT_SPACING)
.width(Fill)
.height(Fill)
.into(),
Back,
)
}
}
impl RepetitionsState {
pub(crate) fn new(state: Arc<Mutex<AppState>>) -> RepetitionsState {
let state_ = state.lock();
let mut map = HashMap::with_capacity(state_.dictionary.len());
state_
.dictionary
.iter()
.enumerate()
.for_each(|(index, word)| {
map.insert(word.id, index);
});
let decks = Self::get_decks_from_state(&state_);
drop(state_);
RepetitionsState {
word_id_index_map: map,
selected_deck_index: None,
decks,
state,
}
}
fn get_decks_from_state(state: &AppState) -> Vec<DeckViewData> {
state
.decks
.iter()
.enumerate()
.map(|(index, deck)| DeckViewData {
general_settings: deck.clone(),
existing_words_indices: Default::default(),
available_words_indices: Default::default(),
indices_ready: false,
append_mode: Default::default(),
index: Some(index),
})
.collect()
}
}
impl RepetitionsState {
fn launch_delete_button(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
if deck.id.is_valid() {
if deck.append_mode == AppendMode::Manual && deck.existing_words_indices.is_empty() {
return text!("Добавьте карточки или измените фильтр").into();
}
return row![
space().width(Fill),
button(text!("Начать повторение").width(200).center())
.style(cta_button)
.on_press(GoToRepetition)
]
.into();
}
button("Удалить").style(danger).on_press(DeleteSet).into()
}
fn selected_deck_view(&self) -> Element<'_, RepetitionsMessage> {
if let Some(deck) = &self.selected_deck() {
return column![
scrollable(
column![
column![
text!("Название набора"),
row![
text_input("", &deck.name).on_input(SetName),
button(svg(Handle::from_memory(SETTINGS_ICON)))
.width(43)
.on_press(GoToSettings),
]
.spacing(HALF_SPACING)
]
.spacing(QUARTER_SPACING),
{
if !deck.id.is_valid() {
column![
column![
text!("Передняя сторона"),
text_input("", &deck.forward).on_input(SetForward),
]
.spacing(QUARTER_SPACING),
column![
text!("Задняя сторона"),
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),
self.count_view(deck),
]
.spacing(QUARTER_SPACING),
]
.spacing(DEFAULT_SPACING)
} else {
column![
self.filled_deck_data_view(deck),
self.word_append_panel(deck),
radio(
"Обычный режим",
OrderMode::Default,
Some(deck.open_mode),
SetOpenMode
),
radio(
"Начать с плохих слов",
OrderMode::TrainWorstFirst,
Some(deck.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
OrderMode::FullRandom,
Some(deck.open_mode),
SetOpenMode
),
button("История").style(jl_button).on_press(GoToHistory),
]
.spacing(HALF_SPACING)
}
},
// self.words_words_view(&set),
]
.spacing(DEFAULT_SPACING)
.padding(Padding {
top: 0.0,
right: DEFAULT_SPACING,
bottom: 0.0,
left: 0.0,
})
)
.height(Fill),
row![
button("Сохранить").style(jl_button).on_press(Save),
self.launch_delete_button(deck)
]
.spacing(DEFAULT_SPACING)
.align_y(Center),
]
.spacing(DEFAULT_SPACING)
.width(Length::FillPortion(2))
.into();
}
space().width(Length::FillPortion(2)).into()
}
fn filled_deck_data_view(&self, deck: &DeckSettings) -> Column<'_, RepetitionsMessage> {
column![self.activity_bar(deck), self.count_comparator_view()]
.align_x(Center)
.width(Fill)
.spacing(DEFAULT_SPACING)
}
fn activity_bar(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
const MAX_DAY_COUNT: f32 = 128.0;
let state = self.state.lock();
let history = state.activity.get(&deck.id);
let mut counts: Vec<u32> = vec![0; 30 * 7];
let now = Local::now().date_naive();
if let Some(history) = history {
for (date, activity) in history {
let distance = now - *date;
let index = counts.len() as i64 - distance.num_days() - 1;
if index < 0 {
continue;
}
counts[index as usize] = *activity;
}
}
lazy((counts, now), |(counts, now)| {
let mut row = Row::new()
.padding(Padding {
top: 0.0,
right: 0.0,
bottom: 0.0,
left: DEFAULT_SPACING,
})
.spacing(QUARTER_SPACING);
let mut iter = counts.iter();
for i in 0..30 {
let mut column = Column::new().spacing(QUARTER_SPACING);
for j in 0..7 {
let value = *iter.next().unwrap() as f32;
let k = (value / MAX_DAY_COUNT).min(1.0) * 0.9 + 0.1;
let date = (*now)
.checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1))
.unwrap_or_default();
column = column.push(tooltip(
iced::widget::container(space().height(15).width(15)).style(
move |x: &Theme| container::Style {
text_color: None,
background: Some(Background::Color(
x.palette().primary.scale_alpha(k),
)),
border: Border {
color: Default::default(),
width: 0.0,
radius: Radius::new(5),
},
shadow: Default::default(),
snap: false,
},
),
text!("{} {} карточки", date.format("%Y.%m.%d"), value),
Top,
));
}
row = row.push(column);
}
scrollable(
column!["Карта активности", row]
.spacing(QUARTER_SPACING)
.align_x(Center),
)
})
.into()
}
fn word_append_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
column![
text!("Режим добавления карточек"),
row![
radio(
"Добавлять все доступные",
AppendMode::Full,
Some(deck.append_mode),
SetAppendMode
),
radio(
"Добавлять вручную",
AppendMode::Manual,
Some(deck.append_mode),
SetAppendMode
)
]
.spacing(HALF_SPACING),
self.adder_panel(deck),
]
.spacing(HALF_SPACING)
.into()
}
fn adder_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
match deck.append_mode {
AppendMode::Full => space().into(),
AppendMode::Manual => row![
button("+5").on_press(AppendWords(5)),
button("+10").on_press(AppendWords(10)),
button("+15").on_press(AppendWords(15)),
button("+20").on_press(AppendWords(20))
]
.spacing(HALF_SPACING)
.into(),
}
}
fn count_comparator_view(&self) -> Element<'_, RepetitionsMessage> {
let selected_deck = self.selected_deck().unwrap();
let now = selected_deck.existing_words_indices.len();
let available = selected_deck.available_words_indices.len();
text!("{} слова добавлено из {}", now, available).into()
}
fn count_view(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
if let Some(count) = deck.count {
return text!("Количество слов: {}", count).into();
}
space().into()
}
fn decks_list(&self) -> Column<'_, RepetitionsMessage> {
let mut column = Column::new();
for (i, deck) in self.decks.iter().enumerate() {
column = column.push(
button(text!("{}", &deck.name))
.on_press_with(move || SelectSet(i))
.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: _x.palette().primary,
border: Border {
color: Default::default(),
width: 0.0,
radius: BUTTON_RADIUS.into(),
},
shadow: Shadow::default(),
snap: false,
}),
);
}
column
}
}
impl RepetitionsState {
fn append_all_words(state: &mut AppState, deck: &DeckViewData) -> MaybeError {
let existing = &deck.existing_words_indices;
let mut created_set = HashSet::with_capacity(existing.len());
existing.iter().for_each(|c| {
created_set.insert(c);
});
let required = deck
.available_words_indices
.iter()
.filter(|i| !created_set.contains(i))
.cloned();
Self::append_words(state, deck, required)?;
Ok(())
}
fn append_words(
state: &mut AppState,
deck: &DeckSettings,
indices: impl Iterator<Item = usize>,
) -> MaybeError {
let words = &state.dictionary;
let stats = &mut indices
.map(|i| {
let word = &words[i];
CardStatistics {
id: 0.into(),
word_id: word.id,
last_open: Utc::now(),
score: 1,
set_id: deck.id,
}
})
.collect::<Vec<_>>();
if !stats.is_empty() {
add_stat_list(stats, &mut state.connection)?;
}
Ok(())
}
fn select_deck(&mut self, index: usize) {
if self.decks.get(index).is_some() {
self.selected_deck_index = Some(index);
}
}
fn selected_deck(&self) -> Option<&DeckViewData> {
self.decks.get(self.selected_deck_index?)
}
fn selected_deck_mut(&mut self) -> Option<&mut DeckViewData> {
self.decks.get_mut(self.selected_deck_index?)
}
fn clear_selection(&mut self) {
self.selected_deck_index = None;
}
fn fill_deck_word_indices(&mut self) -> MaybeError {
let state = &self.state.lock();
let mut deck = self.selected_deck().unwrap().clone();
let added: Vec<_> = load_stats_of_deck(&deck, &state.connection)?
.iter()
.map(|c| self.word_id_index_map[&c.word_id])
.collect();
let total = deck.get_word_list(state);
deck.existing_words_indices = added;
deck.available_words_indices = total;
self.decks[self.selected_deck_index.unwrap()] = deck;
Ok(())
}
}
#[derive(Clone)]
pub enum RepetitionsMessage {
Next,
Back,
GoToRepetition,
CreateSet,
DeleteSet,
SetName(String),
SelectSet(usize),
Save,
SetForward(String),
SetBackward(String),
SetFilter(String),
TryFilter,
SetOpenMode(OrderMode),
SetAppendMode(AppendMode),
GoToHistory,
GoToSettings,
AppendWords(usize),
}
#[derive(Clone)]
struct DeckViewData {
general_settings: DeckSettings,
existing_words_indices: Vec<usize>,
available_words_indices: Vec<usize>,
indices_ready: bool,
append_mode: AppendMode,
index: Option<usize>,
}
impl Deref for DeckViewData {
type Target = DeckSettings;
fn deref(&self) -> &Self::Target {
&self.general_settings
}
}
+14 -16
View File
@@ -1,21 +1,23 @@
use crate::dictionary::DictionaryState; use crate::app::AppState;
use crate::lang::{KanaSet, KanaType}; use crate::core::kana_set::{KanaSet, KanaType};
use crate::navigation::Page::*; use crate::navigation::Page::*;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::randomizer::RandomizerState; use crate::pages::dictionary::DictionaryState;
use crate::repetitions::RepetitionsState; use crate::pages::quiz::QuizState;
use crate::selector::SelectorMessage::ChangeMode; use crate::pages::randomizer::RandomizerState;
use crate::pages::repetitions::RepetitionsState;
use crate::pages::selector::SelectorMessage::ChangeMode;
use crate::pages::sync::SyncState;
use crate::pages::writing::WritingState;
use crate::styling::*; use crate::styling::*;
use crate::sync::SyncState;
use crate::writing::WritingState;
use crate::{AppState, QuizState, RootMessage};
use iced::widget::button::{Status, Style}; use iced::widget::button::{Status, Style};
use iced::widget::*; use iced::widget::*;
use iced::{Element, Task, alignment}; use iced::{Element, Task, alignment};
use iced_core::Alignment::Center; use iced_core::Alignment::Center;
use iced_core::Background; use iced_core::Background;
use iced_core::Color; use iced_core::Color;
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
pub struct SelectorState { pub struct SelectorState {
pub set: KanaSet, pub set: KanaSet,
@@ -36,7 +38,7 @@ pub enum SelectorMessage {
} }
impl NavigatedPage<SelectorMessage> for SelectorState { impl NavigatedPage<SelectorMessage> for SelectorState {
fn navigate(&self, message: &SelectorMessage) -> Option<Page> { fn navigate(&mut self, message: &SelectorMessage) -> Option<Page> {
if let SelectorMessage::Goto = message { if let SelectorMessage::Goto = message {
return if self.is_writing { return if self.is_writing {
let writing = WritingState::new(&self.set); let writing = WritingState::new(&self.set);
@@ -62,8 +64,7 @@ impl NavigatedPage<SelectorMessage> for SelectorState {
None None
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: SelectorMessage) -> Task<RootMessage> { fn update(&mut self, message: SelectorMessage) -> Task<RootMessage> {
match message { match message {
SelectorMessage::Change => match self.set.chars_type { SelectorMessage::Change => match self.set.chars_type {
@@ -121,7 +122,6 @@ impl SelectorState {
} }
} }
fn nav_style(theme: &Theme, status: Status) -> Style { fn nav_style(theme: &Theme, status: Status) -> Style {
let mut basic = button::text(theme, status); let mut basic = button::text(theme, status);
basic.background = if status == Status::Hovered { basic.background = if status == Status::Hovered {
@@ -133,8 +133,6 @@ impl SelectorState {
basic basic
} }
fn rows_selector(&self) -> Element<'_, SelectorMessage> { fn rows_selector(&self) -> Element<'_, SelectorMessage> {
let mut row = Row::new(); let mut row = Row::new();
+50 -27
View File
@@ -1,18 +1,21 @@
use crate::app::{AppState, fill_state};
use crate::data_provider::settings::{delete_settings, set_setting}; use crate::data_provider::settings::{delete_settings, set_setting};
use crate::data_provider::web_api::*; use crate::data_provider::web_api::*;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::notification::{NotificationData, NotificationRequest};
use crate::pages::sync::SyncMessage::*;
use crate::styling::*; use crate::styling::*;
use crate::sync::SyncMessage::*; use crate::{push_error, push_error_task};
use crate::{fill_state, AppState, RootMessage};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::container::rounded_box; use iced::widget::container::rounded_box;
use iced::widget::{button, column, container, progress_bar, row, space, text, toggler}; use iced::widget::{button, column, container, progress_bar, row, space, text, toggler};
use iced::{Center, Element, Fill, Font, Length, Task}; use iced::{Center, Element, Fill, Font, Length, Task};
use std::sync::{Arc, Mutex}; use log::error;
use parking_lot::Mutex;
use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
#[derive(Clone)] #[derive(Clone)]
pub enum SyncMessage { pub enum SyncMessage {
Back, Back,
@@ -38,7 +41,7 @@ pub struct SyncState {
} }
impl NavigatedPage<SyncMessage> for SyncState { impl NavigatedPage<SyncMessage> for SyncState {
fn navigate(&self, message: &SyncMessage) -> Option<Page> { fn navigate(&mut self, message: &SyncMessage) -> Option<Page> {
if let Back = message if let Back = message
&& !self.frozen && !self.frozen
{ {
@@ -53,13 +56,16 @@ impl NavigatedPage<SyncMessage> for SyncState {
match message { match message {
Back => {} Back => {}
CopyKey => { CopyKey => {
let state = self.state.lock().unwrap(); let state = self.state.lock();
let key = state.sync_data.key.clone().unwrap(); let key = state.sync_data.key.clone().unwrap();
return iced::clipboard::write(key) return iced::clipboard::write(key)
.map(|_val: String| RootMessage::Sync(KeyCopied)); .map(|_val: String| RootMessage::Sync(KeyCopied));
} }
InitSync => { InitSync => {
return Task::perform(first_sync(), |id| RootMessage::Sync(IdReceived(id))); return Task::perform(first_sync(), |id| match id {
Ok(id) => RootMessage::Sync(IdReceived(id)),
Err(err) => push_error!(err),
});
} }
GetKey => { GetKey => {
return iced::clipboard::read() return iced::clipboard::read()
@@ -67,17 +73,19 @@ impl NavigatedPage<SyncMessage> for SyncState {
} }
KeyCopied => {} KeyCopied => {}
IdReceived(new_id) => { IdReceived(new_id) => {
if validate_id(&new_id) == false { if !validate_id(&new_id) {
return Task::none(); return Task::none();
} }
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data.key = Some(new_id.clone()); state.sync_data.key = Some(new_id.clone());
set_setting("SYNC_KEY".to_string(), new_id, &state.connection); if let Err(err) = set_setting("SYNC_KEY".to_string(), new_id, &state.connection) {
return push_error_task!(err);
}
} }
Send => { Send => {
self.prepare_to_db_interaction(); self.prepare_to_db_interaction();
let id = self.state.lock().unwrap().sync_data.key.clone().unwrap(); let id = self.state.lock().sync_data.key.clone().unwrap();
let tasks = Task::batch([ let tasks = Task::batch([
Task::perform( Task::perform(
async { tokio::time::sleep(Duration::from_millis(200)).await }, async { tokio::time::sleep(Duration::from_millis(200)).await },
@@ -89,7 +97,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
return tasks; return tasks;
} }
GetLast => { GetLast => {
let id = self.state.lock().unwrap().sync_data.key.clone().unwrap(); let id = self.state.lock().sync_data.key.clone().unwrap();
let tasks = Task::batch([ let tasks = Task::batch([
Task::perform( Task::perform(
async { tokio::time::sleep(Duration::from_millis(200)).await }, async { tokio::time::sleep(Duration::from_millis(200)).await },
@@ -117,26 +125,41 @@ impl NavigatedPage<SyncMessage> for SyncState {
let mut updated_state = AppState::new(); let mut updated_state = AppState::new();
fill_state(&mut updated_state); fill_state(&mut updated_state);
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data = updated_state.sync_data; state.sync_data = updated_state.sync_data;
state.connection = updated_state.connection; state.connection = updated_state.connection;
state.card_sets = updated_state.card_sets; state.decks = updated_state.decks;
state.dictionary = updated_state.dictionary; state.dictionary = updated_state.dictionary;
state.word_groups = updated_state.word_groups; state.word_groups = updated_state.word_groups;
return Task::done(RootMessage::PushNotification(NotificationRequest::Info(
NotificationData::DataLoaded,
)));
} }
Disable => {} Disable => {}
DisableSync => { DisableSync => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data.key = None; state.sync_data.key = None;
delete_settings("SYNC_KEY".to_string(), &state.connection); let save_result = || {
delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection); delete_settings("SYNC_KEY".to_string(), &state.connection)?;
delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection)?;
Ok::<(), NotificationData>(())
};
if let Err(error) = save_result() {
return push_error_task!(error);
}
} }
SwitchAutoSync => { SwitchAutoSync => {
self.auto_fetch = !self.auto_fetch; self.auto_fetch = !self.auto_fetch;
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.sync_data.auto_web_fetch = self.auto_fetch; state.sync_data.auto_web_fetch = self.auto_fetch;
set_setting("AUTO_WEB_FETCH".to_string(), self.auto_fetch.to_string(), &state.connection); if let Err(err) = set_setting(
"AUTO_WEB_FETCH".to_string(),
self.auto_fetch.to_string(),
&state.connection,
) {
return push_error_task!(err);
}
} }
} }
Task::none() Task::none()
@@ -157,7 +180,7 @@ impl SyncState {
pub fn new(state: Arc<Mutex<AppState>>) -> SyncState { pub fn new(state: Arc<Mutex<AppState>>) -> SyncState {
let auto_fetch; let auto_fetch;
{ {
auto_fetch = state.lock().unwrap().sync_data.auto_web_fetch; auto_fetch = state.lock().sync_data.auto_web_fetch;
} }
Self { Self {
auto_fetch, auto_fetch,
@@ -167,8 +190,6 @@ impl SyncState {
} }
} }
fn sync_column(&self) -> Element<'_, SyncMessage> { fn sync_column(&self) -> Element<'_, SyncMessage> {
let network_view: Element<'_, SyncMessage> = if self.frozen { let network_view: Element<'_, SyncMessage> = if self.frozen {
progress_bar(0.0..=5.0, self.progress).into() progress_bar(0.0..=5.0, self.progress).into()
@@ -176,7 +197,7 @@ impl SyncState {
space().into() space().into()
}; };
{ {
if let Some(key) = self.state.lock().unwrap().sync_data.key.clone() { if let Some(key) = self.state.lock().sync_data.key.clone() {
column![ column![
text!("Ваш ключ синхронизации"), text!("Ваш ключ синхронизации"),
container( container(
@@ -198,7 +219,9 @@ impl SyncState {
button("↓ Скачать").style(jl_button).on_press(GetLast) button("↓ Скачать").style(jl_button).on_press(GetLast)
] ]
.spacing(DEFAULT_SPACING), .spacing(DEFAULT_SPACING),
toggler(self.auto_fetch).label("Автоматическая синхронизация").on_toggle(|_| SwitchAutoSync), toggler(self.auto_fetch)
.label("Автоматическая синхронизация")
.on_toggle(|_| SwitchAutoSync),
container(network_view).width(Fill), container(network_view).width(Fill),
button("Отключить синхронизацию") button("Отключить синхронизацию")
.style(danger) .style(danger)
@@ -231,12 +254,12 @@ impl SyncState {
} }
self.frozen = true; self.frozen = true;
self.progress = 0.0; self.progress = 0.0;
let state = self.state.lock().unwrap(); let state = self.state.lock();
state state
.connection .connection
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
eprintln!("Ошибка при checkpoint WAL: {e}"); error!("Ошибка при checkpoint WAL: {e}");
}); });
} }
} }
+23 -22
View File
@@ -1,14 +1,17 @@
use crate::app::AppState;
use crate::data::entities::WordData;
use crate::data_provider::words::{delete_word, update_word}; use crate::data_provider::words::{delete_word, update_word};
use crate::lang::WordData;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::pages::word::WordMessage::*;
use crate::push_error;
use crate::push_error_task;
use crate::styling::*; use crate::styling::*;
use crate::word::WordMessage::*;
use crate::{AppState, RootMessage};
use iced::widget::button::danger; use iced::widget::button::danger;
use iced::widget::{button, column, row, rule, scrollable, text, text_input}; use iced::widget::{button, column, row, rule, scrollable, text, text_input};
use iced::{Element, Fill, Task}; use iced::{Element, Fill, Task};
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Clone)] #[derive(Clone)]
pub struct WordState { pub struct WordState {
@@ -18,7 +21,7 @@ pub struct WordState {
} }
impl NavigatedPage<WordMessage> for WordState { impl NavigatedPage<WordMessage> for WordState {
fn navigate(&self, message: &WordMessage) -> Option<Page> { fn navigate(&mut self, message: &WordMessage) -> Option<Page> {
if let Back = message { if let Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -31,15 +34,20 @@ impl NavigatedPage<WordMessage> for WordState {
match message { match message {
Back => {} Back => {}
Save => { Save => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.dictionary[self.index] = self.word.clone(); state.dictionary[self.index] = self.word.clone();
update_word(&mut self.word, &state.connection);
if let Err(err) = update_word(&mut self.word, &state.connection) {
return push_error_task!(err);
}
return Task::done(RootMessage::Word(Back)); return Task::done(RootMessage::Word(Back));
} }
Delete => { Delete => {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock();
state.dictionary.remove(self.index); state.dictionary.remove(self.index);
delete_word(&self.word, &state.connection); if let Err(err) = delete_word(&self.word, &state.connection) {
return push_error_task!(err);
}
return Task::done(RootMessage::Word(Back)); return Task::done(RootMessage::Word(Back));
} }
SetTags(n) => self.word.tags = n, SetTags(n) => self.word.tags = n,
@@ -49,11 +57,9 @@ impl NavigatedPage<WordMessage> for WordState {
SetValue(n) => { SetValue(n) => {
self.word.value = n; self.word.value = n;
} }
SetAdditional(key, value) => match key.as_str() { SetAdditional(key, value) => {
_ => {
self.word.additional.insert(key, value.clone()); self.word.additional.insert(key, value.clone());
} }
},
AddAdditional(key) => { AddAdditional(key) => {
self.word.additional.insert(key, "".to_string()); self.word.additional.insert(key, "".to_string());
} }
@@ -145,23 +151,18 @@ impl WordState {
} }
} }
fn reading_field(&self, value: &String) -> Element<'_, WordMessage> { fn reading_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "Чтение слова".to_string(), "reading".to_string()) self.additional_field(value, "Чтение слова".to_string(), "reading".to_string())
} }
fn description_field(&self, value: &String) -> Element<'_, WordMessage> { fn description_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "Описание".to_string(), "description".to_string()) self.additional_field(value, "Описание".to_string(), "description".to_string())
} }
fn context_field(&self, value: &String) -> Element<'_, WordMessage> { fn context_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "В контексте".to_string(), "context".to_string()) self.additional_field(value, "В контексте".to_string(), "context".to_string())
} }
fn additional_field( fn additional_field(&self, value: &str, name: String, id: String) -> Element<'_, WordMessage> {
&self,
value: &String,
name: String,
id: String,
) -> Element<'_, WordMessage> {
column![ column![
text!("{}", name), text!("{}", name),
row![ row![
+11 -17
View File
@@ -1,10 +1,9 @@
use crate::lang::KanaSet; use crate::core::kana_set::KanaSet;
use crate::navigation::Page::PreviousPage; use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page}; use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::styling::*; use crate::styling::*;
use crate::RootMessage;
use iced::widget::*; use iced::widget::*;
use iced::{alignment, Element, Fill, Task}; use iced::{Element, Fill, Task, alignment};
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -19,7 +18,7 @@ pub struct WritingState {
} }
impl NavigatedPage<WritingMessage> for WritingState { impl NavigatedPage<WritingMessage> for WritingState {
fn navigate(&self, message: &WritingMessage) -> Option<Page> { fn navigate(&mut self, message: &WritingMessage) -> Option<Page> {
if let WritingMessage::Back = message { if let WritingMessage::Back = message {
Some(PreviousPage) Some(PreviousPage)
} else { } else {
@@ -27,11 +26,10 @@ impl NavigatedPage<WritingMessage> for WritingState {
} }
} }
fn navigated(&mut self) { fn navigated(&mut self) {}
}
fn update(&mut self, message: WritingMessage) -> Task<RootMessage> { fn update(&mut self, message: WritingMessage) -> Task<RootMessage> {
match message { match message {
WritingMessage::Back => todo!(), WritingMessage::Back => {}
WritingMessage::Next => self.next(), WritingMessage::Next => self.next(),
WritingMessage::SwitchShowMode(b) => self.show_all = b, WritingMessage::SwitchShowMode(b) => self.show_all = b,
} }
@@ -83,8 +81,6 @@ impl WritingState {
} }
impl WritingState { impl WritingState {
fn next(&mut self) { fn next(&mut self) {
if self.set.is_empty() { if self.set.is_empty() {
self.kana = "".to_string(); self.kana = "".to_string();
@@ -97,24 +93,22 @@ impl WritingState {
} }
if self.show_all { if self.show_all {
if self.set.is_empty() == false && self.kana_total.is_empty() == false { if !self.set.is_empty() && !self.kana_total.is_empty() {
self.set.clear(); self.set.clear();
} }
for pair in &self.set { for pair in &self.set {
self.kana = "---".to_string(); self.kana = "---".to_string();
self.roman_total += &*format!("{} ", &pair.1.clone()).to_string(); self.roman_total += &*format!("{} ", pair.1.clone()).to_string();
self.kana_total += &*format!("{} ", &pair.0).to_string(); self.kana_total += &*format!("{} ", pair.0).to_string();
} }
} else { } else {
let current = self.set.pop().unwrap(); let current = self.set.pop().unwrap();
self.kana_total += &*format!("{} ", &current.0).to_string(); self.kana_total += &*format!("{} ", current.0).to_string();
self.roman_total += &*format!("{} ", &current.1.clone()).to_string(); self.roman_total += &*format!("{} ", current.1.clone()).to_string();
self.kana = current.1; self.kana = current.1;
} }
} }
fn answers(&self) -> Element<'_, WritingMessage> { fn answers(&self) -> Element<'_, WritingMessage> {
if self.set.is_empty() { if self.set.is_empty() {
text!("{}", self.kana_total).size(36).into() text!("{}", self.kana_total).size(36).into()
-533
View File
@@ -1,533 +0,0 @@
use crate::data_provider::card_sets::{delete_set, update_card_set};
use crate::data_provider::card_stats::load_stats_of_set;
use crate::history::HistoryState;
use crate::lang::{SetOrderMode, WordData};
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
use crate::navigation::{NavigatedPage, Page};
use crate::repetition::RepetitionState;
use crate::repetition_settings::RepetitionSettingsState;
use crate::repetitions::RepetitionsMessage::*;
use crate::styling::*;
use crate::{AppState, RootMessage};
use chrono::{Days, Local};
use iced::widget::button::{danger, Status};
pub use iced::widget::button::{Catalog, Style};
use iced::widget::container::bordered_box;
use iced::widget::tooltip::Position::Top;
use iced::widget::{button, column, container, lazy, radio, row, scrollable, space, svg, text, text_input, tooltip, Column, Row};
use iced::{Background, Border, Center, Color, Element, Fill, Length, Shadow, Task, Theme};
use iced_core::border::Radius;
use iced_core::svg::Handle;
use iced_core::Padding;
use rhai::{Engine, Scope};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
pub struct RepetitionsState {
selected_set: Option<usize>,
correct_filters: Vec<bool>,
pub state: Arc<Mutex<AppState>>,
}
impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
fn navigate(&self, message: &RepetitionsMessage) -> Option<Page> {
if let Back = message {
Some(PreviousPage)
} else if let GoToHistory = message {
let card_set;
{
card_set = self.state.lock().unwrap().card_sets[self.selected_set.unwrap()].id;
}
Some(History(HistoryState::new(card_set, self.state.clone())))
} else if let GoToRepetition = message {
let clone = self.state.clone();
let card_set;
{
card_set = self.state.lock().unwrap().card_sets[self.selected_set.unwrap()].clone();
}
Some(Repetition(RepetitionState::new(card_set, clone)))
} else if let GoToSettings = message {
Some(RepetitionSettings(RepetitionSettingsState::new(
self.selected_set.unwrap(),
self.state.clone(),
)))
} else {
None
}
}
fn navigated(&mut self) {
self.selected_set = None;
}
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
let mut state = self.state.lock().unwrap();
match message {
Next => {}
Back => {}
GoToRepetition => {}
GoToHistory => {}
GoToSettings => {}
CreateSet => {
let index = state.card_sets.len() + 1;
state
.card_sets
.push(CardSetSettings::with_name(format!("Card set #{}", index)));
self.correct_filters.push(true);
}
DeleteSet => {
let set = state.card_sets.remove(self.selected_set.unwrap());
self.correct_filters.remove(self.selected_set.unwrap());
self.selected_set = None;
delete_set(&set, &state.connection);
}
SelectSet(index) => {
self.selected_set = Some(index);
let mut set = state.card_sets.get(index).unwrap().clone();
set.update_worst_words(&state);
state.card_sets[index] = set;
}
SetName(new) => {
state.card_sets[self.selected_set.unwrap()].name = new;
}
Save => {
for i in 0..state.card_sets.len() {
self.correct_filters[i] = state.card_sets[i].check_filter();
}
let set = &mut state.card_sets[self.selected_set.unwrap()].clone();
update_card_set(set, &state.connection);
state.card_sets[self.selected_set.unwrap()] = set.clone();
}
SetForward(new) => {
state.card_sets[self.selected_set.unwrap()].forward = new;
}
SetBackward(new) => {
state.card_sets[self.selected_set.unwrap()].backward = new;
}
SetFilter(new) => {
state.card_sets[self.selected_set.unwrap()].filter = new;
}
TryFilter => {
let set = state.card_sets.get(self.selected_set.unwrap()).unwrap();
let count = set.get_word_list(&state).len();
state.card_sets[self.selected_set.unwrap()].count = Some(count);
}
SetOpenMode(mode) => {
state
.card_sets
.get_mut(self.selected_set.unwrap())
.unwrap()
.open_mode = mode;
}
}
Task::none()
}
fn view(&self) -> Element<'_, RepetitionsMessage> {
back_overlay(
row![
column![
scrollable(self.sets_list()).height(Fill),
button("Добавить")
.style(jl_button)
.width(Fill)
.on_press(CreateSet),
]
.spacing(DEFAULT_SPACING)
.width(Length::FillPortion(1)),
self.selected_set_view(),
]
.align_y(Center)
.spacing(DEFAULT_SPACING)
.width(Fill)
.height(Fill)
.into(),
Back,
)
}
}
impl RepetitionsState {
pub(crate) fn new(state: Arc<Mutex<AppState>>) -> RepetitionsState {
let count = state.lock().unwrap().card_sets.len();
RepetitionsState {
selected_set: None,
correct_filters: vec![true; count],
state,
}
}
}
impl RepetitionsState {
fn launch_delete_button(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
if set.id != 0 {
return row![
space().width(Fill),
button(text!("Начать повторение").width(200).center())
.style(cta_button)
.on_press(GoToRepetition)
]
.into();
}
button("Удалить").style(danger).on_press(DeleteSet).into()
}
fn selected_set_view(&self) -> Element<'_, RepetitionsMessage> {
if let Some(index) = self.selected_set {
let set;
{
let state = self.state.lock().unwrap();
if state.card_sets.len() <= index {
return space().width(Length::FillPortion(3)).into();
}
set = state.card_sets[index].clone();
}
return column![
scrollable(
column![
column![
text!("Название набора"),
row![
text_input("", &set.name).on_input(SetName),
button(svg(Handle::from_memory(SETTINGS_ICON)))
.width(43)
.on_press(GoToSettings),
]
.spacing(HALF_SPACING)
]
.spacing(QUARTER_SPACING),
{
if set.id == 0 {
column![
column![
text!("Передняя сторона"),
text_input("", &set.forward).on_input(SetForward),
]
.spacing(QUARTER_SPACING),
column![
text!("Задняя сторона"),
text_input("", &set.backward).on_input(SetBackward),
]
.spacing(QUARTER_SPACING),
column![
text!("Фильтр"),
text_input("", &set.filter).on_input(SetFilter),
button("Проверить фильтр")
.style(jl_button)
.on_press(TryFilter),
self.count_view(&set),
]
.spacing(QUARTER_SPACING),
]
.spacing(DEFAULT_SPACING)
} else {
self.filled_set_data_view(&set)
}
},
radio(
"Обычный режим",
SetOrderMode::Default,
Some(set.open_mode),
SetOpenMode
),
self.words_words_view(&set),
button("История").style(jl_button).on_press(GoToHistory),
]
.spacing(DEFAULT_SPACING)
.padding(Padding {
top: 0.0,
right: DEFAULT_SPACING,
bottom: 0.0,
left: 0.0,
})
)
.height(Fill),
row![
button("Сохранить").style(jl_button).on_press(Save),
self.launch_delete_button(&set)
]
.spacing(DEFAULT_SPACING),
]
.spacing(DEFAULT_SPACING)
.width(Length::FillPortion(3))
.into();
}
space().width(Length::FillPortion(3)).into()
}
fn filled_set_data_view(&self, set: &CardSetSettings) -> Column<'_, RepetitionsMessage> {
column![self.activity_bar(set)].align_x(Center)
.width(Fill)
.spacing(DEFAULT_SPACING)
.into()
}
fn activity_bar(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
const MAX_DAY_COUNT: f32 = 128.0;
let state = self.state.lock().unwrap();
let history = state.activity.get(&set.id);
let mut counts: Vec<u32> = vec![0; 30 * 7];
let now = Local::now().date_naive();
if let Some(history) = history {
for (date, activity) in history {
let distance = now - *date;
let index = counts.len() as i64 - distance.num_days() - 1;
if index == 210 {
println!("invalid index")
}
if index < 0 {
continue;
}
counts[index as usize] = *activity;
}
}
lazy((counts, now), |(counts, now)| {
let mut row = Row::new()
.padding(Padding {
top: 0.0,
right: 0.0,
bottom: 0.0,
left: DEFAULT_SPACING,
})
.spacing(QUARTER_SPACING);
let mut iter = counts.into_iter();
for i in 0..30 {
let mut column = Column::new().spacing(QUARTER_SPACING);
for j in 0..7 {
let value = *iter.next().unwrap() as f32;
let k = (value / MAX_DAY_COUNT).min(1.0) * 0.9 + 0.1;
let date = now.clone().checked_sub_days(Days::new(30 * 7 - i * 7 - j - 1)).unwrap();
column = column.push(tooltip(
iced::widget::container(space().height(15).width(15)).style(
move |x: &Theme| container::Style {
text_color: None,
background: Some(Background::Color(x.palette().primary.scale_alpha(k))),
border: Border {
color: Default::default(),
width: 0.0,
radius: Radius::new(5),
},
shadow: Default::default(),
snap: false,
},
),
text!("{} {} карточки", date.format("%Y.%m.%d"), value),
Top,
));
}
row = row.push(column);
}
scrollable(column!["Карта активности", row].spacing(QUARTER_SPACING).align_x(Center))
}).into()
}
fn words_words_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
column![
text!("Худшие слова"),
container(scrollable(self.worst_words_list(&set)).height(200)).style(bordered_box),
radio(
"Начать с плохих слов",
SetOrderMode::TrainWorstFirst,
Some(set.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
SetOrderMode::FullRandom,
Some(set.open_mode),
SetOpenMode
)
]
.spacing(DEFAULT_SPACING)
.into()
}
fn worst_words_list(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
let mut column = Column::new();
for word in set.worst_words_list.clone().unwrap() {
column = column.push(text!("{} | {}", &word.key, &word.value));
}
column.into()
}
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
if let Some(count) = set.count {
return text!("Количество слов: {}", count).into();
}
space().into()
}
fn sets_list(&self) -> Column<'_, RepetitionsMessage> {
let mut column = Column::new();
let mut i = 0;
let sets = &self.state.lock().unwrap().card_sets;
for set in sets {
column = column.push(
button(text!("{}", set.name.clone()))
.on_press_with(move || SelectSet(i.clone()))
.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 self.correct_filters[i.clone()] {
_x.palette().primary
} else {
_x.palette().warning
},
border: Border {
color: Default::default(),
width: 0.0,
radius: BUTTON_RADIUS.into(),
},
shadow: Shadow::default(),
snap: false,
}),
);
i += 1;
}
column
}
}
#[derive(Clone)]
pub enum RepetitionsMessage {
Next,
Back,
GoToRepetition,
CreateSet,
DeleteSet,
SetName(String),
SelectSet(usize),
Save,
SetForward(String),
SetBackward(String),
SetFilter(String),
TryFilter,
SetOpenMode(SetOrderMode),
GoToHistory,
GoToSettings,
}
#[derive(Clone)]
pub struct CardSetSettings {
pub id: u32,
pub name: String,
pub forward: String,
pub backward: String,
pub filter: String,
pub count: Option<usize>,
pub worst_words_list: Option<Vec<WordData>>,
pub open_mode: SetOrderMode,
}
impl CardSetSettings {
fn with_name(name: String) -> CardSetSettings {
CardSetSettings {
id: 0,
name,
forward: "".to_string(),
backward: "".to_string(),
filter: "true".to_string(),
count: None,
worst_words_list: None,
open_mode: SetOrderMode::Default,
}
}
fn check_filter(&self) -> bool {
let engine = Engine::new();
let ast = engine.compile(&self.filter);
ast.is_ok()
}
pub fn get_word_list(&self, state: &AppState) -> Vec<WordData> {
let mut list = vec![];
let engine = Engine::new();
let ast = engine.compile(&self.filter);
if ast.is_err() {
return list;
}
let ast = ast.unwrap();
let groups = &state.word_groups;
for word in &state.dictionary {
let mut more = rhai::Map::new();
for iced in &word.additional {
more.insert(iced.0.clone().into(), iced.1.clone().into());
}
let mut scope = Scope::new();
scope
.push_constant("key", word.key.clone())
.push_constant("value", word.value.clone())
.push_constant("tags", word.tags.clone())
.push_constant("more", more)
.push_constant(
"group",
groups
.iter()
.find(|g| g.id == word.group_id)
.cloned()
.unwrap()
.name,
);
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
if result.is_ok() && result.unwrap() {
list.push(word.clone());
}
}
list
}
pub fn require_speech(&self) -> bool {
self.forward == "speech" || self.backward == "speech"
}
fn update_worst_words(&mut self, state: &AppState) {
if let Some(_) = self.worst_words_list {
return;
}
let connection = &state.connection;
let mut stats = load_stats_of_set(self, connection);
stats.sort_by_key(|s| s.calculated_score() as i32);
let avg = stats.iter().map(|s| s.calculated_score()).sum::<f32>() / stats.len() as f32;
let avg = avg * 0.7;
let bad: Vec<WordData> = stats
.iter()
.take_while(|word| word.calculated_score() < avg)
.map(|stat| {
state.dictionary[state
.dictionary
.binary_search_by_key(&stat.word_id, |x| x.id)
.unwrap()]
.clone()
})
.collect();
self.worst_words_list = Some(bad.clone());
}
}
+2 -3
View File
@@ -1,10 +1,9 @@
use crate::repetitions::Style; use iced::Element;
use iced::border::Radius; use iced::border::Radius;
use iced::widget::button::*; use iced::widget::button::*;
use iced::widget::{button, container}; use iced::widget::{button, container};
use iced::Element;
use iced_core::alignment::Horizontal::Left;
use iced_core::Length::Fill; use iced_core::Length::Fill;
use iced_core::alignment::Horizontal::Left;
use iced_core::{Border, Theme}; use iced_core::{Border, Theme};
pub const HALF_SPACING: f32 = DEFAULT_SPACING / 2.0; pub const HALF_SPACING: f32 = DEFAULT_SPACING / 2.0;
+123
View File
@@ -0,0 +1,123 @@
#[cfg(test)]
mod mod_tests {
use crate::data::Id;
use crate::data::entities::{EntityData, EntityHandle};
use crate::data::repositories::fast_position_of;
struct ProtoEntity {
id: Id,
_data: i128,
}
impl EntityData for ProtoEntity {
fn id(&self) -> Id {
self.id
}
fn set_id(&mut self, id: Id) {
self.id = id;
}
}
impl ProtoEntity {
fn new(n: i128) -> Self {
Self {
id: (n as u32).into(),
_data: n,
}
}
}
#[test]
fn search_direct() {
let mut entity = EntityHandle::new(8.into(), 3, true);
assert_eq!(
fast_position_of(&[1, 2, 3, 8, 9, 12].map(ProtoEntity::new), &mut entity),
Some(3)
);
}
#[test]
fn search_0() {
let mut entity = EntityHandle::new(8.into(), 4, true);
assert_eq!(
fast_position_of(&[1, 2, 3, 8, 9, 12].map(ProtoEntity::new), &mut entity),
Some(3)
);
}
#[test]
fn search_1() {
let mut entity = EntityHandle::new(9.into(), 5, true);
assert_eq!(
fast_position_of(&[1, 2, 3, 8, 9, 12].map(ProtoEntity::new), &mut entity),
Some(4)
);
}
#[test]
fn search_2() {
let mut entity = EntityHandle::new(106.into(), 25, true);
assert_eq!(
fast_position_of(
&[
1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 105, 106, 107,
108, 109, 110
]
.map(ProtoEntity::new),
&mut entity
),
Some(18)
);
}
#[test]
fn id_0() {
let entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, true);
assert_eq!(entity.real(), true)
}
#[test]
fn id_1() {
let entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, false);
assert_eq!(entity.real(), false)
}
#[test]
fn id_3() {
let entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, true);
assert_eq!(entity.index(), 25)
}
#[test]
fn id_4() {
let entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, false);
assert_eq!(entity.index(), 25)
}
#[test]
fn id_5() {
let mut entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, true);
entity.set_real(true);
assert_eq!(entity.real(), true)
}
#[test]
fn id_6() {
let mut entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, false);
entity.set_real(true);
assert_eq!(entity.real(), true)
}
#[test]
fn id_7() {
let mut entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, true);
entity.set_index(0);
assert_eq!(entity.index(), 0)
}
#[test]
fn id_8() {
let mut entity: EntityHandle<ProtoEntity> = EntityHandle::new(8.into(), 25, false);
entity.set_index(0);
assert_eq!(entity.index(), 0)
}
}