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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use log::{error, trace};
use portable_atomic::AtomicPtr;
use serde::de::DeserializeOwned;
use std::fmt::Debug;
use std::sync::atomic::Ordering;
use tauri::Manager;
use tauri::{plugin::PluginApi, AppHandle, Runtime};
use crate::error::Result;
use crate::utils::Convert;
use crate::view;
pub(crate) fn init<R: Runtime, C: DeserializeOwned>(
app: &AppHandle<R>,
_api: PluginApi<R, C>,
f: PolygonCallback<R>,
) -> crate::Result<Polygon<R>> {
Ok(Polygon {
app_handle: app.clone(),
callback: AtomicPtr::new(Box::into_raw(Box::new(f))),
})
}
pub(crate) type PolygonCallback<R> =
Box<dyn FnMut(&AppHandle<R>, crate::Event) + Send + Sync + 'static>;
/// Access to the Polygon APIs.
pub struct Polygon<R: Runtime> {
pub app_handle: AppHandle<R>,
callback: AtomicPtr<PolygonCallback<R>>,
}
impl<R: Runtime> Polygon<R> {
pub(crate) fn emit(&self, app_handle: &AppHandle<R>, event: crate::Event) {
let ptr = self.callback.load(Ordering::SeqCst);
let mut callback = unsafe { Box::from_raw(ptr) };
callback(app_handle, event);
self.callback
.store(Box::into_raw(callback), Ordering::SeqCst);
}
/// Register a default polygon with given id.
///
/// Frequent calls to this function may cause performance issues.
/// It is recommended to use `register_all` to register multiple polygons at once.
///
/// # Errors
/// This function will return an error if the `id` provided has already been registered.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().register("my-polygon")?;
/// ```
/// ```javascript
/// // frontend with js
/// import { register } from 'tauri-plugin-polygon-api';
/// await register('my-polygon');
/// ```
pub fn register(&self, id: &str) -> Result<()> {
trace!("register: {id}");
match view::register(id.into()) {
Ok(_) => Ok(()),
Err(e) => {
error!("register: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
/// Register multiple polygons.
///
/// # Errors
/// This function will `not` return errors even if the `id` provided has already been registered.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().register(Vec::from(["my-polygon", "another-polygon"]))?;
/// ```
/// ```javascript
/// // frontend with js
/// import { registerAll } from 'tauri-plugin-polygon-api';
/// await registerAll(['my-polygon', 'another-polygon']);
/// ```
pub fn register_all<S: AsRef<str> + Debug>(&self, ids: Vec<S>) -> Result<()> {
trace!("register_all: {ids:?}");
match view::register_all(ids.iter().map(|id| id.as_ref().to_string()).collect()) {
Ok(_) => Ok(()),
Err(e) => {
error!("register_all: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
/// Remove a polygon physically.
///
/// After this function call ends, the specified polygon will be deleted physically,
/// and needs to be re-registered before it can be used again.
///
/// Frequent calls to this function may cause performance issues.
/// It is recommended to use `hide` to disable the polygon logically.
///
/// # Errors
/// This function will return an error if the `id` provided can not be found.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().remove("my-polygon")?;
/// ```
/// ```javascript
/// // frontend with js
/// import { remove } from 'tauri-plugin-polygon-api';
/// await remove('my-polygon');
/// ```
pub fn remove(&self, id: &str) -> Result<()> {
trace!("remove: {id}");
match view::remove(&id) {
Ok(_) => Ok(()),
Err(e) => {
error!("remove: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
/// Enable the polygon by given id.
///
/// # Errors
/// This function will return an error if the `id` provided can not be found.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().show("my-polygon")?;
/// ```
/// ```javascript
/// // frontend with js
/// import { show } from 'tauri-plugin-polygon-api';
/// await show('my-polygon');
/// ```
pub fn show(&self, id: &str) -> Result<()> {
trace!("show: {id}");
match view::show(&id) {
Ok(_) => Ok(()),
Err(e) => {
error!("show: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
/// Disable the polygon logically by given id.
///
/// # Errors
/// This function will return an error if the `id` provided can not be found.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().hide("my-polygon")?;
/// ```
/// ```javascript
/// // frontend with js
/// import { hide } from 'tauri-plugin-polygon-api';
/// await hide('my-polygon');
/// ```
pub fn hide(&self, id: &str) -> Result<()> {
trace!("hide: {id}");
self.app_handle
.get_webview_window("main")
.unwrap()
.set_ignore_cursor_events(true)
.unwrap();
match view::hide(&id) {
Ok(_) => Ok(()),
Err(e) => {
error!("hide: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
/// Update vertices of the polygon by given id.
/// Within these points, mouse events will not go through.
///
/// # Notice
/// 1. All positions should be converted to a `percentage based on the screen width`.
/// Position from 0 to 1, 0.1 means 10% of the `screen width`.
/// 2. At least `3` points are required.
/// 3. The order in which you define the points matters and can result in different shapes.
///
/// # Errors
/// This function will return an error if the `id` provided can not be found.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().update("my-polygon", vec![(0.0, 0.0), (0.1, 0.0), (0.1, 0.1), (0.0, 0.1)])?;
/// ```
/// ```javascript
/// // frontend with js
/// import { update } from 'tauri-plugin-polygon-api';
///
/// await update('my-polygon', {
/// id: "EXAMPLE",
/// polygon: [
/// [0, 0],
/// [0.1, 0],
/// [0.1, 0.1],
/// [0, 0.1]
/// ]
/// })
/// ```
pub fn update(&self, id: &str, points: Vec<(f64, f64)>) -> Result<()> {
trace!("update: {id} - {points:?}");
match view::update(
&id,
&points
.iter()
.map(|(x, y)| Convert::from_viewport(*x, *y))
.collect::<Vec<(f64, f64)>>(),
) {
Ok(_) => Ok(()),
Err(e) => {
error!("update: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
/// Clear all polygons physically.
///
/// # Example
/// ```no_run
/// // backend with rust
/// app.polygon().clear()?;
/// ```
/// ```javascript
/// // frontend with js
/// import { clear } from 'tauri-plugin-polygon-api';
/// await clear();
/// ```
pub fn clear(&self) -> Result<()> {
trace!("clear");
match view::clear() {
Ok(_) => Ok(()),
Err(e) => {
error!("clear: {e}");
self.emit(&self.app_handle, crate::Event::Error(e.clone()));
Err(e)
}
}
}
pub(crate) fn destroy(&self) -> Result<()> {
let ptr = self.callback.load(Ordering::SeqCst);
self.callback.store(std::ptr::null_mut(), Ordering::SeqCst);
drop(unsafe { Box::from_raw(ptr) });
Ok(())
}
}