@g9tm/app-diagnostic-tauri 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/Cargo.toml +1 -1
  2. package/README.md +2 -0
  3. package/android/build.gradle.kts +29 -29
  4. package/android/proguard-rules.pro +2 -2
  5. package/android/settings.gradle +2 -2
  6. package/android/src/main/AndroidManifest.xml +5 -5
  7. package/android/src/main/java/com/g9tm/appdiagnostic/tauri/G9DiagnosticPlugin.kt +1 -1
  8. package/build.rs +13 -13
  9. package/ios/Package.swift +20 -20
  10. package/ios/Sources/G9AppDiagnosticCore/G9AppDiagnosticHost.m +72 -72
  11. package/ios/Sources/G9AppDiagnosticCore/G9DiagnosticRecorders.m +514 -514
  12. package/ios/Sources/G9AppDiagnosticCore/include/G9AppDiagnosticHost.h +32 -32
  13. package/ios/Sources/G9AppDiagnosticCore/include/G9DiagnosticRecorders.h +36 -36
  14. package/ios/Sources/G9DiagnosticPlugin/G9DiagnosticPlugin.swift +135 -135
  15. package/package.json +3 -3
  16. package/permissions/autogenerated/commands/capabilities.toml +13 -13
  17. package/permissions/autogenerated/commands/read_chunk.toml +13 -13
  18. package/permissions/autogenerated/commands/registerListener.toml +13 -13
  19. package/permissions/autogenerated/commands/remove.toml +13 -13
  20. package/permissions/autogenerated/commands/remove_listener.toml +13 -13
  21. package/permissions/autogenerated/commands/screenshot.toml +13 -13
  22. package/permissions/autogenerated/commands/start_screen.toml +13 -13
  23. package/permissions/autogenerated/commands/start_voice.toml +13 -13
  24. package/permissions/autogenerated/commands/state.toml +13 -13
  25. package/permissions/autogenerated/commands/stop_screen.toml +13 -13
  26. package/permissions/autogenerated/commands/stop_voice.toml +13 -13
  27. package/permissions/autogenerated/commands/touch.toml +13 -13
  28. package/permissions/autogenerated/commands/watch_touches.toml +13 -13
  29. package/permissions/autogenerated/reference.md +367 -367
  30. package/permissions/default.toml +9 -9
  31. package/permissions/schemas/schema.json +461 -461
  32. package/src/index.ts +97 -97
  33. package/src/lib.rs +119 -119
