Author SHA1 Message Date
micialware 144e258292 Add performance measuring 2026-09-22 00:05:25 +03:00
12 changed files with 889 additions and 180 deletions

No files matched your search

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