From db3ed3cf8e258bdb52384f49abe30a75c1124a70 Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Tue, 28 Nov 2023 18:37:28 +0100 Subject: [PATCH 1/7] a few low hanging error fruits --- package.json | 5 ++- src-tauri/src/loose_idasen.rs | 72 ++++++++++++++++++++++++++--------- src-tauri/src/main.rs | 5 ++- 3 files changed, 60 insertions(+), 22 deletions(-) diff --git a/package.json b/package.json index 71bb7d9..1ec3bdb 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "lint": "eslint src", "lint:fix": "eslint src --fix", "tauri:dev": "tauri dev", - "tauri:build": "tauri build" + "tauri:build": "tauri build", + "tauri:test": "cd src-tauri && cargo test && cd .." }, "dependencies": { "@radix-ui/react-checkbox": "^1.0.3", @@ -47,4 +48,4 @@ "typescript": "^4.6.4", "vite": "^4.0.0" } -} +} \ No newline at end of file diff --git a/src-tauri/src/loose_idasen.rs b/src-tauri/src/loose_idasen.rs index a12d523..8761359 100644 --- a/src-tauri/src/loose_idasen.rs +++ b/src-tauri/src/loose_idasen.rs @@ -86,8 +86,8 @@ pub async fn setup_bt_desk_device( ) -> Result, BtError> { let mac_addr = BDAddr::default(); println!("got the mac! desk: {:?}", &device); - device.connect().await.unwrap(); - device.discover_services().await.unwrap(); + device.connect().await?; + device.discover_services().await?; let control_characteristic = get_control_characteristic(device).await; let position_characteristic = get_position_characteristic(device).await; @@ -122,26 +122,26 @@ async fn get_list_of_desks_once( } } -pub async fn get_list_of_desks(loc_name: &Option) -> Vec { - let mut desks = get_list_of_desks_once(loc_name).await; - let mut success = false; +pub async fn get_list_of_desks( + loc_name: &Option, +) -> Result, BtError> { + // TODO: Refactor this so it's not having that ugly while loop let mut tries = 0; // try 3 times before erroring - while tries < 2 { + + let mut desks; + for loop_iter in 0..3 { desks = get_list_of_desks_once(loc_name).await; - let ok = desks.is_ok(); - if ok { - success = true; - break; + if desks.is_ok() { + return desks; + // break; } tries += 1; } - if success == false { - panic!("Error while getting a list of desks"); - } - desks.unwrap() + + Err(BtError::CannotFindDevice) } // Getting characteristics every time is wasteful @@ -317,9 +317,17 @@ pub struct PotentialDesk { // https://github.com/tauri-apps/tauri/issues/2533 - this has to be a Result /// Desk we're connecting to for UI info #[tauri::command] -pub async fn get_desk_to_connect() -> Result, ()> { +pub async fn get_desk_to_connect() -> Result, String> { let config = config_utils::get_or_create_config(); let desk_list = get_list_of_desks(&config.local_name).await; + let desk_list = match desk_list { + Ok(desks) => desks, + Err(_) => { + // TODO: probably should not panic here + panic!("PANIC!"); + } + }; + let desk_list_view = desk_list .iter() .map(|x| match config.local_name { @@ -339,8 +347,8 @@ pub async fn get_desk_to_connect() -> Result, ()> { Ok(desk_list_view) } -pub async fn connect_to_desk_by_name_internal(name: String) -> Result { - let desk_to_connect = get_list_of_desks(&Some(name.clone())).await; +pub async fn connect_to_desk_by_name_internal(name: String) -> Result { + let desk_to_connect = get_list_of_desks(&Some(name.clone())).await?; let desk_to_connect = desk_to_connect .into_iter() .next() @@ -350,7 +358,35 @@ pub async fn connect_to_desk_by_name_internal(name: String) -> Result Val, + Err(asd) => { + println!("{:?}", asd); + panic!("asd"); + } + }; + // if bt.is_err() { + // let bt_err = bt.expect_err("asd"); + // return Err(bt_err); + // } Ok(desk_to_connect) } + +#[cfg(test)] +mod tests { + #[tokio::test] + async fn it_works() { + let result = + crate::loose_idasen::connect_to_desk_by_name_internal("nonexistant_desk".to_string()) + .await; + let is_err = result.is_err(); + + // assert_eq!(result, 4); + } +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index b97b596..8b2856b 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -71,7 +71,7 @@ fn create_new_elem( /// Provided a name, will connect to a desk with this name - after this step, desk actually becomes usable #[tauri::command] async fn connect_to_desk_by_name(name: String) -> Result<(), ()> { - loose_idasen::connect_to_desk_by_name_internal(name).await?; + _ = loose_idasen::connect_to_desk_by_name_internal(name).await; Ok(()) } @@ -88,7 +88,8 @@ fn main() { if let Some(local_name) = local_name.clone() { let cached_desk = loose_idasen::connect_to_desk_by_name_internal(local_name.clone()).await; - *initiated_desk.0.lock().unwrap() = Some(cached_desk.unwrap()); + let cached_desk = cached_desk.expect("Cannot connect to desk"); + *initiated_desk.0.lock().unwrap() = Some(cached_desk); } }); From 43d0ed16240a6fd472504fae43a54242e14efe7f Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Tue, 28 Nov 2023 20:02:34 +0100 Subject: [PATCH 2/7] add dummy error page --- src-tauri/src/loose_idasen.rs | 4 +- src-tauri/src/main.rs | 94 ++++++++++++++++++++++++----------- src-tauri/src/tray_utils.rs | 78 +++++++++++++++-------------- src/App.tsx | 5 ++ 4 files changed, 115 insertions(+), 66 deletions(-) diff --git a/src-tauri/src/loose_idasen.rs b/src-tauri/src/loose_idasen.rs index 8761359..d53c515 100644 --- a/src-tauri/src/loose_idasen.rs +++ b/src-tauri/src/loose_idasen.rs @@ -348,7 +348,9 @@ pub async fn get_desk_to_connect() -> Result, String> { } pub async fn connect_to_desk_by_name_internal(name: String) -> Result { + println!("meet me startway"); let desk_to_connect = get_list_of_desks(&Some(name.clone())).await?; + println!("meet me halfway"); let desk_to_connect = desk_to_connect .into_iter() .next() @@ -364,7 +366,7 @@ pub async fn connect_to_desk_by_name_internal(name: String) -> Result Val, + Ok(val) => val, Err(asd) => { println!("{:?}", asd); panic!("asd"); diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 8b2856b..b55ad32 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -10,6 +10,8 @@ use btleplug::platform::Peripheral as PlatformPeripheral; use tauri::GlobalShortcutManager; use tauri::{async_runtime::block_on, Manager, SystemTray, SystemTrayEvent}; +use crate::tray_utils::handle_error_window_show; + mod config_utils; mod loose_idasen; mod tray_utils; @@ -86,10 +88,14 @@ fn main() { let local_name = &config.local_name; block_on(async { if let Some(local_name) = local_name.clone() { - let cached_desk = - loose_idasen::connect_to_desk_by_name_internal(local_name.clone()).await; - let cached_desk = cached_desk.expect("Cannot connect to desk"); - *initiated_desk.0.lock().unwrap() = Some(cached_desk); + let cached_desk = loose_idasen::connect_to_desk_by_name_internal(local_name.clone()) + .await + .ok(); + + *initiated_desk + .0 + .lock() + .expect("Failed to deref mutex during instantiation") = cached_desk; } }); @@ -120,11 +126,6 @@ fn main() { let window = app.get_window("main").unwrap(); if let Some(_) = loc_name { - // If the user is returning(has a config) immidiately close the window, not to eat resources - // And then proceed to try to connect to the provided desk name. - window - .close() - .expect("Error while closing the initial window"); let desk_state = app.state::(); // We expect the desk to already exist at this point, since if loc_name, the first thing we do in the app is connect @@ -132,28 +133,63 @@ fn main() { .0 .lock() .expect("Error while unwrapping shared desk"); - let desk = desk - .as_ref() - .expect("Desk should have been defined at this point"); - - // Register all shortcuts - let mut shortcut_manager = app.global_shortcut_manager(); - let all_positions = &config.saved_positions; - let cloned_pos = all_positions.clone(); - for pos in cloned_pos.into_iter() { - // Each iteration needs it's own clone; we do not want to consume the app state - let cloned_desk = desk.clone(); - if let Some(shortcut_key) = &pos.shortcut { - if shortcut_key != "" { - _ = shortcut_manager.register(shortcut_key.as_str(), move || { - block_on(async { - loose_idasen::move_to_target(&cloned_desk, pos.value) - .await - .unwrap(); - }); - }); + let desk = desk.as_ref(); + match desk { + /* + If the user is returning(has a config) immidiately close the window, not to eat resources + And then proceed to try to create the menu. + */ + Some(desk) => { + window + .close() + .expect("Error while closing the initial window"); + // Register all shortcuts + let mut shortcut_manager = app.global_shortcut_manager(); + let all_positions = &config.saved_positions; + let cloned_pos = all_positions.clone(); + for pos in cloned_pos.into_iter() { + // Each iteration needs it's own clone; we do not want to consume the app state + let cloned_desk = desk.clone(); + if let Some(shortcut_key) = &pos.shortcut { + if shortcut_key != "" { + _ = shortcut_manager.register( + shortcut_key.as_str(), + move || { + block_on(async { + loose_idasen::move_to_target( + &cloned_desk, + pos.value, + ) + .await + .unwrap(); + }); + }, + ); + } + } } } + None => { + /* + If the desk name is defined, but we've got no desk instance at this point, + it means that we've failed to connect to the desk previously + */ + + // Open error window with the error + // window.sh + // handle_error_window_show(&app.app_handle()); + + println!("setting the path!"); + + window + .show() + .expect("Error while trying to show the window"); + _ = window.eval( + r#" + history.replaceState({}, '','/error'); + "#, + ); + } } } else { window diff --git a/src-tauri/src/tray_utils.rs b/src-tauri/src/tray_utils.rs index e9d8f6c..3743bbd 100644 --- a/src-tauri/src/tray_utils.rs +++ b/src-tauri/src/tray_utils.rs @@ -4,20 +4,34 @@ pub fn handle_exit_menu_click() { std::process::exit(0); } +pub fn handle_error_window_show(app: &AppHandle) { + match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) + .always_on_top(true) + .initialization_script( + r#" + history.replaceState({}, '','/error'); + "#, + ) + .title("Trayasen - Woops!") + .build() + { + Ok(_) => {} + Err(err) => { + println!("Error while trying to open error window. Err: {:?}", err); + } + } +} + pub fn handle_about_menu_click(app: &AppHandle) { - match tauri::WindowBuilder::new( - app, - "main", - tauri::WindowUrl::App("index.html".into()), - ) - .always_on_top(true) - .initialization_script( - r#" + match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) + .always_on_top(true) + .initialization_script( + r#" history.replaceState({}, '','/about'); "#, - ) - .title("Trayasen - About/Options") - .build() + ) + .title("Trayasen - About/Options") + .build() { Ok(_) => {} Err(_) => { @@ -26,20 +40,16 @@ pub fn handle_about_menu_click(app: &AppHandle) { } } -pub fn handle_new_position_menu_click(app:&AppHandle) { - match tauri::WindowBuilder::new( - app, - "main", - tauri::WindowUrl::App("index.html".into()), - ) - .always_on_top(true) - .initialization_script( - r#" +pub fn handle_new_position_menu_click(app: &AppHandle) { + match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) + .always_on_top(true) + .initialization_script( + r#" history.replaceState({}, '','/new-position'); "#, - ) - .title("Trayasen - Add position") - .build() + ) + .title("Trayasen - Add position") + .build() { Ok(_) => {} Err(_) => { @@ -48,24 +58,20 @@ pub fn handle_new_position_menu_click(app:&AppHandle) { } } -pub fn handle_manage_positions_menu_click(app:&AppHandle) { - match tauri::WindowBuilder::new( - app, - "main", - tauri::WindowUrl::App("index.html".into()), - ) - .always_on_top(true) - .initialization_script( - r#" +pub fn handle_manage_positions_menu_click(app: &AppHandle) { + match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) + .always_on_top(true) + .initialization_script( + r#" history.replaceState({}, '','/manage-positions'); "#, - ) - .title("Trayasen - Manage positions") - .build() + ) + .title("Trayasen - Manage positions") + .build() { Ok(_) => {} Err(_) => { println!("Error while trying to open manage positions window"); } } -} \ No newline at end of file +} diff --git a/src/App.tsx b/src/App.tsx index 2d78c91..6e73191 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,7 +4,12 @@ import NewPositionPage from "./NewPositionPage"; import IntroPage from "./IntroPage"; import ManagePositionsPage from "./ManagePositionsPage"; +const ErrorPage = () => { + return
error!
; +}; + const routeConfig: RouteConfig = [ + { path: "/error", Component: ErrorPage }, { path: "/about", Component: AboutPage }, { path: "/new-position", Component: NewPositionPage }, { path: "/manage-positions", Component: ManagePositionsPage }, From c4918d4f9c4dcd4e44b6088cf94ef629db93b85e Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Sat, 9 Dec 2023 20:41:11 +0100 Subject: [PATCH 3/7] fix: couple of nits --- src-tauri/src/loose_idasen.rs | 24 +++++++----------------- src-tauri/src/main.rs | 20 ++++---------------- src-tauri/src/tray_utils.rs | 34 +++++++++++++++++----------------- 3 files changed, 28 insertions(+), 50 deletions(-) diff --git a/src-tauri/src/loose_idasen.rs b/src-tauri/src/loose_idasen.rs index d53c515..563c153 100644 --- a/src-tauri/src/loose_idasen.rs +++ b/src-tauri/src/loose_idasen.rs @@ -125,20 +125,15 @@ async fn get_list_of_desks_once( pub async fn get_list_of_desks( loc_name: &Option, ) -> Result, BtError> { - // TODO: Refactor this so it's not having that ugly while loop - let mut tries = 0; // try 3 times before erroring - let mut desks; - for loop_iter in 0..3 { + for _loop_iter in 0..3 { desks = get_list_of_desks_once(loc_name).await; if desks.is_ok() { return desks; // break; } - - tries += 1; } Err(BtError::CannotFindDevice) @@ -348,9 +343,7 @@ pub async fn get_desk_to_connect() -> Result, String> { } pub async fn connect_to_desk_by_name_internal(name: String) -> Result { - println!("meet me startway"); let desk_to_connect = get_list_of_desks(&Some(name.clone())).await?; - println!("meet me halfway"); let desk_to_connect = desk_to_connect .into_iter() .next() @@ -365,30 +358,27 @@ pub async fn connect_to_desk_by_name_internal(name: String) -> Result val, Err(asd) => { println!("{:?}", asd); panic!("asd"); } }; - // if bt.is_err() { - // let bt_err = bt.expect_err("asd"); - // return Err(bt_err); - // } Ok(desk_to_connect) } +// TODO: Figure out bluetooth mocking to improve testing; without mocks tests are impossible #[cfg(test)] -mod tests { +mod connecting_suite { #[tokio::test] - async fn it_works() { + async fn should_fail_for_not_found_desk() { let result = crate::loose_idasen::connect_to_desk_by_name_internal("nonexistant_desk".to_string()) .await; - let is_err = result.is_err(); + let err = result.unwrap_err(); - // assert_eq!(result, 4); + assert_eq!(err.to_string(), "Cannot find the device."); } } diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index b55ad32..5063ad0 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -10,8 +10,6 @@ use btleplug::platform::Peripheral as PlatformPeripheral; use tauri::GlobalShortcutManager; use tauri::{async_runtime::block_on, Manager, SystemTray, SystemTrayEvent}; -use crate::tray_utils::handle_error_window_show; - mod config_utils; mod loose_idasen; mod tray_utils; @@ -170,17 +168,9 @@ fn main() { } } None => { - /* - If the desk name is defined, but we've got no desk instance at this point, - it means that we've failed to connect to the desk previously - */ - // Open error window with the error - // window.sh - // handle_error_window_show(&app.app_handle()); - - println!("setting the path!"); - + println!("opening error window!"); + _ = window.set_title("Trayasen - Woops!"); window .show() .expect("Error while trying to show the window"); @@ -230,7 +220,6 @@ fn main() { block_on(async { let desk = app.state::(); - let desk = desk; let desk = desk.0.lock(); let desk = desk.expect("Error while unwrapping shared desk"); let desk = desk @@ -250,13 +239,12 @@ fn main() { .run(move |app_handle, event| match event { tauri::RunEvent::Ready => {} /* - Exit requested, might mean that a new position has been added. - This is troublesome; since all the positions are actually system tray elements, we need to re-instantiate it + Exit requested, might mean that a new position has been added(or that just a window has been closed). + This is troublesome; since all the positions are actually system tray elements, we need to re-instantiate the entire tray So, when we detected an exit requested, just to be safe, refresh the system tray. TODO: We should probably have a way of checking for new elements, to remove redundant system tray refreshes */ tauri::RunEvent::ExitRequested { api, .. } => { - // Exit requested might mean that a new element has been added. println!("Exit requested"); let config = config_utils::get_config(); let main_menu = config_utils::create_main_tray_menu(&config); diff --git a/src-tauri/src/tray_utils.rs b/src-tauri/src/tray_utils.rs index 3743bbd..35fd957 100644 --- a/src-tauri/src/tray_utils.rs +++ b/src-tauri/src/tray_utils.rs @@ -4,23 +4,23 @@ pub fn handle_exit_menu_click() { std::process::exit(0); } -pub fn handle_error_window_show(app: &AppHandle) { - match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) - .always_on_top(true) - .initialization_script( - r#" - history.replaceState({}, '','/error'); - "#, - ) - .title("Trayasen - Woops!") - .build() - { - Ok(_) => {} - Err(err) => { - println!("Error while trying to open error window. Err: {:?}", err); - } - } -} +// pub fn handle_error_window_show(app: &AppHandle) { +// match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) +// .always_on_top(true) +// .initialization_script( +// r#" +// history.replaceState({}, '','/error'); +// "#, +// ) +// .title("Trayasen - Woops!") +// .build() +// { +// Ok(_) => {} +// Err(err) => { +// println!("Error while trying to open error window. Err: {:?}", err); +// } +// } +// } pub fn handle_about_menu_click(app: &AppHandle) { match tauri::WindowBuilder::new(app, "main", tauri::WindowUrl::App("index.html".into())) From 08b72bf083d074904947bd741eba2e1225668855 Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Sat, 9 Dec 2023 20:51:23 +0100 Subject: [PATCH 4/7] fix: autostart api --- package.json | 4 ++-- src-tauri/Cargo.lock | 8 ++++---- src-tauri/Cargo.toml | 2 +- yarn.lock | 11 +++++++++++ 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 1ec3bdb..b2cf894 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "react-dom": "^18.2.0", "tailwind-merge": "^1.12.0", "tailwindcss-animate": "^1.0.5", - "tauri-plugin-autostart-api": "https://github.com/tauri-apps/tauri-plugin-autostart", + "tauri-plugin-autostart-api": "https://github.com/tauri-apps/tauri-plugin-autostart#v1", "use-simple-async": "^1.4.2" }, "devDependencies": { @@ -48,4 +48,4 @@ "typescript": "^4.6.4", "vite": "^4.0.0" } -} \ No newline at end of file +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 92c4309..627a079 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -232,9 +232,9 @@ checksum = "1181e1e0d1fce796a03db1ae795d67167da795f9cf4a39c37589e85ef57f26d3" [[package]] name = "auto-launch" -version = "0.4.0" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5904a4d734f0235edf29aab320a14899f3e090446e594ff96508a6215f76f89c" +checksum = "1f012b8cc0c850f34117ec8252a44418f2e34a2cf501de89e29b241ae5f79471" dependencies = [ "dirs", "thiserror", @@ -3757,8 +3757,8 @@ dependencies = [ [[package]] name = "tauri-plugin-autostart" -version = "0.1.0" -source = "git+https://github.com/tauri-apps/plugins-workspace?branch=dev#265acf745435dabe78321ff7cf1e0af92df566e2" +version = "0.0.0" +source = "git+https://github.com/tauri-apps/plugins-workspace?branch=v1#af2892f6a1271907c0efc67f0b7c09799bb64dd4" dependencies = [ "auto-launch", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 0cd25c5..23692b9 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -22,7 +22,7 @@ btleplug = "0.11.0" tokio = { version = "1.24.1", features = ["full"] } thiserror = "1.0.30" uuid = "1.3.0" -tauri-plugin-autostart = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "dev" } +tauri-plugin-autostart = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" } [features] # by default Tauri runs in production mode diff --git a/yarn.lock b/yarn.lock index 0e9a7b6..61baef0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -831,6 +831,11 @@ dependencies: dequal "^2.0.2" +"@tauri-apps/api@1.5.1": + version "1.5.1" + resolved "https://registry.yarnpkg.com/@tauri-apps/api/-/api-1.5.1.tgz#9074476c4323f71351db624e9711c99277cdfb99" + integrity sha512-6unsZDOdlXTmauU3NhWhn+Cx0rODV+rvNvTdvolE5Kls5ybA6cqndQENDt1+FS0tF7ozCP66jwWoH6a5h90BrA== + "@tauri-apps/api@^1.2.0": version "1.2.0" resolved "https://registry.npmjs.org/@tauri-apps/api/-/api-1.2.0.tgz" @@ -3060,6 +3065,12 @@ tailwindcss@^3.2.4: dependencies: "@tauri-apps/api" "^1.2.0" +"tauri-plugin-autostart-api@https://github.com/tauri-apps/tauri-plugin-autostart#v1": + version "0.0.0" + resolved "https://github.com/tauri-apps/tauri-plugin-autostart#7404c3ccd2e45c642e3b876500ab79d88af85e4d" + dependencies: + "@tauri-apps/api" "1.5.1" + text-table@^0.2.0: version "0.2.0" resolved "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz" From 04b469f9845839e110877b5137b7d63a0101a6e7 Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Sat, 9 Dec 2023 23:07:31 +0100 Subject: [PATCH 5/7] feat: error edge cases --- index.html | 2 +- src-tauri/src/loose_idasen.rs | 48 ++++++------- src-tauri/src/main.rs | 126 +++++++++++++++++++--------------- src/App.tsx | 22 +++++- 4 files changed, 114 insertions(+), 84 deletions(-) diff --git a/index.html b/index.html index 194012b..1af6bc0 100644 --- a/index.html +++ b/index.html @@ -8,7 +8,7 @@ -
+
Loading...
diff --git a/src-tauri/src/loose_idasen.rs b/src-tauri/src/loose_idasen.rs index 563c153..eb11491 100644 --- a/src-tauri/src/loose_idasen.rs +++ b/src-tauri/src/loose_idasen.rs @@ -315,31 +315,31 @@ pub struct PotentialDesk { pub async fn get_desk_to_connect() -> Result, String> { let config = config_utils::get_or_create_config(); let desk_list = get_list_of_desks(&config.local_name).await; - let desk_list = match desk_list { - Ok(desks) => desks, - Err(_) => { - // TODO: probably should not panic here - panic!("PANIC!"); - } - }; - let desk_list_view = desk_list - .iter() - .map(|x| match config.local_name { - Some(_) => PotentialDesk { - name: x.name.to_string(), - status: SavedDeskStates::Saved.as_str().to_string(), - }, - None => PotentialDesk { - name: x.name.to_string(), - status: SavedDeskStates::New.as_str().to_string(), - }, - }) - .collect::>(); - - println!("Found desk list: {:?}", &desk_list_view); - - Ok(desk_list_view) + match desk_list { + Ok(desk_list) => { + let desk_list_view = desk_list + .iter() + .map(|x| match config.local_name { + Some(_) => PotentialDesk { + name: x.name.to_string(), + status: SavedDeskStates::Saved.as_str().to_string(), + }, + None => PotentialDesk { + name: x.name.to_string(), + status: SavedDeskStates::New.as_str().to_string(), + }, + }) + .collect::>(); + + println!("Found desk list: {:?}", &desk_list_view); + + return Ok(desk_list_view); + } + Err(e) => { + return Err(e.to_string()); + } + } } pub async fn connect_to_desk_by_name_internal(name: String) -> Result { diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 5063ad0..d3541cf 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -123,69 +123,81 @@ fn main() { let loc_name = &config.local_name; let window = app.get_window("main").unwrap(); - if let Some(_) = loc_name { - let desk_state = app.state::(); + match loc_name { + Some(actual_loc_name) => { + let desk_state = app.state::(); - // We expect the desk to already exist at this point, since if loc_name, the first thing we do in the app is connect - let desk = desk_state - .0 - .lock() - .expect("Error while unwrapping shared desk"); - let desk = desk.as_ref(); - match desk { - /* - If the user is returning(has a config) immidiately close the window, not to eat resources - And then proceed to try to create the menu. - */ - Some(desk) => { - window - .close() - .expect("Error while closing the initial window"); - // Register all shortcuts - let mut shortcut_manager = app.global_shortcut_manager(); - let all_positions = &config.saved_positions; - let cloned_pos = all_positions.clone(); - for pos in cloned_pos.into_iter() { - // Each iteration needs it's own clone; we do not want to consume the app state - let cloned_desk = desk.clone(); - if let Some(shortcut_key) = &pos.shortcut { - if shortcut_key != "" { - _ = shortcut_manager.register( - shortcut_key.as_str(), - move || { - block_on(async { - loose_idasen::move_to_target( - &cloned_desk, - pos.value, - ) - .await - .unwrap(); - }); - }, - ); + // We expect the desk to already exist at this point, since if loc_name exists, the first thing we do in the app is connect + let desk = desk_state + .0 + .lock() + .expect("Error while unwrapping shared desk"); + let desk = desk.as_ref(); + match desk { + /* + If the user is returning(has a config) immidiately close the window, not to eat resources + And then proceed to try to create the menu. + */ + Some(desk) => { + window + .close() + .expect("Error while closing the initial window"); + // Register all shortcuts + let mut shortcut_manager = app.global_shortcut_manager(); + let all_positions = &config.saved_positions; + let cloned_pos = all_positions.clone(); + for pos in cloned_pos.into_iter() { + // Each iteration needs it's own clone; we do not want to consume the app state + let cloned_desk = desk.clone(); + if let Some(shortcut_key) = &pos.shortcut { + if shortcut_key != "" { + _ = shortcut_manager.register( + shortcut_key.as_str(), + move || { + block_on(async { + loose_idasen::move_to_target( + &cloned_desk, + pos.value, + ) + .await + .unwrap(); + }); + }, + ); + } } } } - } - None => { - // Open error window with the error - println!("opening error window!"); - _ = window.set_title("Trayasen - Woops!"); - window - .show() - .expect("Error while trying to show the window"); - _ = window.eval( - r#" - history.replaceState({}, '','/error'); - "#, - ); + None => { + // Open error window with the error + println!("opening error window!"); + _ = window.set_title("Trayasen - Woops!"); + window + .show() + .expect("Error while trying to show the window"); + + // TODO: Passing state as a string literal to window via `eval` is a terrible way to handle state. + // This should be passed/handled via tauri state. + + _ = window.eval( + format!(r#" + window.stateWorkaround = {{ + title: "The app was not able to connect to your saved desk with name: `{}`.", + description: "Either try reconnecting with that desk from your system and relaunch Trayasen, or click the button below to run the setup again." + }} + history.replaceState({{}}, '','/error'); + "#, actual_loc_name).as_str(), + ); + } } } - } else { - window - .show() - .expect("Error while trying to show the window"); - }; + None => { + // If loc_name doesn't exist, that means there's no saved desk - meaning we need to show the initial setup window + window + .show() + .expect("Error while trying to show the window"); + } + } Ok(()) }) diff --git a/src/App.tsx b/src/App.tsx index 6e73191..c0a812a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,11 +1,29 @@ -import { RouteConfig, createBrowserRouter } from "found"; +import { Link, RouteConfig, createBrowserRouter } from "found"; import AboutPage from "./AboutPage"; import NewPositionPage from "./NewPositionPage"; import IntroPage from "./IntroPage"; import ManagePositionsPage from "./ManagePositionsPage"; +import { Button } from "./generic/button"; const ErrorPage = () => { - return
error!
; + return ( +
+
{(window as any)?.stateWorkaround?.title}
+
{(window as any)?.stateWorkaround?.description}
+
+ +
+
+ ); }; const routeConfig: RouteConfig = [ From 936a18da377da02d8fcca06f8431a78a9c9f06b0 Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Sun, 10 Dec 2023 00:43:19 +0100 Subject: [PATCH 6/7] stupid but working solutions --- src-tauri/src/config_utils.rs | 21 ++++++++++++++- src-tauri/src/loose_idasen.rs | 4 ++- src-tauri/src/main.rs | 51 ++++++++++++++++++++++------------- src/App.tsx | 13 ++++++--- src/rustUtils.ts | 4 +++ 5 files changed, 69 insertions(+), 24 deletions(-) diff --git a/src-tauri/src/config_utils.rs b/src-tauri/src/config_utils.rs index 7de4aeb..6a220d4 100644 --- a/src-tauri/src/config_utils.rs +++ b/src-tauri/src/config_utils.rs @@ -145,7 +145,7 @@ pub fn update_config(updated_config: &ConfigData) { let stringified_new_config = to_string::(&updated_config).unwrap(); fs::write(config_path, stringified_new_config) - .expect("Saving a config after updatign a config"); + .expect("Saving a config after updating a config"); } #[tauri::command] @@ -155,6 +155,25 @@ pub fn remove_config() { let _ = remove_file(config_path); } +#[tauri::command] +pub fn reset_desk() { + let config_path = get_config_path().trim_end().to_string(); + + let config = + read_to_string(&config_path).expect("err while reading config while resetting desk"); + // Config exists + let config = from_str::(config.as_str()).expect("Error while parsing config file"); + + let updated_config = ConfigData { + local_name: None, + saved_positions: config.saved_positions, + }; + + let stringified_new_config = to_string::(&updated_config).unwrap(); + fs::write(config_path, stringified_new_config) + .expect("Saving a config after updating a config"); +} + pub struct MenuConfigItem { pub position_elem: CustomMenuItem, pub name: String, diff --git a/src-tauri/src/loose_idasen.rs b/src-tauri/src/loose_idasen.rs index eb11491..0a80927 100644 --- a/src-tauri/src/loose_idasen.rs +++ b/src-tauri/src/loose_idasen.rs @@ -14,7 +14,7 @@ use btleplug::{ use serde::Serialize; use uuid::Uuid; -use crate::config_utils; +use crate::{config_utils, TauriSharedDesk}; /* This file contains loose utils to interact with a desk bluetooth peripheral as if it's a desk. @@ -342,6 +342,8 @@ pub async fn get_desk_to_connect() -> Result, String> { } } +// TODO: UPDATE THE DESK INSTANCE MUTEX EVERY TIME YOU USE THIS FUNCTION HERE OTHERWISE IT WILL BREAK +// AS WE WILL HAVE DESYNC OF ACTUAL DESK AND CONNECTED ONE pub async fn connect_to_desk_by_name_internal(name: String) -> Result { let desk_to_connect = get_list_of_desks(&Some(name.clone())).await?; let desk_to_connect = desk_to_connect diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index d3541cf..7bd0d55 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -4,6 +4,7 @@ )] use std::sync::Mutex; +use btleplug::api::Peripheral; use tauri_plugin_autostart::MacosLauncher; use btleplug::platform::Peripheral as PlatformPeripheral; @@ -17,6 +18,22 @@ mod tray_utils; #[derive(Default)] pub struct TauriSharedDesk(Mutex>); +pub fn get_desk_from_app_state(app_handle: &tauri::AppHandle) -> PlatformPeripheral { + let desk = app_handle.state::(); + let desk = desk.0.lock().expect("Error while unwrapping shared desk"); + let desk = desk + .as_ref() + .expect("Desk should have been defined at this point"); + desk.clone() +} + +pub fn assign_desk_to_mutex(desk: &TauriSharedDesk, new_desk: Option) { + *desk + .0 + .lock() + .expect("Failed to deref mutex during instantiation") = new_desk; +} + #[tauri::command] fn create_new_elem( app_handle: tauri::AppHandle, @@ -44,11 +61,7 @@ fn create_new_elem( }); config_utils::update_config(&config); - let desk = app_handle.state::(); - let desk = desk.0.lock().expect("Error while unwrapping shared desk"); - let desk = desk - .as_ref() - .expect("Desk should have been defined at this point"); + let desk = get_desk_from_app_state(&app_handle); let cloned_desk = desk.clone(); if let Some(shortcut_acc) = shortcutvalue { @@ -70,9 +83,13 @@ fn create_new_elem( /// Provided a name, will connect to a desk with this name - after this step, desk actually becomes usable #[tauri::command] -async fn connect_to_desk_by_name(name: String) -> Result<(), ()> { - _ = loose_idasen::connect_to_desk_by_name_internal(name).await; +async fn connect_to_desk_by_name(app_handle: tauri::AppHandle, name: String) -> Result<(), ()> { + println!("saving name: {name}"); + + let instantiated_desk = app_handle.state::(); + let cached_desk = loose_idasen::connect_to_desk_by_name_internal(name).await.ok(); + assign_desk_to_mutex(&instantiated_desk, cached_desk); Ok(()) } @@ -90,10 +107,11 @@ fn main() { .await .ok(); - *initiated_desk - .0 - .lock() - .expect("Failed to deref mutex during instantiation") = cached_desk; + assign_desk_to_mutex(&initiated_desk, cached_desk); + // *initiated_desk + // .0 + // .lock() + // .expect("Failed to deref mutex during instantiation") = cached_desk; } }); @@ -207,6 +225,7 @@ fn main() { config_utils::get_config, config_utils::remove_position, config_utils::remove_config, + config_utils::reset_desk, loose_idasen::get_desk_to_connect, connect_to_desk_by_name, ]) @@ -230,15 +249,9 @@ fn main() { .find(|pos| pos.position_elem.id_str == remaining_id) .expect("Clicked element not found"); block_on(async { - let desk = app.state::(); - - let desk = desk.0.lock(); - let desk = desk.expect("Error while unwrapping shared desk"); - let desk = desk - .as_ref() - .expect("Desk should have been defined at this point"); + let desk = get_desk_from_app_state(app); - loose_idasen::move_to_target(desk, found_elem.value) + loose_idasen::move_to_target(&desk, found_elem.value) .await .unwrap(); }); diff --git a/src/App.tsx b/src/App.tsx index c0a812a..d238ca6 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,9 +1,11 @@ -import { Link, RouteConfig, createBrowserRouter } from "found"; +import { RouteConfig, createBrowserRouter } from "found"; +import { relaunch } from "@tauri-apps/api/process"; import AboutPage from "./AboutPage"; import NewPositionPage from "./NewPositionPage"; import IntroPage from "./IntroPage"; import ManagePositionsPage from "./ManagePositionsPage"; import { Button } from "./generic/button"; +import { resetDesk } from "./rustUtils"; const ErrorPage = () => { return ( @@ -18,8 +20,13 @@ const ErrorPage = () => {
{(window as any)?.stateWorkaround?.title}
{(window as any)?.stateWorkaround?.description}
-
diff --git a/src/rustUtils.ts b/src/rustUtils.ts index ef21e0b..ef2d07e 100644 --- a/src/rustUtils.ts +++ b/src/rustUtils.ts @@ -46,3 +46,7 @@ export const createNewElem = async ( export const removeConfig = async () => { return await invoke("remove_config"); }; + +export const resetDesk = async () => { + return await invoke("reset_desk"); +}; From cdff53dfd66ea7ab8269d3ff8d438ab676fe4cd5 Mon Sep 17 00:00:00 2001 From: Szymon Wiszczuk Date: Sun, 10 Dec 2023 13:19:22 +0100 Subject: [PATCH 7/7] last batch of low hanging fruits --- src-tauri/Cargo.lock | 32 ++++++++++++++++---------------- src-tauri/Cargo.toml | 2 +- src-tauri/src/desk_mutex.rs | 22 ++++++++++++++++++++++ src-tauri/src/main.rs | 30 +++++------------------------- 4 files changed, 44 insertions(+), 42 deletions(-) create mode 100644 src-tauri/src/desk_mutex.rs diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 627a079..b839254 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2,22 +2,6 @@ # It is not intended for manual editing. version = 3 -[[package]] -name = "Trayasen" -version = "0.0.6" -dependencies = [ - "btleplug", - "serde", - "serde_derive", - "serde_json", - "tauri", - "tauri-build", - "tauri-plugin-autostart", - "thiserror", - "tokio", - "uuid", -] - [[package]] name = "addr2line" version = "0.20.0" @@ -4155,6 +4139,22 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "trayasen" +version = "0.0.6" +dependencies = [ + "btleplug", + "serde", + "serde_derive", + "serde_json", + "tauri", + "tauri-build", + "tauri-plugin-autostart", + "thiserror", + "tokio", + "uuid", +] + [[package]] name = "treediff" version = "4.0.2" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 23692b9..03ae359 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "Trayasen" +name = "trayasen" version = "0.0.6" description = "An app to control IKEA Idasen desk" authors = ["Szymon Wiszczuk"] diff --git a/src-tauri/src/desk_mutex.rs b/src-tauri/src/desk_mutex.rs new file mode 100644 index 0000000..ce7207d --- /dev/null +++ b/src-tauri/src/desk_mutex.rs @@ -0,0 +1,22 @@ +// Set of utils to interact with desk mutex, since it's pretty complex + +use btleplug::platform::Peripheral as PlatformPeripheral; +use tauri::Manager; + +use crate::TauriSharedDesk; + +pub fn get_desk_from_app_state(app_handle: &tauri::AppHandle) -> PlatformPeripheral { + let desk = app_handle.state::(); + let desk = desk.0.lock().expect("Error while unwrapping shared desk"); + let desk = desk + .as_ref() + .expect("Desk should have been defined at this point"); + desk.clone() +} + +pub fn assign_desk_to_mutex(desk_mutex: &TauriSharedDesk, new_desk: Option) { + *desk_mutex + .0 + .lock() + .expect("Failed to deref mutex during instantiation") = new_desk; +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 7bd0d55..c215166 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -4,13 +4,13 @@ )] use std::sync::Mutex; -use btleplug::api::Peripheral; use tauri_plugin_autostart::MacosLauncher; use btleplug::platform::Peripheral as PlatformPeripheral; use tauri::GlobalShortcutManager; use tauri::{async_runtime::block_on, Manager, SystemTray, SystemTrayEvent}; +mod desk_mutex; mod config_utils; mod loose_idasen; mod tray_utils; @@ -18,22 +18,6 @@ mod tray_utils; #[derive(Default)] pub struct TauriSharedDesk(Mutex>); -pub fn get_desk_from_app_state(app_handle: &tauri::AppHandle) -> PlatformPeripheral { - let desk = app_handle.state::(); - let desk = desk.0.lock().expect("Error while unwrapping shared desk"); - let desk = desk - .as_ref() - .expect("Desk should have been defined at this point"); - desk.clone() -} - -pub fn assign_desk_to_mutex(desk: &TauriSharedDesk, new_desk: Option) { - *desk - .0 - .lock() - .expect("Failed to deref mutex during instantiation") = new_desk; -} - #[tauri::command] fn create_new_elem( app_handle: tauri::AppHandle, @@ -61,7 +45,7 @@ fn create_new_elem( }); config_utils::update_config(&config); - let desk = get_desk_from_app_state(&app_handle); + let desk = desk_mutex::get_desk_from_app_state(&app_handle); let cloned_desk = desk.clone(); if let Some(shortcut_acc) = shortcutvalue { @@ -89,7 +73,7 @@ async fn connect_to_desk_by_name(app_handle: tauri::AppHandle, name: String) -> let instantiated_desk = app_handle.state::(); let cached_desk = loose_idasen::connect_to_desk_by_name_internal(name).await.ok(); - assign_desk_to_mutex(&instantiated_desk, cached_desk); + desk_mutex::assign_desk_to_mutex(&instantiated_desk, cached_desk); Ok(()) } @@ -107,11 +91,7 @@ fn main() { .await .ok(); - assign_desk_to_mutex(&initiated_desk, cached_desk); - // *initiated_desk - // .0 - // .lock() - // .expect("Failed to deref mutex during instantiation") = cached_desk; + desk_mutex::assign_desk_to_mutex(&initiated_desk, cached_desk); } }); @@ -249,7 +229,7 @@ fn main() { .find(|pos| pos.position_elem.id_str == remaining_id) .expect("Clicked element not found"); block_on(async { - let desk = get_desk_from_app_state(app); + let desk = desk_mutex::get_desk_from_app_state(app); loose_idasen::move_to_target(&desk, found_elem.value) .await