package/src/index.ts CHANGED
@@ -1,97 +1,97 @@
1
- // @g9tm/app-diagnostic-tauri — the tester mode of a Tauri v2 app (0.5.0): the JS side of tauri-plugin-g9-diagnostic.
2
- // On Android and iOS the recorders are native (the real screen, a map's surface included; the gesture held away from the
3
- // views); on a desktop the plugin answers «no native half» and the web recorders of @g9tm/app-diagnostic-web work
4
- // (getDisplayMedia in WebView2, the page drawn into a canvas elsewhere).
5
- //
6
- // import { startTauriTester } from '@g9tm/app-diagnostic-tauri';
7
- // const tester = await startTauriTester({ gateway, appId, productName, appVersion, environment });
8
- // tester.engine.setEnabled(true);
9
- // (= @g9tm/app-diagnostic-web's startTester with media: tauriMedia and the platform tauri-android, tauri-ios, tauri-windows…)
10
- //
11
- // Rust: .plugin(tauri_plugin_g9_diagnostic::init()); capability: "g9-diagnostic:default".
12
- import { addPluginListener, invoke } from '@tauri-apps/api/core';
13
- import type { MediaRecording, TesterMedia, TesterTouchEvent, Unsubscribe } from '@g9tm/app-diagnostic';
14
- import { type ByteStore, inside, ROOT, startTester, type StartTesterOptions, type Tester } from '@g9tm/app-diagnostic-web';
15
-
16
- const call = <T>(command: string, args: Record<string, unknown> = {}) => invoke<T>(`plugin:g9-diagnostic|${command}`, { args });
17
-
18
- interface NativeRecording { path: string; bytes: number; durationMs: number; capped?: boolean }
19
-
20
- const CHUNK = 512 * 1024;
21
- const unb64 = (text: string): Uint8Array => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
22
-
23
- async function adopt(store: ByteStore, nativePath: string, webPath: string): Promise<number> {
24
- const target = inside(webPath);
25
- let offset = 0;
26
- await store.remove(target);
27
- for (;;) {
28
- const { data } = await call<{ data: string }>('read_chunk', { path: nativePath, offset, length: CHUNK });
29
- if (!data) break;
30
- const bytes = unb64(data);
31
- await store.write(target, bytes, offset > 0);
32
- offset += bytes.length;
33
- if (bytes.length < CHUNK) break;
34
- }
35
- await call('remove', { path: nativePath }).catch(() => undefined);
36
- return offset;
37
- }
38
-
39
- /**
40
- * The TesterMedia over the plugin where it has a native half (Android, iOS), the browser's (`fallback`) where it has not
41
- * (a desktop) — decided once, by the plugin's `capabilities`.
42
- */
43
- export function tauriMedia(fallback: TesterMedia, store: ByteStore): TesterMedia {
44
- const native = call<{ native?: boolean; screen: boolean; voice: boolean }>('capabilities').then((c) => (c.native ? c : null), () => null);
45
- const listeners = new Set<(e: TesterTouchEvent) => void>();
46
- let listening = false;
47
- let screenDir = `${ROOT}/drafts`, voiceDir = `${ROOT}/drafts`;
48
- const done = async (r: NativeRecording | null, dir: string, kind: string): Promise<MediaRecording | null> => {
49
- if (!r) return null;
50
- const path = `${dir}/${kind}-${Date.now()}${r.path.slice(r.path.lastIndexOf('.'))}`;
51
- const bytes = await adopt(store, r.path, path);
52
- return bytes > 0 ? { path: inside(path), bytes, durationMs: r.durationMs, ...(r.capped ? { capped: true } : {}) } : null;
53
- };
54
- const either = async <T>(n: () => Promise<T>, f: () => Promise<T>): Promise<T> => ((await native) ? n() : f());
55
- return {
56
- support: () => either(async () => { const c = (await native)!; return { screen: c.screen, voice: c.voice }; }, () => fallback.support()),
57
- state: () => either(() => call<{ screen: boolean; voice: boolean }>('state'), () => fallback.state()),
58
- startScreen: (dir, o) => either(async () => { screenDir = dir; await call('start_screen', { maxFps: o.maxFps }); }, () => fallback.startScreen(dir, o)),
59
- stopScreen: () => either(async () => done((await call<{ recording: NativeRecording | null }>('stop_screen')).recording, screenDir, 'screen'), () => fallback.stopScreen()),
60
- startVoice: (dir) => either(async () => { voiceDir = dir; await call('start_voice'); }, () => fallback.startVoice(dir)),
61
- stopVoice: () => either(async () => done((await call<{ recording: NativeRecording | null }>('stop_voice')).recording, voiceDir, 'voice'), () => fallback.stopVoice()),
62
- screenshot: (maxEdge, quality) => either(async () => {
63
- const shot = await call<{ path: string }>('screenshot', { maxEdge, quality });
64
- const path = `${ROOT}/shots/shot-${Date.now()}.jpg`;
65
- await adopt(store, shot.path, path);
66
- return { path: inside(path) };
67
- }, () => fallback.screenshot(maxEdge, quality)),
68
- pick: (mimes) => fallback.pick(mimes),
69
- watchTouches: (o) => either(async () => {
70
- if (!listening) {
71
- listening = true;
72
- await addPluginListener('g9-diagnostic', 'touch', (p: { json: string }) => {
73
- try {
74
- const e = JSON.parse(p.json) as { type: string; fingers: number; x: number; y: number; cx?: number; cy?: number; excluded?: boolean };
75
- if (e.type === 'tap' || e.type === 'down') listeners.forEach((l) => l({ type: e.type as 'tap' | 'down', fingers: e.fingers, x: e.cx ?? e.x, y: e.cy ?? e.y, excluded: !!e.excluded }));
76
- } catch { /* not a touch */ }
77
- });
78
- }
79
- await call('watch_touches', { taps: o.gesture, touches: o.touches, consume: !!o.consume, excludeSurfaces: !!o.excludeSurfaces });
80
- }, () => fallback.watchTouches(o)),
81
- onTouch(listener): Unsubscribe {
82
- listeners.add(listener);
83
- const off = fallback.onTouch(listener); // a desktop's pointer events and shortcut
84
- return () => { listeners.delete(listener); off(); };
85
- },
86
- };
87
- }
88
-
89
- /** The operator's remote touch on the native half (Android: a real gesture; iOS: a logical tap; a desktop: refused). */
90
- export const remoteTouch = (kind: 'tap' | 'longPress' | 'drag', x: number, y: number, toX = x, toY = y, durationMs = kind === 'longPress' ? 800 : kind === 'drag' ? 300 : 50) =>
91
- call<{ handled: boolean }>('touch', { kind, x, y, toX, toY, durationMs }).then((r) => r.handled, () => false);
92
-
93
- /** The tester mode of a Tauri app in one call: the web layer with the native recorders where there are some, the platform named. */
94
- export async function startTauriTester(o: Omit<StartTesterOptions, 'media' | 'platform'>): Promise<Tester> {
95
- const platform = await call<{ platform?: string }>('capabilities').then((c) => c.platform ?? 'desktop', () => 'desktop');
96
- return startTester({ ...o, media: tauriMedia, platform: `tauri-${platform}` });
97
- }
1
+ // @g9tm/app-diagnostic-tauri — the tester mode of a Tauri v2 app (0.5.0): the JS side of tauri-plugin-g9-diagnostic.
2
+ // On Android and iOS the recorders are native (the real screen, a map's surface included; the gesture held away from the
3
+ // views); on a desktop the plugin answers «no native half» and the web recorders of @g9tm/app-diagnostic-web work
4
+ // (getDisplayMedia in WebView2, the page drawn into a canvas elsewhere).
5
+ //
6
+ // import { startTauriTester } from '@g9tm/app-diagnostic-tauri';
7
+ // const tester = await startTauriTester({ gateway, appId, productName, appVersion, environment });
8
+ // tester.engine.setEnabled(true);
9
+ // (= @g9tm/app-diagnostic-web's startTester with media: tauriMedia and the platform tauri-android, tauri-ios, tauri-windows…)
10
+ //
11
+ // Rust: .plugin(tauri_plugin_g9_diagnostic::init()); capability: "g9-diagnostic:default".
12
+ import { addPluginListener, invoke } from '@tauri-apps/api/core';
13
+ import type { MediaRecording, TesterMedia, TesterTouchEvent, Unsubscribe } from '@g9tm/app-diagnostic';
14
+ import { type ByteStore, inside, ROOT, startTester, type StartTesterOptions, type Tester } from '@g9tm/app-diagnostic-web';
15
+
16
+ const call = <T>(command: string, args: Record<string, unknown> = {}) => invoke<T>(`plugin:g9-diagnostic|${command}`, { args });
17
+
18
+ interface NativeRecording { path: string; bytes: number; durationMs: number; capped?: boolean }
19
+
20
+ const CHUNK = 512 * 1024;
21
+ const unb64 = (text: string): Uint8Array => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
22
+
23
+ async function adopt(store: ByteStore, nativePath: string, webPath: string): Promise<number> {
24
+ const target = inside(webPath);
25
+ let offset = 0;
26
+ await store.remove(target);
27
+ for (;;) {
28
+ const { data } = await call<{ data: string }>('read_chunk', { path: nativePath, offset, length: CHUNK });
29
+ if (!data) break;
30
+ const bytes = unb64(data);
31
+ await store.write(target, bytes, offset > 0);
32
+ offset += bytes.length;
33
+ if (bytes.length < CHUNK) break;
34
+ }
35
+ await call('remove', { path: nativePath }).catch(() => undefined);
36
+ return offset;
37
+ }
38
+
39
+ /**
40
+ * The TesterMedia over the plugin where it has a native half (Android, iOS), the browser's (`fallback`) where it has not
41
+ * (a desktop) — decided once, by the plugin's `capabilities`.
42
+ */
43
+ export function tauriMedia(fallback: TesterMedia, store: ByteStore): TesterMedia {
44
+ const native = call<{ native?: boolean; screen: boolean; voice: boolean }>('capabilities').then((c) => (c.native ? c : null), () => null);
45
+ const listeners = new Set<(e: TesterTouchEvent) => void>();
46
+ let listening = false;
47
+ let screenDir = `${ROOT}/drafts`, voiceDir = `${ROOT}/drafts`;
48
+ const done = async (r: NativeRecording | null, dir: string, kind: string): Promise<MediaRecording | null> => {
49
+ if (!r) return null;
50
+ const path = `${dir}/${kind}-${Date.now()}${r.path.slice(r.path.lastIndexOf('.'))}`;
51
+ const bytes = await adopt(store, r.path, path);
52
+ return bytes > 0 ? { path: inside(path), bytes, durationMs: r.durationMs, ...(r.capped ? { capped: true } : {}) } : null;
53
+ };
54
+ const either = async <T>(n: () => Promise<T>, f: () => Promise<T>): Promise<T> => ((await native) ? n() : f());
55
+ return {
56
+ support: () => either(async () => { const c = (await native)!; return { screen: c.screen, voice: c.voice }; }, () => fallback.support()),
57
+ state: () => either(() => call<{ screen: boolean; voice: boolean }>('state'), () => fallback.state()),
58
+ startScreen: (dir, o) => either(async () => { screenDir = dir; await call('start_screen', { maxFps: o.maxFps }); }, () => fallback.startScreen(dir, o)),
59
+ stopScreen: () => either(async () => done((await call<{ recording: NativeRecording | null }>('stop_screen')).recording, screenDir, 'screen'), () => fallback.stopScreen()),
60
+ startVoice: (dir) => either(async () => { voiceDir = dir; await call('start_voice'); }, () => fallback.startVoice(dir)),
61
+ stopVoice: () => either(async () => done((await call<{ recording: NativeRecording | null }>('stop_voice')).recording, voiceDir, 'voice'), () => fallback.stopVoice()),
62
+ screenshot: (maxEdge, quality) => either(async () => {
63
+ const shot = await call<{ path: string }>('screenshot', { maxEdge, quality });
64
+ const path = `${ROOT}/shots/shot-${Date.now()}.jpg`;
65
+ await adopt(store, shot.path, path);
66
+ return { path: inside(path) };
67
+ }, () => fallback.screenshot(maxEdge, quality)),
68
+ pick: (mimes) => fallback.pick(mimes),
69
+ watchTouches: (o) => either(async () => {
70
+ if (!listening) {
71
+ listening = true;
72
+ await addPluginListener('g9-diagnostic', 'touch', (p: { json: string }) => {
73
+ try {
74
+ const e = JSON.parse(p.json) as { type: string; fingers: number; x: number; y: number; cx?: number; cy?: number; excluded?: boolean };
75
+ if (e.type === 'tap' || e.type === 'down') listeners.forEach((l) => l({ type: e.type as 'tap' | 'down', fingers: e.fingers, x: e.cx ?? e.x, y: e.cy ?? e.y, excluded: !!e.excluded }));
76
+ } catch { /* not a touch */ }
77
+ });
78
+ }
79
+ await call('watch_touches', { taps: o.gesture, touches: o.touches, consume: !!o.consume, excludeSurfaces: !!o.excludeSurfaces });
80
+ }, () => fallback.watchTouches(o)),
81
+ onTouch(listener): Unsubscribe {
82
+ listeners.add(listener);
83
+ const off = fallback.onTouch(listener); // a desktop's pointer events and shortcut
84
+ return () => { listeners.delete(listener); off(); };
85
+ },
86
+ };
87
+ }
88
+
89
+ /** The operator's remote touch on the native half (Android: a real gesture; iOS: a logical tap; a desktop: refused). */
90
+ export const remoteTouch = (kind: 'tap' | 'longPress' | 'drag', x: number, y: number, toX = x, toY = y, durationMs = kind === 'longPress' ? 800 : kind === 'drag' ? 300 : 50) =>
91
+ call<{ handled: boolean }>('touch', { kind, x, y, toX, toY, durationMs }).then((r) => r.handled, () => false);
92
+
93
+ /** The tester mode of a Tauri app in one call: the web layer with the native recorders where there are some, the platform named. */
94
+ export async function startTauriTester(o: Omit<StartTesterOptions, 'media' | 'platform'>): Promise<Tester> {
95
+ const platform = await call<{ platform?: string }>('capabilities').then((c) => c.platform ?? 'desktop', () => 'desktop');
96
+ return startTester({ ...o, media: tauriMedia, platform: `tauri-${platform}` });
97
+ }
package/src/lib.rs CHANGED
@@ -1,119 +1,119 @@
1
- //! tauri-plugin-g9-diagnostic (0.5.0): the tester mode of a Tauri v2 app.
2
- //!
3
- //! On Android and iOS every command goes to the mobile half — the SAME recorders, window capture, gesture and remote touch
4
- //! as @g9tm/app-diagnostic-lynx (copied, never edited, by scripts/sync-native.mjs). On a desktop the commands answer
5
- //! «unavailable» and the web layer (@g9tm/app-diagnostic-web: getDisplayMedia in WebView2, the page drawn elsewhere) does
6
- //! the work — the JS side (@g9tm/app-diagnostic-tauri) asks `capabilities` and falls back by itself.
7
- //!
8
- //! ```ignore
9
- //! tauri::Builder::default().plugin(tauri_plugin_g9_diagnostic::init())
10
- //! ```
11
- //! and in the capability file: `"permissions": ["g9-diagnostic:default"]`.
12
-
13
- use serde_json::Value;
14
- use tauri::{
15
- plugin::{Builder, TauriPlugin},
16
- Manager, Runtime,
17
- };
18
-
19
- #[cfg(target_os = "ios")]
20
- tauri::ios_plugin_binding!(init_plugin_g9_diagnostic);
21
-
22
- /// A failure with the module's code (types/g9-app-diagnostic-module.d.ts of the Lynx package).
23
- #[derive(Debug, thiserror::Error)]
24
- pub enum Error {
25
- #[error("{0}")]
26
- Unavailable(String),
27
- #[cfg(mobile)]
28
- #[error(transparent)]
29
- Mobile(#[from] tauri::plugin::mobile::PluginInvokeError),
30
- }
31
-
32
- impl serde::Serialize for Error {
33
- fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
34
- use serde::ser::SerializeMap;
35
- let mut m = s.serialize_map(Some(2))?;
36
- match self {
37
- Error::Unavailable(msg) => {
38
- m.serialize_entry("code", "unavailable")?;
39
- m.serialize_entry("message", msg)?;
40
- }
41
- #[cfg(mobile)]
42
- Error::Mobile(e) => {
43
- m.serialize_entry("code", "io")?;
44
- m.serialize_entry("message", &e.to_string())?;
45
- }
46
- }
47
- m.end()
48
- }
49
- }
50
-
51
- type Result<T> = std::result::Result<T, Error>;
52
-
53
- /// The mobile half (a handle to it), or the desktop's «no native half».
54
- pub struct G9Diagnostic<R: Runtime> {
55
- #[cfg(mobile)]
56
- handle: tauri::plugin::PluginHandle<R>,
57
- #[cfg(desktop)]
58
- _r: std::marker::PhantomData<fn() -> R>,
59
- }
60
-
61
- impl<R: Runtime> G9Diagnostic<R> {
62
- /// One command of the native half with its arguments (JSON), its answer as JSON.
63
- pub fn call(&self, command: &str, args: Value) -> Result<Value> {
64
- #[cfg(mobile)]
65
- {
66
- return self.handle.run_mobile_plugin::<Value>(command, args).map_err(Into::into);
67
- }
68
- #[cfg(desktop)]
69
- {
70
- let _ = args;
71
- if command == "capabilities" {
72
- return Ok(serde_json::json!({ "version": "0.5.0", "platform": std::env::consts::OS, "screen": false, "voice": false, "consume": false, "native": false }));
73
- }
74
- Err(Error::Unavailable(format!("«{command}» has no native half on a desktop: the web layer records")))
75
- }
76
- }
77
- }
78
-
79
- macro_rules! command {
80
- ($name:ident, $native:literal) => {
81
- #[tauri::command]
82
- async fn $name<R: Runtime>(app: tauri::AppHandle<R>, args: Option<Value>) -> Result<Value> {
83
- app.state::<G9Diagnostic<R>>().call($native, args.unwrap_or(Value::Object(Default::default())))
84
- }
85
- };
86
- }
87
-
88
- command!(capabilities, "capabilities");
89
- command!(state, "state");
90
- command!(start_screen, "startScreen");
91
- command!(stop_screen, "stopScreen");
92
- command!(start_voice, "startVoice");
93
- command!(stop_voice, "stopVoice");
94
- command!(screenshot, "screenshot");
95
- command!(watch_touches, "watchTouches");
96
- command!(touch, "touch");
97
- command!(read_chunk, "readChunk");
98
- command!(remove, "remove");
99
-
100
- /// The plugin: `.plugin(tauri_plugin_g9_diagnostic::init())`.
101
- pub fn init<R: Runtime>() -> TauriPlugin<R> {
102
- Builder::new("g9-diagnostic")
103
- .invoke_handler(tauri::generate_handler![capabilities, state, start_screen, stop_screen, start_voice, stop_voice, screenshot, watch_touches, touch, read_chunk, remove])
104
- .setup(|app, api| {
105
- #[cfg(target_os = "android")]
106
- let handle = api.register_android_plugin("com.g9tm.appdiagnostic.tauri", "G9DiagnosticPlugin")?;
107
- #[cfg(target_os = "ios")]
108
- let handle = api.register_ios_plugin(init_plugin_g9_diagnostic)?;
109
- #[cfg(mobile)]
110
- app.manage(G9Diagnostic::<R> { handle });
111
- #[cfg(desktop)]
112
- {
113
- let _ = api;
114
- app.manage(G9Diagnostic::<R> { _r: std::marker::PhantomData });
115
- }
116
- Ok(())
117
- })
118
- .build()
119
- }
1
+ //! tauri-plugin-g9-diagnostic (0.5.0): the tester mode of a Tauri v2 app.
2
+ //!
3
+ //! On Android and iOS every command goes to the mobile half — the SAME recorders, window capture, gesture and remote touch
4
+ //! as @g9tm/app-diagnostic-lynx (copied, never edited, by scripts/sync-native.mjs). On a desktop the commands answer
5
+ //! «unavailable» and the web layer (@g9tm/app-diagnostic-web: getDisplayMedia in WebView2, the page drawn elsewhere) does
6
+ //! the work — the JS side (@g9tm/app-diagnostic-tauri) asks `capabilities` and falls back by itself.
7
+ //!
8
+ //! ```ignore
9
+ //! tauri::Builder::default().plugin(tauri_plugin_g9_diagnostic::init())
10
+ //! ```
11
+ //! and in the capability file: `"permissions": ["g9-diagnostic:default"]`.
12
+
13
+ use serde_json::Value;
14
+ use tauri::{
15
+ plugin::{Builder, TauriPlugin},
16
+ Manager, Runtime,
17
+ };
18
+
19
+ #[cfg(target_os = "ios")]
20
+ tauri::ios_plugin_binding!(init_plugin_g9_diagnostic);
21
+
22
+ /// A failure with the module's code (types/g9-app-diagnostic-module.d.ts of the Lynx package).
23
+ #[derive(Debug, thiserror::Error)]
24
+ pub enum Error {
25
+ #[error("{0}")]
26
+ Unavailable(String),
27
+ #[cfg(mobile)]
28
+ #[error(transparent)]
29
+ Mobile(#[from] tauri::plugin::mobile::PluginInvokeError),
30
+ }
31
+
32
+ impl serde::Serialize for Error {
33
+ fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
34
+ use serde::ser::SerializeMap;
35
+ let mut m = s.serialize_map(Some(2))?;
36
+ match self {
37
+ Error::Unavailable(msg) => {
38
+ m.serialize_entry("code", "unavailable")?;
39
+ m.serialize_entry("message", msg)?;
40
+ }
41
+ #[cfg(mobile)]
42
+ Error::Mobile(e) => {
43
+ m.serialize_entry("code", "io")?;
44
+ m.serialize_entry("message", &e.to_string())?;
45
+ }
46
+ }
47
+ m.end()
48
+ }
49
+ }
50
+
51
+ type Result<T> = std::result::Result<T, Error>;
52
+
53
+ /// The mobile half (a handle to it), or the desktop's «no native half».
54
+ pub struct G9Diagnostic<R: Runtime> {
55
+ #[cfg(mobile)]
56
+ handle: tauri::plugin::PluginHandle<R>,
57
+ #[cfg(desktop)]
58
+ _r: std::marker::PhantomData<fn() -> R>,
59
+ }
60
+
61
+ impl<R: Runtime> G9Diagnostic<R> {
62
+ /// One command of the native half with its arguments (JSON), its answer as JSON.
63
+ pub fn call(&self, command: &str, args: Value) -> Result<Value> {
64
+ #[cfg(mobile)]
65
+ {
66
+ return self.handle.run_mobile_plugin::<Value>(command, args).map_err(Into::into);
67
+ }
68
+ #[cfg(desktop)]
69
+ {
70
+ let _ = args;
71
+ if command == "capabilities" {
72
+ return Ok(serde_json::json!({ "version": "0.5.0", "platform": std::env::consts::OS, "screen": false, "voice": false, "consume": false, "native": false }));
73
+ }
74
+ Err(Error::Unavailable(format!("«{command}» has no native half on a desktop: the web layer records")))
75
+ }
76
+ }
77
+ }
78
+
79
+ macro_rules! command {
80
+ ($name:ident, $native:literal) => {
81
+ #[tauri::command]
82
+ async fn $name<R: Runtime>(app: tauri::AppHandle<R>, args: Option<Value>) -> Result<Value> {
83
+ app.state::<G9Diagnostic<R>>().call($native, args.unwrap_or(Value::Object(Default::default())))
84
+ }
85
+ };
86
+ }
87
+
88
+ command!(capabilities, "capabilities");
89
+ command!(state, "state");
90
+ command!(start_screen, "startScreen");
91
+ command!(stop_screen, "stopScreen");
92
+ command!(start_voice, "startVoice");
93
+ command!(stop_voice, "stopVoice");
94
+ command!(screenshot, "screenshot");
95
+ command!(watch_touches, "watchTouches");
96
+ command!(touch, "touch");
97
+ command!(read_chunk, "readChunk");
98
+ command!(remove, "remove");
99
+
100
+ /// The plugin: `.plugin(tauri_plugin_g9_diagnostic::init())`.
101
+ pub fn init<R: Runtime>() -> TauriPlugin<R> {
102
+ Builder::new("g9-diagnostic")
103
+ .invoke_handler(tauri::generate_handler![capabilities, state, start_screen, stop_screen, start_voice, stop_voice, screenshot, watch_touches, touch, read_chunk, remove])
104
+ .setup(|app, api| {
105
+ #[cfg(target_os = "android")]
106
+ let handle = api.register_android_plugin("com.g9tm.appdiagnostic.tauri", "G9DiagnosticPlugin")?;
107
+ #[cfg(target_os = "ios")]
108
+ let handle = api.register_ios_plugin(init_plugin_g9_diagnostic)?;
109
+ #[cfg(mobile)]
110
+ app.manage(G9Diagnostic::<R> { handle });
111
+ #[cfg(desktop)]
112
+ {
113
+ let _ = api;
114
+ app.manage(G9Diagnostic::<R> { _r: std::marker::PhantomData });
115
+ }
116
+ Ok(())
117
+ })
118
+ .build()
119
+ }