Author SHA1 Message Date
micialware f4903725aa deck list code 2026-10-04 16:47:16 +03:00
micialware 936efd0e99 Fsrs pools change 2026-09-23 18:05:58 +03:00
micialware 8603e9b981 Fix editor bug 2026-09-23 14:37:42 +03:00
micialware 824a868d73 Small database sync update 2026-09-22 21:57:29 +03:00
micialware 8b673e52da Change selection type on extended editing 2026-09-22 15:48:18 +03:00
micialware b210b2013d Fix saving bug 2026-09-22 15:27:39 +03:00
12 changed files with 182 additions and 891 deletions

No files matched your search

Generated
+27 -777
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -4,7 +4,7 @@ version = "0.2.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
iced = { version = "0.14.0", features = ["tokio", "svg", "lazy", "crisp", "tiny-skia", "wayland", "wgpu", "tester"], default-features = false} iced = { version = "0.14.0", features = ["tokio", "svg", "lazy", "crisp", "tiny-skia", "wayland", "wgpu"], default-features = false}
iced_core = "0.14.0" iced_core = "0.14.0"
rand = "0.10.3" rand = "0.10.3"
dirs = "7.0.0" dirs = "7.0.0"
@@ -28,7 +28,6 @@ env_logger = "0.11.11"
log = "0.4.34" log = "0.4.34"
fsrs = "6.6.2" fsrs = "6.6.2"
litemap = { version = "0.8.3" } litemap = { version = "0.8.3" }
remote_marker = {git = "https://gitea.micialware.ru/micialware/remote_marker"}
[profile.super-release] [profile.super-release]
inherits = "release" inherits = "release"
+31 -57
View File
@@ -1,7 +1,6 @@
use crate::data::entities::CardState; use crate::data::entities::CardState;
use chrono::{Local, TimeDelta}; use chrono::{Local, TimeDelta};
use fsrs::FSRS; use fsrs::FSRS;
use log::{debug, info};
use rand::distr::weighted::WeightedIndex; use rand::distr::weighted::WeightedIndex;
use rand::prelude::ThreadRng; use rand::prelude::ThreadRng;
use rand::prelude::{Distribution, SliceRandom}; use rand::prelude::{Distribution, SliceRandom};
@@ -67,6 +66,18 @@ pub struct SemiRandomSRSModule {
generator: ThreadRng, generator: ThreadRng,
} }
impl SRSModule for SemiRandomSRSModule { impl SRSModule for SemiRandomSRSModule {
fn new(set: &[&CardState]) -> Self {
let weights = set
.iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>();
Self {
generator: rng(),
last_weights: WeightedIndex::new(weights).expect("Incorrect weights update"),
history: vec![],
}
}
fn next(&mut self, set: &[&CardState]) -> usize { fn next(&mut self, set: &[&CardState]) -> usize {
let index = self.last_weights.sample(&mut self.generator); let index = self.last_weights.sample(&mut self.generator);
@@ -87,18 +98,6 @@ impl SRSModule for SemiRandomSRSModule {
.update_weights(&[(index, &new_weight)]) .update_weights(&[(index, &new_weight)])
.expect("update weights error"); .expect("update weights error");
} }
fn new(set: &[&CardState]) -> Self {
let weights = set
.iter()
.map(|s| (100.0 / s.calculated_score()).powf(2.0) * 2.0)
.collect::<Vec<f32>>();
Self {
generator: rng(),
last_weights: WeightedIndex::new(weights).expect("Incorrect weights update"),
history: vec![],
}
}
} }
impl SemiRandomSRSModule { impl SemiRandomSRSModule {
fn history_len(&self, set: &[&CardState]) -> usize { fn history_len(&self, set: &[&CardState]) -> usize {
@@ -114,6 +113,16 @@ pub struct WorstWordsSRSModule {
rounds_count: u8, rounds_count: u8,
} }
impl SRSModule for WorstWordsSRSModule { impl SRSModule for WorstWordsSRSModule {
fn new(_: &[&CardState]) -> Self {
WorstWordsSRSModule {
pool_size: PARTIAL_POOL_SIZE,
rounds_count: 2,
rounds_remaining: 0,
pool: vec![],
queue: vec![],
}
}
fn next(&mut self, set: &[&CardState]) -> usize { fn next(&mut self, set: &[&CardState]) -> usize {
if self.rounds_remaining == 0 { if self.rounds_remaining == 0 {
self.fill_pool(set); self.fill_pool(set);
@@ -131,16 +140,6 @@ impl SRSModule for WorstWordsSRSModule {
} }
fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {} fn open(&mut self, _: WordOpenMode, _: usize, _: &mut CardState) {}
fn new(_: &[&CardState]) -> Self {
WorstWordsSRSModule {
pool_size: PARTIAL_POOL_SIZE,
rounds_count: 2,
rounds_remaining: 0,
pool: vec![],
queue: vec![],
}
}
} }
impl WorstWordsSRSModule { impl WorstWordsSRSModule {
fn fill_pool(&mut self, set: &[&CardState]) { fn fill_pool(&mut self, set: &[&CardState]) {
@@ -157,9 +156,7 @@ impl WorstWordsSRSModule {
#[derive(Clone)] #[derive(Clone)]
pub struct FsrsModule { pub struct FsrsModule {
today_set: Vec<usize>, next_round: Vec<usize>,
solved: Vec<usize>,
current_group: Vec<usize>,
queue: Vec<usize>, queue: Vec<usize>,
rng: ThreadRng, rng: ThreadRng,
fsrs: FSRS, fsrs: FSRS,
@@ -170,29 +167,22 @@ impl SRSModule for FsrsModule {
let today = Local::now().date_naive(); let today = Local::now().date_naive();
let mut new = Self { let mut new = Self {
today_set: set queue: set
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, c)| c.fsrs_open_day <= today) .filter(|(_, c)| c.fsrs_open_day <= today)
.map(|(index, _)| index) .map(|(index, _)| index)
.collect(), .collect(),
current_group: vec![], next_round: vec![],
queue: vec![],
solved: vec![],
rng: rng(), rng: rng(),
fsrs: FSRS::default(), fsrs: FSRS::default(),
}; };
new.today_set.shuffle(&mut new.rng); new.queue.shuffle(&mut new.rng);
new.fill_partial_pool();
new new
} }
fn next(&mut self, _: &[&CardState]) -> usize { fn next(&mut self, _: &[&CardState]) -> usize {
if self.current_group.is_empty() {
self.fill_partial_pool();
}
if self.queue.is_empty() { if self.queue.is_empty() {
self.fill_queue(); self.fill_queue();
self.queue.shuffle(&mut self.rng); self.queue.shuffle(&mut self.rng);
@@ -230,37 +220,21 @@ impl SRSModule for FsrsModule {
updated_word.fsrs_open_day = next_day; updated_word.fsrs_open_day = next_day;
updated_word.fsrs_opened = updated_word.last_open.date_naive(); updated_word.fsrs_opened = updated_word.last_open.date_naive();
if (updated_word.fsrs_open_day != today && !first_time) if (updated_word.fsrs_open_day == today && !first_time)
|| (first_time && status == WordOpenMode::Easy) || (first_time && status != WordOpenMode::Easy)
{ {
info!("For today word on index {} solved", index); self.next_round.push(index);
self.solved.push(index);
let index = self.current_group.iter().position(|x| *x == index).unwrap();
self.current_group.remove(index);
} }
} }
} }
impl FsrsModule { impl FsrsModule {
fn fill_partial_pool(&mut self) {
debug!("Filling partial pool");
self.current_group.extend(
self.today_set
.iter()
.filter(|x| !self.solved.contains(*x))
.take(PARTIAL_POOL_SIZE),
);
self.queue.clear();
self.queue.extend(self.current_group.clone());
}
fn fill_queue(&mut self) { fn fill_queue(&mut self) {
self.queue.extend(self.current_group.clone()); self.queue.append(&mut self.next_round);
} }
pub fn finished(&self) -> bool { pub fn finished(&self) -> bool {
self.today_set.len() == self.solved.len() self.queue.is_empty() && self.next_round.is_empty()
} }
} }
+21 -3
View File
@@ -93,9 +93,7 @@ fn load_old_schema(connection: &Connection) -> Result<ImportData, NotificationDa
} }
Err(IncorrectAnkiFile) Err(IncorrectAnkiFile)
} }
fn load_new_schema(connection: &Connection) -> Result<ImportData, NotificationData> {
return Err(IncorrectAnkiFile);
}
pub fn get_words_of_group( pub fn get_words_of_group(
connection: &Connection, connection: &Connection,
group_id: u64, group_id: u64,
@@ -119,3 +117,23 @@ pub fn get_words_of_group(
.filter_map(|x| x.ok()) .filter_map(|x| x.ok())
.collect::<Vec<ImportNote>>()) .collect::<Vec<ImportNote>>())
} }
fn load_new_schema(connection: &Connection) -> Result<ImportData, NotificationData> {
return Err(IncorrectAnkiFile);
}
pub struct DeckHeader {
pub id: u64,
pub name: String,
pub count: u64,
}
pub fn load_decks(connection: &Connection) -> Result<Vec<DeckHeader>, NotificationData> {
let mut stmt = connection
.prepare("select id, name from decks")
.unwrap();
Ok(stmt.query_map([], |row| Ok(DeckHeader{
id: row.get::<usize, i64>(0)? as u64,
name: row.get(1)?
})).unwrap().filter_map(|x| x.ok()).collect::<Vec<DeckHeader>>())
}
+1 -4
View File
@@ -76,12 +76,9 @@ pub fn default_connection() -> Connection {
.expect("Failed to set PRAGMA"); .expect("Failed to set PRAGMA");
connection connection
.query_one("PRAGMA journal_mode = WAL;", [], |row| { .query_one("PRAGMA journal_mode = WAL;", [], |row| {
println!("{:?}", row);
Ok(()) Ok(())
}) })
.unwrap_or_else(|e| { .expect("Failed to init database");
println!("{}", e);
});
connection connection
.execute("PRAGMA synchronous = NORMAL;", []) .execute("PRAGMA synchronous = NORMAL;", [])
.expect("Failed to set PRAGMA"); .expect("Failed to set PRAGMA");
+4 -2
View File
@@ -1,9 +1,9 @@
use crate::fs::*; use crate::fs::*;
use crate::notification::NotificationData::{CompressError, PermissionDenied, WebApiUnavailable}; use crate::notification::NotificationData::{CompressError, OpenFileError, PermissionDenied, WebApiUnavailable};
use crate::notification::{MaybeError, NotificationData}; use crate::notification::{MaybeError, NotificationData};
use log::info; use log::info;
use std::io; use std::io;
use tokio::fs::{File, OpenOptions}; use tokio::fs::{remove_file, File, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder}; use zstd::{DEFAULT_COMPRESSION_LEVEL, Decoder, Encoder};
@@ -74,6 +74,8 @@ pub async fn load_data(id: String, temp: bool) -> MaybeError {
.await .await
.map_err(|_| WebApiUnavailable)?; .map_err(|_| WebApiUnavailable)?;
set_local_version(version.parse::<u32>().unwrap_or_default()).await?; set_local_version(version.parse::<u32>().unwrap_or_default()).await?;
remove_file(db_wal()).await.map_err(|_| OpenFileError)?;
remove_file(db_wal()).await.map_err(|_| OpenFileError)?;
Ok(()) Ok(())
} }
+8
View File
@@ -16,6 +16,14 @@ pub fn app_data_dir() -> PathBuf {
pub fn db_path() -> PathBuf { pub fn db_path() -> PathBuf {
app_data_dir().join("data.db") app_data_dir().join("data.db")
} }
pub fn db_wal() -> PathBuf {
app_data_dir().join("data.db-wal")
}
pub fn db_shm() -> PathBuf {
app_data_dir().join("data.db-shm")
}
pub fn temp_db_path() -> PathBuf { pub fn temp_db_path() -> PathBuf {
app_data_dir().join("data.db.tmp") app_data_dir().join("data.db.tmp")
} }
+1 -7
View File
@@ -32,8 +32,6 @@ use iced::{Element, Task};
use iced_core::Length::Fill; use iced_core::Length::Fill;
use log::{debug, info}; use log::{debug, info};
use std::time::Instant; use std::time::Instant;
use chrono::Local;
use remote_marker::{alias, push};
impl Default for ScreenState { impl Default for ScreenState {
fn default() -> Self { fn default() -> Self {
@@ -93,9 +91,6 @@ pub struct ScreenState {
impl ScreenState { impl ScreenState {
pub fn boot() -> (ScreenState, Task<RootMessage>) { pub fn boot() -> (ScreenState, Task<RootMessage>) {
let time = Local::now().timestamp_millis();
alias("frame", format!("frame_{}", time).as_str());
alias("update", format!("update_{}", time).as_str());
info!("Booting"); info!("Booting");
create_db(); create_db();
info!("Db created"); info!("Db created");
@@ -191,7 +186,7 @@ impl ScreenState {
); );
} }
debug!("Update took {:?}", time.elapsed()); debug!("Update took {:?}", time.elapsed());
push("update", time.elapsed().as_nanos());
task.0 task.0
} }
@@ -236,7 +231,6 @@ impl ScreenState {
let notifications = self.notification_manager.draw().map(Notification); let notifications = self.notification_manager.draw().map(Notification);
debug!("View took {:?}", time.elapsed()); debug!("View took {:?}", time.elapsed());
push("frame", time.elapsed().as_nanos());
stack![view, notifications].width(Fill).height(Fill).into() stack![view, notifications].width(Fill).height(Fill).into()
} }
+60 -27
View File
@@ -21,19 +21,19 @@ use chrono::{DateTime, TimeDelta, Utc};
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use iced::alignment::Vertical::Center; use iced::alignment::Vertical::Center;
use iced::widget::button::Style; use iced::widget::button::Style;
use iced::widget::button::{danger, text}; use iced::widget::button::{danger};
use iced::widget::operation::focus; use iced::widget::operation::focus;
use iced::widget::space::horizontal; use iced::widget::space::horizontal;
use iced::widget::text_input::Status::Active; use iced::widget::text_input::Status::Active;
use iced::widget::text_input::default; use iced::widget::text_input::default;
use iced::widget::*; use iced::widget::{row, container, column, text_input, space, button, scrollable, text, Row, checkbox, Column, toggler, lazy};
use iced::{Border, Color, Shadow, Task}; use iced::{Border, Color, Element, Shadow, Task};
use iced_core::Length::{Fill, FillPortion}; use iced_core::Length::{Fill, FillPortion};
use iced_core::border::Radius; use iced_core::border::Radius;
use iced_core::keyboard;
use iced_core::keyboard::Key::Named; use iced_core::keyboard::Key::Named;
use iced_core::keyboard::key::Physical::Code; use iced_core::keyboard::key::Physical::Code;
use iced_core::keyboard::{Event, Modifiers}; use iced_core::keyboard::{Event, Modifiers};
use iced_core::{keyboard, Padding, Theme};
use log::info; use log::info;
use rand::random_range; use rand::random_range;
use std::ops::Add; use std::ops::Add;
@@ -98,6 +98,7 @@ pub enum BasicWordFields {
Key, Key,
Value, Value,
Tags, Tags,
TotalLine,
} }
const FIELDS: &[BasicWordFields] = &[Key, Value, Tags]; const FIELDS: &[BasicWordFields] = &[Key, Value, Tags];
@@ -151,8 +152,8 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
ExtendedEdit(i) => { ExtendedEdit(i) => {
self.word_editor = Some(self.editor_for_word(i)); self.word_editor = Some(self.editor_for_word(i));
if let Some((handle, cell, index)) = self.selected_cell.clone() { if let Some((_, _, index)) = self.selected_cell.clone() {
self.selected_cell = Some((i, cell, index)) self.selected_cell = Some((i, TotalLine, index))
} }
} }
Include(i, b) => { Include(i, b) => {
@@ -295,6 +296,7 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
Tags => { Tags => {
word.tags = value; word.tags = value;
} }
_ => {}
} }
} }
@@ -371,24 +373,27 @@ impl NavigatedPage<DictionaryMessage> for DictionaryState {
} }
} }
ExtendedWordEdited => { ExtendedWordEdited => {
return self.launch_auto_save_offset(self.selected_cell.unwrap().0); let handle = self.word_editor.as_ref().unwrap().word_handle;
return self.launch_auto_save_offset(handle);
} }
} }
Task::none() Task::none()
} }
fn view(&self) -> iced::Element<'_, DictionaryMessage> { fn view(&self) -> Element<'_, DictionaryMessage> {
back_overlay( back_overlay(
row![ row![
iced::widget::column![ column![
self.groups_panel(), self.groups_panel(),
row![horizontal().width(8), self.words_list(),], column![
self.selection_editor(), row![horizontal().width(8), self.words_list(),],
self.selection_editor(),
],
row![ row![
self.add_word_button(), self.add_word_button(),
horizontal().width(Fill), horizontal().width(Fill),
button("Импорт").style(text).on_press(GotoImport), button("Импорт").style(button::text).on_press(GotoImport),
] ]
] ]
.spacing(5) .spacing(5)
@@ -462,7 +467,7 @@ impl DictionaryState {
) )
} }
fn words_list(&self) -> iced::Element<'_, DictionaryMessage> { fn words_list(&self) -> Element<'_, DictionaryMessage> {
let time = Instant::now(); let time = Instant::now();
let mut col = Column::new().width(Fill); let mut col = Column::new().width(Fill);
@@ -512,7 +517,7 @@ impl DictionaryState {
scrollable(col).height(Fill).into() scrollable(col).height(Fill).into()
} }
fn word_line<'a>(data: &WordLineState) -> Row<'a, DictionaryMessage> { fn word_line<'a>(data: &WordLineState) -> Element<'a, DictionaryMessage> {
let mut line = Row::new().width(Fill).align_y(Center); let mut line = Row::new().width(Fill).align_y(Center);
let handle = data.handle; let handle = data.handle;
line = line.push( line = line.push(
@@ -582,10 +587,30 @@ impl DictionaryState {
.style(button::primary) .style(button::primary)
.width(15) .width(15)
}; };
line.push(line_button()).push(space().width(10))
let assembled = line.push(line_button()).push(space().width(10));
if let Some(selection) = data.selection
&& selection == TotalLine
{
return container(assembled.padding(Padding {
top: 2.0,
right: 0.0,
bottom: 2.0,
left: 0.0,
}))
.style(|theme: &Theme| {
let mut style = container::Style::default();
style.border.color = theme.extended_palette().secondary.base.color;
style.border.width = 3.0_f32;
style
})
.into();
}
assembled.into()
} }
fn right_panel(&self) -> iced::Element<'_, DictionaryMessage> { fn right_panel(&self) -> Element<'_, DictionaryMessage> {
if let Some(editor) = &self.word_editor { if let Some(editor) = &self.word_editor {
container(editor.view().map(EditorAction)) container(editor.view().map(EditorAction))
.width(FillPortion(3)) .width(FillPortion(3))
@@ -595,10 +620,10 @@ impl DictionaryState {
} }
} }
fn filters(&self) -> iced::Element<'_, DictionaryMessage> { fn filters(&self) -> Element<'_, DictionaryMessage> {
let dict = &self.state.dictionary.read(); let dict = &self.state.dictionary.read();
iced::widget::column![ column![
jl_text_input!("Поиск", &self.search) jl_text_input!("Поиск", &self.search)
.on_input(Search) .on_input(Search)
.width(Fill), .width(Fill),
@@ -621,7 +646,7 @@ impl DictionaryState {
.into() .into()
} }
fn tags_selector(&self) -> iced::Element<'_, DictionaryMessage> { fn tags_selector(&self) -> Element<'_, DictionaryMessage> {
let mut col = Column::new().width(Fill); let mut col = Column::new().width(Fill);
col = col.push( col = col.push(
button("Сбросить") button("Сбросить")
@@ -716,10 +741,12 @@ impl DictionaryState {
info!("Time {}", time.elapsed().as_micros()); info!("Time {}", time.elapsed().as_micros());
} }
fn selection_editor(&self) -> iced::Element<'_, DictionaryMessage> { fn selection_editor(&self) -> Element<'_, DictionaryMessage> {
let mut display = String::new(); let mut display = String::new();
let mut editable = false; let mut editable = false;
if let Some(selected) = self.selected_cell.as_ref() { if let Some(selected) = self.selected_cell.as_ref()
&& selected.1 != TotalLine
{
let mut dictionary = self.state.dictionary.write(); let mut dictionary = self.state.dictionary.write();
let word = dictionary.get_mut_static(selected.0).unwrap(); let word = dictionary.get_mut_static(selected.0).unwrap();
@@ -733,6 +760,7 @@ impl DictionaryState {
Tags => { Tags => {
display = word.tags.clone(); display = word.tags.clone();
} }
_ => {}
} }
editable = true; editable = true;
} }
@@ -751,9 +779,9 @@ impl DictionaryState {
field.into() field.into()
} }
fn groups_panel(&self) -> iced::Element<'_, DictionaryMessage> { fn groups_panel(&self) -> Element<'_, DictionaryMessage> {
let mut row = Row::new(); let mut row = Row::new();
row = row.push(button("+").style(text).on_press(CreateGroup)); row = row.push(button("+").style(button::text).on_press(CreateGroup));
let groups = &self.state.word_groups.read(); let groups = &self.state.word_groups.read();
@@ -761,7 +789,7 @@ impl DictionaryState {
let group_name = groups.get(&mut group).unwrap().name.clone(); let group_name = groups.get(&mut group).unwrap().name.clone();
row = row.push( row = row.push(
button(text!("{}", group_name)) button(text!("{}", group_name))
.style(text) .style(button::text)
.on_press(SelectGroup(group)), .on_press(SelectGroup(group)),
); );
} }
@@ -769,7 +797,7 @@ impl DictionaryState {
let groups = self.state.word_groups.read(); let groups = self.state.word_groups.read();
let group = groups.get_static(self.selected_group).unwrap(); let group = groups.get_static(self.selected_group).unwrap();
iced::widget::column![ column![
scrollable(row).width(Fill).horizontal(), scrollable(row).width(Fill).horizontal(),
row![ row![
jl_button!("⇳").on_press(ChangeDirection), jl_button!("⇳").on_press(ChangeDirection),
@@ -785,7 +813,7 @@ impl DictionaryState {
.into() .into()
} }
fn group_delete_button(&self) -> iced::Element<'_, DictionaryMessage> { fn group_delete_button(&self) -> Element<'_, DictionaryMessage> {
if self.selected_group.real() && self.selected_group.id != 1.into() { if self.selected_group.real() && self.selected_group.id != 1.into() {
button("Удалить").style(danger).on_press(DeleteGroup).into() button("Удалить").style(danger).on_press(DeleteGroup).into()
} else { } else {
@@ -793,7 +821,7 @@ impl DictionaryState {
} }
} }
fn add_word_button(&self) -> iced::Element<'_, DictionaryMessage> { fn add_word_button(&self) -> Element<'_, DictionaryMessage> {
let button = jl_button!("Добавить слово"); let button = jl_button!("Добавить слово");
if self.selected_group.real() { if self.selected_group.real() {
@@ -838,6 +866,11 @@ impl KeyPressedPage for DictionaryState {
keyboard::key::Code::Escape => { keyboard::key::Code::Escape => {
if self.word_editor.is_some() { if self.word_editor.is_some() {
self.word_editor = None; self.word_editor = None;
if let Some(selected) = self.selected_cell
&& selected.1 == TotalLine
{
self.selected_cell = None;
}
} else if self.selected_cell.is_some() { } else if self.selected_cell.is_some() {
self.selected_cell = None; self.selected_cell = None;
} }
+1 -1
View File
@@ -102,7 +102,7 @@ impl NavigatedPage<SyncMessage> for SyncState {
return tasks; return tasks;
} }
GetLast => { GetLast => {
if self.real_load == false { if !self.real_load {
self.real_load = true; self.real_load = true;
return Task::batch([ return Task::batch([
Task::future(async { Task::future(async {
+10 -10
View File
@@ -11,21 +11,21 @@ use iced::widget::{button, column, row, rule, scrollable, text};
use iced::{Element, Fill}; use iced::{Element, Fill};
use iced_core::Padding; use iced_core::Padding;
pub struct WordEditor<Message> { pub struct WordEditor<Message : Clone> {
state: AppState, state: AppState,
handle: EntityHandle<WordData>, pub word_handle: EntityHandle<WordData>,
on_delete: Option<Message>, on_delete: Option<Message>,
on_edit: Option<Message>, on_edit: Option<Message>,
fields: Vec<CustomField>, fields: Vec<CustomField>,
} }
impl<Message> WordEditor<Message> { impl<Message: std::clone::Clone> WordEditor<Message> {
pub(crate) fn update(&mut self, message: WordMessage) -> Option<Message> { pub(crate) fn update(&mut self, message: WordMessage) -> Option<Message> {
let dictionary = &mut self.state.dictionary.write(); let dictionary = &mut self.state.dictionary.write();
let word = dictionary.get_mut(&mut self.handle).unwrap(); let word = dictionary.get_mut(&mut self.word_handle).unwrap();
match message { match message {
Delete => { Delete => {
return self.on_delete.take(); return self.on_delete.clone();
} }
SetTags(n) => word.tags = n, SetTags(n) => word.tags = n,
SetKey(n) => { SetKey(n) => {
@@ -44,7 +44,7 @@ impl<Message> WordEditor<Message> {
word.additional.remove(&key); word.additional.remove(&key);
} }
} }
self.on_edit.take() self.on_edit.clone()
} }
pub(crate) fn view(&self) -> Element<'_, WordMessage> { pub(crate) fn view(&self) -> Element<'_, WordMessage> {
@@ -53,7 +53,7 @@ impl<Message> WordEditor<Message> {
.state .state
.dictionary .dictionary
.read() .read()
.get_static(self.handle) .get_static(self.word_handle)
.unwrap(); .unwrap();
for field in &self.fields { for field in &self.fields {
if !word.additional.contains_key(&field.id) { if !word.additional.contains_key(&field.id) {
@@ -108,7 +108,7 @@ impl<Message> WordEditor<Message> {
} }
} }
impl<Message> WordEditor<Message> { impl<Message: std::clone::Clone> WordEditor<Message> {
pub fn new(handle: EntityHandle<WordData>, state: AppState) -> Self { pub fn new(handle: EntityHandle<WordData>, state: AppState) -> Self {
let fields = state let fields = state
.custom_fields .custom_fields
@@ -118,7 +118,7 @@ impl<Message> WordEditor<Message> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Self { Self {
state, state,
handle, word_handle: handle,
on_delete: None, on_delete: None,
on_edit: None, on_edit: None,
fields, fields,
@@ -135,7 +135,7 @@ impl<Message> WordEditor<Message> {
} }
} }
impl<Message> WordEditor<Message> { impl<Message: std::clone::Clone> WordEditor<Message> {
fn get_view_for_more(&self, value: (&Id, &String)) -> Element<'_, WordMessage> { fn get_view_for_more(&self, value: (&Id, &String)) -> Element<'_, WordMessage> {
let field = self.fields.iter().find(|f| f.id == *value.0).unwrap(); let field = self.fields.iter().find(|f| f.id == *value.0).unwrap();
match value.0 { match value.0 {
+17 -1
View File
@@ -1,5 +1,5 @@
#[cfg(test)] #[cfg(test)]
mod mod_tests { mod data_access {
use crate::data::Id; use crate::data::Id;
use crate::data::entities::{EntityData, EntityHandle}; use crate::data::entities::{EntityData, EntityHandle};
use crate::data::repositories::fast_position_of; use crate::data::repositories::fast_position_of;
@@ -121,3 +121,19 @@ mod mod_tests {
assert_eq!(entity.index(), 0) assert_eq!(entity.index(), 0)
} }
} }
#[cfg(test)]
mod anki_import{
use std::path::{Path, PathBuf};
use rusqlite::Connection;
use crate::data_provider::import::load_decks;
use crate::notification::NotificationData::IncorrectAnkiFile;
#[test]
pub fn decks(){
let file_name = Path::new("import");
let connection = Connection::open(file_name).unwrap();
let decks = load_decks(&connection).unwrap();
assert_eq!(decks.len(), 2);
}
}