setting home path now works

This commit is contained in:
Iaphetes 2025-03-08 19:50:09 +01:00
parent 75d172fc3f
commit 2ac3c9a45a
16 changed files with 764 additions and 71 deletions

66
src-tauri/src/config.rs Normal file
View file

@ -0,0 +1,66 @@
use serde::{Deserialize, Serialize};
use std::{
path::{Path, PathBuf},
sync::Mutex,
};
use tauri::Manager;
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct Config {
pub core_cfg: CoreCFG,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CoreCFG {
pub home_path: Option<PathBuf>,
pub current_file: Option<PathBuf>,
}
impl Default for CoreCFG {
fn default() -> Self {
CoreCFG {
home_path: None,
current_file: None,
}
}
}
pub fn load_config(path: Option<PathBuf>) -> Config {
match path {
Some(p) => confy::load_path(p).expect("Configuration could not be loaded"),
None => confy::load("apographe", Some("config"))
.ok()
.unwrap_or_else(|| {
let config: Config = Config::default();
let _ = confy::store("aphorme", Some("config"), Config::default());
config
}),
}
}
#[tauri::command]
pub fn get_basepath(app_handle: tauri::AppHandle) -> Option<String> {
let config = app_handle.state::<Mutex<Config>>();
// Lock the mutex to get mutable access:
let config = config.lock().unwrap();
let base_path = config.core_cfg.home_path.clone();
return base_path.map(|p| p.to_string_lossy().into_owned());
}
#[tauri::command]
pub fn set_basepath(app_handle: tauri::AppHandle, path: String) -> bool {
if let Ok(resolved_path) = shellexpand::full(&path)
{
let basepath = Path::new(&resolved_path.to_string()).to_path_buf();
if !basepath.is_dir(){
println!("{:?}", basepath);
return false;
}
let config = app_handle.state::<Mutex<Config>>();
// Lock the mutex to get mutable access:
let mut config = config.lock().unwrap();
config.core_cfg.home_path = Some(basepath);
return true;
}
else {return false};
}

View file

@ -6,14 +6,13 @@ use std::{
use sqlx::{migrate::MigrateDatabase, Sqlite, SqlitePool};
use tauri::{ipc::RuntimeCapability, App, AssetResolver, Manager, Url};
async fn populate_file_db(db: &SqlitePool) {}
#[tauri::command]
pub async fn initialize_database(
app_handle: tauri::AppHandle,
basepath: String,
pathtemplate: String,
) {
println!("hello");
let db_path = Path::new("Documents")
.join(Path::new("Knowledgebase"))
.join("db.sqlite");
@ -31,27 +30,24 @@ pub async fn initialize_database(
.await
.unwrap_or(false)
{
println!("Creating database {}", unicode_db_path);
match Sqlite::create_database(&unicode_db_path).await {
Ok(_) => println!("Create db success"),
Err(error) => panic!("error: {}", error),
}
} else {
println!("Database already exists");
}
let db = SqlitePool::connect(unicode_db_path).await.unwrap();
let result = sqlx::query(
"CREATE TABLE IF NOT EXISTS files
(
id INTEGER PRIMARY KEY NOT NULL,
relative_path TEXT NOT NULL
relative_path TEXT NOT NULL,
file_name TEXT NOT NULL
);",
)
.execute(&db)
.await
.unwrap();
println!("Create file table result: {:?}", result);
let result = sqlx::query(
"CREATE TABLE IF NOT EXISTS file_diffs
(
@ -65,7 +61,6 @@ pub async fn initialize_database(
.execute(&db)
.await
.unwrap();
println!("Create diff table result: {:?}", result);
}
#[tauri::command]

View file

@ -0,0 +1,13 @@
// #[tauri::command]
// pub fn open_file(app_handle: tauri::AppHandle, relative_path: String) -> Option<String> {
// let mut file = File::open("foo.txt")?;
// let mut contents = String::new();
// file.read_to_string(&mut contents)?;
// assert_eq!(contents, "Hello, world!");
// Ok(())
// }
use std::{path::Path, sync::Mutex};
use crate::Config;
use tauri::Manager;

View file

@ -1,19 +1,24 @@
mod config;
mod database;
mod file_access;
mod file_tree;
mod markdown_parser;
mod search;
use std::env;
use tauri::Manager;
use tauri_plugin_fs::FsExt;
use config::{get_basepath, load_config, set_basepath, Config};
use database::initialize_database;
use file_tree::dir_tree_html;
use markdown_parser::parse_markdown;
use search::search_files;
use std::env;
use std::sync::Mutex;
use tauri::Manager;
use tauri_plugin_fs::FsExt;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_log::Builder::new().build())
.plugin(tauri_plugin_shell::init())
@ -23,13 +28,18 @@ pub fn run() {
scope.allow_directory(tauri::path::BaseDirectory::Home.variable(), true);
app.set_theme(Some(tauri::Theme::Dark));
let config = load_config(None);
app.manage(Mutex::new(config)); //RWLock
Ok(())
})
.invoke_handler(tauri::generate_handler![
initialize_database,
dir_tree_html,
parse_markdown,
search_files
search_files,
get_basepath,
set_basepath,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");

View file

@ -3,13 +3,11 @@ use std::{
env,
path::{absolute, Path},
};
use crate::get_basepath;
#[tauri::command]
pub fn parse_markdown(document: &str, pathtemplate: &str, basepath: &str) -> String {
pub fn parse_markdown(app_handle: tauri::AppHandle, document: &str, pathtemplate: &str) -> String {
let rendered_markdown: String;
let path = "/foo/bar.txt";
println!("{:?}", shellexpand::full(path));
let arena = Arena::new();
// Parse the document into a root `AstNode`
let mut options = Options::default();
options.render.unsafe_ = true;
@ -18,31 +16,36 @@ pub fn parse_markdown(document: &str, pathtemplate: &str, basepath: &str) -> Str
// Iterate over all the descendants of root.
if let Ok(resolved_basepath) = shellexpand::full(&basepath) {
println!(
"{:?}",
env::set_current_dir(&resolved_basepath.into_owned())
);
}
for node in root.descendants() {
if let NodeValue::Image(ref mut image_node) = node.data.borrow_mut().value {
let image_path = Path::new(&image_node.url).to_path_buf();
let absolute_image_path_res = absolute(image_node.url.clone());
let absolute_image_path = absolute_image_path_res.unwrap_or(image_path.clone());
let absolute_image_path_str = absolute_image_path.as_path().to_string_lossy();
if let Ok(resolved_path) = shellexpand::full(&absolute_image_path_str) {
image_node.url = pathtemplate.replace("FILEPATH", &resolved_path);
}
println!("{}", image_node.url);
if let Some(basepath) = get_basepath(app_handle) {
if let Ok(resolved_basepath) = shellexpand::full(&basepath) {
println!(
"{:?}",
env::set_current_dir(&resolved_basepath.into_owned())
);
}
for node in root.descendants() {
if let NodeValue::Image(ref mut image_node) = node.data.borrow_mut().value {
let image_path = Path::new(&image_node.url).to_path_buf();
let absolute_image_path_res = absolute(image_node.url.clone());
let absolute_image_path = absolute_image_path_res.unwrap_or(image_path.clone());
let absolute_image_path_str = absolute_image_path.as_path().to_string_lossy();
if let Ok(resolved_path) = shellexpand::full(&absolute_image_path_str) {
image_node.url = pathtemplate.replace("FILEPATH", &resolved_path);
}
println!("{}", image_node.url);
}
}
let mut html = vec![];
format_html(root, &options, &mut html).unwrap();
// println!("{}", String::from_utf8(html.clone()).unwrap());
rendered_markdown = String::from_utf8(html).unwrap();
return rendered_markdown.to_owned();
}
let mut html = vec![];
format_html(root, &options, &mut html).unwrap();
// println!("{}", String::from_utf8(html.clone()).unwrap());
rendered_markdown = String::from_utf8(html).unwrap();
return rendered_markdown.to_owned();
return String::new()
// String::from_str("lololo").unwrap()
}