main.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
  5. use std::{
  6. collections::HashMap,
  7. sync::{
  8. atomic::{AtomicUsize, Ordering},
  9. Arc, Mutex,
  10. },
  11. };
  12. use tauri::State;
  13. struct Counter(AtomicUsize);
  14. #[derive(Default)]
  15. struct Database(Arc<Mutex<HashMap<String, String>>>);
  16. struct Client;
  17. impl Client {
  18. fn send(&self) {}
  19. }
  20. #[derive(Default)]
  21. struct Connection(Mutex<Option<Client>>);
  22. #[tauri::command]
  23. fn connect(connection: State<'_, Connection>) {
  24. *connection.0.lock().unwrap() = Some(Client {});
  25. }
  26. #[tauri::command]
  27. fn disconnect(connection: State<'_, Connection>) {
  28. // drop the connection
  29. *connection.0.lock().unwrap() = None;
  30. }
  31. #[tauri::command]
  32. fn connection_send(connection: State<'_, Connection>) {
  33. connection
  34. .0
  35. .lock()
  36. .unwrap()
  37. .as_ref()
  38. .expect("connection not initialize; use the `connect` command first")
  39. .send();
  40. }
  41. #[tauri::command]
  42. fn increment_counter(counter: State<'_, Counter>) -> usize {
  43. counter.0.fetch_add(1, Ordering::Relaxed) + 1
  44. }
  45. #[tauri::command]
  46. fn db_insert(key: String, value: String, db: State<'_, Database>) {
  47. db.0.lock().unwrap().insert(key, value);
  48. }
  49. #[tauri::command]
  50. fn db_read(key: String, db: State<'_, Database>) -> Option<String> {
  51. db.0.lock().unwrap().get(&key).cloned()
  52. }
  53. fn main() {
  54. tauri::Builder::default()
  55. .manage(Counter(AtomicUsize::new(0)))
  56. .manage(Database(Default::default()))
  57. .manage(Connection(Default::default()))
  58. .invoke_handler(tauri::generate_handler![
  59. increment_counter,
  60. db_insert,
  61. db_read,
  62. connect,
  63. disconnect,
  64. connection_send
  65. ])
  66. .run(tauri::generate_context!(
  67. "../../examples/state/tauri.conf.json"
  68. ))
  69. .expect("error while running tauri application");
  70. }