main.rs 2.0 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. let context = tauri::generate_context!("../../examples/state/tauri.conf.json");
  58. tauri::Builder::default()
  59. .menu(tauri::Menu::os_default(&context.package_info().name))
  60. .manage(Counter(AtomicUsize::new(0)))
  61. .manage(Database(Default::default()))
  62. .manage(Connection(Default::default()))
  63. .invoke_handler(tauri::generate_handler![
  64. increment_counter,
  65. db_insert,
  66. db_read,
  67. connect,
  68. disconnect,
  69. connection_send
  70. ])
  71. .run(context)
  72. .expect("error while running tauri application");
  73. }