main.rs 1.9 KB

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