Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39f8845119 | ||
|
|
e7023752f1 | ||
|
|
746071125a | ||
|
|
bb673ed7c7 | ||
|
|
98c8093961 | ||
|
|
a4d77196d0 | ||
|
|
4187344a29 | ||
|
|
d3c28179b6 | ||
|
|
3cd7c12baa | ||
|
|
306febc514 | ||
|
|
80785ff9e6 | ||
|
|
9e28b05167 | ||
|
|
97c76350e1 | ||
|
|
99b3818181 |
@@ -1,42 +0,0 @@
|
||||
use criterion::{Criterion, black_box, criterion_group, criterion_main};
|
||||
|
||||
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);
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::lang::{AppendMode, CardSetSettings, OrderMode};
|
||||
use crate::lang::{DeckSettings, OrderMode};
|
||||
|
||||
use rusqlite::Connection;
|
||||
|
||||
pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> {
|
||||
pub fn load_sets(connection: &Connection) -> Vec<DeckSettings> {
|
||||
let mut stmt = connection
|
||||
.prepare("SELECT id, name, forward, backward, filter FROM card_set")
|
||||
.unwrap();
|
||||
let iter = stmt
|
||||
.query_map([], |row| {
|
||||
Ok(CardSetSettings {
|
||||
Ok(DeckSettings {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
forward: row.get(2)?,
|
||||
@@ -17,7 +17,6 @@ pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> {
|
||||
count: None,
|
||||
worst_words_list: None,
|
||||
open_mode: OrderMode::Default,
|
||||
append_mode: AppendMode::Manual,
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
@@ -30,7 +29,7 @@ pub fn load_sets(connection: &Connection) -> Vec<CardSetSettings> {
|
||||
buffer
|
||||
}
|
||||
|
||||
pub fn add_set(set: &mut CardSetSettings, connection: &Connection) {
|
||||
pub fn add_set(set: &mut DeckSettings, connection: &Connection) {
|
||||
let index = connection
|
||||
.query_row(
|
||||
"INSERT INTO card_set (name, forward, backward, filter) VALUES (?1, ?2, ?3, ?4) RETURNING id",
|
||||
@@ -44,11 +43,11 @@ pub fn add_set(set: &mut CardSetSettings, connection: &Connection) {
|
||||
)
|
||||
.unwrap_or_else(|e| {println!("{}", e); 0});
|
||||
|
||||
set.id = index;
|
||||
set.id = index.into();
|
||||
}
|
||||
|
||||
pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) {
|
||||
if set.id == 0 {
|
||||
pub fn update_deck(set: &mut DeckSettings, connection: &Connection) {
|
||||
if !set.id.is_valid() {
|
||||
add_set(set, connection);
|
||||
} else {
|
||||
connection
|
||||
@@ -66,8 +65,8 @@ pub fn update_card_set(set: &mut CardSetSettings, connection: &Connection) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_set(set: &CardSetSettings, connection: &Connection) {
|
||||
if set.id == 0 {
|
||||
pub fn delete_set(set: &DeckSettings, connection: &Connection) {
|
||||
if !set.id.is_valid() {
|
||||
return;
|
||||
}
|
||||
connection
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::lang::{CardSetSettings, CardStatistics};
|
||||
use rusqlite::Connection;
|
||||
use crate::lang::{CardStatistics, DeckSettings};
|
||||
use rusqlite::{params, Connection};
|
||||
use std::time::Instant;
|
||||
|
||||
pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec<CardStatistics> {
|
||||
pub fn load_stats_of_deck(set: &DeckSettings, connection: &Connection) -> Vec<CardStatistics> {
|
||||
let mut stmt = connection
|
||||
.prepare("SELECT id, word_id, score, last_opened FROM card_stats WHERE set_id = ?1")
|
||||
.unwrap();
|
||||
@@ -26,67 +26,41 @@ pub fn load_stats_of_set(set: &CardSetSettings, connection: &Connection) -> Vec<
|
||||
buffer
|
||||
}
|
||||
|
||||
pub fn add_stat_list(stat: &mut [CardStatistics], connection: &Connection) {
|
||||
pub fn add_stat_list(stats: &mut [CardStatistics], connection: &mut Connection) {
|
||||
let time = Instant::now();
|
||||
let inserting = stat
|
||||
.iter()
|
||||
.map(|stat| {
|
||||
format!(
|
||||
"({}, {}, {}, {})",
|
||||
let tx = connection.transaction().unwrap();
|
||||
let count = stats.len();
|
||||
|
||||
{
|
||||
let mut stmt = tx
|
||||
.prepare(
|
||||
"INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4)",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for stat in stats.iter() {
|
||||
stmt.execute(params![
|
||||
stat.word_id,
|
||||
stat.set_id,
|
||||
stat.score,
|
||||
stat.last_open.timestamp()
|
||||
)
|
||||
})
|
||||
.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() {
|
||||
return;
|
||||
])
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let last_index: u32 = connection
|
||||
.query_one(
|
||||
"SELECT seq from sqlite_sequence WHERE name == ?1",
|
||||
("card_stats".to_string(),),
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
let last_index: u32 = tx.last_insert_rowid() as u32;
|
||||
tx.commit().unwrap();
|
||||
|
||||
let start_index = last_index - (stat.len() as u32) + 1;
|
||||
let start_index = last_index - (count as u32) + 1;
|
||||
|
||||
for (index, id) in (start_index..=last_index).enumerate() {
|
||||
stat[index].id = id;
|
||||
stats[index].id = id.into();
|
||||
}
|
||||
|
||||
println!("Added {} cards for {:?}", stat.len(), time.elapsed());
|
||||
println!("Added {} cards for {:?}", stats.len(), time.elapsed());
|
||||
}
|
||||
|
||||
// pub fn add_stat(stat: &mut CardStatistics, connection: &Connection) {
|
||||
// let time = Instant::now();
|
||||
// let index = connection
|
||||
// .query_row(
|
||||
// "INSERT INTO card_stats (word_id, set_id, score, last_opened) VALUES (?1, ?2, ?3, ?4) RETURNING id",
|
||||
// (
|
||||
// &stat.word_id,
|
||||
// &stat.set_id,
|
||||
// &stat.score,
|
||||
// &stat.last_open.timestamp(),
|
||||
// ),
|
||||
// |row| row.get(0)
|
||||
// )
|
||||
// .unwrap_or_else(|e| {println!("{}", e); 0});
|
||||
//
|
||||
// stat.id = index;
|
||||
// println!("Added stat: {}", time.elapsed().as_millis());
|
||||
// }
|
||||
|
||||
pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
|
||||
let time = Instant::now();
|
||||
|
||||
@@ -103,7 +77,7 @@ pub fn update_stat_score(stat: &CardStatistics, connection: &Connection) {
|
||||
}
|
||||
|
||||
pub fn delete_stat(stat: &CardStatistics, connection: &Connection) {
|
||||
if stat.id == 0 {
|
||||
if !stat.id.is_valid() {
|
||||
return;
|
||||
}
|
||||
connection
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::dictionary::app_data_dir;
|
||||
use crate::lang::WordOpenMode;
|
||||
use crate::lang::{Id, WordOpenMode};
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::fs;
|
||||
use std::fs::{File, OpenOptions};
|
||||
@@ -7,7 +7,7 @@ use std::io::Write;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn get_history_of_set(id: u32) -> Vec<HistoryItem> {
|
||||
pub fn get_history_of_set(id: Id) -> Vec<HistoryItem> {
|
||||
let app_dir = history_dir();
|
||||
let head = app_dir.clone().join(format!("set_{}_history.csv", id));
|
||||
let mut lines = Vec::new();
|
||||
@@ -32,7 +32,7 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
|
||||
if let [time, word, mode, before, after] = string.split(';').collect::<Vec<&str>>()[..] {
|
||||
items.push(HistoryItem {
|
||||
timestamp: DateTime::from_timestamp(time.parse().unwrap(), 0).unwrap(),
|
||||
word_id: word.parse::<u32>().unwrap(),
|
||||
word_id: word.parse::<Id>().unwrap(),
|
||||
mode: match mode.parse::<u8>().unwrap() {
|
||||
2 => WordOpenMode::Hard,
|
||||
3 => WordOpenMode::Ok,
|
||||
@@ -48,7 +48,7 @@ fn parse_history_items(strings: Vec<String>) -> Vec<HistoryItem> {
|
||||
items
|
||||
}
|
||||
|
||||
pub fn push_note(set_id: u32, item: HistoryItem) {
|
||||
pub fn push_note(set_id: Id, item: HistoryItem) {
|
||||
let app_dir = history_dir();
|
||||
let path = app_dir.clone().join(format!("set_{}_history.csv", set_id));
|
||||
|
||||
@@ -84,7 +84,7 @@ pub fn history_dir() -> PathBuf {
|
||||
#[derive(Clone)]
|
||||
pub struct HistoryItem {
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub word_id: u32,
|
||||
pub word_id: Id,
|
||||
pub mode: WordOpenMode,
|
||||
pub before: u8,
|
||||
pub after: u8,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use hashbrown::HashMap;
|
||||
use rusqlite::Connection;
|
||||
use serde_json::Value;
|
||||
use hashbrown::HashMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ImportData(pub(crate) Vec<ImportGroup>);
|
||||
|
||||
@@ -98,7 +98,8 @@ pub async fn get_web_version(key: &str) -> Result<u32, reqwest::Error> {
|
||||
let id_url = format!("{API_URL}{key}/version");
|
||||
let client = reqwest::Client::new();
|
||||
let version = client.get(&id_url).send().await?.text().await?;
|
||||
Ok(version.parse::<u32>().unwrap())
|
||||
println!("version: {}", version);
|
||||
Ok(version.parse::<u32>().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub async fn get_local_version() -> u32 {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::lang::{WordData, WordGroup};
|
||||
use rusqlite::{Connection, params};
|
||||
use rusqlite::{params, Connection};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub fn add_word(word: &mut WordData, connection: &Connection) {
|
||||
@@ -20,7 +20,7 @@ pub fn add_word(word: &mut WordData, connection: &Connection) {
|
||||
0
|
||||
});
|
||||
|
||||
word.id = index;
|
||||
word.id = index.into();
|
||||
}
|
||||
|
||||
pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
|
||||
@@ -46,25 +46,19 @@ pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
|
||||
}
|
||||
}
|
||||
|
||||
let last_index: u32 = tx.last_insert_rowid() as u32;
|
||||
tx.commit().unwrap();
|
||||
|
||||
let last_index: u32 = connection
|
||||
.query_one(
|
||||
"SELECT seq from sqlite_sequence WHERE name == ?1",
|
||||
("words".to_string(),),
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let start_index = last_index - (count as u32) + 1;
|
||||
|
||||
for (index, id) in (start_index..=last_index).enumerate() {
|
||||
words[index].id = id;
|
||||
words[index].id = id.into();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_word(word: &mut WordData, connection: &Connection) {
|
||||
if word.id == 0 {
|
||||
if !word.id.is_valid() {
|
||||
add_word(word, connection);
|
||||
} else {
|
||||
connection
|
||||
@@ -86,7 +80,7 @@ pub fn update_word(word: &mut WordData, connection: &Connection) {
|
||||
}
|
||||
|
||||
pub fn delete_word(word: &WordData, connection: &Connection) {
|
||||
if word.id == 0 {
|
||||
if !word.id.is_valid() {
|
||||
return;
|
||||
}
|
||||
connection
|
||||
@@ -156,11 +150,11 @@ pub fn add_group(group: &mut WordGroup, connection: &Connection) {
|
||||
0
|
||||
});
|
||||
|
||||
group.id = index;
|
||||
group.id = index.into();
|
||||
}
|
||||
|
||||
pub fn update_group(group: &mut WordGroup, connection: &Connection) {
|
||||
if group.id == 0 {
|
||||
if !group.id.is_valid() {
|
||||
add_group(group, connection);
|
||||
} else {
|
||||
connection
|
||||
@@ -176,7 +170,7 @@ pub fn update_group(group: &mut WordGroup, connection: &Connection) {
|
||||
}
|
||||
|
||||
pub fn delete_group(group: &WordGroup, connection: &Connection) {
|
||||
if group.id == 0 {
|
||||
if !group.id.is_valid() {
|
||||
return;
|
||||
}
|
||||
connection
|
||||
|
||||
+16
-19
@@ -9,6 +9,7 @@ use crate::styling::*;
|
||||
use crate::word::WordState;
|
||||
use crate::{AppState, RootMessage};
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use iced::alignment::Vertical::Center;
|
||||
use iced::widget::button::Style;
|
||||
use iced::widget::button::{danger, text};
|
||||
@@ -18,7 +19,6 @@ use iced::widget::*;
|
||||
use iced::{Border, Color, Shadow, Task};
|
||||
use iced_core::Length::Fill;
|
||||
use rand::random_range;
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::ops::Add;
|
||||
use std::path::PathBuf;
|
||||
@@ -65,7 +65,7 @@ pub enum DictionaryMessage {
|
||||
}
|
||||
|
||||
impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
fn navigate(&self, message: &DictionaryMessage) -> Option<Page> {
|
||||
fn navigate(&mut self, message: &DictionaryMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
return Some(Page::PreviousPage);
|
||||
}
|
||||
@@ -96,7 +96,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
let dict = &state.dictionary;
|
||||
word = dict[*index].clone();
|
||||
}
|
||||
if word.id != 0 {
|
||||
if word.id.is_valid() {
|
||||
return Some(Word(WordState::new(word, *index, self.state.clone())));
|
||||
}
|
||||
}
|
||||
@@ -150,12 +150,11 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
v = v[..v.len() - 2].to_string()
|
||||
}
|
||||
|
||||
while v.contains(",,") {
|
||||
let index = v.find(",,").unwrap();
|
||||
while let Some(index) = v.find(",,") {
|
||||
v.remove(index);
|
||||
}
|
||||
|
||||
dict.get_mut(i).unwrap().tags = v;
|
||||
dict[i].tags = v;
|
||||
}
|
||||
|
||||
self.update_tags();
|
||||
@@ -172,7 +171,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
}
|
||||
Include(i, b) => self.include_map[i] = b,
|
||||
IncludeTag(t, v) => {
|
||||
let index: u32;
|
||||
let index;
|
||||
{
|
||||
let state = self.state.lock().unwrap();
|
||||
index = state.word_groups[self.selected_group_index].id;
|
||||
@@ -197,7 +196,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
let state = &mut self.state.lock().unwrap();
|
||||
|
||||
state.word_groups.push(WordGroup {
|
||||
id: 0,
|
||||
id: 0.into(),
|
||||
name: format!("Группа слов {}", random_range(100..1000)),
|
||||
});
|
||||
}
|
||||
@@ -211,18 +210,16 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
|
||||
SaveGroup => {
|
||||
let state = &mut self.state.lock().unwrap();
|
||||
let connection = &state.connection;
|
||||
let group = &mut state
|
||||
.word_groups
|
||||
.get(self.selected_group_index)
|
||||
.unwrap()
|
||||
let mut group = state
|
||||
.word_groups[self.selected_group_index]
|
||||
.clone();
|
||||
|
||||
update_group(group, connection);
|
||||
state.word_groups[self.selected_group_index] = group.clone();
|
||||
update_group(&mut group, connection);
|
||||
state.word_groups[self.selected_group_index] = group;
|
||||
}
|
||||
SelectGroup(i) => {
|
||||
self.selected_group_index = i;
|
||||
let index: u32;
|
||||
let index;
|
||||
{
|
||||
let state = self.state.lock().unwrap();
|
||||
index = state.word_groups[i].id;
|
||||
@@ -316,7 +313,7 @@ impl DictionaryState {
|
||||
fn save_word(&mut self, i: usize) {
|
||||
let state = &mut self.state.lock().unwrap();
|
||||
let connection = &state.connection;
|
||||
let word = &mut state.dictionary.get(i).unwrap().clone();
|
||||
let word = &mut state.dictionary[i].clone();
|
||||
|
||||
update_word(word, connection);
|
||||
state.dictionary[i] = word.clone();
|
||||
@@ -423,7 +420,7 @@ impl DictionaryState {
|
||||
let line_button = || {
|
||||
let action = WordAction(index);
|
||||
|
||||
if data.id == 0 {
|
||||
if !data.id.is_valid() {
|
||||
return button("-").on_press(action).style(|_x, _status| Style {
|
||||
background: None,
|
||||
text_color: Color::BLACK,
|
||||
@@ -532,7 +529,7 @@ impl DictionaryState {
|
||||
});
|
||||
}
|
||||
|
||||
fn update_words_include(&mut self, group_id: u32) {
|
||||
fn update_words_include(&mut self, group_id: crate::lang::Id) {
|
||||
let include_tags = self
|
||||
.tag_map
|
||||
.iter()
|
||||
@@ -626,6 +623,6 @@ struct WordLineState {
|
||||
key: String,
|
||||
value: String,
|
||||
tags: String,
|
||||
id: u32,
|
||||
id: crate::lang::Id,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ pub enum DictionaryQuizMessage {
|
||||
}
|
||||
|
||||
impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
|
||||
fn navigate(&self, message: &DictionaryQuizMessage) -> Option<Page> {
|
||||
fn navigate(&mut self, message: &DictionaryQuizMessage) -> Option<Page> {
|
||||
match message {
|
||||
Back => Some(PreviousPage),
|
||||
_ => None,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
+2
-2
@@ -18,7 +18,7 @@ pub struct HistoryState {
|
||||
}
|
||||
|
||||
impl NavigatedPage<HistoryMessage> for HistoryState {
|
||||
fn navigate(&self, message: &HistoryMessage) -> Option<Page> {
|
||||
fn navigate(&mut self, message: &HistoryMessage) -> Option<Page> {
|
||||
match message {
|
||||
Back => Some(Page::PreviousPage),
|
||||
}
|
||||
@@ -46,7 +46,7 @@ impl NavigatedPage<HistoryMessage> for HistoryState {
|
||||
}
|
||||
|
||||
impl HistoryState {
|
||||
pub fn new(id: u32, state: Arc<Mutex<AppState>>) -> Self {
|
||||
pub fn new(id: crate::lang::Id, state: Arc<Mutex<AppState>>) -> Self {
|
||||
let state = state.lock().unwrap();
|
||||
let history = get_history_of_set(id);
|
||||
let words = history
|
||||
|
||||
+11
-18
@@ -1,15 +1,15 @@
|
||||
use crate::AppState;
|
||||
use crate::data_provider::import::{ImportData, ImportGroup, get_words_of_group, load_groups};
|
||||
use crate::data_provider::import::{get_words_of_group, load_groups, ImportData, ImportGroup};
|
||||
use crate::data_provider::words::{add_group, add_words};
|
||||
use crate::dictionary::app_data_dir;
|
||||
use crate::import::ImportMessage::*;
|
||||
use crate::lang::{WordData, WordGroup};
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::styling::*;
|
||||
use crate::AppState;
|
||||
use iced::widget::button::danger;
|
||||
use iced::widget::container::success;
|
||||
use iced::widget::{
|
||||
Row, button, checkbox, column, container, progress_bar, row, rule, text, text_input,
|
||||
button, checkbox, column, container, progress_bar, row, rule, text, text_input, Row,
|
||||
};
|
||||
use iced::widget::{scrollable, space};
|
||||
use iced::{Element, Task};
|
||||
@@ -62,7 +62,7 @@ pub enum ImportMessage {
|
||||
}
|
||||
|
||||
impl NavigatedPage<ImportMessage> for ImportState {
|
||||
fn navigate(&self, message: &ImportMessage) -> Option<Page> {
|
||||
fn navigate(&mut self, message: &ImportMessage) -> Option<Page> {
|
||||
if self.progress.is_some() {
|
||||
return None;
|
||||
}
|
||||
@@ -130,13 +130,7 @@ impl NavigatedPage<ImportMessage> for ImportState {
|
||||
}
|
||||
ImportFinished => {
|
||||
self.progress = None;
|
||||
let group = self
|
||||
.import_data
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.0
|
||||
.get_mut(self.selected_index)
|
||||
.unwrap();
|
||||
let group = &mut self.import_data.as_mut().unwrap().0[self.selected_index];
|
||||
group.imported = true;
|
||||
}
|
||||
}
|
||||
@@ -409,7 +403,7 @@ impl ImportState {
|
||||
}
|
||||
fn setup_mapping(&mut self, property_name: String) {
|
||||
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
|
||||
.mapping
|
||||
.insert(self.selected_property.clone().unwrap(), property_name);
|
||||
@@ -418,7 +412,7 @@ impl ImportState {
|
||||
}
|
||||
fn remove_mapping(&mut self, property_name: String) {
|
||||
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
|
||||
.mapping
|
||||
.keys()
|
||||
@@ -446,7 +440,7 @@ impl ImportState {
|
||||
|
||||
let map_indices = Self::get_mapping_indices(&group);
|
||||
let mut group_entity = WordGroup {
|
||||
id: 0,
|
||||
id: 0.into(),
|
||||
name: group.name.clone(),
|
||||
};
|
||||
{
|
||||
@@ -517,14 +511,13 @@ impl ImportState {
|
||||
.iter()
|
||||
.map(|name| (name.clone(), Vec::<usize>::with_capacity(1)))
|
||||
.collect::<Vec<_>>();
|
||||
for key in group.mapping.keys() {
|
||||
let endpoint = group.mapping.get(key).unwrap();
|
||||
for (key, endpoint) in &group.mapping {
|
||||
let property_index = group.fields.iter().position(|f| f == key).unwrap();
|
||||
let group_index = result
|
||||
.iter()
|
||||
.position(|(name, _)| name == endpoint)
|
||||
.unwrap();
|
||||
result.get_mut(group_index).unwrap().1.push(property_index);
|
||||
result[group_index].1.push(property_index);
|
||||
}
|
||||
|
||||
result
|
||||
@@ -538,7 +531,7 @@ impl ImportState {
|
||||
) -> String {
|
||||
let mut working_words = Vec::with_capacity(indices.len());
|
||||
for index in indices {
|
||||
let str = properties.get(*index).unwrap();
|
||||
let str = &properties[*index];
|
||||
if skip_empty && str.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
+96
-105
@@ -1,5 +1,5 @@
|
||||
use crate::AppState;
|
||||
use crate::data_provider::card_stats::{delete_stat, load_stats_of_set, update_stat_score};
|
||||
use crate::data_provider::card_stats::{delete_stat, load_stats_of_deck, update_stat_score};
|
||||
use crate::data_provider::history::{HistoryItem, push_note};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rand::distr::Distribution;
|
||||
@@ -11,9 +11,13 @@ use rayon::iter::IndexedParallelIterator;
|
||||
use rayon::iter::IntoParallelRefIterator;
|
||||
use rayon::iter::ParallelIterator;
|
||||
use rhai::{Engine, Scope};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cmp::min;
|
||||
use rusqlite::ToSql;
|
||||
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
|
||||
use std::cmp::PartialEq;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::num::ParseIntError;
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -21,6 +25,55 @@ const MAX_HISTORY_LEN: usize = 20;
|
||||
const MAX_HISTORY_LEN_PART: f32 = 0.33;
|
||||
const MAX_SCORE: u8 = 25;
|
||||
const FADE_PER_DAY: f32 = 0.95;
|
||||
#[derive(Clone, PartialEq, Eq, Debug, Hash, Copy)]
|
||||
pub struct Id(u32);
|
||||
pub const INVALID_ID: Id = Id(0);
|
||||
impl FromStr for Id {
|
||||
type Err = ParseIntError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(Id(s.parse::<u32>()?))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u32> for Id {
|
||||
fn from(value: u32) -> Self {
|
||||
Id(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<u32> for Id {
|
||||
fn into(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
impl Display for Id {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for Id {
|
||||
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
|
||||
match value {
|
||||
ValueRef::Integer(i) => Ok(Id(i as u32)),
|
||||
_ => Err(FromSqlError::InvalidType),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSql for Id {
|
||||
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
|
||||
Ok(ToSqlOutput::from(self.0 as i64))
|
||||
}
|
||||
}
|
||||
|
||||
impl Id {
|
||||
pub(crate) fn is_valid(self) -> bool {
|
||||
self.0 != 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct KanaSet {
|
||||
name: String,
|
||||
@@ -28,13 +81,11 @@ pub struct KanaSet {
|
||||
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 {
|
||||
@@ -214,7 +265,6 @@ impl KanaSet {
|
||||
current_set
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for KanaSet {
|
||||
fn default() -> Self {
|
||||
KanaSet::hiragana()
|
||||
@@ -225,45 +275,40 @@ impl PartialEq<Self> for KanaSet {
|
||||
self.name == other.name
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WordData {
|
||||
pub id: u32,
|
||||
pub id: Id,
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
pub tags: String,
|
||||
pub additional: HashMap<String, String>,
|
||||
pub group_id: u32,
|
||||
pub group_id: Id,
|
||||
}
|
||||
|
||||
impl WordData {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
id: 0,
|
||||
id: INVALID_ID,
|
||||
key: String::new(),
|
||||
value: String::new(),
|
||||
tags: String::new(),
|
||||
additional: Default::default(),
|
||||
group_id: 1,
|
||||
group_id: 1.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WordGroup {
|
||||
pub id: u32,
|
||||
pub id: Id,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct CardStatistics {
|
||||
pub id: u32,
|
||||
pub word_id: u32,
|
||||
pub set_id: u32,
|
||||
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 {
|
||||
@@ -290,7 +335,6 @@ impl CardStatistics {
|
||||
(self.score as f32 * multiplier).max(1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum WordOpenMode {
|
||||
Easy,
|
||||
@@ -298,55 +342,29 @@ pub enum WordOpenMode {
|
||||
Hard,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CardSet {
|
||||
pub struct DeckData {
|
||||
words: Vec<WordData>,
|
||||
set: Vec<CardStatistics>,
|
||||
current_word_index: Option<usize>,
|
||||
state: Arc<Mutex<AppState>>,
|
||||
order_module: OrderModule,
|
||||
settings: CardSetSettings,
|
||||
settings: DeckSettings,
|
||||
}
|
||||
|
||||
impl CardSet {
|
||||
pub fn new(settings: &CardSetSettings, state: Arc<Mutex<AppState>>) -> Self {
|
||||
impl DeckData {
|
||||
pub fn new(settings: &DeckSettings, 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 mut current_set = load_stats_of_deck(settings, &state_locked.connection);
|
||||
let last_list: Vec<_> = settings
|
||||
.get_word_list(&state_locked)
|
||||
.iter()
|
||||
.map(|w| state_locked.dictionary.get(*w).unwrap())
|
||||
.map(|w| &state_locked.dictionary[*w])
|
||||
.cloned()
|
||||
.collect();
|
||||
let word_ids = last_list.iter().map(|l| l.id).collect::<Vec<u32>>();
|
||||
let word_ids = last_list.iter().map(|l| l.id).collect::<Vec<Id>>();
|
||||
|
||||
// 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,
|
||||
// last_open: Utc::now(),
|
||||
// score: 1,
|
||||
// set_id: settings.id,
|
||||
// })
|
||||
// .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) {
|
||||
@@ -372,7 +390,6 @@ impl CardSet {
|
||||
settings: settings.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next(&mut self) -> (WordData, CardStatistics) {
|
||||
let index = match self.order_module.clone() {
|
||||
OrderModule::SemiRandomSRS(mut module) => {
|
||||
@@ -404,7 +421,6 @@ impl CardSet {
|
||||
self.current_word_index = Some(index);
|
||||
(self.words[index].clone(), self.set[index].clone())
|
||||
}
|
||||
|
||||
pub fn open(&mut self, status: WordOpenMode) {
|
||||
if self.current_word_index.is_none() {
|
||||
return;
|
||||
@@ -436,50 +452,44 @@ impl CardSet {
|
||||
HistoryItem {
|
||||
timestamp: Utc::now(),
|
||||
word_id: word.word_id,
|
||||
mode: WordOpenMode::Easy,
|
||||
mode: status,
|
||||
before: old_score,
|
||||
after: new_score,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.set.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Copy, Eq)]
|
||||
pub enum OrderMode {
|
||||
Default,
|
||||
TrainWorstFirst,
|
||||
FullRandom,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
#[derive(Clone, Copy, Eq, PartialEq, Default)]
|
||||
pub enum AppendMode {
|
||||
Full,
|
||||
#[default]
|
||||
Manual,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum OrderModule {
|
||||
SemiRandomSRS(SemiRandomSRSModule),
|
||||
RandomSRS(RandomSRSModule),
|
||||
WorstWordsSRS(WorstWordsSRSModule),
|
||||
}
|
||||
|
||||
trait SRSModule {
|
||||
fn next(&mut self, set: &mut CardSet) -> usize;
|
||||
fn next(&mut self, set: &mut DeckData) -> usize;
|
||||
fn open(&mut self, status: WordOpenMode, index: usize, updated_word: CardStatistics);
|
||||
fn init(&mut self, set: &mut CardSet);
|
||||
fn init(&mut self, set: &mut DeckData);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RandomSRSModule {
|
||||
basket: Vec<usize>,
|
||||
initialized: bool,
|
||||
}
|
||||
|
||||
impl RandomSRSModule {
|
||||
fn new() -> RandomSRSModule {
|
||||
Self {
|
||||
@@ -488,9 +498,8 @@ impl RandomSRSModule {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SRSModule for RandomSRSModule {
|
||||
fn next(&mut self, set: &mut CardSet) -> usize {
|
||||
fn next(&mut self, set: &mut DeckData) -> usize {
|
||||
if self.basket.is_empty() {
|
||||
self.basket = (0..set.words.len()).collect::<Vec<usize>>();
|
||||
self.basket.shuffle(&mut rand::rng())
|
||||
@@ -501,13 +510,12 @@ impl SRSModule for RandomSRSModule {
|
||||
|
||||
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
|
||||
|
||||
fn init(&mut self, set: &mut CardSet) {
|
||||
fn init(&mut self, set: &mut DeckData) {
|
||||
self.initialized = true;
|
||||
self.basket = (0..set.words.len()).collect::<Vec<usize>>();
|
||||
self.basket.shuffle(&mut rand::rng())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SemiRandomSRSModule {
|
||||
history: Vec<usize>,
|
||||
@@ -515,7 +523,6 @@ struct SemiRandomSRSModule {
|
||||
generator: ThreadRng,
|
||||
initialized: bool,
|
||||
}
|
||||
|
||||
impl SemiRandomSRSModule {
|
||||
fn new() -> SemiRandomSRSModule {
|
||||
SemiRandomSRSModule {
|
||||
@@ -526,9 +533,8 @@ impl SemiRandomSRSModule {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SRSModule for SemiRandomSRSModule {
|
||||
fn next(&mut self, set: &mut CardSet) -> usize {
|
||||
fn next(&mut self, set: &mut DeckData) -> usize {
|
||||
let index = self.last_weights.sample(&mut self.generator);
|
||||
|
||||
if self.history.contains(&index) {
|
||||
@@ -542,15 +548,13 @@ impl SRSModule for SemiRandomSRSModule {
|
||||
|
||||
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) {
|
||||
fn init(&mut self, set: &mut DeckData) {
|
||||
self.initialized = true;
|
||||
let weights = set
|
||||
.set
|
||||
@@ -560,16 +564,11 @@ impl SRSModule for SemiRandomSRSModule {
|
||||
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,
|
||||
)
|
||||
fn history_len(&self, set: &DeckData) -> usize {
|
||||
((set.len() as f32 * MAX_HISTORY_LEN_PART) as usize).clamp(1, MAX_HISTORY_LEN)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WorstWordsSRSModule {
|
||||
initialized: bool,
|
||||
@@ -579,9 +578,8 @@ struct WorstWordsSRSModule {
|
||||
queue: Vec<usize>,
|
||||
rounds_count: u8,
|
||||
}
|
||||
|
||||
impl SRSModule for WorstWordsSRSModule {
|
||||
fn next(&mut self, set: &mut CardSet) -> usize {
|
||||
fn next(&mut self, set: &mut DeckData) -> usize {
|
||||
if self.rounds_remaining == 0 {
|
||||
self.fill_pool(set);
|
||||
self.rounds_remaining = self.rounds_count;
|
||||
@@ -597,11 +595,10 @@ impl SRSModule for WorstWordsSRSModule {
|
||||
|
||||
fn open(&mut self, _: WordOpenMode, _: usize, _: CardStatistics) {}
|
||||
|
||||
fn init(&mut self, _: &mut CardSet) {
|
||||
fn init(&mut self, _: &mut DeckData) {
|
||||
self.initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl WorstWordsSRSModule {
|
||||
fn new() -> WorstWordsSRSModule {
|
||||
WorstWordsSRSModule {
|
||||
@@ -613,8 +610,7 @@ impl WorstWordsSRSModule {
|
||||
queue: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_pool(&mut self, set: &CardSet) {
|
||||
fn fill_pool(&mut self, set: &DeckData) {
|
||||
let mut sorted = set
|
||||
.set
|
||||
.clone()
|
||||
@@ -630,10 +626,9 @@ impl WorstWordsSRSModule {
|
||||
self.pool = worst;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CardSetSettings {
|
||||
pub id: u32,
|
||||
pub struct DeckSettings {
|
||||
pub id: Id,
|
||||
pub name: String,
|
||||
pub forward: String,
|
||||
pub backward: String,
|
||||
@@ -641,13 +636,11 @@ pub struct CardSetSettings {
|
||||
pub count: Option<usize>,
|
||||
pub worst_words_list: Option<Vec<WordData>>,
|
||||
pub open_mode: OrderMode,
|
||||
pub append_mode: AppendMode,
|
||||
}
|
||||
|
||||
impl CardSetSettings {
|
||||
pub(crate) fn with_name(name: String) -> CardSetSettings {
|
||||
CardSetSettings {
|
||||
id: 0,
|
||||
impl DeckSettings {
|
||||
pub(crate) fn with_name(name: String) -> DeckSettings {
|
||||
DeckSettings {
|
||||
id: 0.into(),
|
||||
name,
|
||||
forward: "".to_string(),
|
||||
backward: "".to_string(),
|
||||
@@ -655,16 +648,15 @@ impl CardSetSettings {
|
||||
count: None,
|
||||
worst_words_list: None,
|
||||
open_mode: OrderMode::Default,
|
||||
append_mode: AppendMode::Manual,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_filter(&self) -> bool {
|
||||
pub fn check_filter(&self) -> bool {
|
||||
let time = Instant::now();
|
||||
let engine = Engine::new();
|
||||
let ast = engine.compile(&self.filter);
|
||||
println!("Compile time is {:?}", time.elapsed());
|
||||
ast.is_ok()
|
||||
}
|
||||
|
||||
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
|
||||
let time = Instant::now();
|
||||
let mut list = vec![];
|
||||
@@ -690,7 +682,7 @@ impl CardSetSettings {
|
||||
}
|
||||
let mut scope = Scope::new();
|
||||
scope
|
||||
.push_constant("id", word.id)
|
||||
.push_constant("id", word.id.0)
|
||||
.push_constant("key", word.key.clone())
|
||||
.push_constant("value", word.value.clone())
|
||||
.push_constant("tags", word.tags.clone())
|
||||
@@ -715,7 +707,6 @@ impl CardSetSettings {
|
||||
|
||||
list
|
||||
}
|
||||
|
||||
pub fn require_speech(&self) -> bool {
|
||||
self.forward == "speech" || self.backward == "speech"
|
||||
}
|
||||
|
||||
+8
-9
@@ -2,7 +2,6 @@
|
||||
mod data_provider;
|
||||
mod dictionary;
|
||||
mod dictionary_test;
|
||||
pub mod helpers;
|
||||
mod history;
|
||||
pub mod import;
|
||||
mod lang;
|
||||
@@ -23,19 +22,19 @@ use crate::data_provider::card_sets::load_sets;
|
||||
use crate::data_provider::settings::get_setting;
|
||||
use crate::data_provider::sqlite::default_connection;
|
||||
use crate::data_provider::words::{load_word_groups, load_words};
|
||||
use crate::lang::{CardSetSettings, WordData, WordGroup};
|
||||
use crate::lang::{DeckSettings, Id, WordData, WordGroup};
|
||||
use crate::navigation::{AppSettings, RootMessage, ScreenState};
|
||||
use crate::quiz::*;
|
||||
use chrono::NaiveDate;
|
||||
use hashbrown::HashMap;
|
||||
use iced::{Font, window};
|
||||
use iced::{Subscription, Theme, keyboard};
|
||||
use iced_core::Size;
|
||||
use iced_core::window::Position;
|
||||
use iced_core::window::settings::PlatformSpecific;
|
||||
use mimalloc::MiMalloc;
|
||||
use rusqlite::Connection;
|
||||
use hashbrown::HashMap;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use iced_core::window::settings::PlatformSpecific;
|
||||
#[global_allocator]
|
||||
static GLOBAL: MiMalloc = MiMalloc;
|
||||
|
||||
@@ -81,11 +80,11 @@ fn subscription(_state: &ScreenState) -> Subscription<RootMessage> {
|
||||
|
||||
pub struct AppState {
|
||||
pub dictionary: Vec<WordData>,
|
||||
pub card_sets: Vec<CardSetSettings>,
|
||||
pub decks: Vec<DeckSettings>,
|
||||
pub word_groups: Vec<WordGroup>,
|
||||
pub connection: Connection,
|
||||
pub sync_data: AppSettings,
|
||||
pub activity: HashMap<u32, Vec<(NaiveDate, u32)>>,
|
||||
pub activity: HashMap<Id, Vec<(NaiveDate, u32)>>,
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
@@ -98,7 +97,7 @@ impl AppState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
dictionary: vec![],
|
||||
card_sets: vec![],
|
||||
decks: vec![],
|
||||
word_groups: vec![],
|
||||
connection: default_connection(),
|
||||
sync_data: AppSettings {
|
||||
@@ -117,7 +116,7 @@ fn fill_state(state: &mut AppState) {
|
||||
let setting = load_settings(&state.connection);
|
||||
|
||||
state.dictionary = list;
|
||||
state.card_sets = sets;
|
||||
state.decks = sets;
|
||||
state.word_groups = groups;
|
||||
state.sync_data = setting
|
||||
}
|
||||
|
||||
+7
-6
@@ -7,6 +7,7 @@ use crate::dictionary::{DictionaryMessage, DictionaryState, app_data_dir};
|
||||
use crate::dictionary_test::{DictionaryQuizMessage, DictionaryQuizState};
|
||||
use crate::history::{HistoryMessage, HistoryState};
|
||||
use crate::import::{ImportMessage, ImportState};
|
||||
use crate::lang::Id;
|
||||
use crate::message_navigation;
|
||||
use crate::navigation::Page::*;
|
||||
use crate::navigation::RootMessage::{DataLoaded, Keyboard, UpdateData};
|
||||
@@ -24,13 +25,13 @@ use crate::word::{WordMessage, WordState};
|
||||
use crate::writing::{WritingMessage, WritingState};
|
||||
use crate::{AppState, fill_state};
|
||||
use chrono::NaiveDate;
|
||||
use hashbrown::HashMap;
|
||||
use iced::keyboard::Event;
|
||||
use iced::{Element, Task};
|
||||
use reqwest::Error;
|
||||
use hashbrown::HashMap;
|
||||
use rusqlite::Connection;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
use rusqlite::Connection;
|
||||
|
||||
impl Default for ScreenState {
|
||||
fn default() -> Self {
|
||||
@@ -60,7 +61,7 @@ pub enum RootMessage {
|
||||
RepetitionSettings(RepetitionSettingsMessage),
|
||||
Import(ImportMessage),
|
||||
Keyboard(Event),
|
||||
DataLoaded(HashMap<u32, Vec<(NaiveDate, u32)>>),
|
||||
DataLoaded(HashMap<Id, Vec<(NaiveDate, u32)>>),
|
||||
None,
|
||||
UpdateData,
|
||||
}
|
||||
@@ -126,8 +127,8 @@ impl ScreenState {
|
||||
for file in directory.read_dir().unwrap().flatten() {
|
||||
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>()
|
||||
let id: Id = history_file_name[4..history_file_name.len() - 12]
|
||||
.parse::<Id>()
|
||||
.unwrap();
|
||||
|
||||
let history = get_history_of_set(id);
|
||||
@@ -330,7 +331,7 @@ macro_rules! state_navigate_handle {
|
||||
}
|
||||
|
||||
pub trait NavigatedPage<T> {
|
||||
fn navigate(&self, message: &T) -> Option<Page>;
|
||||
fn navigate(&mut self, message: &T) -> Option<Page>;
|
||||
fn navigated(&mut self);
|
||||
fn update(&mut self, message: T) -> Task<RootMessage>;
|
||||
fn view(&self) -> Element<'_, T>;
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ pub struct 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 {
|
||||
Some(PreviousPage)
|
||||
} else {
|
||||
@@ -54,7 +54,7 @@ impl NavigatedPage<QuizMessage> for QuizState {
|
||||
self.update_showed()
|
||||
}
|
||||
}
|
||||
Back => todo!(),
|
||||
Back => {},
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ pub enum RandomizerMessage {
|
||||
}
|
||||
|
||||
impl NavigatedPage<RandomizerMessage> for RandomizerState {
|
||||
fn navigate(&self, message: &RandomizerMessage) -> Option<Page> {
|
||||
fn navigate(&mut self, message: &RandomizerMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
return Some(Page::PreviousPage);
|
||||
}
|
||||
|
||||
+8
-7
@@ -1,5 +1,6 @@
|
||||
use crate::data_provider::voice::get_voice;
|
||||
use crate::lang::{CardSet, CardSetSettings, CardStatistics, WordData, WordOpenMode};
|
||||
use crate::lang::Id;
|
||||
use crate::lang::{CardStatistics, DeckData, DeckSettings, WordData, WordOpenMode};
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{KeyPressedPage, NavigatedPage, Page};
|
||||
use crate::styling::*;
|
||||
@@ -17,18 +18,18 @@ use tokio::task::spawn_blocking;
|
||||
|
||||
pub struct RepetitionState {
|
||||
state: Arc<Mutex<AppState>>,
|
||||
pub settings: CardSetSettings,
|
||||
pub set: CardSet,
|
||||
pub settings: DeckSettings,
|
||||
pub set: DeckData,
|
||||
current_word: WordData,
|
||||
current_statistic: CardStatistics,
|
||||
open: bool,
|
||||
can_play: bool,
|
||||
sink: Arc<MixerDeviceSink>,
|
||||
opened: HashSet<u32>,
|
||||
opened: HashSet<Id>,
|
||||
}
|
||||
|
||||
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 {
|
||||
Some(PreviousPage)
|
||||
} else {
|
||||
@@ -95,8 +96,8 @@ impl NavigatedPage<RepetitionMessage> for RepetitionState {
|
||||
}
|
||||
|
||||
impl RepetitionState {
|
||||
pub(crate) fn new(set: CardSetSettings, state: Arc<Mutex<AppState>>) -> RepetitionState {
|
||||
let mut card_set = CardSet::new(&set, state.clone());
|
||||
pub(crate) fn new(set: DeckSettings, state: Arc<Mutex<AppState>>) -> RepetitionState {
|
||||
let mut card_set = DeckData::new(&set, state.clone());
|
||||
let (word, stat) = card_set.next();
|
||||
let sink_handle = rodio::DeviceSinkBuilder::open_default_sink().unwrap();
|
||||
|
||||
|
||||
+23
-11
@@ -1,6 +1,6 @@
|
||||
use crate::AppState;
|
||||
use crate::data_provider::card_sets::{delete_set, update_card_set};
|
||||
use crate::lang::CardSetSettings;
|
||||
use crate::data_provider::card_sets::{delete_set, update_deck};
|
||||
use crate::lang::DeckSettings;
|
||||
use crate::navigation::Page::PreviousPage;
|
||||
use crate::navigation::{NavigatedPage, Page, RootMessage};
|
||||
use crate::repetition_settings::RepetitionSettingsMessage::*;
|
||||
@@ -9,15 +9,17 @@ use iced::widget::button::danger;
|
||||
use iced::widget::{button, column, row, scrollable, space, text, text_input};
|
||||
use iced::{Element, Task};
|
||||
use iced_core::Length::Fill;
|
||||
use iced_core::Padding;
|
||||
use iced_core::{color, Padding, Theme};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use iced::widget::text_input::Catalog;
|
||||
|
||||
pub struct RepetitionSettingsState {
|
||||
set: CardSetSettings,
|
||||
set: DeckSettings,
|
||||
index: usize,
|
||||
state: Arc<Mutex<AppState>>,
|
||||
real_delete: bool,
|
||||
correct_filter: bool,
|
||||
}
|
||||
|
||||
impl RepetitionSettingsState {
|
||||
@@ -25,19 +27,22 @@ impl RepetitionSettingsState {
|
||||
let set;
|
||||
{
|
||||
let local_state = p1.lock().unwrap();
|
||||
set = local_state.card_sets[index].clone();
|
||||
set = local_state.decks[index].clone();
|
||||
}
|
||||
let filter_state = set.check_filter();
|
||||
|
||||
RepetitionSettingsState {
|
||||
index,
|
||||
set,
|
||||
state: p1,
|
||||
real_delete: false,
|
||||
correct_filter: filter_state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
fn navigate(&self, message: &RepetitionSettingsMessage) -> Option<Page> {
|
||||
fn navigate(&mut self, message: &RepetitionSettingsMessage) -> Option<Page> {
|
||||
if let Back = message {
|
||||
Some(PreviousPage)
|
||||
} else {
|
||||
@@ -51,8 +56,8 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
Back => {}
|
||||
Save => {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
update_card_set(&mut self.set, &state.connection);
|
||||
state.card_sets[self.index] = self.set.clone();
|
||||
update_deck(&mut self.set, &state.connection);
|
||||
state.decks[self.index] = self.set.clone();
|
||||
}
|
||||
SetName(new) => {
|
||||
self.set.name = new;
|
||||
@@ -65,6 +70,7 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
}
|
||||
SetFilter(new) => {
|
||||
self.set.filter = new;
|
||||
self.correct_filter = self.set.check_filter();
|
||||
}
|
||||
TryFilter => {
|
||||
let state = self.state.lock().unwrap();
|
||||
@@ -81,7 +87,7 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
}
|
||||
let mut state = self.state.lock().unwrap();
|
||||
delete_set(&self.set, &state.connection);
|
||||
state.card_sets.remove(self.index);
|
||||
state.decks.remove(self.index);
|
||||
return Task::done(RootMessage::RepetitionSettings(Back));
|
||||
}
|
||||
RevertDeleteSet => self.real_delete = false,
|
||||
@@ -111,7 +117,13 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
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("Проверить фильтр")
|
||||
.style(jl_button)
|
||||
.on_press(TryFilter),
|
||||
@@ -149,7 +161,7 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
|
||||
}
|
||||
|
||||
impl RepetitionSettingsState {
|
||||
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionSettingsMessage> {
|
||||
fn count_view(&self, set: &DeckSettings) -> Element<'_, RepetitionSettingsMessage> {
|
||||
if let Some(count) = set.count {
|
||||
return text!("Количество слов: {}", count).into();
|
||||
}
|
||||
|
||||
+282
-184
@@ -1,7 +1,7 @@
|
||||
use crate::data_provider::card_sets::{delete_set, update_card_set};
|
||||
use crate::data_provider::card_stats::{add_stat_list, load_stats_of_set};
|
||||
use crate::data_provider::card_sets::update_deck;
|
||||
use crate::data_provider::card_stats::{add_stat_list, load_stats_of_deck};
|
||||
use crate::history::HistoryState;
|
||||
use crate::lang::{AppendMode, CardSetSettings, CardStatistics, OrderMode};
|
||||
use crate::lang::{AppendMode, CardStatistics, DeckSettings, Id, OrderMode};
|
||||
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
|
||||
use crate::navigation::{NavigatedPage, Page};
|
||||
use crate::repetition::RepetitionState;
|
||||
@@ -11,53 +11,67 @@ use crate::styling::*;
|
||||
use crate::{AppState, RootMessage};
|
||||
use chrono::{Days, Local, Utc};
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use iced::widget::button::{danger, Status};
|
||||
pub use iced::widget::button::{Catalog, Style};
|
||||
use iced::widget::button::{Status, danger};
|
||||
use iced::widget::tooltip::Position::Top;
|
||||
use iced::widget::{
|
||||
button, column, container, lazy, radio, row, scrollable, space, svg, text, text_input, tooltip,
|
||||
Column, Row,
|
||||
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 iced_core::Padding;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RepetitionsState {
|
||||
selected_set: Option<usize>,
|
||||
correct_filters: Vec<bool>,
|
||||
current_sets_cards_cache: HashMap<usize, (Vec<usize>, Vec<usize>)>,
|
||||
word_id_index_map: HashMap<u32, usize>,
|
||||
pub state: Arc<Mutex<AppState>>,
|
||||
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(&self, message: &RepetitionsMessage) -> Option<Page> {
|
||||
fn navigate(&mut 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())))
|
||||
Some(History(HistoryState::new(
|
||||
self.selected_deck().unwrap().id,
|
||||
self.state.clone(),
|
||||
)))
|
||||
} else if let GoToRepetition = message {
|
||||
let clone = self.state.clone();
|
||||
let card_set;
|
||||
|
||||
let selected_set = self.selected_deck_mut().unwrap();
|
||||
if selected_set.append_mode == AppendMode::Full {
|
||||
Self::append_all_words(&mut clone.lock().unwrap(), selected_set);
|
||||
selected_set.existing_words_indices = selected_set.available_words_indices.clone();
|
||||
} else {
|
||||
if selected_set
|
||||
.available_words_indices
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
|| selected_set
|
||||
.existing_words_indices
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
{
|
||||
card_set = self.state.lock().unwrap().card_sets[self.selected_set.unwrap()].clone();
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
if card_set.append_mode == AppendMode::Full {
|
||||
self.append_all_words(&card_set);
|
||||
}
|
||||
|
||||
Some(Repetition(RepetitionState::new(card_set, clone)))
|
||||
Some(Repetition(RepetitionState::new(
|
||||
selected_set.general_settings.clone(),
|
||||
clone,
|
||||
)))
|
||||
} else if let GoToSettings = message {
|
||||
Some(RepetitionSettings(RepetitionSettingsState::new(
|
||||
self.selected_set.unwrap(),
|
||||
self.selected_deck().unwrap().index.unwrap(),
|
||||
self.state.clone(),
|
||||
)))
|
||||
} else {
|
||||
@@ -65,109 +79,149 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
}
|
||||
}
|
||||
fn navigated(&mut self) {
|
||||
self.selected_set = None;
|
||||
self.current_sets_cards_cache.clear();
|
||||
let index = self.selected_deck_index.unwrap();
|
||||
let state = self.state.lock().unwrap();
|
||||
if let Some(global_deck) = state.decks.get(index) {
|
||||
if global_deck.id != self.selected_deck().unwrap().id {
|
||||
drop(state);
|
||||
self.decks.remove(index);
|
||||
self.clear_selection();
|
||||
}
|
||||
} else {
|
||||
drop(state);
|
||||
self.decks.remove(index);
|
||||
self.clear_selection()
|
||||
}
|
||||
}
|
||||
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
|
||||
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);
|
||||
let index = self.decks.len() + 1;
|
||||
self.decks.push(DeckViewData {
|
||||
general_settings: DeckSettings::with_name(format!("Колода #{}", index)),
|
||||
existing_words_indices: None,
|
||||
available_words_indices: None,
|
||||
append_mode: Default::default(),
|
||||
index: None,
|
||||
});
|
||||
}
|
||||
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);
|
||||
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().unwrap();
|
||||
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.selected_set = Some(index);
|
||||
let set = state.card_sets.get(index).unwrap().clone();
|
||||
if !self.current_sets_cards_cache.contains_key(&index) {
|
||||
let added: Vec<_> = load_stats_of_set(&set, &state.connection)
|
||||
self.select_deck(index);
|
||||
let deck = self.selected_deck().unwrap();
|
||||
if deck.existing_words_indices.is_none() {
|
||||
let state = self.state.lock().unwrap();
|
||||
let added: Vec<_> = load_stats_of_deck(deck, &state.connection)
|
||||
.iter()
|
||||
.map(|c| self.word_id_index_map[&c.word_id])
|
||||
.collect();
|
||||
let total = set.get_word_list(&state);
|
||||
|
||||
self.current_sets_cards_cache.insert(index, (added, total));
|
||||
|
||||
let total = deck.get_word_list(&state);
|
||||
drop(state);
|
||||
let deck = self.selected_deck_mut().unwrap();
|
||||
deck.existing_words_indices = Some(added);
|
||||
deck.available_words_indices = Some(total);
|
||||
}
|
||||
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 mut deck = self.selected_deck().unwrap().clone();
|
||||
let mut state = self.state.lock().unwrap();
|
||||
{
|
||||
update_deck(&mut deck.general_settings, &state.connection);
|
||||
if let Some(index) = deck.index {
|
||||
state.decks[index] = deck.general_settings.clone();
|
||||
} else {
|
||||
state.decks.push(deck.general_settings.clone());
|
||||
deck.index = Some(state.decks.len() - 1);
|
||||
self.decks[self.selected_deck_index.unwrap()] = deck.clone();
|
||||
}
|
||||
|
||||
let set = &mut state.card_sets[self.selected_set.unwrap()].clone();
|
||||
|
||||
update_card_set(set, &state.connection);
|
||||
|
||||
state.card_sets[self.selected_set.unwrap()] = set.clone();
|
||||
}
|
||||
SetForward(new) => {
|
||||
state.card_sets[self.selected_set.unwrap()].forward = new;
|
||||
}
|
||||
SetBackward(new) => {
|
||||
state.card_sets[self.selected_set.unwrap()].backward = new;
|
||||
SetForward(value) => {
|
||||
let deck = self.selected_deck_mut().unwrap();
|
||||
deck.general_settings.forward = value;
|
||||
}
|
||||
SetFilter(new) => {
|
||||
state.card_sets[self.selected_set.unwrap()].filter = new;
|
||||
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 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);
|
||||
let state = self.state.lock().unwrap();
|
||||
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) => {
|
||||
state
|
||||
.card_sets
|
||||
.get_mut(self.selected_set.unwrap())
|
||||
.unwrap()
|
||||
.open_mode = mode;
|
||||
let deck = self.selected_deck_mut().unwrap();
|
||||
deck.general_settings.open_mode = mode;
|
||||
}
|
||||
SetAppendMode(mode) => {
|
||||
let set = state.card_sets.get_mut(self.selected_set.unwrap()).unwrap();
|
||||
set.append_mode = mode;
|
||||
let deck = self.selected_deck_mut().unwrap();
|
||||
deck.append_mode = mode;
|
||||
}
|
||||
AppendWords(count) => {
|
||||
let adding: Vec<usize>;
|
||||
let set = state.card_sets.get(self.selected_set.unwrap()).unwrap();
|
||||
let index = self.selected_set.unwrap();
|
||||
{
|
||||
let total_cache = &mut self.current_sets_cards_cache;
|
||||
let cache = total_cache.get_mut(&index).unwrap().clone();
|
||||
let mut created_set = HashSet::with_capacity(cache.0.len());
|
||||
cache.0.iter().for_each(|c| {
|
||||
{
|
||||
let deck = self.selected_deck().unwrap();
|
||||
let existing_words_indices = deck.existing_words_indices.as_ref().unwrap();
|
||||
let mut created_set = HashSet::with_capacity(existing_words_indices.len());
|
||||
existing_words_indices.iter().for_each(|c| {
|
||||
created_set.insert(c);
|
||||
});
|
||||
adding = cache
|
||||
.1
|
||||
adding = deck
|
||||
.available_words_indices
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| !created_set.contains(c))
|
||||
.take(count)
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
let mut new_current = cache.0.clone();
|
||||
new_current.append(&mut adding.clone());
|
||||
total_cache.insert(index, (new_current, cache.1.clone()));
|
||||
}
|
||||
|
||||
Self::append_words(&state, set, adding.into_iter());
|
||||
let deck = self.selected_deck_mut().unwrap();
|
||||
deck.existing_words_indices
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.append(&mut adding.clone());
|
||||
}
|
||||
|
||||
let deck = self.selected_deck().unwrap();
|
||||
let mut state = self.state.lock().unwrap();
|
||||
Self::append_words(&mut state, &deck.general_settings, adding.into_iter());
|
||||
}
|
||||
}
|
||||
Task::none()
|
||||
@@ -177,7 +231,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
back_overlay(
|
||||
row![
|
||||
column![
|
||||
scrollable(self.sets_list()).height(Fill),
|
||||
scrollable(self.decks_list()).height(Fill),
|
||||
button("Добавить")
|
||||
.style(jl_button)
|
||||
.width(Fill)
|
||||
@@ -185,7 +239,7 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.width(Length::FillPortion(1)),
|
||||
self.selected_set_view(),
|
||||
self.selected_deck_view(),
|
||||
]
|
||||
.align_y(Center)
|
||||
.spacing(DEFAULT_SPACING)
|
||||
@@ -200,59 +254,50 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
|
||||
impl RepetitionsState {
|
||||
pub(crate) fn new(state: Arc<Mutex<AppState>>) -> RepetitionsState {
|
||||
let state_ = state.lock().unwrap();
|
||||
let count = state_.card_sets.len();
|
||||
let mut map = HashMap::with_capacity(state_.dictionary.len());
|
||||
|
||||
state_.dictionary.iter().enumerate().for_each(|(index, word)| {map.insert(word.id, index);});
|
||||
state_
|
||||
.dictionary
|
||||
.iter()
|
||||
.enumerate()
|
||||
.for_each(|(index, word)| {
|
||||
map.insert(word.id, index);
|
||||
});
|
||||
|
||||
let decks = Self::get_decks_from_state(&state_);
|
||||
drop(state_);
|
||||
RepetitionsState {
|
||||
selected_set: None,
|
||||
correct_filters: vec![true; count],
|
||||
current_sets_cards_cache: Default::default(),
|
||||
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: None,
|
||||
available_words_indices: None,
|
||||
append_mode: Default::default(),
|
||||
index: Some(index),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl RepetitionsState {
|
||||
fn append_all_words(&self, set: &CardSetSettings) {
|
||||
let index = self.selected_set.unwrap();
|
||||
let cache = &self.current_sets_cards_cache[&index];
|
||||
let mut created_set = HashSet::with_capacity(cache.0.len());
|
||||
cache.0.iter().for_each(|c| {
|
||||
created_set.insert(c);
|
||||
});
|
||||
let required = cache
|
||||
.1
|
||||
.iter()
|
||||
.filter(|i| !created_set.contains(i)).cloned();
|
||||
Self::append_words(&self.state.lock().unwrap(), set, required);
|
||||
fn launch_delete_button(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||
if deck.id.is_valid() {
|
||||
if deck.append_mode == AppendMode::Manual
|
||||
&& deck.existing_words_indices.as_ref().unwrap().is_empty()
|
||||
{
|
||||
return text!("Добавьте карточки или измените фильтр").into();
|
||||
}
|
||||
|
||||
fn append_words(state: &AppState, set: &CardSetSettings, indices: impl Iterator<Item = usize>) {
|
||||
let words = &state.dictionary;
|
||||
let stats = &mut indices
|
||||
.map(|i| {
|
||||
let word = words.get(i).unwrap();
|
||||
CardStatistics {
|
||||
id: 0,
|
||||
word_id: word.id,
|
||||
last_open: Utc::now(),
|
||||
score: 1,
|
||||
set_id: set.id,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !stats.is_empty() {
|
||||
add_stat_list(stats, &state.connection);
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_delete_button(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
|
||||
if set.id != 0 {
|
||||
return row![
|
||||
space().width(Fill),
|
||||
button(text!("Начать повторение").width(200).center())
|
||||
@@ -263,24 +308,15 @@ impl RepetitionsState {
|
||||
}
|
||||
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();
|
||||
}
|
||||
fn selected_deck_view(&self) -> Element<'_, RepetitionsMessage> {
|
||||
if let Some(deck) = &self.selected_deck() {
|
||||
return column![
|
||||
scrollable(
|
||||
column![
|
||||
column![
|
||||
text!("Название набора"),
|
||||
row![
|
||||
text_input("", &set.name).on_input(SetName),
|
||||
text_input("", &deck.name).on_input(SetName),
|
||||
button(svg(Handle::from_memory(SETTINGS_ICON)))
|
||||
.width(43)
|
||||
.on_press(GoToSettings),
|
||||
@@ -289,49 +325,49 @@ impl RepetitionsState {
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
{
|
||||
if set.id == 0 {
|
||||
if !deck.id.is_valid() {
|
||||
column![
|
||||
column![
|
||||
text!("Передняя сторона"),
|
||||
text_input("", &set.forward).on_input(SetForward),
|
||||
text_input("", &deck.forward).on_input(SetForward),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Задняя сторона"),
|
||||
text_input("", &set.backward).on_input(SetBackward),
|
||||
text_input("", &deck.backward).on_input(SetBackward),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
column![
|
||||
text!("Фильтр"),
|
||||
text_input("", &set.filter).on_input(SetFilter),
|
||||
text_input("", &deck.filter).on_input(SetFilter),
|
||||
button("Проверить фильтр")
|
||||
.style(jl_button)
|
||||
.on_press(TryFilter),
|
||||
self.count_view(&set),
|
||||
self.count_view(deck),
|
||||
]
|
||||
.spacing(QUARTER_SPACING),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
} else {
|
||||
column![
|
||||
self.filled_set_data_view(&set),
|
||||
self.word_append_panel(&set),
|
||||
self.filled_deck_data_view(deck),
|
||||
self.word_append_panel(deck),
|
||||
radio(
|
||||
"Обычный режим",
|
||||
OrderMode::Default,
|
||||
Some(set.open_mode),
|
||||
Some(deck.open_mode),
|
||||
SetOpenMode
|
||||
),
|
||||
radio(
|
||||
"Начать с плохих слов",
|
||||
OrderMode::TrainWorstFirst,
|
||||
Some(set.open_mode),
|
||||
Some(deck.open_mode),
|
||||
SetOpenMode
|
||||
),
|
||||
radio(
|
||||
"Полностью случайно",
|
||||
OrderMode::FullRandom,
|
||||
Some(set.open_mode),
|
||||
Some(deck.open_mode),
|
||||
SetOpenMode
|
||||
),
|
||||
button("История").style(jl_button).on_press(GoToHistory),
|
||||
@@ -352,9 +388,10 @@ impl RepetitionsState {
|
||||
.height(Fill),
|
||||
row![
|
||||
button("Сохранить").style(jl_button).on_press(Save),
|
||||
self.launch_delete_button(&set)
|
||||
self.launch_delete_button(deck)
|
||||
]
|
||||
.spacing(DEFAULT_SPACING),
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.align_y(Center),
|
||||
]
|
||||
.spacing(DEFAULT_SPACING)
|
||||
.width(Length::FillPortion(2))
|
||||
@@ -362,18 +399,17 @@ impl RepetitionsState {
|
||||
}
|
||||
space().width(Length::FillPortion(2)).into()
|
||||
}
|
||||
|
||||
fn filled_set_data_view(&self, set: &CardSetSettings) -> Column<'_, RepetitionsMessage> {
|
||||
column![self.activity_bar(set), self.count_comparator_view()]
|
||||
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, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
|
||||
fn activity_bar(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
|
||||
const MAX_DAY_COUNT: f32 = 128.0;
|
||||
|
||||
let state = self.state.lock().unwrap();
|
||||
let history = state.activity.get(&set.id);
|
||||
let history = state.activity.get(&deck.id);
|
||||
let mut counts: Vec<u32> = vec![0; 30 * 7];
|
||||
let now = Local::now().date_naive();
|
||||
|
||||
@@ -382,9 +418,6 @@ impl RepetitionsState {
|
||||
let distance = now - *date;
|
||||
let index = counts.len() as i64 - distance.num_days() - 1;
|
||||
|
||||
if index == 210 {
|
||||
println!("invalid index")
|
||||
}
|
||||
if index < 0 {
|
||||
continue;
|
||||
}
|
||||
@@ -446,33 +479,31 @@ impl RepetitionsState {
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
fn word_append_panel(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
|
||||
fn word_append_panel(&self, deck: &DeckViewData) -> Element<'_, RepetitionsMessage> {
|
||||
column![
|
||||
text!("Режим добавления карточек"),
|
||||
row![
|
||||
radio(
|
||||
"Добавлять все доступные",
|
||||
AppendMode::Full,
|
||||
Some(set.append_mode),
|
||||
Some(deck.append_mode),
|
||||
SetAppendMode
|
||||
),
|
||||
radio(
|
||||
"Добавлять вручную",
|
||||
AppendMode::Manual,
|
||||
Some(set.append_mode),
|
||||
Some(deck.append_mode),
|
||||
SetAppendMode
|
||||
)
|
||||
]
|
||||
.spacing(HALF_SPACING),
|
||||
self.adder_panel(set),
|
||||
self.adder_panel(deck),
|
||||
]
|
||||
.spacing(HALF_SPACING)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn adder_panel(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
|
||||
match set.append_mode {
|
||||
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)),
|
||||
@@ -486,25 +517,27 @@ impl RepetitionsState {
|
||||
}
|
||||
|
||||
fn count_comparator_view(&self) -> Element<'_, RepetitionsMessage> {
|
||||
let cache = &self.current_sets_cards_cache[&self.selected_set.unwrap()];
|
||||
let now = cache.0.len();
|
||||
let available = cache.1.len();
|
||||
let selected_deck = self.selected_deck().unwrap();
|
||||
let now = selected_deck.existing_words_indices.as_ref().unwrap().len();
|
||||
let available = selected_deck
|
||||
.available_words_indices
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.len();
|
||||
text!("{} слова добавлено из {}", now, available).into()
|
||||
}
|
||||
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
|
||||
if let Some(count) = set.count {
|
||||
fn count_view(&self, deck: &DeckSettings) -> Element<'_, RepetitionsMessage> {
|
||||
if let Some(count) = deck.count {
|
||||
return text!("Количество слов: {}", count).into();
|
||||
}
|
||||
space().into()
|
||||
}
|
||||
|
||||
fn sets_list(&self) -> Column<'_, RepetitionsMessage> {
|
||||
fn decks_list(&self) -> Column<'_, RepetitionsMessage> {
|
||||
let mut column = Column::new();
|
||||
|
||||
let sets = &self.state.lock().unwrap().card_sets;
|
||||
for (i, set) in sets.iter().enumerate() {
|
||||
for (i, deck) in self.decks.iter().enumerate() {
|
||||
column = column.push(
|
||||
button(text!("{}", set.name.clone()))
|
||||
button(text!("{}", &deck.name))
|
||||
.on_press_with(move || SelectSet(i))
|
||||
.style(move |_x: &Theme, status: Status| Style {
|
||||
background: if status == Status::Hovered {
|
||||
@@ -512,11 +545,7 @@ impl RepetitionsState {
|
||||
} else {
|
||||
None
|
||||
},
|
||||
text_color: if self.correct_filters[i] {
|
||||
_x.palette().primary
|
||||
} else {
|
||||
_x.palette().warning
|
||||
},
|
||||
text_color: _x.palette().primary,
|
||||
border: Border {
|
||||
color: Default::default(),
|
||||
width: 0.0,
|
||||
@@ -532,6 +561,59 @@ impl RepetitionsState {
|
||||
}
|
||||
}
|
||||
|
||||
impl RepetitionsState {
|
||||
fn append_all_words(state: &mut AppState, deck: &DeckViewData) {
|
||||
let existing = deck.existing_words_indices.as_ref().unwrap();
|
||||
let mut created_set = HashSet::with_capacity(existing.len());
|
||||
existing.iter().for_each(|c| {
|
||||
created_set.insert(c);
|
||||
});
|
||||
let required = deck
|
||||
.available_words_indices
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|i| !created_set.contains(i))
|
||||
.cloned();
|
||||
Self::append_words(state, deck, required);
|
||||
}
|
||||
fn append_words(state: &mut AppState, deck: &DeckSettings, indices: impl Iterator<Item = usize>) {
|
||||
let words = &state.dictionary;
|
||||
let stats = &mut indices
|
||||
.map(|i| {
|
||||
let word = &words[i];
|
||||
CardStatistics {
|
||||
id: 0.into(),
|
||||
word_id: word.id,
|
||||
last_open: Utc::now(),
|
||||
score: 1,
|
||||
set_id: deck.id,
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !stats.is_empty() {
|
||||
add_stat_list(stats, &mut state.connection);
|
||||
}
|
||||
}
|
||||
|
||||
fn select_deck(&mut self, index: usize) {
|
||||
if self.decks.get(index).is_some() {
|
||||
self.selected_deck_index = Some(index);
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_deck(&self) -> Option<&DeckViewData> {
|
||||
self.decks.get(self.selected_deck_index?)
|
||||
}
|
||||
fn selected_deck_mut(&mut self) -> Option<&mut DeckViewData> {
|
||||
self.decks.get_mut(self.selected_deck_index?)
|
||||
}
|
||||
|
||||
fn clear_selection(&mut self) {
|
||||
self.selected_deck_index = None;
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub enum RepetitionsMessage {
|
||||
Next,
|
||||
@@ -552,3 +634,19 @@ pub enum RepetitionsMessage {
|
||||
GoToSettings,
|
||||
AppendWords(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct DeckViewData {
|
||||
general_settings: DeckSettings,
|
||||
existing_words_indices: Option<Vec<usize>>,
|
||||
available_words_indices: Option<Vec<usize>>,
|
||||
append_mode: AppendMode,
|
||||
index: Option<usize>,
|
||||
}
|
||||
impl Deref for DeckViewData {
|
||||
type Target = DeckSettings;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.general_settings
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ pub enum SelectorMessage {
|
||||
}
|
||||
|
||||
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 {
|
||||
return if self.is_writing {
|
||||
let writing = WritingState::new(&self.set);
|
||||
|
||||
+2
-2
@@ -37,7 +37,7 @@ pub struct 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
|
||||
&& !self.frozen
|
||||
{
|
||||
@@ -119,7 +119,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.sync_data = updated_state.sync_data;
|
||||
state.connection = updated_state.connection;
|
||||
state.card_sets = updated_state.card_sets;
|
||||
state.decks = updated_state.decks;
|
||||
state.dictionary = updated_state.dictionary;
|
||||
state.word_groups = updated_state.word_groups;
|
||||
}
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ pub struct 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 {
|
||||
Some(PreviousPage)
|
||||
} else {
|
||||
|
||||
+2
-2
@@ -19,7 +19,7 @@ pub struct 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 {
|
||||
Some(PreviousPage)
|
||||
} else {
|
||||
@@ -30,7 +30,7 @@ impl NavigatedPage<WritingMessage> for WritingState {
|
||||
fn navigated(&mut self) {}
|
||||
fn update(&mut self, message: WritingMessage) -> Task<RootMessage> {
|
||||
match message {
|
||||
WritingMessage::Back => todo!(),
|
||||
WritingMessage::Back => {},
|
||||
WritingMessage::Next => self.next(),
|
||||
WritingMessage::SwitchShowMode(b) => self.show_all = b,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user