1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Copyright 2019-2022 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

#![allow(unused_imports)]

use super::InvokeContext;
use crate::{
  api::ipc::CallbackFn,
  event::is_event_name_valid,
  event::{listen_js, unlisten_js},
  runtime::window::is_label_valid,
  sealed::ManagerBase,
  Manager, Runtime,
};
use serde::{de::Deserializer, Deserialize};
use tauri_macros::{command_enum, CommandModule};

pub struct EventId(String);

impl<'de> Deserialize<'de> for EventId {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    let event_id = String::deserialize(deserializer)?;
    if is_event_name_valid(&event_id) {
      Ok(EventId(event_id))
    } else {
      Err(serde::de::Error::custom(
        "Event name must include only alphanumeric characters, `-`, `/`, `:` and `_`.",
      ))
    }
  }
}

pub struct WindowLabel(String);

impl<'de> Deserialize<'de> for WindowLabel {
  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  where
    D: Deserializer<'de>,
  {
    let event_id = String::deserialize(deserializer)?;
    if is_label_valid(&event_id) {
      Ok(WindowLabel(event_id))
    } else {
      Err(serde::de::Error::custom(
        "Window label must include only alphanumeric characters, `-`, `/`, `:` and `_`.",
      ))
    }
  }
}

/// The API descriptor.
#[command_enum]
#[derive(Deserialize, CommandModule)]
#[serde(tag = "cmd", rename_all = "camelCase")]
pub enum Cmd {
  /// Listen to an event.
  #[serde(rename_all = "camelCase")]
  Listen {
    event: EventId,
    window_label: Option<WindowLabel>,
    handler: CallbackFn,
  },
  /// Unlisten to an event.
  #[serde(rename_all = "camelCase")]
  Unlisten { event: EventId, event_id: u64 },
  /// Emit an event to the webview associated with the given window.
  /// If the window_label is omitted, the event will be triggered on all listeners.
  #[serde(rename_all = "camelCase")]
  Emit {
    event: EventId,
    window_label: Option<WindowLabel>,
    payload: Option<String>,
  },
}

impl Cmd {
  fn listen<R: Runtime>(
    context: InvokeContext<R>,
    event: EventId,
    window_label: Option<WindowLabel>,
    handler: CallbackFn,
  ) -> super::Result<u64> {
    let event_id = rand::random();

    let window_label = window_label.map(|l| l.0);

    context
      .window
      .eval(&listen_js(
        context.window.manager().event_listeners_object_name(),
        format!("'{}'", event.0),
        event_id,
        window_label.clone(),
        format!("window['_{}']", handler.0),
      ))
      .map_err(crate::error::into_anyhow)?;

    context
      .window
      .register_js_listener(window_label, event.0, event_id);

    Ok(event_id)
  }

  fn unlisten<R: Runtime>(
    context: InvokeContext<R>,
    event: EventId,
    event_id: u64,
  ) -> super::Result<()> {
    context
      .window
      .eval(&unlisten_js(
        context.window.manager().event_listeners_object_name(),
        event.0,
        event_id,
      ))
      .map_err(crate::error::into_anyhow)?;
    context.window.unregister_js_listener(event_id);
    Ok(())
  }

  fn emit<R: Runtime>(
    context: InvokeContext<R>,
    event: EventId,
    window_label: Option<WindowLabel>,
    payload: Option<String>,
  ) -> super::Result<()> {
    // dispatch the event to Rust listeners
    context.window.trigger(&event.0, payload.clone());

    if let Some(target) = window_label {
      context
        .window
        .emit_to(&target.0, &event.0, payload)
        .map_err(crate::error::into_anyhow)?;
    } else {
      context
        .window
        .emit_all(&event.0, payload)
        .map_err(crate::error::into_anyhow)?;
    }
    Ok(())
  }
}