event.rs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. use std::boxed::Box;
  2. use std::collections::HashMap;
  3. use std::sync::{Arc, Mutex};
  4. use web_view::Handle;
  5. struct EventHandler {
  6. on_event: Box<dyn FnOnce(String)>,
  7. }
  8. thread_local!(static LISTENERS: Arc<Mutex<HashMap<String, EventHandler>>> = Arc::new(Mutex::new(HashMap::new())));
  9. lazy_static! {
  10. static ref EMIT_FUNCTION_NAME: String = uuid::Uuid::new_v4().to_string();
  11. static ref EVENT_LISTENERS_OBJECT_NAME: String = uuid::Uuid::new_v4().to_string();
  12. static ref EVENT_QUEUE_OBJECT_NAME: String = uuid::Uuid::new_v4().to_string();
  13. }
  14. pub fn emit_function_name() -> String {
  15. EMIT_FUNCTION_NAME.to_string()
  16. }
  17. pub fn event_listeners_object_name() -> String {
  18. EVENT_LISTENERS_OBJECT_NAME.to_string()
  19. }
  20. pub fn event_queue_object_name() -> String {
  21. EVENT_QUEUE_OBJECT_NAME.to_string()
  22. }
  23. pub fn listen<F: FnOnce(String) + 'static>(id: &'static str, handler: F) {
  24. LISTENERS.with(|listeners| {
  25. let mut l = listeners.lock().unwrap();
  26. l.insert(
  27. id.to_string(),
  28. EventHandler {
  29. on_event: Box::new(handler),
  30. },
  31. );
  32. });
  33. }
  34. pub fn emit<T: 'static>(webview_handle: Handle<T>, event: &'static str, mut payload: String) {
  35. let salt = crate::salt::generate();
  36. if payload == "" {
  37. payload = "void 0".to_string();
  38. }
  39. webview_handle
  40. .dispatch(move |_webview| {
  41. _webview.eval(&format!(
  42. "window['{}']({{type: '{}', payload: {}}}, '{}')",
  43. emit_function_name(),
  44. event,
  45. payload,
  46. salt
  47. ))
  48. })
  49. .unwrap();
  50. }
  51. pub fn on_event(event: String, data: String) {
  52. LISTENERS.with(|l| {
  53. let mut listeners = l.lock().unwrap();
  54. let key = event.clone();
  55. if listeners.contains_key(&event) {
  56. let handler = listeners.remove(&event).unwrap();
  57. (handler.on_event)(data);
  58. }
  59. listeners.remove(&key);
  60. });
  61. }