fix: rewrite state system

This commit is contained in:
Artemy Egorov 2024-07-30 15:36:11 +03:00
parent 7bb18fd062
commit febafc94df
12 changed files with 243 additions and 158 deletions

4
src-tauri/Cargo.lock generated
View file

@ -501,9 +501,9 @@ dependencies = [
[[package]]
name = "dalet"
version = "1.0.0-pre2"
version = "1.0.0-pre3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7a4c96bc370794e34c34ed93abe3f04140b9909bc80b942b98a9abd7b8c248d"
checksum = "c629ef0fc95fddd843a73e72de3f509665a73f51323f7b6c1b7946eb8937b660"
dependencies = [
"serde",
]

View file

@ -25,7 +25,7 @@ tauri = { version = "1", features = [
] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dalet = "1.0.0-pre2"
dalet = "1.0.0-pre3"
reqwest = "0.12.5"
[features]

View file

@ -1,118 +1,79 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::{
fs::{self},
sync::Mutex,
};
use dalet::{Argument, Body, Tag};
use std::fs::{self};
mod types;
mod utils;
use tauri::Manager;
use types::{TabType, VigiError, VigiState};
use tauri::async_runtime::Mutex;
use types::{VigiError, VigiJsState, VigiState};
use utils::{read_or_create_jsonl, read_or_create_number};
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
async fn process_input(
async fn update_input(
input: String,
state: tauri::State<'_, Mutex<VigiState>>,
) -> Result<Vec<Tag>, VigiError> {
// TODO: Implement mime type, language, protocol or search detection
// TODO: Implement text links parsing
println!("Processing: {}", input);
match reqwest::get(input.clone()).await {
Ok(res) => match res.text().await {
Ok(res) => {
update_tab(state, TabType::Text, res.clone(), input.clone())?;
Ok(vec![Tag::new(0, Body::Text(res), Argument::Null)])
}
Err(_) => Err(VigiError::Parse),
},
Err(_) => Err(VigiError::Network),
}
}
#[tauri::command]
fn get_state(state: tauri::State<Mutex<VigiState>>) -> VigiState {
(*state.lock().unwrap()).clone()
}
#[tauri::command]
fn select_tab(state: tauri::State<Mutex<VigiState>>, index: usize) -> Result<(), VigiError> {
match state.lock() {
Ok(mut state) => {
state.update_current_tab_index(index)?;
Ok(())
}
Err(_) => Err(VigiError::StateLock),
}
}
#[tauri::command]
fn add_tab(state: tauri::State<Mutex<VigiState>>) -> Result<(), VigiError> {
match state.lock() {
Ok(mut state) => {
state.add_tab()?;
Ok(())
}
Err(_) => Err(VigiError::StateLock),
}
}
#[tauri::command]
fn remove_tab(state: tauri::State<Mutex<VigiState>>, index: usize) -> Result<(), VigiError> {
match state.lock() {
Ok(mut state) => {
state.remove_tab(index)?;
Ok(())
}
Err(_) => Err(VigiError::StateLock),
}
}
fn update_tab(
state: tauri::State<Mutex<VigiState>>,
tab_type: TabType,
tab_title: String,
tab_url: String,
) -> Result<(), VigiError> {
match state.lock() {
Ok(mut state) => {
state.update_tab(tab_type, tab_title, tab_url)?;
Ok(())
}
Err(_) => Err(VigiError::StateLock),
}
state.lock().await.update_input(input).await
}
#[tauri::command]
async fn get_js_state(state: tauri::State<'_, Mutex<VigiState>>) -> Result<VigiJsState, VigiError> {
Ok(state.lock().await.get_js_state())
}
#[tauri::command]
async fn select_tab(
index: usize,
state: tauri::State<'_, Mutex<VigiState>>,
) -> Result<(), VigiError> {
state.lock().await.select_tab(index).await
}
#[tauri::command]
async fn load_tab(state: tauri::State<'_, Mutex<VigiState>>) -> Result<(), VigiError> {
state.lock().await.load_tab().await
}
#[tauri::command]
async fn add_tab(state: tauri::State<'_, Mutex<VigiState>>) -> Result<(), VigiError> {
state.lock().await.add_tab()
}
#[tauri::command]
async fn remove_tab(
state: tauri::State<'_, Mutex<VigiState>>,
index: usize,
) -> Result<(), VigiError> {
state.lock().await.remove_tab(index)
}
fn main() {
tauri::Builder::default()
.manage(Mutex::new(VigiState::null()))
.setup(setup_handler)
.invoke_handler(tauri::generate_handler![
process_input,
get_state,
update_input,
get_js_state,
select_tab,
load_tab,
add_tab,
remove_tab
remove_tab,
setup
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
fn setup_handler(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error + 'static>> {
#[tauri::command]
async fn setup(
state: tauri::State<'_, Mutex<VigiState>>,
app_handle: tauri::AppHandle,
) -> Result<(), VigiError> {
println!("---Setup---");
let app_handle = app.handle();
let state = app.state::<Mutex<VigiState>>();
let mut state = state.lock().unwrap();
let mut state = state.lock().await;
let config_dir = app_handle
.path_resolver()
@ -138,7 +99,7 @@ fn setup_handler(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error +
// check if config/favorites.jsonl exists
if !config_dir.exists() {
println!(" Creating config dir");
fs::create_dir_all(&config_dir)?;
fs::create_dir_all(&config_dir).map_err(|_| VigiError::Config)?;
}
state.favorites_tabs_path = config_dir.join("favorites.jsonl");
@ -147,7 +108,7 @@ fn setup_handler(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error +
println!("Checking local data dir");
if !local_data_dir.exists() {
println!(" Creating local data dir");
fs::create_dir_all(&local_data_dir)?;
fs::create_dir_all(&local_data_dir).map_err(|_| VigiError::Config)?;
}
state.local_tabs_path = local_data_dir.join("tabs.jsonl");
@ -159,6 +120,8 @@ fn setup_handler(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error +
state.current_tab_index_path = local_data_dir.join("current_tab_index");
state.current_tab_index = read_or_create_number(&state.current_tab_index_path);
state.update_top_bar_input();
println!("---Setup done---");
Ok(())

View file

@ -1,3 +1,4 @@
use dalet::{Argument, Body, Tag};
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf};
@ -9,9 +10,11 @@ pub enum VigiError {
Parse,
StateLock,
StateUpdate,
Filesystem,
Config,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[derive(Serialize, Debug, Clone)]
pub struct VigiState {
pub tabs_id_counter_path: PathBuf,
pub current_tab_index_path: PathBuf,
@ -20,10 +23,25 @@ pub struct VigiState {
pub cache_dir: PathBuf,
// Persistent
pub tabs_id_counter: usize,
pub current_tab_index: usize,
pub tabs: Vec<Tab>,
pub favorites_tabs: Vec<Tab>,
// Temporary
pub top_bar_input: String,
pub current_data: Vec<Tag>,
}
#[derive(Serialize, Debug, Clone)]
pub struct VigiJsState {
pub current_tab_index: usize,
pub tabs: Vec<Tab>,
pub favorites_tabs: Vec<Tab>,
pub top_bar_input: String,
pub current_data: Vec<Tag>,
}
impl VigiState {
@ -39,16 +57,24 @@ impl VigiState {
current_tab_index: 0,
tabs: Vec::new(),
favorites_tabs: Vec::new(),
top_bar_input: "".to_string(),
current_data: Vec::new(),
}
}
pub fn update_current_tab_index(&mut self, new_index: usize) -> Result<(), VigiError> {
pub async fn select_tab(&mut self, new_index: usize) -> Result<(), VigiError> {
self.current_tab_index = new_index;
self.write_current_tab_index()?;
self.update_top_bar_input();
Ok(())
}
pub fn update_top_bar_input(&mut self) {
self.top_bar_input = self.tabs[self.current_tab_index].url.clone();
}
fn write_current_tab_index(&mut self) -> Result<(), VigiError> {
fs::write(
&self.current_tab_index_path,
@ -62,7 +88,61 @@ impl VigiState {
.map_err(|_| VigiError::StateUpdate)
}
pub fn update_tab(
async fn process_input(&mut self) -> Result<(), VigiError> {
// TODO: Implement mime type, language, protocol or search detection
// TODO: Implement text links parsing
println!("process_input {{\n \"{}\"", self.top_bar_input);
let result = match self.top_bar_input.as_str() {
"" => {
self.update_tab(TabType::HomePage, "Home".to_owned(), "".to_owned())?;
self.current_data = vec![Tag::new(
0,
Body::Text("Type something in the address bar".to_owned()),
Argument::Null,
)];
Ok(())
}
input => match reqwest::get(input).await {
Ok(res) => match res.text().await {
Ok(res) => {
let mut truncated = res.clone();
truncated.truncate(50);
self.update_tab(TabType::Text, truncated, input.to_owned())?;
self.current_data = vec![Tag::new(0, Body::Text(res), Argument::Null)];
Ok(())
}
Err(_) => Err(VigiError::Parse),
},
Err(_) => Err(VigiError::Network),
},
};
if result.is_ok() {
println!(" Ok\n}}");
} else {
println!(" Err\n}}");
}
result
}
pub async fn update_input(&mut self, input: String) -> Result<(), VigiError> {
self.top_bar_input = input;
self.process_input().await
}
pub async fn load_tab(&mut self) -> Result<(), VigiError> {
self.process_input().await
}
fn update_tab(
&mut self,
tab_type: TabType,
tab_title: String,
@ -84,7 +164,7 @@ impl VigiState {
self.tabs_id_counter += 1;
self.tabs.push(Tab::new(
TabType::HomePage,
"New tab".to_string(),
"Home".to_string(),
"".to_string(),
self.tabs_id_counter,
));
@ -95,6 +175,8 @@ impl VigiState {
self.current_tab_index = self.tabs.len() - 1;
self.write_current_tab_index()?;
self.update_top_bar_input();
Ok(())
}
@ -112,14 +194,25 @@ impl VigiState {
Ok(())
}
pub fn get_js_state(&self) -> VigiJsState {
VigiJsState {
current_tab_index: self.current_tab_index,
tabs: self.tabs.clone(),
favorites_tabs: self.favorites_tabs.clone(),
top_bar_input: self.top_bar_input.clone(),
current_data: self.current_data.clone(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Tab {
ty: TabType,
title: String,
url: String,
id: usize,
pub ty: TabType,
pub title: String,
pub url: String,
pub id: usize,
}
impl Tab {