Adding words by parts

This commit is contained in:
2026-08-15 21:32:24 +03:00
parent 8f789facd7
commit 51c8d7be74
23 changed files with 409 additions and 241 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
use criterion::{criterion_group, criterion_main, Criterion};
use criterion::{Criterion, criterion_group, criterion_main};
use std::collections::HashMap as StdHashMap;
use std::hint::black_box;
+1 -2
View File
@@ -1,4 +1,4 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use criterion::{Criterion, black_box, criterion_group, criterion_main};
fn bench_split(c: &mut Criterion) {
let input = "data_1";
@@ -22,7 +22,6 @@ fn bench_split_new(c: &mut Criterion) {
});
}
pub fn split_with_coma(ts: &str) -> Vec<String> {
ts.split(',')
.map(|ts| ts.to_lowercase().trim().to_string())
+1 -1
View File
@@ -1,7 +1,7 @@
use std::fs;
use crate::dictionary::app_data_dir;
use crate::lang::WordOpenMode;
use chrono::{DateTime, Utc};
use std::fs;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::io::{BufRead, BufReader};
+10 -5
View File
@@ -12,7 +12,7 @@ pub struct ImportGroup {
pub fields: Vec<String>,
pub length: u64,
pub mapping: HashMap<String, String>,
pub imported: bool
pub imported: bool,
}
#[derive(Clone)]
@@ -68,13 +68,18 @@ pub fn get_words_of_group(connection: &Connection, group_id: u64) -> Vec<ImportN
.prepare("select tags, flds from notes where mid == ?1;")
.unwrap();
count_stmt.query_map((group_id as i64, ), |row| {
count_stmt
.query_map((group_id as i64,), |row| {
Ok(ImportNote {
tags: row.get(0)?,
fields: row.get::<usize, String>(1)?
fields: row
.get::<usize, String>(1)?
.split('')
.map(|x| x.to_string())
.collect()
.collect(),
})
}).unwrap().map(|x| x.unwrap()).collect::<Vec<ImportNote>>()
})
.unwrap()
.map(|x| x.unwrap())
.collect::<Vec<ImportNote>>()
}
+2 -2
View File
@@ -1,9 +1,9 @@
pub(crate) mod card_sets;
pub(crate) mod card_stats;
pub(crate) mod history;
pub(crate) mod import;
pub(crate) mod settings;
pub(crate) mod sqlite;
pub(crate) mod voice;
pub(crate) mod words;
pub(crate) mod web_api;
pub(crate) mod import;
pub(crate) mod words;
+2 -1
View File
@@ -6,7 +6,8 @@ pub fn get_setting(key: String, connection: &Connection) -> Option<String> {
.unwrap();
let mut iter = stmt.query_map((key,), |row| row.get(0)).unwrap();
if let Some(row) = iter.next() && let Ok(value) = row
if let Some(row) = iter.next()
&& let Ok(value) = row
{
return Some(value);
}
+41 -8
View File
@@ -2,7 +2,7 @@ use crate::dictionary::app_data_dir;
use std::io;
use tokio::fs::{File, OpenOptions};
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 = "https://learning.micialware.ru/";
@@ -17,7 +17,15 @@ pub async fn send_data(id: String) {
let id_url = format!("{api_url}upload/stream/{id}");
let client = reqwest::Client::new();
let new_version = client.post(&id_url).body(data).send().await.unwrap().text().await.unwrap();
let new_version = client
.post(&id_url)
.body(data)
.send()
.await
.unwrap()
.text()
.await
.unwrap();
set_local_version(new_version.parse::<u32>().unwrap()).await;
}
@@ -49,7 +57,14 @@ pub async fn load_data(id: String, temp: bool) {
tokio::fs::write(db_file, data).await.unwrap();
let version_url = format!("{API_URL}{id}/version");
let version = client.get(&version_url).send().await.unwrap().text().await.unwrap();
let version = client
.get(&version_url)
.send()
.await
.unwrap()
.text()
.await
.unwrap();
set_local_version(version.parse::<u32>().unwrap()).await;
}
@@ -90,18 +105,36 @@ pub async fn get_local_version() -> u32 {
let file = app_data_dir().join("data.meta");
if file.exists() {
let mut data = String::new();
File::open(file.clone()).await.unwrap().read_to_string(&mut data).await.unwrap();
File::open(file.clone())
.await
.unwrap()
.read_to_string(&mut data)
.await
.unwrap();
return data.parse::<u32>().unwrap();
}
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(file).await.unwrap();
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(file)
.await
.unwrap();
file.write_all("0".as_bytes()).await.unwrap();
0
}
pub async fn set_local_version(version: u32) {
let file_path = app_data_dir().join("data.meta");
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(file_path).await.unwrap();
file.write_all(version.to_string().as_bytes()).await.unwrap();
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(file_path)
.await
.unwrap();
file.write_all(version.to_string().as_bytes())
.await
.unwrap();
}
+14 -6
View File
@@ -1,5 +1,5 @@
use crate::lang::{WordData, WordGroup};
use rusqlite::{params, Connection};
use rusqlite::{Connection, params};
use std::collections::HashMap;
pub fn add_word(word: &mut WordData, connection: &Connection) {
@@ -23,18 +23,26 @@ pub fn add_word(word: &mut WordData, connection: &Connection) {
word.id = index;
}
pub fn add_words(words: &mut[WordData], connection: &mut Connection) {
pub fn add_words(words: &mut [WordData], connection: &mut Connection) {
let tx = connection.transaction().unwrap();
let 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)",
).unwrap();
)
.unwrap();
for word in words.iter() {
stmt.execute(params![word.key, word.value, word.tags, serde_json::to_string(&word.additional).unwrap(), word.group_id]).unwrap();
stmt.execute(params![
word.key,
word.value,
word.tags,
serde_json::to_string(&word.additional).unwrap(),
word.group_id
])
.unwrap();
}
}
+5 -7
View File
@@ -1,3 +1,4 @@
use crate::RootMessage;
use crate::dictionary::split_with_coma;
use crate::dictionary_test::DictionaryQuizMessage::*;
use crate::lang::WordData;
@@ -5,12 +6,11 @@ use crate::navigation::Page::PreviousPage;
use crate::navigation::*;
use crate::quiz::Score;
use crate::styling::*;
use crate::RootMessage;
use iced::Background::Color;
use iced::border::Radius;
use iced::widget::container::Style;
use iced::widget::{button, container, row, space, text, text_input, Row};
use iced::Background::Color;
use iced::{alignment, Border, Element, Fill, Task, Theme};
use iced::widget::{Row, button, container, row, space, text, text_input};
use iced::{Border, Element, Fill, Task, Theme, alignment};
use rand::prelude::SliceRandom;
#[derive(Debug, Clone)]
@@ -42,8 +42,7 @@ impl NavigatedPage<DictionaryQuizMessage> for DictionaryQuizState {
}
}
fn navigated(&mut self) {
}
fn navigated(&mut self) {}
fn update(&mut self, message: DictionaryQuizMessage) -> Task<RootMessage> {
match message {
@@ -120,7 +119,6 @@ impl DictionaryQuizState {
}
}
fn submit(&mut self) {
if self.view == "---" {
self.show_next();
+1
View File
@@ -0,0 +1 @@
+5 -6
View File
@@ -23,8 +23,7 @@ impl NavigatedPage<HistoryMessage> for HistoryState {
Back => Some(Page::PreviousPage),
}
}
fn navigated(&mut self) {
}
fn navigated(&mut self) {}
fn update(&mut self, _: HistoryMessage) -> Task<RootMessage> {
Task::none()
}
@@ -68,8 +67,6 @@ impl HistoryState {
}
}
fn history_lines(&self) -> Column<'_, HistoryMessage> {
let mut column = Column::new();
for (item, index) in self.list.iter().zip(0..self.list.len()) {
@@ -86,11 +83,13 @@ impl HistoryState {
.align_x(Center),
iced::widget::column![
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)
.align_x(Center)
]
.spacing(5),
);
+23 -13
View File
@@ -1,14 +1,13 @@
use crate::data_provider::card_stats::{
delete_stat, load_stats_of_set, update_stat_score,
};
use crate::data_provider::history::{push_note, HistoryItem};
use crate::AppState;
use crate::data_provider::card_stats::{delete_stat, load_stats_of_set, update_stat_score};
use crate::data_provider::history::{HistoryItem, push_note};
use chrono::{DateTime, Utc};
use rand::distr::weighted::WeightedIndex;
use rand::distr::Distribution;
use rand::distr::weighted::WeightedIndex;
use rand::prelude::SliceRandom;
use rand::rng;
use rand::rngs::ThreadRng;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use rhai::{Engine, Scope};
@@ -316,7 +315,12 @@ impl CardSet {
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 last_list: Vec<_> = settings
.get_word_list(&state_locked)
.iter()
.map(|w| state_locked.dictionary.get(*w).unwrap())
.cloned()
.collect();
let word_ids = last_list.iter().map(|l| l.id).collect::<Vec<u32>>();
// let new_stats: &mut Vec<CardStatistics> = &mut last_list
@@ -452,9 +456,9 @@ pub enum OrderMode {
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum AppendMode{
pub enum AppendMode {
Full,
Manual
Manual,
}
#[derive(Clone)]
@@ -637,7 +641,7 @@ pub struct CardSetSettings {
pub count: Option<usize>,
pub worst_words_list: Option<Vec<WordData>>,
pub open_mode: OrderMode,
pub append_mode: AppendMode
pub append_mode: AppendMode,
}
impl CardSetSettings {
@@ -651,7 +655,7 @@ impl CardSetSettings {
count: None,
worst_words_list: None,
open_mode: OrderMode::Default,
append_mode: AppendMode::Full
append_mode: AppendMode::Full,
}
}
@@ -661,7 +665,7 @@ impl CardSetSettings {
ast.is_ok()
}
pub fn get_word_list(&self, state: &AppState) -> Vec<WordData> {
pub fn get_word_list(&self, state: &AppState) -> Vec<usize> {
let time = Instant::now();
let mut list = vec![];
let engine = Engine::new();
@@ -675,7 +679,11 @@ impl CardSetSettings {
let groups = &state.word_groups;
list = state.dictionary.par_iter().filter(|word| {
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());
@@ -699,7 +707,9 @@ impl CardSetSettings {
let result = engine.eval_ast_with_scope::<bool>(&mut scope, &ast);
result.is_ok() && result.unwrap()
}).cloned().collect();
})
.map(|(index, _)| index)
.collect();
println!("Collecting available words is {:?}", time.elapsed());
+30 -22
View File
@@ -2,22 +2,23 @@
mod data_provider;
mod dictionary;
mod dictionary_test;
pub mod helpers;
mod history;
pub mod import;
mod lang;
pub mod navigation;
mod quiz;
mod randomizer;
mod repetition;
mod repetition_settings;
mod repetitions;
mod selector;
pub mod styling;
mod sync;
mod word;
mod writing;
mod repetition_settings;
pub mod import;
pub mod helpers;
use crate::RootMessage::Keyboard;
use crate::data_provider::card_sets::load_sets;
use crate::data_provider::settings::get_setting;
use crate::data_provider::sqlite::default_connection;
@@ -25,16 +26,15 @@ use crate::data_provider::words::{load_word_groups, load_words};
use crate::lang::{CardSetSettings, WordData, WordGroup};
use crate::navigation::{AppSettings, RootMessage, ScreenState};
use crate::quiz::*;
use crate::RootMessage::Keyboard;
use chrono::NaiveDate;
use iced::{keyboard, Subscription, Theme};
use iced::{window, Font};
use iced_core::window::Position;
use iced::{Font, window};
use iced::{Subscription, Theme, keyboard};
use iced_core::Size;
use rusqlite::Connection;
use std::collections::HashMap;
use iced_core::window::Position;
use iced_core::window::settings::PlatformSpecific;
use mimalloc::MiMalloc;
use rusqlite::Connection;
use std::collections::HashMap;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
@@ -43,7 +43,8 @@ const USER_FONT: Font = Font::with_name("Noto Sans JP");
fn main() -> iced::Result {
println!("Welcome to JapLearn");
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view).window(window_settings())
iced::application(ScreenState::boot, ScreenState::update, ScreenState::view)
.window(window_settings())
.subscription(subscription)
.title("JapLearn")
.settings(iced::Settings {
@@ -52,22 +53,22 @@ fn main() -> iced::Result {
})
.font(include_bytes!("../noto.ttf"))
.default_font(USER_FONT)
.theme(Theme::GruvboxDark).run()
.theme(Theme::GruvboxDark)
.run()
}
fn window_settings() -> window::Settings {
let mut settings = window::Settings{
let mut settings = window::Settings {
position: Position::Centered,
min_size: Some(Size::new(700.0_f32, 700.0_f32)),
.. Default::default()
..Default::default()
};
#[cfg(target_os = "linux")]
{
settings.platform_specific =
PlatformSpecific {
settings.platform_specific = PlatformSpecific {
application_id: "JapLearn".to_string(),
override_redirect: false
override_redirect: false,
};
}
@@ -84,7 +85,7 @@ pub struct AppState {
pub word_groups: Vec<WordGroup>,
pub connection: Connection,
pub sync_data: AppSettings,
pub activity: HashMap<u32, Vec<(NaiveDate, u32)>>
pub activity: HashMap<u32, Vec<(NaiveDate, u32)>>,
}
impl Default for AppState {
@@ -95,14 +96,15 @@ impl Default for AppState {
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 },
sync_data: AppSettings {
key: None,
auto_web_fetch: false,
},
activity: Default::default(),
}
}
@@ -122,6 +124,12 @@ fn fill_state(state: &mut AppState) {
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 }
let fetch = get_setting("AUTO_WEB_FETCH".to_string(), connection)
.unwrap_or("false".to_string())
.parse::<bool>()
.unwrap();
AppSettings {
key,
auto_web_fetch: fetch,
}
}
+4 -6
View File
@@ -5,7 +5,7 @@ use crate::quiz::QuizMessage::*;
use crate::styling::*;
use crate::{RootMessage, USER_FONT};
use iced::widget::*;
use iced::{alignment, Element, Fill, Task};
use iced::{Element, Fill, Task, alignment};
use rand::seq::SliceRandom;
#[derive(Clone, Debug)]
@@ -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> {
match message {
@@ -60,8 +59,6 @@ impl NavigatedPage<QuizMessage> for QuizState {
Task::none()
}
fn view(&self) -> Element<'_, QuizMessage> {
container(
iced::widget::column![
@@ -106,7 +103,8 @@ fn score_display<'a, T: 'a>(score: &Score) -> Element<'a, T> {
.color(iced::Color::from_rgb8(255, 79, 0))
.size(25),
]
.spacing(DEFAULT_SPACING).into()
.spacing(DEFAULT_SPACING)
.into()
}
impl QuizState {
+6 -8
View File
@@ -1,9 +1,9 @@
use crate::RootMessage;
use crate::navigation::{NavigatedPage, Page};
use crate::randomizer::RandomizerMessage::{Back, Edit, Start};
use crate::styling::{back_overlay, jl_button, HALF_SPACING};
use crate::RootMessage;
use iced::widget::{button, text_editor};
use crate::styling::{HALF_SPACING, back_overlay, jl_button};
use iced::Task;
use iced::widget::{button, text_editor};
use rand::prelude::SliceRandom;
#[derive(Clone, Debug)]
@@ -27,8 +27,7 @@ impl NavigatedPage<RandomizerMessage> for RandomizerState {
None
}
fn navigated(&mut self) {
}
fn navigated(&mut self) {}
fn update(&mut self, message: RandomizerMessage) -> Task<RootMessage> {
match message {
Edit(action) => {
@@ -63,7 +62,8 @@ impl NavigatedPage<RandomizerMessage> for RandomizerState {
.into(),
Back,
)
}}
}
}
impl Default for RandomizerState {
fn default() -> Self {
@@ -78,6 +78,4 @@ impl RandomizerState {
list: vec![],
}
}
}
+4 -7
View File
@@ -1,9 +1,10 @@
use crate::AppState;
use crate::data_provider::card_sets::{delete_set, update_card_set};
use crate::lang::CardSetSettings;
use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page, RootMessage};
use crate::repetition_settings::RepetitionSettingsMessage::*;
use crate::styling::*;
use crate::AppState;
use iced::widget::button::danger;
use iced::widget::{button, column, row, scrollable, space, text, text_input};
use iced::{Element, Task};
@@ -11,7 +12,6 @@ use iced_core::Length::Fill;
use iced_core::Padding;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::lang::CardSetSettings;
pub struct RepetitionSettingsState {
set: CardSetSettings,
@@ -45,8 +45,7 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
}
}
fn navigated(&mut self) {
}
fn navigated(&mut self) {}
fn update(&mut self, message: RepetitionSettingsMessage) -> Task<RootMessage> {
match message {
Back => {}
@@ -84,7 +83,7 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
delete_set(&self.set, &state.connection);
state.card_sets.remove(self.index);
return Task::done(RootMessage::RepetitionSettings(Back));
},
}
RevertDeleteSet => self.real_delete = false,
}
Task::none()
@@ -150,8 +149,6 @@ impl NavigatedPage<RepetitionSettingsMessage> for RepetitionSettingsState {
}
impl RepetitionSettingsState {
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionSettingsMessage> {
if let Some(count) = set.count {
return text!("Количество слов: {}", count).into();
+162 -37
View File
@@ -1,6 +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::history::HistoryState;
use crate::lang::{AppendMode, CardSetSettings, OrderMode};
use crate::lang::{AppendMode, CardSetSettings, CardStatistics, OrderMode};
use crate::navigation::Page::{History, PreviousPage, Repetition, RepetitionSettings};
use crate::navigation::{NavigatedPage, Page};
use crate::repetition::RepetitionState;
@@ -8,22 +9,27 @@ 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};
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::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::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 iced_core::Padding;
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>)>,
pub state: Arc<Mutex<AppState>>,
}
@@ -43,6 +49,11 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
{
card_set = self.state.lock().unwrap().card_sets[self.selected_set.unwrap()].clone();
}
if card_set.append_mode == AppendMode::Full {
self.append_all_words(&card_set);
}
Some(Repetition(RepetitionState::new(card_set, clone)))
} else if let GoToSettings = message {
Some(RepetitionSettings(RepetitionSettingsState::new(
@@ -53,9 +64,9 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
None
}
}
fn navigated(&mut self) {
self.selected_set = None;
self.current_sets_cards_cache.clear();
}
fn update(&mut self, message: RepetitionsMessage) -> Task<RootMessage> {
let mut state = self.state.lock().unwrap();
@@ -80,8 +91,15 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
}
SelectSet(index) => {
self.selected_set = Some(index);
let mut set = state.card_sets.get(index).unwrap().clone();
set.update_worst_words(&state);
let set = state.card_sets.get(index).unwrap().clone();
if !self.current_sets_cards_cache.contains_key(&index) {
let added = load_stats_of_set(&set, &state.connection)
.iter()
.map(|c| c.word_id as usize)
.collect();
let total = set.get_word_list(&state);
self.current_sets_cards_cache.insert(index, (added, total));
}
state.card_sets[index] = set;
}
SetName(new) => {
@@ -123,6 +141,31 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
let set = state.card_sets.get_mut(self.selected_set.unwrap()).unwrap();
set.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| {
created_set.insert(c);
});
adding = cache
.1
.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.as_slice());
}
}
Task::none()
}
@@ -149,7 +192,6 @@ impl NavigatedPage<RepetitionsMessage> for RepetitionsState {
Back,
)
}
}
impl RepetitionsState {
@@ -158,12 +200,49 @@ impl RepetitionsState {
RepetitionsState {
selected_set: None,
correct_filters: vec![true; count],
current_sets_cards_cache: Default::default(),
state,
}
}
}
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()
.collect::<Vec<_>>();
Self::append_words(&self.state.lock().unwrap(), set, required.as_slice());
}
fn append_words(state: &AppState, set: &CardSetSettings, indices: &[usize]) {
let words = &state.dictionary;
let stats = &mut indices
.iter()
.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 {
@@ -227,19 +306,34 @@ impl RepetitionsState {
]
.spacing(DEFAULT_SPACING)
} else {
self.filled_set_data_view(&set)
}
},
column![
self.filled_set_data_view(&set),
self.word_append_panel(&set),
radio(
"Обычный режим",
OrderMode::Default,
Some(set.open_mode),
SetOpenMode
),
// self.words_words_view(&set),
self.word_append_panel(&set),
radio(
"Начать с плохих слов",
OrderMode::TrainWorstFirst,
Some(set.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
OrderMode::FullRandom,
Some(set.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,
@@ -263,7 +357,8 @@ impl RepetitionsState {
}
fn filled_set_data_view(&self, set: &CardSetSettings) -> Column<'_, RepetitionsMessage> {
column![self.activity_bar(set)].align_x(Center)
column![self.activity_bar(set), self.count_comparator_view()]
.align_x(Center)
.width(Fill)
.spacing(DEFAULT_SPACING)
}
@@ -275,7 +370,6 @@ impl RepetitionsState {
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;
@@ -302,7 +396,6 @@ impl RepetitionsState {
})
.spacing(QUARTER_SPACING);
let mut iter = counts.iter();
for i in 0..30 {
let mut column = Column::new().spacing(QUARTER_SPACING);
@@ -311,13 +404,17 @@ impl RepetitionsState {
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();
let date = (*now)
.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))),
background: Some(Background::Color(
x.palette().primary.scale_alpha(k),
)),
border: Border {
color: Default::default(),
width: 0.0,
@@ -334,27 +431,19 @@ impl RepetitionsState {
row = row.push(column);
}
scrollable(column!["Карта активности", row].spacing(QUARTER_SPACING).align_x(Center))
}).into()
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(
"Начать с плохих слов",
OrderMode::TrainWorstFirst,
Some(set.open_mode),
SetOpenMode
),
radio(
"Полностью случайно",
OrderMode::FullRandom,
Some(set.open_mode),
SetOpenMode
)
]
.spacing(DEFAULT_SPACING)
.into()
@@ -363,10 +452,40 @@ impl RepetitionsState {
fn word_append_panel(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
column![
text!("Режим добавления карточек"),
row![radio("Добавлять все доступные", AppendMode::Full, Some(set.append_mode), SetAppendMode), radio("Добавлять вручную", AppendMode::Manual, Some(set.append_mode), SetAppendMode)].spacing(HALF_SPACING),
].spacing(HALF_SPACING).into()
row![
radio(
"Добавлять все доступные",
AppendMode::Full,
Some(set.append_mode),
SetAppendMode
),
radio(
"Добавлять вручную",
AppendMode::Manual,
Some(set.append_mode),
SetAppendMode
)
]
.spacing(HALF_SPACING),
self.adder_panel(&set),
]
.spacing(HALF_SPACING)
.into()
}
fn adder_panel(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
match set.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 worst_words_list(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
let mut column = Column::new();
@@ -376,6 +495,12 @@ impl RepetitionsState {
column.into()
}
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();
text!("{} слова добавлено из {}", now, available).into()
}
fn count_view(&self, set: &CardSetSettings) -> Element<'_, RepetitionsMessage> {
if let Some(count) = set.count {
return text!("Количество слов: {}", count).into();
@@ -435,5 +560,5 @@ pub enum RepetitionsMessage {
SetAppendMode(AppendMode),
GoToHistory,
GoToSettings,
AppendWords(usize),
}
+1 -5
View File
@@ -62,8 +62,7 @@ impl NavigatedPage<SelectorMessage> for SelectorState {
None
}
fn navigated(&mut self) {
}
fn navigated(&mut self) {}
fn update(&mut self, message: SelectorMessage) -> Task<RootMessage> {
match message {
SelectorMessage::Change => match self.set.chars_type {
@@ -121,7 +120,6 @@ impl SelectorState {
}
}
fn nav_style(theme: &Theme, status: Status) -> Style {
let mut basic = button::text(theme, status);
basic.background = if status == Status::Hovered {
@@ -133,8 +131,6 @@ impl SelectorState {
basic
}
fn rows_selector(&self) -> Element<'_, SelectorMessage> {
let mut row = Row::new();
+2 -2
View File
@@ -1,10 +1,10 @@
use crate::repetitions::Style;
use iced::Element;
use iced::border::Radius;
use iced::widget::button::*;
use iced::widget::{button, container};
use iced::Element;
use iced_core::alignment::Horizontal::Left;
use iced_core::Length::Fill;
use iced_core::alignment::Horizontal::Left;
use iced_core::{Border, Theme};
pub const HALF_SPACING: f32 = DEFAULT_SPACING / 2.0;
+9 -7
View File
@@ -4,7 +4,7 @@ use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page};
use crate::styling::*;
use crate::sync::SyncMessage::*;
use crate::{fill_state, AppState, RootMessage};
use crate::{AppState, RootMessage, fill_state};
use iced::widget::button::danger;
use iced::widget::container::rounded_box;
use iced::widget::{button, column, container, progress_bar, row, space, text, toggler};
@@ -12,7 +12,6 @@ use iced::{Center, Element, Fill, Font, Length, Task};
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Clone)]
pub enum SyncMessage {
Back,
@@ -130,13 +129,16 @@ impl NavigatedPage<SyncMessage> for SyncState {
state.sync_data.key = None;
delete_settings("SYNC_KEY".to_string(), &state.connection);
delete_settings("AUTO_WEB_FETCH".to_string(), &state.connection);
}
SwitchAutoSync => {
self.auto_fetch = !self.auto_fetch;
let mut state = self.state.lock().unwrap();
state.sync_data.auto_web_fetch = self.auto_fetch;
set_setting("AUTO_WEB_FETCH".to_string(), self.auto_fetch.to_string(), &state.connection);
set_setting(
"AUTO_WEB_FETCH".to_string(),
self.auto_fetch.to_string(),
&state.connection,
);
}
}
Task::none()
@@ -167,8 +169,6 @@ impl SyncState {
}
}
fn sync_column(&self) -> Element<'_, SyncMessage> {
let network_view: Element<'_, SyncMessage> = if self.frozen {
progress_bar(0.0..=5.0, self.progress).into()
@@ -198,7 +198,9 @@ impl SyncState {
button("↓ Скачать").style(jl_button).on_press(GetLast)
]
.spacing(DEFAULT_SPACING),
toggler(self.auto_fetch).label("Автоматическая синхронизация").on_toggle(|_| SwitchAutoSync),
toggler(self.auto_fetch)
.label("Автоматическая синхронизация")
.on_toggle(|_| SwitchAutoSync),
container(network_view).width(Fill),
button("Отключить синхронизацию")
.style(danger)
+2 -7
View File
@@ -51,7 +51,7 @@ impl NavigatedPage<WordMessage> for WordState {
}
SetAdditional(key, value) => {
self.word.additional.insert(key, value.clone());
},
}
AddAdditional(key) => {
self.word.additional.insert(key, "".to_string());
}
@@ -154,12 +154,7 @@ impl WordState {
fn context_field(&self, value: &str) -> Element<'_, WordMessage> {
self.additional_field(value, "В контексте".to_string(), "context".to_string())
}
fn additional_field(
&self,
value: &str,
name: String,
id: String,
) -> Element<'_, WordMessage> {
fn additional_field(&self, value: &str, name: String, id: String) -> Element<'_, WordMessage> {
column![
text!("{}", name),
row![
+3 -8
View File
@@ -1,10 +1,10 @@
use crate::RootMessage;
use crate::lang::KanaSet;
use crate::navigation::Page::PreviousPage;
use crate::navigation::{NavigatedPage, Page};
use crate::styling::*;
use crate::RootMessage;
use iced::widget::*;
use iced::{alignment, Element, Fill, Task};
use iced::{Element, Fill, Task, alignment};
use rand::seq::SliceRandom;
#[derive(Clone, Debug)]
@@ -27,8 +27,7 @@ impl NavigatedPage<WritingMessage> for WritingState {
}
}
fn navigated(&mut self) {
}
fn navigated(&mut self) {}
fn update(&mut self, message: WritingMessage) -> Task<RootMessage> {
match message {
WritingMessage::Back => todo!(),
@@ -83,8 +82,6 @@ impl WritingState {
}
impl WritingState {
fn next(&mut self) {
if self.set.is_empty() {
self.kana = "".to_string();
@@ -113,8 +110,6 @@ impl WritingState {
}
}
fn answers(&self) -> Element<'_, WritingMessage> {
if self.set.is_empty() {
text!("{}", self.kana_total).size(36).into()